tinsel 0.1.0

Clean, pink-hued terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and more. Zero dependencies.
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
//! The terminal itself: its size, its modes, its background colour, and putting everything
//! back on Ctrl-C. Calls libc directly and shells out to `stty`, to stay dependency-free.

use std::io::{self, IsTerminal, Read, Write};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

/// The width tinsel lays things out in: the terminal's, capped so lines stay readable.
pub fn content_width() -> usize {
    width().min(76)
}

/// Columns in the terminal attached to stdout, falling back to `$COLUMNS`, then 80.
pub fn width() -> usize {
    ioctl_size()
        .map(|(cols, _)| cols)
        .or_else(|| std::env::var("COLUMNS").ok()?.parse().ok())
        .filter(|&w| w > 0)
        .unwrap_or(80)
}

/// Rows in the terminal attached to stdout, falling back to `$LINES`, then 24.
pub(crate) fn height() -> usize {
    ioctl_size()
        .map(|(_, rows)| rows)
        .or_else(|| std::env::var("LINES").ok()?.parse().ok())
        .filter(|&h| h > 0)
        .unwrap_or(24)
}

/// Whether both ends are a terminal: something to draw on, and someone typing.
pub(crate) fn interactive() -> bool {
    io::stdin().is_terminal() && io::stdout().is_terminal()
}

