repon 0.30.5

A terminal UI for the outer loop: seeing many git repos at once and acting on many in one gesture
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
//! Terminal setup and the event thread.
//!
//! One thread owns the terminal's input: it waits on whichever comes first, the next
//! timer or a key, and posts both down a single channel. No tokio, so cancellation is a
//! flag the thread reads between waits rather than a runtime concern.

use std::{
    io::{Stdout, stdout},
    ops::{Deref, DerefMut},
    os::fd::{AsRawFd, RawFd},
    path::Path,
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, Ordering},
    },
    thread::{self, JoinHandle},
    time::{Duration, Instant},
};

use color_eyre::eyre::Result;
use crossbeam_channel::{Receiver, Sender, unbounded};
use crossterm::{
    cursor,
    event::{
        DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
        EnableFocusChange, Event as CrosstermEvent, KeyEvent, KeyEventKind, poll, read,
    },
    terminal::{EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::backend::CrosstermBackend as Backend;

/// Slowest and fastest rates, in hertz, that a tick or frame may be asked to run at.
/// Both ends are guards rather than preferences: below the floor a `Duration` overflows,
/// above the ceiling the event thread stops waiting and spins.
pub const MIN_RATE: f64 = 0.1;
pub const MAX_RATE: f64 = 1000.0;

#[derive(Clone, Debug)]
pub enum Event {
    Init,
    Error,
    Tick,
    Render,
    FocusGained,
    FocusLost,
    Key(KeyEvent),
    /// A whole bracketed paste, delivered as one atomic string rather than the per-character
    /// key events a terminal without bracketed paste would send
    /// ([keybindings.md](../../../docs/spec/keybindings.md#terminal-state)): the ad hoc
    /// command field's own reason for enabling it, since a newline read as a key event would
    /// be indistinguishable from Enter and run a pasted multi-line command halfway through.
    Paste(String),
    Resize(u16, u16),
}

pub struct Tui {
    pub terminal: ratatui::Terminal<Backend<TerminalWriter<Stdout>>>,
    /// Replaced on every start, so that stopping the event thread drops the only sender
    /// and the app sees the channel close rather than blocking on a thread that is gone.
    event_rx: Receiver<Event>,
    running: Arc<AtomicBool>,
    task: Option<JoinHandle<()>>,
    tick_rate: f64,
    frame_rate: f64,
}

impl Tui {
    pub fn new() -> Result<Self> {
        let (_, event_rx) = unbounded();
        Ok(Self {
            terminal: ratatui::Terminal::new(Backend::new(TerminalWriter::stdout()))?,
            event_rx,
            running: Arc::new(AtomicBool::new(false)),
            task: None,
            tick_rate: 4.0,
            frame_rate: 60.0,
        })
    }

    pub fn tick_rate(mut self, tick_rate: f64) -> Self {
        self.tick_rate = tick_rate;
        self
    }

    pub fn frame_rate(mut self, frame_rate: f64) -> Self {
        self.frame_rate = frame_rate;
        self
    }

    /// Claims the five pieces of terminal state [keybindings.md](../../../docs/spec/keybindings.md#terminal-state)
    /// fixes: raw mode on, alternate screen on, bracketed paste on, mouse capture off
    /// (explicit, against an inherited enabled state), focus reporting on. Also diverts fd 2
    /// to the log file ([`redirect_stderr_to_log`]) for as long as the screen is held: a
    /// separate concern from the five, since it has no ANSI trace and nothing releases it,
    /// only [`restore`] putting the real fd back. Stdin's `O_NONBLOCK` flag
    /// ([`set_stdin_nonblocking`]) is a third such concern, needed only for as long as the
    /// event thread is the one reading it.
    pub fn enter(&mut self) -> Result<()> {
        crossterm::terminal::enable_raw_mode()?;
        set_stdin_nonblocking()?;
        redirect_stderr_to_log()?;
        write_enter_sequence(&mut TerminalWriter::stdout())?;
        self.start();
        Ok(())
    }

    pub fn exit(&mut self) -> Result<()> {
        self.stop();
        // If the terminal cannot say whether it is raw, restore anyway: a redundant
        // restore costs nothing, a skipped one follows the user back to their shell.
        if crossterm::terminal::is_raw_mode_enabled().unwrap_or(true) {
            let flushed = self.terminal.flush();
            let restored = restore();
            flushed?;
            restored?;
        }
        Ok(())
    }

    /// Hands the terminal to `command` and takes it back: the shared machinery a Launcher
    /// that takes the terminal and the ad hoc command field's `$EDITOR` handoff both stand on
    /// ([config.md](../../../../docs/spec/config.md#launchers)'s "suspends and execs in the
    /// same one"). Restores the five pieces [`Tui::exit`] restores, including fd 2's real
    /// stderr (`exit`'s own redirect is what this crate holds while the screen is up, never
    /// the child's), runs `command` to completion with the terminal's own stdio (the default,
    /// since this does not touch `command`'s stdio handles), then claims them again with
    /// [`Tui::enter`] regardless of whether the child could even be spawned, so a spawn
    /// failure still returns control to Repon's own screen rather than stranding the shell.
    ///
    /// Panic-safe by construction rather than by a check here: [`crate::errors::init`]'s
    /// panic hook calls the free function [`restore`] unconditionally, which is safe to call
    /// at any point between this method's `exit` and `enter`, so a panic anywhere in the
    /// handoff, including inside `command.status()`, still leaves the terminal as
    /// `exit`/`restore` would.
    pub fn suspend_for_child(
        &mut self,
        command: &mut std::process::Command,
    ) -> Result<std::process::ExitStatus> {
        self.exit()?;
        let status = command.status();
        self.enter()?;
        self.force_full_repaint()?;
        Ok(status?)
    }

    /// Forces the next `Terminal::draw` to write every cell rather than diff against the
    /// buffer from before a full-screen child ran: `command` may have painted over cells
    /// this buffer still believes are unchanged, and a frame that redraws them identically
    /// would then leave them as the child left them
    /// ([keybindings.md](../../../docs/spec/keybindings.md#terminal-state)'s terminal-state
    /// contract). Resizes to the terminal's own current size, which resets ratatui's back
    /// buffer as a side effect of the same call that also picks up a size change the child
    /// made while it held the terminal, rather than calling `Terminal::clear`: that queries
    /// the backend for the cursor position, which blocks on a reply a plain pty with nothing
    /// on its other end (this crate's own pty tests included) never sends.
    fn force_full_repaint(&mut self) -> Result<()> {
        let size = self.terminal.size()?;
        self.terminal
            .resize(ratatui::layout::Rect::new(0, 0, size.width, size.height))?;
        Ok(())
    }

    /// Runs `command` to completion without ever leaving the screen: the other half of
    /// [`Self::suspend_for_child`], for a Launcher that
    /// [config.md](../../../../docs/spec/config.md#launchers) declares does not take the
    /// terminal. All five pieces stay exactly as claimed for the whole run, which is not an
    /// exception to
    /// [keybindings.md](../../../docs/spec/keybindings.md#terminal-state)'s contract but its
    /// plainest case: releasing is what leaving the screen means, and this never leaves it.
    ///
    /// The child is handed `/dev/null` on all three streams instead of the terminal Repon is
    /// still holding, so a byte it writes cannot land inside the frame and a read cannot
    /// steal input from the event thread that owns that stream. Waiting is the contract
    /// rather than an implementation detail: the exit status is a Launcher's only report of
    /// failure once its own output goes nowhere.
    pub fn keep_screen_for_child(
        &mut self,
        command: &mut std::process::Command,
    ) -> Result<std::process::ExitStatus> {
        command
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null());
        Ok(command.status()?)
    }

    /// Blocks until the next event, or returns `None` once the event thread has stopped.
    pub fn next_event(&self) -> Option<Event> {
        self.event_rx.recv().ok()
    }

    pub fn start(&mut self) {
        self.stop();
        let (tx, event_rx) = unbounded();
        self.event_rx = event_rx;
        self.running.store(true, Ordering::Relaxed);
        let running = Arc::clone(&self.running);
        let (tick_rate, frame_rate) = (self.tick_rate, self.frame_rate);
        self.task = Some(thread::spawn(move || {
            event_loop(&tx, &running, tick_rate, frame_rate);
        }));
    }

    pub fn stop(&mut self) {
        self.running.store(false, Ordering::Relaxed);
        if let Some(task) = self.task.take() {
            let _ = task.join();
        }
    }
}

impl Deref for Tui {
    type Target = ratatui::Terminal<Backend<TerminalWriter<Stdout>>>;

    fn deref(&self) -> &Self::Target {
        &self.terminal
    }
}

impl DerefMut for Tui {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.terminal
    }
}

