gitwig 2.6.7

a rust based tui, an alternative to sourcetree and gitui
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Embedded terminal session: a shell running in a PTY, rendered inside the
//! TUI by the terminal panel (`components::terminal_panel`).
//!
//! A detached reader thread pumps PTY output into a shared `vt100::Parser`;
//! the run loop polls `poll_exit` each frame and the draw pass renders the
//! parser's screen. Dropping the session kills and reaps the shell.

use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};

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

/// Lines of scrollback history kept by the parser.
pub const SCROLLBACK_LINES: usize = 1000;

const MIN_ROWS: u16 = 3;
const MIN_COLS: u16 = 10;

/// Panel-level state owned by `App`: the (single) session plus visibility
/// and the user's preferred panel height.
pub struct TerminalPanelState {
    pub session: Option<TerminalSession>,
    pub visible: bool,
    /// Desired outer panel height in rows, including the 2 border rows.
    pub height: u16,
}

impl Default for TerminalPanelState {
    fn default() -> Self {
        Self { session: None, visible: false, height: 12 }
    }
}

/// A live shell attached to a PTY.
pub struct TerminalSession {
    /// Shared with the reader thread: it locks to `process()` output bytes,
    /// the draw pass locks to read the screen.
    parser: Arc<Mutex<vt100::Parser>>,
    /// Kept for `resize()`; dropping it closes the PTY, which unblocks the
    /// reader thread and hangs up the shell.
    master: Box<dyn portable_pty::MasterPty + Send>,
    writer: Box<dyn std::io::Write + Send>,
    child: Box<dyn portable_pty::Child + Send + Sync>,
    /// Set by the reader thread on EOF/read error, or here on write failure.
    exited: Arc<AtomicBool>,
    /// Bumped by the reader thread after every `process()` (and on any local
    /// screen mutation), so the run loop can skip redraws while the shell is
    /// quiet instead of repainting on every poll tick.
    generation: Arc<AtomicU64>,
    exit_status: Option<portable_pty::ExitStatus>,
    /// Last (rows, cols) applied to master + parser; skips no-op resizes.
    size: (u16, u16),
    /// Repo name captured at spawn, shown in the panel title for the whole
    /// life of the session even if the selection moves elsewhere.
    pub repo_label: String,
}

impl TerminalSession {
    /// Spawn `$SHELL` (fallback `/bin/sh`) in a fresh PTY at `cwd`.
    pub fn spawn(
        cwd: &std::path::Path,
        repo_label: String,
        rows: u16,
        cols: u16,
    ) -> Result<Self, String> {
        let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
        let mut cmd = portable_pty::CommandBuilder::new(&shell);
        cmd.cwd(cwd);
        cmd.env("GITWIG", "1");
        cmd.env("GITWIG_SHELL", "1");
        cmd.env("TERM", "xterm-256color");
        Self::spawn_command(cmd, repo_label, rows, cols)
    }

    /// Spawn an arbitrary command in a fresh PTY. Seam for integration tests.
    pub fn spawn_command(
        cmd: portable_pty::CommandBuilder,
        repo_label: String,
        rows: u16,
        cols: u16,
    ) -> Result<Self, String> {
        let rows = rows.max(MIN_ROWS);
        let cols = cols.max(MIN_COLS);
        let pty_system = portable_pty::native_pty_system();
        let pair = pty_system
            .openpty(portable_pty::PtySize { rows, cols, pixel_width: 0, pixel_height: 0 })
            .map_err(|e| format!("Could not open PTY: {}", e))?;

        let child =
            pair.slave.spawn_command(cmd).map_err(|e| format!("Could not start shell: {}", e))?;
        // Keep only the child holding the slave end, so closing the master
        // later reliably delivers EOF/SIGHUP.
        drop(pair.slave);

        let writer =
            pair.master.take_writer().map_err(|e| format!("Could not open PTY writer: {}", e))?;
        let reader = pair
            .master
            .try_clone_reader()
            .map_err(|e| format!("Could not open PTY reader: {}", e))?;

        let parser = Arc::new(Mutex::new(vt100::Parser::new(rows, cols, SCROLLBACK_LINES)));
        let exited = Arc::new(AtomicBool::new(false));
        let generation = Arc::new(AtomicU64::new(0));
        spawn_reader(reader, Arc::clone(&parser), Arc::clone(&exited), Arc::clone(&generation));

        Ok(Self {
            parser,
            master: pair.master,
            writer,
            child,
            exited,
            generation,
            exit_status: None,
            size: (rows, cols),
            repo_label,
        })
    }