/// Run `stty` against the terminal on stdin. `stty` is used rather than termios structs
/// because their layout differs between operating systems.
pub(crate) fn stty(args: &[&str]) -> io::Result<String> {
    let out = Command::new("stty")
        .args(args)
        .stdin(Stdio::inherit())
        .stderr(Stdio::null())
        .output()?;
    if !out.status.success() {
        return Err(io::Error::other("stty couldn't configure the terminal"));
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// Character-at-a-time input with no echo, reads timing out every 0.1s. Returns the
/// settings to hand back to [`stty`] afterwards.
pub(crate) fn enter_cbreak() -> io::Result<String> {
    let saved = stty(&["-g"])?;
    stty(&["-icanon", "-echo", "min", "0", "time", "1"])?;
    Ok(saved)
}

/// Single keypresses for prompts: no echo, no line buffering, Ctrl-C delivered as a byte (so
/// the terminal is always put back before leaving), and reads that give up after 0.1s so a
/// lone Esc can be told apart from the start of an arrow key. Undone when dropped.
pub(crate) struct RawMode {
    #[cfg(not(windows))]
    saved: String,
    #[cfg(windows)]
    saved: win::Saved,
}

impl RawMode {
    pub(crate) fn enter() -> io::Result<RawMode> {
        #[cfg(not(windows))]
        {
            let saved = stty(&["-g"])?;
            stty(&["-icanon", "-echo", "-isig", "min", "0", "time", "1"])?;
            Ok(RawMode { saved })
        }
        #[cfg(windows)]
        {
            Ok(RawMode {
                saved: win::enter_raw()?,
            })
        }
    }
}

impl Drop for RawMode {
    fn drop(&mut self) {
        #[cfg(not(windows))]
        let _ = stty(&[&self.saved]);
        #[cfg(windows)]
        win::leave_raw(&self.saved);
    }
}

/// One byte from the keyboard while in [`RawMode`], or `None` if nothing came within 0.1s.
pub(crate) fn read_byte() -> io::Result<Option<u8>> {
    #[cfg(windows)]
    if !win::key_waiting(100) {
        return Ok(None);
    }
    let mut b = [0u8; 1];
    Ok((io::stdin().lock().read(&mut b)? == 1).then_some(b[0]))
}

/// Ask the terminal for its background colour (OSC 11). Most modern terminals answer within
/// a few milliseconds; ones that don't are given 150ms.
pub(crate) fn query_background() -> Option<(u8, u8, u8)> {
    if !interactive() {
        return None;
    }
    let saved = enter_cbreak().ok()?;
    let mut out = io::stdout();
    let _ = out.write_all(b"\x1b]11;?\x1b\\");
    let _ = out.flush();
    let deadline = Instant::now() + Duration::from_millis(150);
    let mut reply = Vec::new();
    let mut stdin = io::stdin().lock();
    while Instant::now() < deadline {
        let mut b = [0u8; 64];
        let n = stdin.read(&mut b).unwrap_or(0);
        reply.extend_from_slice(&b[..n]);
        // the reply ends with BEL or ST (ESC \)
        if reply.ends_with(b"\x07") || reply.ends_with(b"\x1b\\") {
            break;
        }
    }
    let _ = stty(&[&saved]);
    parse_osc_color(&String::from_utf8_lossy(&reply))
}

/// `rgb:RRRR/GGGG/BBBB` (1-4 hex digits a channel) out of an OSC colour reply.
fn parse_osc_color(reply: &str) -> Option<(u8, u8, u8)> {
    let rgb = &reply[reply.find("rgb:")? + 4..];
    let mut channels = rgb.split('/').map(|c| {
        let hex: String = c.chars().take_while(|c| c.is_ascii_hexdigit()).collect();
        let v = u32::from_str_radix(&hex, 16).ok()?;
        let max = (1u32 << (4 * hex.len() as u32)) - 1;
        Some((v * 255 / max) as u8)
    });
    Some((channels.next()??, channels.next()??, channels.next()??))
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
unsafe extern "C" {
    fn ioctl(fd: i32, request: std::ffi::c_ulong, ...) -> i32;
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
fn ioctl_size() -> Option<(usize, usize)> {
    #[repr(C)]
    #[allow(dead_code)]
    struct WinSize {
        rows: u16,
        cols: u16,
        xpixel: u16,
        ypixel: u16,
    }

    #[cfg(target_os = "macos")]
    const TIOCGWINSZ: std::ffi::c_ulong = 0x4008_7468;
    #[cfg(target_os = "linux")]
    const TIOCGWINSZ: std::ffi::c_ulong = 0x5413;

    let mut ws = WinSize {
        rows: 0,
        cols: 0,
        xpixel: 0,
        ypixel: 0,
    };
    // SAFETY: TIOCGWINSZ writes exactly one winsize struct through the pointer.
    let ok = unsafe { ioctl(1, TIOCGWINSZ, &mut ws as *mut WinSize) } == 0;
    (ok && ws.cols > 0).then_some((ws.cols as usize, ws.rows as usize))
}

#[cfg(windows)]
fn ioctl_size() -> Option<(usize, usize)> {
    win::size()
}

#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
fn ioctl_size() -> Option<(usize, usize)> {
    None
}

/// How far local time is ahead of UTC at `secs` since the epoch, in seconds, from the C
/// library's idea of the time zone. 0 where that can't be found.
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub(crate) fn utc_offset_secs(secs: i64) -> i64 {
    #[repr(C)]
    struct Tm {
        fields: [i32; 9],
        gmtoff: std::ffi::c_long,
        zone: *const std::ffi::c_char,
    }
    unsafe extern "C" {
        fn localtime_r(time: *const i64, out: *mut Tm) -> *mut Tm;
    }
    let mut tm = Tm {
        fields: [0; 9],
        gmtoff: 0,
        zone: std::ptr::null(),
    };
    // SAFETY: localtime_r fills one struct tm, whose leading fields have this layout on both
    // platforms; it returns null on failure, leaving gmtoff at 0.
    unsafe { localtime_r(&secs, &mut tm) };
    tm.gmtoff as i64
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub(crate) fn utc_offset_secs(_: i64) -> i64 {
    0
}

/// Turn on escape-code handling for output in older Windows consoles. Elsewhere, and in
/// Windows Terminal, it's always on.
pub(crate) fn enable_escapes() {
    #[cfg(windows)]
    win::enable_escapes();
}

/// The Windows console API, for what Unix does with `stty` and `ioctl`.
#[cfg(windows)]
mod win {
    use std::ffi::c_void;
    use std::io;

    type Handle = *mut c_void;

    const STD_INPUT_HANDLE: u32 = -10i32 as u32;
    const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
    const STD_ERROR_HANDLE: u32 = -12i32 as u32;
    const ENABLE_PROCESSED_INPUT: u32 = 0x0001;
    const ENABLE_LINE_INPUT: u32 = 0x0002;
    const ENABLE_ECHO_INPUT: u32 = 0x0004;
    const ENABLE_VIRTUAL_TERMINAL_INPUT: u32 = 0x0200;
    const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004;
    const WAIT_OBJECT_0: u32 = 0;
    const KEY_EVENT: u16 = 1;
    const UTF8: u32 = 65001;

    #[repr(C)]
    #[derive(Default)]
    struct Coord {
        x: i16,
        y: i16,
    }

    #[repr(C)]
    #[derive(Default)]
    struct ScreenBufferInfo {
        size: Coord,
        cursor: Coord,
        attributes: u16,
        left: i16,
        top: i16,
        right: i16,
        bottom: i16,
        max_size: Coord,
    }

    /// INPUT_RECORD, with its union read as a KEY_EVENT_RECORD (the largest member, 16 bytes).
    #[repr(C)]
    #[derive(Default, Clone, Copy)]
    struct InputRecord {
        kind: u16,
        _pad: u16,
        key_down: i32,
        repeat: u16,
        virtual_key: u16,
        scan_code: u16,
        ch: u16,
        control_state: u32,
    }

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn GetStdHandle(which: u32) -> Handle;
        fn GetConsoleMode(h: Handle, mode: *mut u32) -> i32;
        fn SetConsoleMode(h: Handle, mode: u32) -> i32;
        fn GetConsoleCP() -> u32;
        fn SetConsoleCP(cp: u32) -> i32;
        fn WaitForSingleObject(h: Handle, ms: u32) -> u32;
        fn PeekConsoleInputW(h: Handle, buf: *mut InputRecord, len: u32, read: *mut u32) -> i32;
        fn ReadConsoleInputW(h: Handle, buf: *mut InputRecord, len: u32, read: *mut u32) -> i32;
        fn GetConsoleScreenBufferInfo(h: Handle, info: *mut ScreenBufferInfo) -> i32;
    }

    pub(super) struct Saved {
        input: u32,
        error: u32,
        code_page: u32,
    }

    fn mode(h: Handle) -> io::Result<u32> {
        let mut m = 0;
        // SAFETY: GetConsoleMode writes one u32 through the pointer.
        if unsafe { GetConsoleMode(h, &mut m) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(m)
    }

    pub(super) fn enter_raw() -> io::Result<Saved> {
        // SAFETY: these calls only read and set console flags on standard handles.
        unsafe {
            let (input, error) = (GetStdHandle(STD_INPUT_HANDLE), GetStdHandle(STD_ERROR_HANDLE));
            let saved = Saved {
                input: mode(input)?,
                error: mode(error).unwrap_or(0),
                code_page: GetConsoleCP(),
            };
            let raw = (saved.input & !(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT))
                | ENABLE_VIRTUAL_TERMINAL_INPUT;
            if SetConsoleMode(input, raw) == 0 {
                return Err(io::Error::last_os_error());
            }
            SetConsoleMode(error, saved.error | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
            SetConsoleCP(UTF8);
            Ok(saved)
        }
    }

    pub(super) fn leave_raw(saved: &Saved) {
        // SAFETY: as above, restoring values read earlier.
        unsafe {
            SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), saved.input);
            SetConsoleMode(GetStdHandle(STD_ERROR_HANDLE), saved.error);
            SetConsoleCP(saved.code_page);
        }
    }

    /// Wait up to `ms` for a keypress that will produce a character, throwing away events that
    /// won't (key releases, focus and mouse events), which would otherwise leave a read blocked.
    pub(super) fn key_waiting(ms: u32) -> bool {
        // SAFETY: the record buffer is one element long, matching the length passed.
        unsafe {
            let input = GetStdHandle(STD_INPUT_HANDLE);
            if WaitForSingleObject(input, ms) != WAIT_OBJECT_0 {
                return false;
            }
            loop {
                let mut rec = InputRecord::default();
                let mut n = 0;
                if PeekConsoleInputW(input, &mut rec, 1, &mut n) == 0 || n == 0 {
                    return false;
                }
                if rec.kind == KEY_EVENT && rec.key_down != 0 && rec.ch != 0 {
                    return true;
                }
                ReadConsoleInputW(input, &mut rec, 1, &mut n);
            }
        }
    }

    pub(super) fn size() -> Option<(usize, usize)> {
        let mut info = ScreenBufferInfo::default();
        // SAFETY: GetConsoleScreenBufferInfo fills one struct through the pointer.
        let ok = unsafe { GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &mut info) } != 0;
        let w = (info.right - info.left + 1) as usize;
        let h = (info.bottom - info.top + 1) as usize;
        (ok && w > 0).then_some((w, h))
    }

    pub(super) fn enable_escapes() {
        for which in [STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
            // SAFETY: as above.
            unsafe {
                let h = GetStdHandle(which);
                if let Ok(m) = mode(h) {
                    SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
                }
            }
        }
    }
}

/// Put bytes back into the terminal's input queue, so keys typed while tinsel was reading
/// stdin reach the shell afterwards. Best effort: newer Linux kernels refuse (TIOCSTI).
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub(crate) fn push_back_input(bytes: &[u8]) {
    #[cfg(target_os = "macos")]
    const TIOCSTI: std::ffi::c_ulong = 0x8001_7472;
    #[cfg(target_os = "linux")]
    const TIOCSTI: std::ffi::c_ulong = 0x5412;
    for b in bytes {
        // SAFETY: TIOCSTI reads one byte through the pointer.
        if unsafe { ioctl(0, TIOCSTI, b as *const u8) } != 0 {
            return;
        }
    }
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub(crate) fn push_back_input(_: &[u8]) {}

// MARK: - Ctrl-C

/// While tinsel has the cursor hidden or the terminal in a special mode, Ctrl-C would leave
/// the user's shell that way. Returns the previous handler so it can be put back afterwards.
#[cfg(unix)]
pub(crate) fn guard_interrupt() -> Option<usize> {
    // SAFETY: on_interrupt only calls async-signal-safe functions.
    let prev = unsafe { signal(SIGINT, on_interrupt as extern "C" fn(i32) as usize) };
    (prev != SIG_ERR).then_some(prev)
}

#[cfg(unix)]
pub(crate) fn restore_interrupt(prev: Option<usize>) {
    if let Some(prev) = prev {
        // SAFETY: prev came from signal() itself, so it is a valid handler value.
        unsafe { signal(SIGINT, prev) };
    }
}

/// Snapshot the terminal's settings so the Ctrl-C handler can restore them. The snapshot is
/// kept as opaque bytes: tcsetattr is safe to call from a signal handler, `stty` isn't, and
/// handing back exactly what tcgetattr gave means never needing to know the struct's layout.
#[cfg(unix)]
pub(crate) fn remember_terminal() {
    // SAFETY: the buffer is larger than any platform's termios struct.
    let ok = unsafe { tcgetattr(0, (&raw mut SAVED_TERMIOS).cast()) } == 0;
    HAVE_SAVED.store(ok, std::sync::atomic::Ordering::SeqCst);
}

#[cfg(unix)]
pub(crate) fn forget_terminal() {
    HAVE_SAVED.store(false, std::sync::atomic::Ordering::SeqCst);
}

/// Put back the settings [`remember_terminal`] saved, if any, and stop focus reports.
#[cfg(unix)]
pub(crate) fn restore_saved_terminal() {
    if HAVE_SAVED.swap(false, std::sync::atomic::Ordering::SeqCst) {
        // SAFETY: SAVED_TERMIOS holds exactly what tcgetattr wrote.
        unsafe { tcsetattr(0, TCSANOW, (&raw const SAVED_TERMIOS).cast()) };
    }
    print!("\x1b[?1004l\x1b[?25h\x1b[?7h");
}

#[cfg(unix)]
const SIGINT: i32 = 2;
#[cfg(unix)]
const SIG_ERR: usize = usize::MAX;
#[cfg(unix)]
const TCSANOW: i32 = 0;

#[cfg(unix)]
static mut SAVED_TERMIOS: [u8; 256] = [0; 256];
#[cfg(unix)]
static HAVE_SAVED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

#[cfg(unix)]
unsafe extern "C" {
    fn signal(sig: i32, handler: usize) -> usize;
    fn write(fd: i32, buf: *const std::ffi::c_void, count: usize) -> isize;
    fn _exit(code: i32) -> !;
    fn tcgetattr(fd: i32, termios: *mut u8) -> i32;
    fn tcsetattr(fd: i32, action: i32, termios: *const u8) -> i32;
}

#[cfg(unix)]
extern "C" fn on_interrupt(_: i32) {
    // stop focus reports, show the cursor, turn line wrapping back on
    let msg = b"\x1b[?1004l\x1b[?25h\x1b[?7h\n";
    // SAFETY: write, tcsetattr and _exit are all async-signal-safe, and SAVED_TERMIOS is only
    // written before HAVE_SAVED is set.
    unsafe {
        if HAVE_SAVED.load(std::sync::atomic::Ordering::SeqCst) {
            tcsetattr(0, TCSANOW, (&raw const SAVED_TERMIOS).cast());
        }
        write(1, msg.as_ptr().cast(), msg.len());
        _exit(130)
    }
}

#[cfg(not(unix))]
pub(crate) fn guard_interrupt() -> Option<usize> {
    None
}

#[cfg(not(unix))]
pub(crate) fn restore_interrupt(_: Option<usize>) {}

#[cfg(not(unix))]
pub(crate) fn remember_terminal() {}

#[cfg(not(unix))]
pub(crate) fn forget_terminal() {}

#[cfg(not(unix))]
pub(crate) fn restore_saved_terminal() {
    print!("\x1b[?25h\x1b[?7h");
}

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

    #[test]
    fn reads_osc_colour_replies() {
        assert_eq!(parse_osc_color("\x1b]11;rgb:ffff/ffff/ffff\x07"), Some((255, 255, 255)));
        assert_eq!(parse_osc_color("\x1b]11;rgb:1e1e/2020/2a2a\x1b\\"), Some((30, 32, 42)));
        assert_eq!(parse_osc_color("\x1b]11;rgb:ff/80/00\x07"), Some((255, 128, 0)));
        assert_eq!(parse_osc_color("garbage"), None);
    }
}