Skip to main content

egui_tty/
lib.rs

1//! A terminal emulator widget for [egui](https://github.com/emilk/egui).
2//!
3//! [libghostty-vt](https://crates.io/crates/libghostty-vt) — the VT engine
4//! [Ghostty](https://ghostty.org) is built on — owns everything that makes a terminal a
5//! terminal: the parser, the screen and its scrollback, reflow on resize, selections, and
6//! input encoding. This crate is the part Ghostty deliberately leaves out: turning the
7//! resulting grid into pixels, and turning window events into terminal events.
8//!
9//! What you get is a real terminal, not a log view. Full-screen programs, mouse reporting,
10//! bracketed paste, OSC 8 links, the Kitty keyboard protocol — they work because the engine
11//! underneath is the one shipping in Ghostty.
12//!
13//! # Attaching a program
14//!
15//! The crate takes no view on where the bytes come from: a local pty, a websocket to another
16//! machine, or a test harness. You provide a [`Tty`] to write to, and an
17//! [`std::sync::mpsc::Receiver`] the program's output arrives on.
18//!
19//! ```no_run
20//! use std::sync::{Arc, mpsc};
21//!
22//! struct Echo;
23//!
24//! impl egui_tty::Tty for Echo {
25//!     fn write(&self, _bytes: &[u8]) -> egui_tty::Result<()> {
26//!         Ok(())
27//!     }
28//!
29//!     fn resize(&self, _cols: u16, _rows: u16) -> egui_tty::Result<()> {
30//!         Ok(())
31//!     }
32//! }
33//!
34//! # fn main() -> egui_tty::Result<()> {
35//! let (writer, output) = mpsc::channel();
36//! writer.send(b"hello from a terminal\r\n".to_vec()).ok();
37//!
38//! let mut terminal = egui_tty::Terminal::new(egui_tty::TtyStream {
39//!     output,
40//!     tty: Arc::new(Echo),
41//! })?;
42//! # let _ = &mut terminal;
43//! # Ok(())
44//! # }
45//! ```
46//!
47//! Then draw it, once per frame, wherever you want it:
48//!
49//! ```no_run
50//! # fn frame(ui: &mut egui::Ui, terminal: &mut egui_tty::Terminal) {
51//! let style = egui_tty::TerminalStyle::from_visuals(ui.visuals());
52//! terminal.ui(ui, &style);
53//! # }
54//! ```
55//!
56//! See `examples/shell.rs` for the whole thing against a real login shell.
57//!
58//! # Building
59//!
60//! `libghostty-vt` compiles Ghostty's VT engine from source, so a
61//! [Zig](https://ziglang.org) 0.15.x toolchain has to be on `PATH` to build this crate.
62
63#![forbid(unsafe_code)]
64#![warn(missing_docs, clippy::doc_markdown)]
65
66mod colors;
67mod error;
68mod keys;
69mod links;
70mod search;
71mod selection;
72mod style;
73mod terminal;
74
75pub use error::{Error, Result};
76pub use style::{ColorScheme, TerminalStyle};
77pub use terminal::{DEFAULT_SCROLLBACK, Terminal, cell_size};
78
79use std::sync::{Arc, mpsc};
80
81/// The program behind a terminal: somewhere to send keystrokes, and a grid size to keep it
82/// informed of.
83///
84/// Implementations are usually a pty ([`portable-pty`](https://crates.io/crates/portable-pty)
85/// is the easy way) or a connection to a shell running on another machine.
86pub trait Tty: Send + Sync {
87    /// Send bytes the terminal has encoded — keystrokes, pastes — to the program.
88    fn write(&self, bytes: &[u8]) -> Result<()>;
89
90    /// Answer a query the program made of the terminal: what it is, where the cursor is, what
91    /// colours it draws in. The program asked for these and nobody typed them, so a handle
92    /// that cares which is which - one waiting to see whether a person has started typing -
93    /// can tell them apart. By default they go the same way keystrokes do.
94    fn reply(&self, bytes: &[u8]) -> Result<()> {
95        self.write(bytes)
96    }
97
98    /// Tell the program its window changed size, so its foreground process gets `SIGWINCH`.
99    fn resize(&self, cols: u16, rows: u16) -> Result<()>;
100
101    /// Whether the program behind this handle has ended.
102    ///
103    /// A terminal notices an ended program on its own when the output channel closes. Override
104    /// this when the channel can outlive the program — which happens when what holds the
105    /// session open is the terminal itself.
106    fn has_exited(&self) -> bool {
107        false
108    }
109}
110
111/// One attached program: the bytes it writes, and the handle to write back to it.
112pub struct TtyStream {
113    /// Everything the program has written, delivered to the thread that draws the terminal.
114    ///
115    /// Send whatever the program printed before the terminal existed as the first chunk, and
116    /// it is replayed into the screen and the scrollback like anything else.
117    pub output: mpsc::Receiver<Vec<u8>>,
118    /// Shared, so the terminal's reply hook can hold a handle without borrowing the widget.
119    pub tty: Arc<dyn Tty>,
120}
121
122#[cfg(test)]
123mod tests {
124    use std::sync::{Arc, Mutex, mpsc};
125
126    use super::*;
127
128    /// A program that records what it was sent and prints whatever a test hands it.
129    #[derive(Default)]
130    struct Recorder {
131        written: Mutex<Vec<u8>>,
132        size: Mutex<(u16, u16)>,
133    }
134
135    impl Tty for Recorder {
136        fn write(&self, bytes: &[u8]) -> Result<()> {
137            self.written.lock().unwrap().extend_from_slice(bytes);
138            Ok(())
139        }
140
141        fn resize(&self, cols: u16, rows: u16) -> Result<()> {
142            *self.size.lock().unwrap() = (cols, rows);
143            Ok(())
144        }
145    }
146
147    fn terminal() -> (Terminal, mpsc::Sender<Vec<u8>>, Arc<Recorder>) {
148        let (writer, output) = mpsc::channel();
149        let recorder = Arc::new(Recorder::default());
150        let terminal = Terminal::new(TtyStream {
151            output,
152            tty: Arc::clone(&recorder) as Arc<dyn Tty>,
153        })
154        .expect("expected a terminal");
155        (terminal, writer, recorder)
156    }
157
158    #[test]
159    fn output_from_the_program_lands_on_the_screen() {
160        let (mut terminal, writer, _) = terminal();
161        writer
162            .send(b"hello\r\nworld\r\n".to_vec())
163            .expect("expected the terminal to be listening");
164
165        assert!(terminal.poll(), "the terminal read what was written");
166        let screen = terminal.visible_text().expect("expected the screen");
167        let lines: Vec<&str> = screen.lines().take(2).collect();
168        assert_eq!(lines, vec!["hello", "world"]);
169    }
170
171    #[test]
172    fn escape_sequences_are_interpreted_rather_than_printed() {
173        let (mut terminal, writer, _) = terminal();
174        // Set a title, then print in red: neither is text that belongs on the grid.
175        writer
176            .send(b"\x1b]0;a title\x07\x1b[31mred\x1b[0m".to_vec())
177            .expect("expected the terminal to be listening");
178        terminal.poll();
179
180        assert_eq!(terminal.title().as_deref(), Some("a title"));
181        assert_eq!(
182            terminal.visible_text().expect("expected the screen").lines().next(),
183            Some("red")
184        );
185    }
186
187    #[test]
188    fn keystrokes_reach_the_program() {
189        let (terminal, _writer, recorder) = terminal();
190
191        terminal.send(b"ls\r").expect("expected the write to land");
192
193        assert_eq!(&*recorder.written.lock().unwrap(), b"ls\r");
194    }
195
196    /// One frame of the widget with a chord held, which is the whole path a keystroke takes:
197    /// egui's event, the physical key it stands for, and the bytes the program is written.
198    fn typed(terminal: &mut Terminal, key: egui::Key, modifiers: egui::Modifiers) {
199        let ctx = egui::Context::default();
200        // Keystrokes only reach a focused widget, and focus is taken on the frame after it is
201        // asked for — so the chord goes in on the second one.
202        terminal.request_focus();
203        ctx.run_ui(egui::RawInput::default(), |ui| {
204            terminal.ui(ui, &TerminalStyle::from_visuals(ui.visuals()));
205        })
206        .drop_without_applying_deltas();
207
208        let input = egui::RawInput {
209            events: vec![egui::Event::Key {
210                key,
211                physical_key: Some(key),
212                pressed: true,
213                repeat: false,
214                modifiers,
215            }],
216            ..Default::default()
217        };
218        ctx.run_ui(input, |ui| {
219            terminal.ui(ui, &TerminalStyle::from_visuals(ui.visuals()));
220        })
221        .drop_without_applying_deltas();
222    }
223
224    /// ⌃← reaching a shell as `ESC [ 1 ; 5 D` is what typed a stray `;5D` into the prompt:
225    /// readline binds `ESC b` and none of the other.
226    #[test]
227    fn a_shell_is_sent_the_word_motion_it_binds() {
228        let (mut terminal, _writer, recorder) = terminal();
229
230        typed(
231            &mut terminal,
232            egui::Key::ArrowLeft,
233            egui::Modifiers {
234                ctrl: true,
235                ..Default::default()
236            },
237        );
238
239        assert_eq!(&*recorder.written.lock().unwrap(), b"\x1bb");
240    }
241
242    /// And a program reading chords for itself is sent the real one.
243    #[test]
244    fn a_program_on_the_kitty_protocol_is_sent_the_chord() {
245        let (mut terminal, writer, recorder) = terminal();
246        writer
247            .send(b"\x1b[>1u".to_vec())
248            .expect("expected the terminal to be listening");
249        terminal.poll();
250
251        typed(
252            &mut terminal,
253            egui::Key::ArrowLeft,
254            egui::Modifiers {
255                ctrl: true,
256                ..Default::default()
257            },
258        );
259
260        let written = recorder.written.lock().unwrap().clone();
261        assert_ne!(written, b"\x1bb", "the chord should not have been rewritten");
262        assert!(
263            String::from_utf8_lossy(&written).contains("[1;5"),
264            "expected the chord itself, got {:?}",
265            String::from_utf8_lossy(&written)
266        );
267    }
268
269    #[test]
270    fn a_closed_output_channel_means_the_program_has_gone() {
271        let (mut terminal, writer, _) = terminal();
272        assert!(!terminal.has_exited());
273
274        drop(writer);
275        terminal.poll();
276
277        assert!(terminal.has_exited());
278    }
279
280    /// A terminal small enough to have a scrollback, filled with numbered lines, and the
281    /// widget frame that scrolls it: the pointer has to be over it for the wheel to count.
282    fn scrollable() -> (Terminal, egui::Context, mpsc::Sender<Vec<u8>>) {
283        let (mut terminal, writer, _) = terminal();
284        let mut output = String::new();
285        for index in 0..80 {
286            output.push_str(&format!("line {index}\r\n"));
287        }
288        writer
289            .send(output.into_bytes())
290            .expect("expected the terminal to be listening");
291        terminal.poll();
292        (terminal, egui::Context::default(), writer)
293    }
294
295    fn wheeled(terminal: &mut Terminal, ctx: &egui::Context, points: f32) {
296        let input = egui::RawInput {
297            events: vec![
298                egui::Event::PointerMoved(egui::pos2(80.0, 80.0)),
299                egui::Event::MouseWheel {
300                    unit: egui::MouseWheelUnit::Point,
301                    delta: egui::vec2(0.0, points),
302                    phase: egui::TouchPhase::Move,
303                    modifiers: Default::default(),
304                },
305            ],
306            // Small enough that 80 lines do not all fit, so there is something to scroll to.
307            screen_rect: Some(egui::Rect::from_min_size(
308                egui::Pos2::ZERO,
309                egui::vec2(400.0, 160.0),
310            )),
311            ..Default::default()
312        };
313        ctx.run_ui(input, |ui| {
314            terminal.ui(ui, &TerminalStyle::from_visuals(ui.visuals()));
315        })
316        .drop_without_applying_deltas();
317    }
318
319    fn top_line(terminal: &mut Terminal) -> String {
320        terminal
321            .visible_text()
322            .expect("expected the screen")
323            .lines()
324            .next()
325            .unwrap_or_default()
326            .trim_end()
327            .to_string()
328    }
329
330    /// A trackpad scrolls in pixels, and a frame of one is worth a fraction of a line. Each
331    /// frame rounded on its own rounded to nothing, so a gesture made of them scrolled a
332    /// terminal not at all — which on a laptop is every gesture there is.
333    #[test]
334    fn a_gesture_of_sub_line_steps_scrolls_as_far_as_it_asks_for() {
335        let (mut terminal, ctx, _writer) = scrollable();
336        wheeled(&mut terminal, &ctx, 0.0);
337        let before = top_line(&mut terminal);
338
339        // Twenty frames worth a quarter-line each: five lines asked for, in steps none of
340        // which is a line on its own.
341        for _ in 0..20 {
342            wheeled(&mut terminal, &ctx, 4.0);
343        }
344
345        assert_ne!(
346            top_line(&mut terminal),
347            before,
348            "a trackpad gesture should scroll the terminal"
349        );
350    }
351
352    /// What is scrolled to stays put when the program writes more, which is the whole point
353    /// of scrolling back while something is still working.
354    #[test]
355    fn output_arriving_does_not_yank_the_view_back_to_the_bottom() {
356        let (mut terminal, ctx, writer) = scrollable();
357        wheeled(&mut terminal, &ctx, 0.0);
358        for _ in 0..20 {
359            wheeled(&mut terminal, &ctx, 4.0);
360        }
361        let scrolled_to = top_line(&mut terminal);
362
363        writer
364            .send(b"more output\r\n".to_vec())
365            .expect("expected the terminal to be listening");
366        terminal.poll();
367
368        assert_eq!(top_line(&mut terminal), scrolled_to);
369    }
370
371    #[test]
372    fn searching_finds_matches_in_the_scrollback() {
373        let (mut terminal, writer, _) = terminal();
374        let mut output = String::new();
375        for index in 0..60 {
376            output.push_str(&format!("line {index}\r\n"));
377        }
378        output.push_str("the needle\r\n");
379        writer
380            .send(output.into_bytes())
381            .expect("expected the terminal to be listening");
382        terminal.poll();
383
384        assert_eq!(terminal.find("needle", 0), 1);
385        assert_eq!(terminal.selected_text().as_deref(), Some("needle"));
386        assert_eq!(terminal.find("line", 0), 60, "the scrollback counts too");
387    }
388
389    #[test]
390    fn the_light_scheme_is_readable_where_the_dark_one_is_not() {
391        let (mut terminal, _writer, _) = terminal();
392
393        terminal.set_color_scheme(ColorScheme::Dark);
394        let (dark_fg, dark_bg) = terminal.drawn_colors().expect("expected colors");
395        terminal.set_color_scheme(ColorScheme::Light);
396        let (light_fg, light_bg) = terminal.drawn_colors().expect("expected colors");
397
398        assert!(dark_bg.r() < light_bg.r(), "the light background is paper");
399        assert!(light_fg.r() < dark_fg.r(), "and its text is ink");
400    }
401}