impl Drop for Tui {
    fn drop(&mut self) {
        let _ = self.exit();
    }
}

/// Puts the terminal back the way it was found: the mirror image of [`Tui::enter`]'s
/// five pieces, plus fd 2's real stderr. Safe to call more than once, and safe to call from a
/// panic hook, which is why it takes nothing; `errors::init`'s hook calls this before its own
/// `eprintln!`, so that report reaches the real terminal rather than the log file.
pub fn restore() -> std::io::Result<()> {
    restore_in_order(
        clear_stdin_nonblocking,
        || write_restore_sequence(&mut TerminalWriter::stdout()),
        crossterm::terminal::disable_raw_mode,
        restore_stderr,
    )
}

/// The four steps [`restore`] is made of, in the order they have to run in and with every one
/// of them attempted whatever the last one reported.
///
/// Giving the descriptor back comes before writing to it. [`TerminalWriter`] waits out a
/// terminal that is behind rather than failing, so a write placed first could wait there while
/// the shell still holds a stdin Repon made non-blocking and will now never hand back. A failed
/// write must not skip disabling raw mode either, which is the half the shell inherits.
///
/// Takes its steps rather than calling them, so their order is a thing a test can read.
fn restore_in_order(
    clear_nonblocking: impl FnOnce() -> std::io::Result<()>,
    write_sequence: impl FnOnce() -> std::io::Result<()>,
    disable_raw_mode: impl FnOnce() -> std::io::Result<()>,
    restore_stderr: impl FnOnce() -> std::io::Result<()>,
) -> std::io::Result<()> {
    let blocking = clear_nonblocking();
    let left = write_sequence();
    let raw = disable_raw_mode();
    let stderr = restore_stderr();
    blocking.and(left).and(raw).and(stderr)
}