    /// Poison-safe access to the parser; the single lock path everywhere.
    pub fn lock_parser(&self) -> MutexGuard<'_, vt100::Parser> {
        self.parser.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Resize the PTY and the parser grid. No-op when unchanged.
    pub fn resize(&mut self, rows: u16, cols: u16) {
        let rows = rows.max(MIN_ROWS);
        let cols = cols.max(MIN_COLS);
        if (rows, cols) == self.size {
            return;
        }
        self.size = (rows, cols);
        // Failure is non-fatal: the shell just keeps its old size.
        let _ = self.master.resize(portable_pty::PtySize {
            rows,
            cols,
            pixel_width: 0,
            pixel_height: 0,
        });
        self.lock_parser().screen_mut().set_size(rows, cols);
        self.bump_generation();
    }

    /// Monotonic counter of screen mutations; unchanged means nothing new to draw.
    pub fn generation(&self) -> u64 {
        self.generation.load(Ordering::Relaxed)
    }

    fn bump_generation(&self) {
        self.generation.fetch_add(1, Ordering::Relaxed);
    }

    /// Whether the shell is gone (reader saw EOF, or a write failed).
    pub fn exited(&self) -> bool {
        self.exited.load(Ordering::Relaxed)
    }
}

impl TerminalSession {
    /// Called once per run-loop iteration. Reaps the child after the reader
    /// saw EOF. Returns `true` exactly once, when the exit is first observed.
    pub fn poll_exit(&mut self) -> bool {
        if !self.exited() || self.exit_status.is_some() {
            return false;
        }
        match self.child.try_wait() {
            Ok(Some(status)) => {
                self.exit_status = Some(status);
                true
            }
            // EOF seen but the child has not been reaped yet; retry next frame.
            Ok(None) => false,
            Err(_) => {
                self.exit_status = Some(portable_pty::ExitStatus::with_exit_code(1));
                true
            }
        }
    }

    /// Exit code of the shell, once reaped.
    pub fn exit_code(&self) -> Option<u32> {
        self.exit_status.as_ref().map(portable_pty::ExitStatus::exit_code)
    }

    /// Write raw bytes to the shell. A broken pipe converges on the exited path.
    pub fn send_bytes(&mut self, bytes: &[u8]) {
        if self.exited() {
            return;
        }
        use std::io::Write;
        if self.writer.write_all(bytes).and_then(|_| self.writer.flush()).is_err() {
            self.exited.store(true, Ordering::Relaxed);
        }
    }

    /// Encode and forward one keystroke; snaps the view back to the live screen.
    pub fn send_key(&mut self, key: KeyEvent) {
        let app_cursor = self.lock_parser().screen().application_cursor();
        if let Some(bytes) = encode_key(key, app_cursor) {
            self.lock_parser().screen_mut().set_scrollback(0);
            self.bump_generation();
            self.send_bytes(&bytes);
        }
    }

    /// Forward pasted text, honoring bracketed-paste mode when the shell
    /// enabled it. The end-paste marker is stripped from the payload so a
    /// malicious paste cannot break out of the bracket.
    pub fn send_paste(&mut self, text: &str) {
        let sanitized = text.replace("\x1b[201~", "");
        let bracketed = self.lock_parser().screen().bracketed_paste();
        self.lock_parser().screen_mut().set_scrollback(0);
        self.bump_generation();
        if bracketed {
            self.send_bytes(b"\x1b[200~");
            let payload = sanitized.into_bytes();
            self.send_bytes(&payload);
            self.send_bytes(b"\x1b[201~");
        } else {
            self.send_bytes(sanitized.as_bytes());
        }
    }

