nandi/jolt-nativepublic Fork 0
121e5f1d751e8003ea229e70debf486b9bea3286
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.

Take a wide glyph off the grid whole, and stop trusting the cursor after one 48212a7 · on 121e5f1d751e8003ea229e70debf486b9bea3286 · nandi · 9d ago
term.rs · 293 lines · 11.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
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
//! 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::event::{
    KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::terminal::supports_keyboard_enhancement;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};
use crossterm::{cursor, execute, queue, style};

use crate::graphics::{self, Graphics, Placement};
use crate::keys;
use crate::screen::{attr, Color, Screen, Style};

/// How far one notch of the wheel moves a list, in rows.
const WHEEL_ROWS: i32 = 3;

/// 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,
    /// The pictures the terminal has been given, and where they are.
    graphics: Graphics,
    /// Whether the keyboard protocol was pushed, and so has to be popped.
    enhanced: 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)?;
        }
        // Shift+Enter is a newline in the compose bar and Enter sends the
        // line, which a terminal can only tell apart when it is asked to: the
        // legacy encoding gives both of them the same byte. This is the kitty
        // keyboard protocol's first flag and nothing more — the terminals that
        // have it answer the query, and the ones that do not are left as they
        // were, with Alt+Enter and Ctrl+J as the way to break a line there.
        let enhanced = matches!(supports_keyboard_enhancement(), Ok(true));
        if enhanced {
            let _ = execute!(
                out,
                PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
            );
        }
        graphics::set_cell(measure_cell());
        Ok(Self {
            out,
            last: Screen::new(w, h),
            mouse,
            enhanced,
            graphics: Graphics::default(),
        })
    }

    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) {
        // The pictures first: a placement is the terminal's, not the screen
        // buffer's, and one left behind outlives the alternate screen it was
        // made on.
        let _ = self.graphics.clear(&mut self.out);
        if self.mouse {
            let _ = execute!(self.out, DisableMouseCapture);
        }
        if self.enhanced {
            let _ = execute!(self.out, PopKeyboardEnhancementFlags);
        }
        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))
                    }
                    // Three rows a notch. A terminal reports one event per
                    // detent and a row is the whole of a line here, so a row a
                    // notch is a backlog that takes forty of them to cross a
                    // screen — which reads as a list that will not move rather
                    // than one moving slowly.
                    MouseEventKind::ScrollDown => {
                        out.push(Input::Wheel(mouse.column, mouse.row, WHEEL_ROWS))
                    }
                    MouseEventKind::ScrollUp => {
                        out.push(Input::Wheel(mouse.column, mouse.row, -WHEEL_ROWS))
                    }
                    _ => {}
                },
                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)>,
        images: &[Placement],
    ) -> io::Result<()> {
        if (self.last.width(), self.last.height()) != (screen.width(), screen.height()) {
            self.last = Screen::new(screen.width(), screen.height());
            // A resize is a new cell size as often as not — a font change, a
            // window dragged to another screen — and every picture's size is
            // measured in cells.
            graphics::set_cell(measure_cell());
            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();
        let cells = screen.cells();
        for (i, cell) in cells.iter().enumerate() {
            let (x, y) = ((i as u16) % width, (i as u16) / width);
            let wide = !cell.trail && x + 1 < width && cells.get(i + 1).is_some_and(|c| c.trail);
            // A wide glyph is its two cells together: when only the right
            // half changed, a terminal has lost the whole glyph, so the left
            // half is written again as well.
            let changed = self.last.cell(x, y) != Some(cell)
                || (wide && self.last.cell(x + 1, y) != cells.get(i + 1));
            if !changed {
                continue;
            }
            // The right half of a double-width glyph is not written: the
            // character to its left was drawn across both cells and left the
            // cursor past them. Writing here would put a second copy of
            // whatever follows one column over, and every column after it on
            // that row would be a column out — which is what a mouse click is
            // then aimed at.
            if cell.trail {
                continue;
            }
            if wide {
                // Blank the right half first. Terminals do not agree on how
                // wide `✏️` or `↩️` is — a symbol carrying the emoji selector
                // is two columns in some and one in others — and one that
                // draws it narrow would otherwise leave whatever stood in that
                // column standing beside it.
                if style != Some(cell.style) {
                    write_style(&mut self.out, cell.style)?;
                    style = Some(cell.style);
                }
                queue!(self.out, cursor::MoveTo(x + 1, y), style::Print(' '))?;
                at = None;
            }
            // 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);
            }
            // The whole glyph, first character and rest: a terminal handed an
            // arrow without the selector that follows it draws the small mono
            // arrow rather than the emoji.
            let mut glyph = cell.ch.to_string();
            if let Some(tail) = &cell.tail {
                glyph.push_str(tail);
            }
            queue!(self.out, style::Print(&glyph))?;
            // After a wide glyph, where the cursor went is the terminal's
            // opinion rather than ours, so the next cell seeks instead of
            // trusting it.
            at = if wide { None } else { Some((x + 1, y)) };
        }
        queue!(self.out, style::ResetColor)?;
        // The pictures after the text, and before the cursor is put back: a
        // placement is drawn where the cursor is, so it moves the cursor, and
        // whatever the frame decided about the caret has to be the last word.
        let cell = graphics::cell();
        self.graphics.sync(&mut self.out, images, cell)?;
        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))
    )
}

/// What one cell measures, asked of the terminal.
fn measure_cell() -> (u16, u16) {
    match crossterm::terminal::window_size() {
        Ok(size) => graphics::cell_pixels(size.columns, size.rows, size.width, size.height),
        Err(_) => graphics::cell_pixels(0, 0, 0, 0),
    }
}