/// Makes stdin's raw reads return `WouldBlock` once nothing more is immediately available
/// rather than parking the calling thread: what the event thread's underlying event source
/// (crossterm's `mio`-based reader, [`event_loop`]) already handles on a `WouldBlock`, but
/// never itself arranges, since it inherits stdin from the shell as an ordinary blocking
/// descriptor. Without this, a partial escape sequence left in stdin (crossterm's own CSI
/// parser waits unconditionally past its first two bytes, regardless of whether a further byte
/// is actually coming) leaves the thread's next raw read blocked on bytes that may never
/// arrive, deaf to [`Tui::stop`] clearing `running`.
fn set_stdin_nonblocking() -> std::io::Result<()> {
    set_fd_nonblocking(libc::STDIN_FILENO, true)
}

/// The mirror of [`set_stdin_nonblocking`], called by [`restore`] so a handed-off child, or the
/// shell once Repon exits, finds stdin exactly as blocking as it was handed.
fn clear_stdin_nonblocking() -> std::io::Result<()> {
    set_fd_nonblocking(libc::STDIN_FILENO, false)
}

/// Adds or removes `O_NONBLOCK` on `fd`'s current flags, preserving every other flag already
/// set.
fn set_fd_nonblocking(fd: RawFd, nonblocking: bool) -> std::io::Result<()> {
    // Safety: `fd` is a valid, currently-open descriptor for the duration of both calls below.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    if flags < 0 {
        return Err(std::io::Error::last_os_error());
    }
    let flags = if nonblocking {
        flags | libc::O_NONBLOCK
    } else {
        flags & !libc::O_NONBLOCK
    };
    // Safety: same as above.
    if unsafe { libc::fcntl(fd, libc::F_SETFL, flags) } < 0 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(())
}

/// How long a write pauses before trying a terminal that is behind on reading again. A terminal
/// catches up in microseconds, so this is short.
const WOULD_BLOCK_PAUSE: Duration = Duration::from_millis(1);

/// Every write Repon makes to the terminal, wrapped so that `WouldBlock` waits rather than
/// ending the session.
///
/// [`set_stdin_nonblocking`] sets `O_NONBLOCK` through fd 0, and a terminal hands one open file
/// description to fd 0, fd 1 and fd 2 alike, so stdout is non-blocking for as long as the event
/// thread needs stdin to be. A write against it reports `WouldBlock` whenever the terminal is
/// behind on reading, and neither `execute!` nor `write_all` retries that (only `Interrupted`),
/// so without this the error reaches `main` and prints as `os error 35`.
///
/// [`Tui::new`] holds one of these, so the enter sequence, the restore sequence and every frame
/// ratatui draws all go through it by construction rather than by remembering to.
pub struct TerminalWriter<W> {
    inner: W,
}

impl TerminalWriter<Stdout> {
    fn stdout() -> Self {
        Self::new(stdout())
    }
}

impl<W> TerminalWriter<W> {
    fn new(inner: W) -> Self {
        Self { inner }
    }
}

impl<W: std::io::Write> TerminalWriter<W> {
    /// Runs `attempt` until it reports something other than `WouldBlock`.
    ///
    /// The wait is unbounded on purpose, because that is what the descriptor would have done on
    /// its own. `EAGAIN` on a terminal means its buffer is full and the reader is behind, never
    /// that the reader is gone: a terminal whose other end has closed answers `EIO`, which is an
    /// error this returns like any other. Giving up after some number of seconds instead would
    /// hand `main` the same `os error 35` this exists to prevent, just less often.
    fn until_the_terminal_catches_up<T>(
        &mut self,
        mut attempt: impl FnMut(&mut W) -> std::io::Result<T>,
    ) -> std::io::Result<T> {
        loop {
            match attempt(&mut self.inner) {
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    thread::sleep(WOULD_BLOCK_PAUSE);
                }
                outcome => return outcome,
            }
        }
    }
}

impl<W: std::io::Write> std::io::Write for TerminalWriter<W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.until_the_terminal_catches_up(|inner| inner.write(buf))
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.until_the_terminal_catches_up(|inner| inner.flush())
    }
}

/// The real fd 2, saved by [`redirect_stderr_to_log`] so [`restore_stderr`] can put it back.
/// `None` while stderr is not redirected. A global rather than `Tui` field because [`restore`]
/// is a free function the panic hook calls with no `Tui` in hand.
static SAVED_STDERR: Mutex<Option<RawFd>> = Mutex::new(None);

/// Diverts fd 2 to the log file for as long as the alternate screen is held, so a dependency
/// thread that writes straight to `std::io::stderr()` (`gix-transport`'s ssh stderr
/// supervisor is the motivating case, not one of Repon's own call sites) cannot paint over the
/// frame: it lands in the log instead, kept rather than dropped. A no-op if already redirected,
/// so a redundant `enter()` never overwrites the saved real fd with the log file's own.
fn redirect_stderr_to_log() -> std::io::Result<()> {
    let mut saved = SAVED_STDERR
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    if saved.is_some() {
        return Ok(());
    }
    *saved = Some(redirect_fd_to_file(
        libc::STDERR_FILENO,
        &crate::logging::log_file_path(),
    )?);
    Ok(())
}