    /// Move the scrollback view by `delta` rows (positive = further back).
    pub fn scroll_by(&mut self, delta: isize) {
        let mut guard = self.lock_parser();
        let screen = guard.screen_mut();
        let current = screen.scrollback();
        let next = if delta >= 0 {
            current.saturating_add(delta as usize)
        } else {
            current.saturating_sub(delta.unsigned_abs())
        };
        screen.set_scrollback(next);
        drop(guard);
        self.bump_generation();
    }
}

impl Drop for TerminalSession {
    fn drop(&mut self) {
        if !self.exited() && self.exit_status.is_none() {
            let _ = self.child.kill();
        }
        // Reap so no zombie outlives the session; returns promptly after
        // kill or a prior exit. Dropping master/writer then closes the PTY,
        // which unblocks the detached reader thread.
        let _ = self.child.wait();
    }
}

/// Detached PTY output pump: reads until EOF, feeding the shared parser.
fn spawn_reader(
    mut reader: Box<dyn std::io::Read + Send>,
    parser: Arc<Mutex<vt100::Parser>>,
    exited: Arc<AtomicBool>,
    generation: Arc<AtomicU64>,
) {
    std::thread::spawn(move || {
        let mut buf = [0u8; 4096];
        loop {
            match reader.read(&mut buf) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    parser.lock().unwrap_or_else(PoisonError::into_inner).process(&buf[..n]);
                    generation.fetch_add(1, Ordering::Relaxed);
                }
            }
        }
        exited.store(true, Ordering::Relaxed);
        // The exit banner needs one more frame even though no bytes arrived.
        generation.fetch_add(1, Ordering::Relaxed);
    });
}

/// Translate a crossterm key event into the byte sequence a terminal would
/// send (legacy xterm encoding). `None` means the key has no terminal
/// representation and is swallowed.
pub fn encode_key(key: KeyEvent, application_cursor: bool) -> Option<Vec<u8>> {
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let alt = key.modifiers.contains(KeyModifiers::ALT);
    let shift = key.modifiers.contains(KeyModifiers::SHIFT);

    // xterm modifier parameter: 1 + shift(1) + alt(2) + ctrl(4).
    let mod_param = 1 + u8::from(shift) + 2 * u8::from(alt) + 4 * u8::from(ctrl);

    // CSI 1;{m}X for arrows/Home/End, CSI {n};{m}~ for the tilde keys.
    let csi_modified = |c: u8| format!("\x1b[1;{}{}", mod_param, c as char).into_bytes();
    let tilde = |n: u8| {
        if mod_param > 1 {
            format!("\x1b[{};{}~", n, mod_param).into_bytes()
        } else {
            format!("\x1b[{}~", n).into_bytes()
        }
    };
    let arrow = |c: u8| {
        if mod_param > 1 {
            csi_modified(c)
        } else if application_cursor {
            vec![0x1b, b'O', c]
        } else {
            vec![0x1b, b'[', c]
        }
    };

    let bytes = match key.code {
        KeyCode::Char(c) => {
            let mut out = Vec::new();
            if alt {
                out.push(0x1b);
            }
            if ctrl {
                out.push(ctrl_byte(c)?);
            } else {
                let mut utf8 = [0u8; 4];
                out.extend_from_slice(c.encode_utf8(&mut utf8).as_bytes());
            }
            out
        }
        KeyCode::Enter => {
            if alt {
                vec![0x1b, b'\r']
            } else {
                vec![b'\r']
            }
        }
        KeyCode::Tab => vec![b'\t'],
        KeyCode::BackTab => b"\x1b[Z".to_vec(),
        KeyCode::Backspace => {
            let base = if ctrl { 0x08 } else { 0x7f };
            if alt { vec![0x1b, base] } else { vec![base] }
        }
        KeyCode::Esc => vec![0x1b],
        KeyCode::Up => arrow(b'A'),
        KeyCode::Down => arrow(b'B'),
        KeyCode::Right => arrow(b'C'),
        KeyCode::Left => arrow(b'D'),
        KeyCode::Home => {
            if mod_param > 1 {
                csi_modified(b'H')
            } else if application_cursor {
                b"\x1bOH".to_vec()
            } else {
                b"\x1b[H".to_vec()
            }
        }
        KeyCode::End => {
            if mod_param > 1 {
                csi_modified(b'F')
            } else if application_cursor {
                b"\x1bOF".to_vec()
            } else {
                b"\x1b[F".to_vec()
            }
        }
        KeyCode::Insert => tilde(2),
        KeyCode::Delete => tilde(3),
        KeyCode::PageUp => tilde(5),
        KeyCode::PageDown => tilde(6),
        KeyCode::F(n @ 1..=4) => vec![0x1b, b'O', b'P' + (n - 1)],
        KeyCode::F(n @ 5..=12) => {
            let code = match n {
                5 => 15,
                6 => 17,
                7 => 18,
                8 => 19,
                9 => 20,
                10 => 21,
                11 => 23,
                _ => 24,
            };
            tilde(code)
        }
        _ => return None,
    };
    Some(bytes)
}

