1#![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
81pub trait Tty: Send + Sync {
87 fn write(&self, bytes: &[u8]) -> Result<()>;
89
90 fn reply(&self, bytes: &[u8]) -> Result<()> {
95 self.write(bytes)
96 }
97
98 fn resize(&self, cols: u16, rows: u16) -> Result<()>;
100
101 fn has_exited(&self) -> bool {
107 false
108 }
109}
110
111pub struct TtyStream {
113 pub output: mpsc::Receiver<Vec<u8>>,
118 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 #[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 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 fn typed(terminal: &mut Terminal, key: egui::Key, modifiers: egui::Modifiers) {
199 let ctx = egui::Context::default();
200 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 #[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 #[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 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 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 #[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 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 #[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}