/// Puts fd 2 back to whatever [`redirect_stderr_to_log`] saved. Safe to call with nothing
/// saved (a no-op), the same contract [`restore`] itself already has, since a panic before
/// `Tui::enter` ever ran must not fail here.
fn restore_stderr() -> std::io::Result<()> {
    let mut saved = SAVED_STDERR
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    let Some(original) = saved.take() else {
        return Ok(());
    };
    restore_fd(libc::STDERR_FILENO, original)
}

/// Points `target` at `path` (creating the file and its parent directory, appending rather
/// than truncating), returning a duplicate of what `target` pointed at before, for
/// [`restore_fd`] to put back later. Generic over the fd number rather than hardcoded to fd 2
/// so the mechanism itself is unit-testable against an fd this process actually owns, without
/// touching the real stderr a test's own harness depends on.
fn redirect_fd_to_file(target: RawFd, path: &Path) -> std::io::Result<RawFd> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    // Safety: `target` is a valid, currently-open fd for the duration of this call.
    let saved = unsafe { libc::dup(target) };
    if saved < 0 {
        return Err(std::io::Error::last_os_error());
    }
    // Safety: `file` stays open (and its fd valid) for the duration of this call; `target` is
    // the same valid fd `dup` just read from above.
    if unsafe { libc::dup2(file.as_raw_fd(), target) } < 0 {
        let error = std::io::Error::last_os_error();
        // Safety: `saved` was just returned by `dup` above and closed nowhere else yet.
        unsafe { libc::close(saved) };
        return Err(error);
    }
    Ok(saved)
}

/// Points `target` back at whatever `saved` (from [`redirect_fd_to_file`]) names, then closes
/// `saved`: the duplicate's job is done once `target` holds its own reference to the same
/// description again.
fn restore_fd(target: RawFd, saved: RawFd) -> std::io::Result<()> {
    // Safety: `target` and `saved` are both valid, currently-open fds for the duration of
    // this call; `saved` is a duplicate this module made and nothing else has claimed.
    let result = if unsafe { libc::dup2(saved, target) } < 0 {
        Err(std::io::Error::last_os_error())
    } else {
        Ok(())
    };
    // Safety: same fd `dup2` above just read from, closed exactly once here.
    unsafe { libc::close(saved) };
    result
}

/// Waits for the sooner of the next tick, the next frame, or a key, and posts it. Returns
/// when the flag clears or the receiver goes away, so a stop costs at most one frame.
fn event_loop(tx: &Sender<Event>, running: &AtomicBool, tick_rate: f64, frame_rate: f64) {
    let (tick, frame) = (interval(tick_rate), interval(frame_rate));
    let (mut next_tick, mut next_frame) = (Instant::now(), Instant::now());

    if tx.send(Event::Init).is_err() {
        return;
    }
    while running.load(Ordering::Relaxed) {
        let now = Instant::now();
        if now >= next_tick {
            next_tick = now + tick;
            if tx.send(Event::Tick).is_err() {
                return;
            }
        }
        if now >= next_frame {
            next_frame = now + frame;
            if tx.send(Event::Render).is_err() {
                return;
            }
        }
        let wait = next_tick
            .min(next_frame)
            .saturating_duration_since(Instant::now());
        let event = match poll(wait) {
            Ok(true) => match read() {
                Ok(event) => translate(event),
                Err(_) => Some(Event::Error),
            },
            Ok(false) => None,
            Err(_) => Some(Event::Error),
        };
        if let Some(event) = event
            && tx.send(event).is_err()
        {
            return;
        }
    }
}

/// A rate in hertz as the wait between two of its events. Clamped, because
/// `Duration::from_secs_f64` panics on a rate of zero and the thread this runs on has
/// the terminal in raw mode when it does.
fn interval(rate: f64) -> Duration {
    let rate = if rate.is_finite() {
        rate.clamp(MIN_RATE, MAX_RATE)
    } else {
        MIN_RATE
    };
    Duration::from_secs_f64(1.0 / rate)
}

fn translate(event: CrosstermEvent) -> Option<Event> {
    Some(match event {
        CrosstermEvent::Key(key) if key.kind == KeyEventKind::Press => Event::Key(key),
        CrosstermEvent::Resize(columns, rows) => Event::Resize(columns, rows),
        CrosstermEvent::FocusGained => Event::FocusGained,
        CrosstermEvent::FocusLost => Event::FocusLost,
        CrosstermEvent::Paste(text) => Event::Paste(text),
        _ => return None,
    })
}

/// The four write-based pieces [`Tui::enter`] claims, in order: alternate screen, bracketed
/// paste, mouse capture (explicitly off), focus reporting, then the cursor hidden. Raw mode
/// is the fifth piece and is not a write; it is a separate `termios` call the caller makes
/// before this. Generic over the writer so a test can assert the exact byte sequence against
/// a `Vec<u8>` without a real terminal.
fn write_enter_sequence(w: &mut TerminalWriter<impl std::io::Write>) -> std::io::Result<()> {
    crossterm::execute!(
        w,
        EnterAlternateScreen,
        EnableBracketedPaste,
        DisableMouseCapture,
        EnableFocusChange,
        cursor::Hide,
    )
}