/// Control-key byte for `ctrl+<c>`, per the ASCII control-character mapping.
fn ctrl_byte(c: char) -> Option<u8> {
    match c {
        'a'..='z' => Some(c as u8 & 0x1f),
        'A'..='Z' => Some(c.to_ascii_lowercase() as u8 & 0x1f),
        ' ' | '@' => Some(0x00),
        '[' => Some(0x1b),
        '\\' => Some(0x1c),
        ']' => Some(0x1d),
        '^' => Some(0x1e),
        '_' => Some(0x1f),
        '?' => Some(0x7f),
        _ => None,
    }
}

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

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::empty())
    }

    fn key_mod(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, modifiers)
    }

    fn enc(code: KeyCode) -> Vec<u8> {
        encode_key(key(code), false).expect("mapped key")
    }

    #[test]
    fn encodes_plain_chars_and_controls() {
        assert_eq!(enc(KeyCode::Char('a')), b"a");
        assert_eq!(enc(KeyCode::Char('é')), "é".as_bytes());
        assert_eq!(enc(KeyCode::Enter), b"\r");
        assert_eq!(enc(KeyCode::Tab), b"\t");
        assert_eq!(enc(KeyCode::BackTab), b"\x1b[Z");
        assert_eq!(enc(KeyCode::Backspace), &[0x7f]);
        assert_eq!(enc(KeyCode::Esc), &[0x1b]);
    }

    #[test]
    fn encodes_ctrl_and_alt_chars() {
        let c = |ch| encode_key(key_mod(KeyCode::Char(ch), KeyModifiers::CONTROL), false);
        assert_eq!(c('c'), Some(vec![0x03]));
        assert_eq!(c('d'), Some(vec![0x04]));
        assert_eq!(c('z'), Some(vec![0x1a]));
        assert_eq!(c(' '), Some(vec![0x00]));
        assert_eq!(c('?'), Some(vec![0x7f]));
        assert_eq!(
            encode_key(key_mod(KeyCode::Char('x'), KeyModifiers::ALT), false),
            Some(b"\x1bx".to_vec())
        );
        assert_eq!(
            encode_key(
                key_mod(KeyCode::Char('c'), KeyModifiers::ALT | KeyModifiers::CONTROL),
                false
            ),
            Some(vec![0x1b, 0x03])
        );
    }

    #[test]
    fn encodes_arrows_and_navigation() {
        assert_eq!(enc(KeyCode::Up), b"\x1b[A");
        assert_eq!(enc(KeyCode::Left), b"\x1b[D");
        // Application-cursor mode switches to SS3.
        assert_eq!(encode_key(key(KeyCode::Up), true), Some(b"\x1bOA".to_vec()));
        assert_eq!(encode_key(key(KeyCode::Home), true), Some(b"\x1bOH".to_vec()));
        assert_eq!(enc(KeyCode::Home), b"\x1b[H");
        assert_eq!(enc(KeyCode::End), b"\x1b[F");
        assert_eq!(enc(KeyCode::PageUp), b"\x1b[5~");
        assert_eq!(enc(KeyCode::PageDown), b"\x1b[6~");
        assert_eq!(enc(KeyCode::Insert), b"\x1b[2~");
        assert_eq!(enc(KeyCode::Delete), b"\x1b[3~");
    }

    #[test]
    fn encodes_modified_arrows_with_xterm_parameter() {
        // shift=+1, alt=+2, ctrl=+4 on top of the base 1.
        assert_eq!(
            encode_key(key_mod(KeyCode::Up, KeyModifiers::SHIFT), false),
            Some(b"\x1b[1;2A".to_vec())
        );
        assert_eq!(
            encode_key(key_mod(KeyCode::Right, KeyModifiers::CONTROL), false),
            Some(b"\x1b[1;5C".to_vec())
        );
        assert_eq!(
            encode_key(
                key_mod(
                    KeyCode::Left,
                    KeyModifiers::SHIFT | KeyModifiers::ALT | KeyModifiers::CONTROL
                ),
                false
            ),
            Some(b"\x1b[1;8D".to_vec())
        );
        assert_eq!(
            encode_key(key_mod(KeyCode::Delete, KeyModifiers::SHIFT), false),
            Some(b"\x1b[3;2~".to_vec())
        );
    }

    #[test]
    fn encodes_function_keys() {
        assert_eq!(enc(KeyCode::F(1)), b"\x1bOP");
        assert_eq!(enc(KeyCode::F(4)), b"\x1bOS");
        assert_eq!(enc(KeyCode::F(5)), b"\x1b[15~");
        assert_eq!(enc(KeyCode::F(12)), b"\x1b[24~");
    }

    #[test]
    fn unmapped_keys_are_swallowed() {
        assert_eq!(encode_key(key(KeyCode::CapsLock), false), None);
        assert_eq!(encode_key(key(KeyCode::F(20)), false), None);
    }

    #[cfg(unix)]
    #[test]
    fn pty_output_bumps_generation_and_quiet_shell_holds_it() {
        let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
        cmd.args(["-c", "printf gitwig_gen_test; sleep 5"]);
        let mut session = TerminalSession::spawn_command(cmd, "test".to_string(), 10, 60)
            .expect("spawn PTY session");

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
        loop {
            let contents = session.lock_parser().screen().contents();
            if contents.contains("gitwig_gen_test") {
                break;
            }
            assert!(std::time::Instant::now() < deadline, "output never arrived: {contents:?}");
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
        assert!(session.generation() > 0, "reader output did not bump the generation");

        // Let any straggler reads land, then verify a quiet shell holds the
        // counter steady — this is what lets the run loop skip redraws.
        std::thread::sleep(std::time::Duration::from_millis(250));
        let settled = session.generation();
        std::thread::sleep(std::time::Duration::from_millis(300));
        assert_eq!(session.generation(), settled, "generation moved with no PTY output");

        // Local screen mutations must invalidate the frame too.
        session.scroll_by(1);
        assert!(session.generation() > settled, "scroll_by did not bump the generation");
    }

    #[cfg(unix)]
    #[test]
    fn pty_session_runs_command_and_exits() {
        let mut cmd = portable_pty::CommandBuilder::new("/bin/sh");
        cmd.args(["-c", "printf gitwig_pty_hello"]);
        let mut session = TerminalSession::spawn_command(cmd, "test".to_string(), 10, 60)
            .expect("spawn PTY session");

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
        loop {
            let contents = session.lock_parser().screen().contents();
            if contents.contains("gitwig_pty_hello") {
                break;
            }
            assert!(std::time::Instant::now() < deadline, "output never arrived: {contents:?}");
            std::thread::sleep(std::time::Duration::from_millis(25));
        }

        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15);
        loop {
            session.poll_exit();
            if session.exited() {
                break;
            }
            assert!(std::time::Instant::now() < deadline, "shell never exited");
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
    }
}