nandi/jolt-nativepublic Fork 0
3cfee15a9d938584f526f606f853771eaad7f56c
Commits
Clone
git clone https://git.rickub.com/nandi/jolt-native.git
git clone ssh://git@rickub.com/nandi/jolt-native.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Paint the same tree into a terminal, for the machines with no window a7f6202 · on 3cfee15a9d938584f526f606f853771eaad7f56c · nandi · 17d ago
term.rs · 190 lines · 6.8 KBRust Blame HistoryRaw
  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
//! The terminal itself: raw mode, the alternate screen, and the diff that
//! turns a grid of cells into the fewest escape sequences that will do.
//!
//! Everything above this file paints into a [`Screen`] and never writes a byte,
//! which is what makes the widget layer testable. This is the one place that
//! knows a TTY exists, and it is behind the `terminal` feature so a build for a
//! machine with no terminal crate at all still has the tree and the layout.

use std::io::{self, Stdout, Write};

use crossterm::event::{
    DisableMouseCapture, EnableMouseCapture, Event, KeyEventKind, MouseButton, MouseEventKind,
};
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use crossterm::{cursor, execute, queue, style};

use crate::keys;
use crate::screen::{attr, Color, Screen, Style};

/// One thing that happened, in the vocabulary [`crate::ui::Ui`] takes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Input {
    Key(String),
    Click(u16, u16),
    Wheel(u16, u16, i32),
    Resize(u16, u16),
}

pub struct Term {
    out: Stdout,
    /// What is on the screen now, so a frame only sends what changed.
    last: Screen,
    mouse: bool,
}

impl Term {
    /// Take the terminal: raw mode, the alternate screen, mouse reporting, and
    /// no cursor until a focused entry asks for one.
    pub fn open(mouse: bool) -> io::Result<Self> {
        let (w, h) = crossterm::terminal::size().unwrap_or((80, 24));
        let mut out = io::stdout();
        enable_raw_mode()?;
        execute!(out, EnterAlternateScreen, cursor::Hide)?;
        if mouse {
            execute!(out, EnableMouseCapture)?;
        }
        Ok(Self {
            out,
            last: Screen::new(w, h),
            mouse,
        })
    }

    pub fn size(&self) -> (u16, u16) {
        crossterm::terminal::size().unwrap_or((80, 24))
    }

    /// Give the terminal back. Called from `tui_close`, and again from a panic
    /// hook — leaving a shell in raw mode with no cursor is the one failure a
    /// TUI must not have.
    pub fn close(&mut self) {
        if self.mouse {
            let _ = execute!(self.out, DisableMouseCapture);
        }
        let _ = execute!(self.out, cursor::Show, LeaveAlternateScreen);
        let _ = disable_raw_mode();
    }

    /// Wait up to `timeout_ms` for input and answer everything that had
    /// arrived. A zero timeout is a poll.
    pub fn poll(&mut self, timeout_ms: u64) -> Vec<Input> {
        let mut out = Vec::new();
        let deadline = std::time::Duration::from_millis(timeout_ms);
        if !crossterm::event::poll(deadline).unwrap_or(false) {
            return out;
        }
        // Drain what is queued rather than one event a call: a held arrow key
        // or a paste arrives as a burst, and handling one per frame would make
        // the UI lag behind the keyboard.
        loop {
            match crossterm::event::read() {
                Ok(Event::Key(key)) => {
                    // Windows reports both press and release; a release would
                    // type every character twice.
                    if key.kind != KeyEventKind::Release {
                        if let Some(name) = keys::name(key) {
                            out.push(Input::Key(name));
                        }
                    }
                }
                Ok(Event::Resize(w, h)) => out.push(Input::Resize(w, h)),
                Ok(Event::Mouse(mouse)) => match mouse.kind {
                    MouseEventKind::Down(MouseButton::Left) => {
                        out.push(Input::Click(mouse.column, mouse.row))
                    }
                    MouseEventKind::ScrollDown => {
                        out.push(Input::Wheel(mouse.column, mouse.row, 1))
                    }
                    MouseEventKind::ScrollUp => out.push(Input::Wheel(mouse.column, mouse.row, -1)),
                    _ => {}
                },
                Ok(_) => {}
                Err(_) => break,
            }
            if !crossterm::event::poll(std::time::Duration::ZERO).unwrap_or(false) {
                break;
            }
        }
        out
    }

    /// Send whatever differs between `screen` and what is already up there.
    pub fn flush(&mut self, screen: &Screen, cursor: Option<(u16, u16)>) -> io::Result<()> {
        if (self.last.width(), self.last.height()) != (screen.width(), screen.height()) {
            self.last = Screen::new(screen.width(), screen.height());
            queue!(
                self.out,
                crossterm::terminal::Clear(crossterm::terminal::ClearType::All)
            )?;
        }
        let mut style = None;
        let mut at: Option<(u16, u16)> = None;
        let width = screen.width();
        for (i, cell) in screen.cells().iter().enumerate() {
            let (x, y) = ((i as u16) % width, (i as u16) / width);
            if self.last.cell(x, y) == Some(cell) {
                continue;
            }
            // Only move when the run breaks: a full-width change is one seek
            // and a line of text, not a seek a cell.
            if at != Some((x, y)) {
                queue!(self.out, cursor::MoveTo(x, y))?;
            }
            if style != Some(cell.style) {
                write_style(&mut self.out, cell.style)?;
                style = Some(cell.style);
            }
            queue!(self.out, style::Print(cell.ch))?;
            at = Some((x + 1, y));
        }
        queue!(self.out, style::ResetColor)?;
        match cursor {
            Some((x, y)) => queue!(self.out, cursor::MoveTo(x, y), cursor::Show)?,
            None => queue!(self.out, cursor::Hide)?,
        }
        self.out.flush()?;
        self.last = screen.clone();
        Ok(())
    }
}

impl Drop for Term {
    fn drop(&mut self) {
        self.close();
    }
}

fn convert(color: Color) -> style::Color {
    match color {
        Color::Default => style::Color::Reset,
        // The terminal downgrades the 256-colour palette itself, which is the
        // only place that knows how many colours it really has.
        Color::Indexed(i) => style::Color::AnsiValue(i),
        Color::Rgb(r, g, b) => style::Color::Rgb { r, g, b },
    }
}

fn write_style(out: &mut Stdout, style: Style) -> io::Result<()> {
    use style::Attribute;
    queue!(out, style::SetAttribute(Attribute::Reset))?;
    for (bit, on) in [
        (attr::BOLD, Attribute::Bold),
        (attr::DIM, Attribute::Dim),
        (attr::UNDERLINE, Attribute::Underlined),
        (attr::REVERSE, Attribute::Reverse),
        (attr::BLINK, Attribute::SlowBlink),
        (attr::ITALIC, Attribute::Italic),
    ] {
        if style.has(bit) {
            queue!(out, style::SetAttribute(on))?;
        }
    }
    queue!(
        out,
        style::SetForegroundColor(convert(style.fg)),
        style::SetBackgroundColor(convert(style.bg))
    )
}