/// Releases what [`write_enter_sequence`] claimed: focus reporting, bracketed paste, alternate
/// screen, then the cursor shown again last, after the screen mode is fully restored rather
/// than in claim-reversed order. Disabling raw mode is the caller's separate final step,
/// matching [`write_enter_sequence`].
///
/// Mouse capture is the one piece [`write_enter_sequence`] claims that this does not release,
/// which is the contract rather than a gap in it: the four pieces Repon *enables* are released
/// so it leaves no residue, and mouse capture is the one it *disables*, so there is nothing to
/// release. [keybindings.md](../../../docs/spec/keybindings.md#terminal-state)'s `released`
/// column is the exception set, and
/// [0024](../../../docs/adr/0024-repon-releases-what-it-enables-and-holds-mouse-capture-off.md)
/// is why: the terminal cannot be asked what it was, and a terminal found with capture on is
/// one some earlier program crashed out of rather than one anybody configured.
fn write_restore_sequence(w: &mut TerminalWriter<impl std::io::Write>) -> std::io::Result<()> {
    crossterm::execute!(
        w,
        DisableFocusChange,
        DisableBracketedPaste,
        LeaveAlternateScreen,
        cursor::Show,
    )
}

#[cfg(test)]
mod tests {
    use std::io::Write as _;

    /// A writer that reports `WouldBlock` for its first `stalls` calls, the way the terminal's
    /// own descriptor does while it is behind on reading, then accepts everything.
    #[derive(Default)]
    struct StallingWriter {
        stalls: usize,
        written: Vec<u8>,
    }

    impl std::io::Write for StallingWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            if self.stalls > 0 {
                self.stalls -= 1;
                return Err(std::io::Error::new(
                    std::io::ErrorKind::WouldBlock,
                    "stalled",
                ));
            }
            self.written.extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// The failure [`TerminalWriter`] exists for: a write that reports `WouldBlock` because the
    /// terminal is behind, which ended the session with `os error 35`.
    #[test]
    fn a_stalled_terminal_does_not_end_the_enter_sequence() {
        let mut writer = TerminalWriter::new(StallingWriter {
            stalls: 3,
            written: Vec::new(),
        });

        write_enter_sequence(&mut writer)
            .expect("write the enter sequence through a stalled terminal");

        assert!(
            !writer.inner.written.is_empty(),
            "expected the enter sequence to reach the terminal once it caught up"
        );
    }

    /// An error that is not `WouldBlock` is the terminal saying something else, and travels
    /// unchanged: `EIO` is how a terminal whose other end has closed answers, and waiting that
    /// out would never end.
    #[test]
    fn an_error_that_is_not_would_block_travels_unchanged() {
        struct Broken;
        impl std::io::Write for Broken {
            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
                Err(std::io::Error::from_raw_os_error(libc::EIO))
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        let error = TerminalWriter::new(Broken)
            .write(b"nowhere to go")
            .expect_err("expected the error to travel rather than be waited out");

        assert_eq!(error.raw_os_error(), Some(libc::EIO));
    }

    /// [`restore`]'s contract, read off the order its steps run in: the shell gets its
    /// descriptor back before anything writes to it, and every step runs whatever the one
    /// before it reported.
    #[test]
    fn restore_returns_the_descriptor_before_writing_and_runs_every_step_regardless() {
        let ran = &std::cell::RefCell::new(Vec::new());
        let step = move |name: &'static str, outcome: std::io::Result<()>| {
            move || {
                ran.borrow_mut().push(name);
                outcome
            }
        };

        let result = restore_in_order(
            step(
                "clear_nonblocking",
                Err(std::io::Error::other("the flag would not clear")),
            ),
            step("write_sequence", Ok(())),
            step("disable_raw_mode", Ok(())),
            step("restore_stderr", Ok(())),
        );

        assert_eq!(
            ran.take(),
            vec![
                "clear_nonblocking",
                "write_sequence",
                "disable_raw_mode",
                "restore_stderr"
            ],
            "expected the descriptor to be handed back before the write, and every later step \
             to run despite the first one failing"
        );
        assert!(
            result.is_err(),
            "expected the first step's failure to still be reported"
        );
    }

    /// The premise [`TerminalWriter`] rests on, kept true rather than only written down:
    /// `O_NONBLOCK` belongs to the open file description, so a call against one descriptor lands
    /// on every descriptor sharing it.
    #[test]
    fn the_non_blocking_flag_is_visible_through_every_descriptor_sharing_one_open_file() {
        let mut fds = [0 as std::os::raw::c_int; 2];
        // Safety: `fds` is a valid two-element out-array for `pipe(2)`.
        assert_eq!(
            unsafe { libc::pipe(fds.as_mut_ptr()) },
            0,
            "create a scratch pipe"
        );
        let (read_fd, write_fd) = (fds[0], fds[1]);
        // Safety: `read_fd` is open, and `dup(2)` returns a second descriptor for the same
        // open file description, exactly as a terminal's fd 0/1/2 are set up.
        let shared_fd = unsafe { libc::dup(read_fd) };
        assert!(shared_fd >= 0, "duplicate the read end");

        set_fd_nonblocking(read_fd, true).expect("set one descriptor non-blocking");

        // Safety: `shared_fd` is still open; `F_GETFL` takes no further argument.
        let flags = unsafe { libc::fcntl(shared_fd, libc::F_GETFL) };
        assert!(flags >= 0, "read the other descriptor's flags");
        assert_ne!(
            flags & libc::O_NONBLOCK,
            0,
            "expected the flag set through one descriptor to be visible through the other"
        );

        // Safety: all three descriptors are open and owned by this test.
        unsafe {
            libc::close(shared_fd);
            libc::close(read_fd);
            libc::close(write_fd);
        }
    }

    use crossterm::event::{KeyCode, KeyModifiers};

    use super::*;
    use crate::test_support::rust_source_files;

    /// [`redirect_fd_to_file`] and [`restore_fd`] against an fd this test owns outright,
    /// rather than the real fd 2 a unit test's own harness depends on: opens a scratch file,
    /// redirects its fd elsewhere, writes through the same `File` value on both sides of the
    /// redirect (proving the divert operates on the fd number itself, not on any Rust-level
    /// handle to it), then restores and writes again.
    #[test]
    fn redirecting_a_raw_fd_diverts_its_writes_until_restored() {
        let scratch_dir = tempfile::tempdir().expect("create scratch tempdir");
        let original_path = scratch_dir.path().join("original.txt");
        let redirected_path = scratch_dir.path().join("redirected.txt");
        let mut scratch = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&original_path)
            .expect("open the scratch file this test redirects");
        let target = scratch.as_raw_fd();

        writeln!(scratch, "before redirect").expect("write before redirect");
        let saved = redirect_fd_to_file(target, &redirected_path).expect("redirect the scratch fd");
        writeln!(scratch, "during redirect").expect("write during redirect");
        restore_fd(target, saved).expect("restore the scratch fd");
        writeln!(scratch, "after restore").expect("write after restore");

        assert_eq!(
            std::fs::read_to_string(&original_path).expect("read the original file"),
            "before redirect\nafter restore\n",
            "the fd's own file must see everything but what was written mid-redirect"
        );
        assert_eq!(
            std::fs::read_to_string(&redirected_path).expect("read the redirected file"),
            "during redirect\n",
            "the redirect target must see only what was written while it was pointed there"
        );
    }

    /// [`redirect_stderr_to_log`]/[`restore_stderr`]'s own no-op contracts: redirecting twice
    /// without restoring in between must not clobber the saved real fd with the log file's
    /// own, and restoring with nothing saved must not error. Exercised against
    /// [`SAVED_STDERR`] directly with a fabricated saved value, never against the real fd 2
    /// this test process's own harness depends on.
    #[test]
    fn redirect_and_restore_stderr_are_no_ops_when_already_in_that_state() {
        let mut saved = SAVED_STDERR.lock().expect("lock SAVED_STDERR");
        assert!(
            saved.is_none(),
            "test order assumption: nothing else touched fd 2"
        );
        *saved = Some(99);
        drop(saved);

        // A second `enter()`-driven redirect while one is already outstanding must leave the
        // fabricated saved value untouched rather than overwrite it with a real dup of fd 2.
        redirect_stderr_to_log().expect("redirect_stderr_to_log is a no-op once already saved");
        assert_eq!(
            *SAVED_STDERR.lock().expect("lock SAVED_STDERR"),
            Some(99),
            "a redundant redirect must not overwrite what is already saved"
        );

        // Clears the fabricated value without ever calling libc on the bogus fd 99: restoring
        // that would corrupt this process's real fd table for every test run after it.
        *SAVED_STDERR.lock().expect("lock SAVED_STDERR") = None;

        // With nothing saved, restoring must be a no-op rather than an error.
        restore_stderr().expect("restore_stderr with nothing saved must be a no-op");
    }

    /// [`set_fd_nonblocking`] against a pipe end this test owns outright, rather than the real
    /// stdin a unit test's own harness may or may not have: a non-blocking read of an empty
    /// pipe must return `WouldBlock` immediately instead of parking the test, and clearing the
    /// flag again must show up in the fd's own reported flags.
    #[test]
    fn set_fd_nonblocking_toggles_would_block_without_leaking_into_other_flags() {
        let mut fds = [0 as std::os::raw::c_int; 2];
        // Safety: `fds` is a valid two-element out-array for `pipe(2)`.
        assert_eq!(
            unsafe { libc::pipe(fds.as_mut_ptr()) },
            0,
            "create a scratch pipe"
        );
        let (read_fd, write_fd) = (fds[0], fds[1]);

        set_fd_nonblocking(read_fd, true).expect("set the read end non-blocking");
        let mut byte = [0u8; 1];
        // Safety: `byte` is a valid one-byte buffer for the duration of this call.
        let read = unsafe { libc::read(read_fd, byte.as_mut_ptr() as *mut libc::c_void, 1) };
        assert_eq!(
            read, -1,
            "expected a non-blocking read of an empty pipe to fail rather than return data"
        );
        assert_eq!(
            std::io::Error::last_os_error().kind(),
            std::io::ErrorKind::WouldBlock,
            "expected WouldBlock rather than parking this test on an empty pipe"
        );

        set_fd_nonblocking(read_fd, false).expect("clear non-blocking on the read end");
        // Safety: `read_fd` is still open; `F_GETFL` takes no further argument.
        let flags = unsafe { libc::fcntl(read_fd, libc::F_GETFL) };
        assert_eq!(
            flags & libc::O_NONBLOCK,
            0,
            "expected O_NONBLOCK cleared after set_fd_nonblocking(fd, false)"
        );

        // Safety: both ends are this test's own, opened above and not yet closed.
        unsafe {
            libc::close(read_fd);
            libc::close(write_fd);
        }
    }

    /// Renders one crossterm `Command` to its ANSI bytes, the same way `execute!` would, so
    /// an expectation here comes from crossterm's own encoding rather than a hand-copied
    /// escape sequence that could silently drift from what a future crossterm version emits.
    fn ansi_bytes(command: impl crossterm::Command) -> Vec<u8> {
        let mut buf = String::new();
        command.write_ansi(&mut buf).expect("encode ansi command");
        buf.into_bytes()
    }

    #[test]
    fn the_enter_sequence_claims_all_four_write_based_pieces_in_order() {
        let mut out = TerminalWriter::new(Vec::new());
        write_enter_sequence(&mut out).expect("write enter sequence");

        let mut expected = Vec::new();
        expected.extend(ansi_bytes(EnterAlternateScreen));
        expected.extend(ansi_bytes(EnableBracketedPaste));
        expected.extend(ansi_bytes(DisableMouseCapture));
        expected.extend(ansi_bytes(EnableFocusChange));
        expected.extend(ansi_bytes(cursor::Hide));

        assert_eq!(out.inner, expected);
    }

    #[test]
    fn the_restore_sequence_releases_focus_paste_and_alt_screen_then_shows_the_cursor_last() {
        let mut out = TerminalWriter::new(Vec::new());
        write_restore_sequence(&mut out).expect("write restore sequence");

        let mut expected = Vec::new();
        expected.extend(ansi_bytes(DisableFocusChange));
        expected.extend(ansi_bytes(DisableBracketedPaste));
        expected.extend(ansi_bytes(LeaveAlternateScreen));
        expected.extend(ansi_bytes(cursor::Show));

        assert_eq!(out.inner, expected);
    }

    /// Whether `needle` occurs anywhere in `haystack`, for asserting on the encoded ANSI
    /// bytes without decoding them back to a string.
    fn bytes_contain(haystack: &[u8], needle: &[u8]) -> bool {
        !needle.is_empty()
            && haystack
                .windows(needle.len())
                .any(|window| window == needle)
    }

    /// [`crate::test_support::production_source_at`] over this file itself: the same
    /// self-scan technique `no_trace_of_the_removed_signal_dependency_remains` below uses,
    /// applied here to prove raw mode's own enable/disable calls exist rather than trusting a
    /// comment about them.
    fn this_files_production_source() -> String {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        crate::test_support::production_source_at(&manifest_dir.join("src/tui.rs"))
    }

    /// Parses [keybindings.md](../../../docs/spec/keybindings.md#terminal-state)'s
    /// `## Terminal state` table into one `(name, setting_on, released)` triple per row. The
    /// `setting` column decides which half of the enable/disable pair entry writes, and the
    /// `released` column decides whether the other half appears on the way out or whether
    /// neither may, so the exception lives in the spec rather than in the assertion below.
    fn spec_terminal_state_pieces(spec: &str) -> Vec<(String, bool, bool)> {
        const ANCHOR: &str = "## Terminal state";
        let after = spec
            .split(ANCHOR)
            .nth(1)
            .expect("the terminal state section is present");
        let cell = |raw: &str| raw.trim().trim_matches('*').trim().to_string();
        after
            .lines()
            .skip_while(|line| !line.starts_with('|'))
            .take_while(|line| line.starts_with('|'))
            .filter(|line| !line.starts_with("| ---"))
            .filter_map(|line| {
                let cells: Vec<String> = line.split('|').map(cell).collect();
                let (name, setting, released) = (&cells[1], &cells[2], &cells[3]);
                if name == "state" {
                    return None;
                }
                let flag = |value: &String, on: &str, off: &str| match value.as_str() {
                    v if v == on => true,
                    v if v == off => false,
                    other => {
                        panic!("unexpected {name} value {other:?} in the terminal state table")
                    }
                };
                Some((
                    name.clone(),
                    flag(setting, "on", "off"),
                    flag(released, "yes", "no"),
                ))
            })
            .collect()
    }

    // Criterion 1's "single source of truth" trap, applied to the terminal-state contract:
    // reads the pieces and their claim/release asymmetry out of the spec at test time, so a
    // sixth piece grows this vector and fails the equality assertion, and a second piece
    // going asymmetric is a spec edit rather than a silent code change. 0024 is why the
    // asymmetry is a column here and not a hardcoded exception.
    #[test]
    fn the_enter_and_restore_sequences_account_for_every_piece_the_spec_names() {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let spec = std::fs::read_to_string(manifest_dir.join("../../docs/spec/keybindings.md"))
            .expect("read docs/spec/keybindings.md");
        let pieces = spec_terminal_state_pieces(&spec);
        assert_eq!(
            pieces,
            vec![
                ("Raw mode".to_string(), true, true),
                ("Alternate screen".to_string(), true, true),
                ("Bracketed paste".to_string(), true, true),
                ("Mouse capture".to_string(), false, false),
                ("Focus reporting".to_string(), true, true),
            ],
            "a piece added, removed or reworded here must be deliberately accounted for \
             below, not merely counted"
        );

        let mut enter = TerminalWriter::new(Vec::new());
        write_enter_sequence(&mut enter).expect("write enter sequence");
        let mut restore = TerminalWriter::new(Vec::new());
        write_restore_sequence(&mut restore).expect("write restore sequence");
        let (enter, restore) = (enter.inner, restore.inner);
        let source = this_files_production_source();

        for (name, setting_on, released) in pieces {
            // Raw mode has no ANSI trace; it is claimed and released by a direct termios call
            // instead of write_enter_sequence/write_restore_sequence.
            if name == "Raw mode" {
                assert!(
                    source.contains("enable_raw_mode()") && source.contains("disable_raw_mode()"),
                    "expected raw mode to be claimed and released by termios calls"
                );
                continue;
            }

            let (on, off) = match name.as_str() {
                "Alternate screen" => (
                    ansi_bytes(EnterAlternateScreen),
                    ansi_bytes(LeaveAlternateScreen),
                ),
                "Bracketed paste" => (
                    ansi_bytes(EnableBracketedPaste),
                    ansi_bytes(DisableBracketedPaste),
                ),
                "Mouse capture" => (
                    ansi_bytes(crossterm::event::EnableMouseCapture),
                    ansi_bytes(DisableMouseCapture),
                ),
                "Focus reporting" => (
                    ansi_bytes(EnableFocusChange),
                    ansi_bytes(DisableFocusChange),
                ),
                other => panic!("no sequence known for the spec's {other:?}"),
            };
            let (claim, opposite) = if setting_on { (&on, &off) } else { (&off, &on) };

            assert!(
                bytes_contain(&enter, claim),
                "expected {name} to be claimed in the enter sequence"
            );
            if released {
                assert!(
                    bytes_contain(&restore, opposite),
                    "expected {name} to be released in the restore sequence"
                );
            } else {
                for unwanted in [&on, &off] {
                    assert!(
                        !bytes_contain(&restore, unwanted),
                        "{name} is marked not released, so it must never be written on restore"
                    );
                }
            }
        }
    }

    /// config.md owned the contract until 0024 moved it, so a reader still goes there for it.
    /// The redirect is asserted rather than trusted, because a pointer nobody checks decays
    /// into the second copy the two documents disagreed over.
    #[test]
    fn config_md_redirects_to_the_terminal_state_contract_rather_than_restating_it() {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let config_md = std::fs::read_to_string(manifest_dir.join("../../docs/spec/config.md"))
            .expect("read docs/spec/config.md");
        assert!(
            config_md.contains("keybindings.md#terminal-state"),
            "expected config.md's Launchers section to link the terminal-state contract"
        );
        assert!(
            !config_md.contains("must be restored"),
            "expected config.md to point at the contract rather than restate it"
        );
    }

    /// crossterm's `KeyEventKind` has three variants, not two: a physical key held down
    /// generates `Repeat` events between the `Press` and the eventual `Release`. Only `Press`
    /// may reach [`BindingTable::dispatch`](crate::keys::BindingTable::dispatch), or every
    /// bound key would fire twice.
    #[test]
    fn translate_passes_through_a_press_and_filters_every_other_key_event_kind() {
        let press = KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE);
        assert!(matches!(
            translate(CrosstermEvent::Key(press)),
            Some(Event::Key(_))
        ));

        for kind in [KeyEventKind::Release, KeyEventKind::Repeat] {
            let key = KeyEvent { kind, ..press };
            assert!(
                translate(CrosstermEvent::Key(key)).is_none(),
                "a {kind:?} key event must not reach dispatch"
            );
        }
    }

    /// The ad hoc command field's own reason for enabling bracketed paste: a pasted
    /// multi-line command must arrive as one atomic event, embedded newlines and all, never
    /// decomposed into the per-character key events that would let a newline read as Enter.
    #[test]
    fn translate_passes_a_bracketed_paste_through_as_one_whole_string() {
        let pasted = "first line\nsecond line".to_string();
        assert!(matches!(
            translate(CrosstermEvent::Paste(pasted.clone())),
            Some(Event::Paste(text)) if text == pasted
        ));
    }

    /// [keybindings.md](../../../docs/spec/keybindings.md#quitting-and-confirming): raw mode
    /// clears ISIG, so quit is an ordinary key handler rather than a signal handler, and this
    /// crate raises no signal at itself for any reason. It therefore has no legitimate use
    /// for `signal_hook` at all, which is why the guard polices the dependency's absence
    /// outright rather than allowing one blessed call site.
    #[test]
    fn no_trace_of_the_removed_signal_dependency_remains() {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));

        let cargo_toml = std::fs::read_to_string(manifest_dir.join("Cargo.toml"))
            .expect("read this crate's Cargo.toml");
        assert!(
            !cargo_toml.contains("signal-hook"),
            "expected the signal-hook dependency to be gone from this crate's Cargo.toml"
        );

        // Built from pieces so this line is never a self-match once this file is scanned,
        // the same trick `app.rs`'s own source-scan tests use.
        let needle = format!("{}_{}", "signal", "hook");
        let mut offending_locations = Vec::new();
        for path in rust_source_files(&manifest_dir.join("src")) {
            let source = std::fs::read_to_string(&path).expect("read a crate source file");
            for (number, line) in source.lines().enumerate() {
                let trimmed = line.trim_start();
                if trimmed.starts_with("//") {
                    continue;
                }
                if line.contains(&needle) {
                    offending_locations.push(format!("{}:{}", path.display(), number + 1));
                }
            }
        }
        assert!(
            offending_locations.is_empty(),
            "expected no `{needle}` usage anywhere in this crate's source, found: \
             {offending_locations:?}"
        );
    }
}