1pub mod mappings;
2
3pub use alacritty_terminal;
4
5mod pty_info;
6mod terminal_hyperlinks;
7pub mod terminal_settings;
8
9use alacritty_terminal::{
10 Term,
11 event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
12 event_loop::{EventLoop, Msg, Notifier},
13 grid::{Dimensions, Grid, Row, Scroll as AlacScroll},
14 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
15 selection::{Selection, SelectionRange, SelectionType},
16 sync::FairMutex,
17 term::{
18 Config, RenderableCursor, TermMode,
19 cell::{Cell, Flags},
20 search::{Match, RegexIter, RegexSearch},
21 },
22 tty::{self},
23 vi_mode::{ViModeCursor, ViMotion},
24 vte::ansi::{
25 ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
26 },
27};
28use anyhow::{Result, bail};
29
30use futures::{
31 FutureExt,
32 channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded},
33};
34
35use mappings::mouse::{
36 alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
37 scroll_report,
38};
39
40use collections::{HashMap, VecDeque};
41use futures::StreamExt;
42use pty_info::PtyProcessInfo;
43use serde::{Deserialize, Serialize};
44use settings::Settings;
45use smol::channel::{Receiver, Sender};
46use task::{HideStrategy, Shell, TaskId};
47use terminal_hyperlinks::RegexSearches;
48use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
49use theme::{ActiveTheme, Theme};
50use urlencoding;
51use util::{paths::home_dir, truncate_and_trailoff};
52
53use std::{
54 borrow::Cow,
55 cmp::{self, min},
56 fmt::Display,
57 ops::{Deref, RangeInclusive},
58 path::PathBuf,
59 process::ExitStatus,
60 sync::Arc,
61 time::{Duration, Instant},
62};
63use thiserror::Error;
64
65use gpui::{
66 App, AppContext as _, Bounds, ClipboardItem, Context, EventEmitter, Hsla, Keystroke, Modifiers,
67 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, Rgba,
68 ScrollWheelEvent, SharedString, Size, Task, TouchPhase, Window, actions, black, px,
69};
70
71use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
72
73actions!(
74 terminal,
75 [
76 /// Clears the terminal screen.
77 Clear,
78 /// Copies selected text to the clipboard.
79 Copy,
80 /// Pastes from the clipboard.
81 Paste,
82 /// Shows the character palette for special characters.
83 ShowCharacterPalette,
84 /// Searches for text in the terminal.
85 SearchTest,
86 /// Scrolls up by one line.
87 ScrollLineUp,
88 /// Scrolls down by one line.
89 ScrollLineDown,
90 /// Scrolls up by one page.
91 ScrollPageUp,
92 /// Scrolls down by one page.
93 ScrollPageDown,
94 /// Scrolls up by half a page.
95 ScrollHalfPageUp,
96 /// Scrolls down by half a page.
97 ScrollHalfPageDown,
98 /// Scrolls to the top of the terminal buffer.
99 ScrollToTop,
100 /// Scrolls to the bottom of the terminal buffer.
101 ScrollToBottom,
102 /// Toggles vi mode in the terminal.
103 ToggleViMode,
104 /// Selects all text in the terminal.
105 SelectAll,
106 ]
107);
108
109///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
110///Scroll multiplier that is set to 3 by default. This will be removed when I
111///Implement scroll bars.
112#[cfg(target_os = "macos")]
113const SCROLL_MULTIPLIER: f32 = 4.;
114#[cfg(not(target_os = "macos"))]
115const SCROLL_MULTIPLIER: f32 = 1.;
116const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
117const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
118const DEBUG_CELL_WIDTH: Pixels = px(5.);
119const DEBUG_LINE_HEIGHT: Pixels = px(5.);
120
121///Upward flowing events, for changing the title and such
122#[derive(Clone, Debug)]
123pub enum Event {
124 TitleChanged,
125 BreadcrumbsChanged,
126 CloseTerminal,
127 Bell,
128 Wakeup,
129 BlinkChanged(bool),
130 SelectionsChanged,
131 NewNavigationTarget(Option<MaybeNavigationTarget>),
132 Open(MaybeNavigationTarget),
133}
134
135#[derive(Clone, Debug)]
136pub struct PathLikeTarget {
137 /// File system path, absolute or relative, existing or not.
138 /// Might have line and column number(s) attached as `file.rs:1:23`
139 pub maybe_path: String,
140 /// Current working directory of the terminal
141 pub terminal_dir: Option<PathBuf>,
142}
143
144/// A string inside terminal, potentially useful as a URI that can be opened.
145#[derive(Clone, Debug)]
146pub enum MaybeNavigationTarget {
147 /// HTTP, git, etc. string determined by the `URL_REGEX` regex.
148 Url(String),
149 /// File system path, absolute or relative, existing or not.
150 /// Might have line and column number(s) attached as `file.rs:1:23`
151 PathLike(PathLikeTarget),
152}
153
154#[derive(Clone)]
155enum InternalEvent {
156 Resize(TerminalBounds),
157 Clear,
158 // FocusNextMatch,
159 Scroll(AlacScroll),
160 ScrollToAlacPoint(AlacPoint),
161 SetSelection(Option<(Selection, AlacPoint)>),
162 UpdateSelection(Point<Pixels>),
163 // Adjusted mouse position, should open
164 FindHyperlink(Point<Pixels>, bool),
165 // Whether keep selection when copy
166 Copy(Option<bool>),
167 // Vi mode events
168 ToggleViMode,
169 ViMotion(ViMotion),
170}
171
172///A translation struct for Alacritty to communicate with us from their event loop
173#[derive(Clone)]
174pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
175
176impl EventListener for ZedListener {
177 fn send_event(&self, event: AlacTermEvent) {
178 self.0.unbounded_send(event).ok();
179 }
180}
181
182pub fn init(cx: &mut App) {
183 TerminalSettings::register(cx);
184}
185
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
187pub struct TerminalBounds {
188 pub cell_width: Pixels,
189 pub line_height: Pixels,
190 pub bounds: Bounds<Pixels>,
191}
192
193impl TerminalBounds {
194 pub fn new(line_height: Pixels, cell_width: Pixels, bounds: Bounds<Pixels>) -> Self {
195 TerminalBounds {
196 cell_width,
197 line_height,
198 bounds,
199 }
200 }
201
202 pub fn num_lines(&self) -> usize {
203 (self.bounds.size.height / self.line_height).floor() as usize
204 }
205
206 pub fn num_columns(&self) -> usize {
207 (self.bounds.size.width / self.cell_width).floor() as usize
208 }
209
210 pub fn height(&self) -> Pixels {
211 self.bounds.size.height
212 }
213
214 pub fn width(&self) -> Pixels {
215 self.bounds.size.width
216 }
217
218 pub fn cell_width(&self) -> Pixels {
219 self.cell_width
220 }
221
222 pub fn line_height(&self) -> Pixels {
223 self.line_height
224 }
225}
226
227impl Default for TerminalBounds {
228 fn default() -> Self {
229 TerminalBounds::new(
230 DEBUG_LINE_HEIGHT,
231 DEBUG_CELL_WIDTH,
232 Bounds {
233 origin: Point::default(),
234 size: Size {
235 width: DEBUG_TERMINAL_WIDTH,
236 height: DEBUG_TERMINAL_HEIGHT,
237 },
238 },
239 )
240 }
241}
242
243impl From<TerminalBounds> for WindowSize {
244 fn from(val: TerminalBounds) -> Self {
245 WindowSize {
246 num_lines: val.num_lines() as u16,
247 num_cols: val.num_columns() as u16,
248 cell_width: f32::from(val.cell_width()) as u16,
249 cell_height: f32::from(val.line_height()) as u16,
250 }
251 }
252}
253
254impl Dimensions for TerminalBounds {
255 /// Note: this is supposed to be for the back buffer's length,
256 /// but we exclusively use it to resize the terminal, which does not
257 /// use this method. We still have to implement it for the trait though,
258 /// hence, this comment.
259 fn total_lines(&self) -> usize {
260 self.screen_lines()
261 }
262
263 fn screen_lines(&self) -> usize {
264 self.num_lines()
265 }
266
267 fn columns(&self) -> usize {
268 self.num_columns()
269 }
270}
271
272#[derive(Error, Debug)]
273pub struct TerminalError {
274 pub directory: Option<PathBuf>,
275 pub shell: Shell,
276 pub source: std::io::Error,
277}
278
279impl TerminalError {
280 pub fn fmt_directory(&self) -> String {
281 self.directory
282 .clone()
283 .map(|path| {
284 match path
285 .into_os_string()
286 .into_string()
287 .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
288 {
289 Ok(s) => s,
290 Err(s) => s,
291 }
292 })
293 .unwrap_or_else(|| match dirs::home_dir() {
294 Some(dir) => format!(
295 "<none specified, using home directory> {}",
296 dir.into_os_string().to_string_lossy()
297 ),
298 None => "<none specified, could not find home directory>".to_string(),
299 })
300 }
301
302 pub fn fmt_shell(&self) -> String {
303 match &self.shell {
304 Shell::System => "<system defined shell>".to_string(),
305 Shell::Program(s) => s.to_string(),
306 Shell::WithArguments {
307 program,
308 args,
309 title_override,
310 } => {
311 if let Some(title_override) = title_override {
312 format!("{} {} ({})", program, args.join(" "), title_override)
313 } else {
314 format!("{} {}", program, args.join(" "))
315 }
316 }
317 }
318 }
319}
320
321impl Display for TerminalError {
322 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323 let dir_string: String = self.fmt_directory();
324 let shell = self.fmt_shell();
325
326 write!(
327 f,
328 "Working directory: {} Shell command: `{}`, IOError: {}",
329 dir_string, shell, self.source
330 )
331 }
332}
333
334// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
335const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
336pub const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
337
338pub struct TerminalBuilder {
339 terminal: Terminal,
340 events_rx: UnboundedReceiver<AlacTermEvent>,
341}
342
343impl TerminalBuilder {
344 pub fn new(
345 working_directory: Option<PathBuf>,
346 python_venv_directory: Option<PathBuf>,
347 task: Option<TaskState>,
348 shell: Shell,
349 mut env: HashMap<String, String>,
350 cursor_shape: CursorShape,
351 alternate_scroll: AlternateScroll,
352 max_scroll_history_lines: Option<usize>,
353 is_ssh_terminal: bool,
354 window_id: u64,
355 completion_tx: Sender<Option<ExitStatus>>,
356 cx: &App,
357 ) -> Result<TerminalBuilder> {
358 // If the parent environment doesn't have a locale set
359 // (As is the case when launched from a .app on MacOS),
360 // and the Project doesn't have a locale set, then
361 // set a fallback for our child environment to use.
362 if std::env::var("LANG").is_err() {
363 env.entry("LANG".to_string())
364 .or_insert_with(|| "en_US.UTF-8".to_string());
365 }
366
367 env.insert("ZED_TERM".to_string(), "true".to_string());
368 env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
369 env.insert("TERM".to_string(), "xterm-256color".to_string());
370 env.insert(
371 "TERM_PROGRAM_VERSION".to_string(),
372 release_channel::AppVersion::global(cx).to_string(),
373 );
374
375 #[derive(Default)]
376 struct ShellParams {
377 program: String,
378 args: Option<Vec<String>>,
379 title_override: Option<SharedString>,
380 }
381
382 let shell_params = match shell.clone() {
383 Shell::System => {
384 #[cfg(target_os = "windows")]
385 {
386 Some(ShellParams {
387 program: util::get_windows_system_shell(),
388 ..Default::default()
389 })
390 }
391 #[cfg(not(target_os = "windows"))]
392 None
393 }
394 Shell::Program(program) => Some(ShellParams {
395 program,
396 ..Default::default()
397 }),
398 Shell::WithArguments {
399 program,
400 args,
401 title_override,
402 } => Some(ShellParams {
403 program,
404 args: Some(args),
405 title_override,
406 }),
407 };
408 let terminal_title_override = shell_params.as_ref().and_then(|e| e.title_override.clone());
409
410 #[cfg(windows)]
411 let shell_program = shell_params.as_ref().map(|params| params.program.clone());
412
413 let pty_options = {
414 let alac_shell = shell_params.map(|params| {
415 alacritty_terminal::tty::Shell::new(params.program, params.args.unwrap_or_default())
416 });
417
418 alacritty_terminal::tty::Options {
419 shell: alac_shell,
420 working_directory: working_directory
421 .clone()
422 .or_else(|| Some(home_dir().to_path_buf())),
423 drain_on_exit: true,
424 env: env.into_iter().collect(),
425 }
426 };
427
428 // Setup Alacritty's env, which modifies the current process's environment
429 alacritty_terminal::tty::setup_env();
430
431 let default_cursor_style = AlacCursorStyle::from(cursor_shape);
432 let scrolling_history = if task.is_some() {
433 // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
434 // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
435 // cause excessive memory usage over time.
436 MAX_SCROLL_HISTORY_LINES
437 } else {
438 max_scroll_history_lines
439 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
440 .min(MAX_SCROLL_HISTORY_LINES)
441 };
442 let config = Config {
443 scrolling_history,
444 default_cursor_style,
445 ..Config::default()
446 };
447
448 //Spawn a task so the Alacritty EventLoop can communicate with us
449 //TODO: Remove with a bounded sender which can be dispatched on &self
450 let (events_tx, events_rx) = unbounded();
451 //Set up the terminal...
452 let mut term = Term::new(
453 config.clone(),
454 &TerminalBounds::default(),
455 ZedListener(events_tx.clone()),
456 );
457
458 //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
459 if let AlternateScroll::Off = alternate_scroll {
460 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
461 }
462
463 let term = Arc::new(FairMutex::new(term));
464
465 //Setup the pty...
466 let pty = match tty::new(&pty_options, TerminalBounds::default().into(), window_id) {
467 Ok(pty) => pty,
468 Err(error) => {
469 bail!(TerminalError {
470 directory: working_directory,
471 shell,
472 source: error,
473 });
474 }
475 };
476
477 let pty_info = PtyProcessInfo::new(&pty);
478
479 //And connect them together
480 let event_loop = EventLoop::new(
481 term.clone(),
482 ZedListener(events_tx.clone()),
483 pty,
484 pty_options.drain_on_exit,
485 false,
486 )?;
487
488 //Kick things off
489 let pty_tx = event_loop.channel();
490 let _io_thread = event_loop.spawn(); // DANGER
491
492 let terminal = Terminal {
493 task,
494 pty_tx: Notifier(pty_tx),
495 completion_tx,
496 term,
497 term_config: config,
498 title_override: terminal_title_override,
499 events: VecDeque::with_capacity(10), //Should never get this high.
500 last_content: Default::default(),
501 last_mouse: None,
502 matches: Vec::new(),
503 selection_head: None,
504 pty_info,
505 breadcrumb_text: String::new(),
506 scroll_px: px(0.),
507 next_link_id: 0,
508 selection_phase: SelectionPhase::Ended,
509 // hovered_word: false,
510 hyperlink_regex_searches: RegexSearches::new(),
511 vi_mode_enabled: false,
512 is_ssh_terminal,
513 python_venv_directory,
514 last_mouse_move_time: Instant::now(),
515 last_hyperlink_search_position: None,
516 #[cfg(windows)]
517 shell_program,
518 };
519
520 Ok(TerminalBuilder {
521 terminal,
522 events_rx,
523 })
524 }
525
526 pub fn subscribe(mut self, cx: &Context<Terminal>) -> Terminal {
527 //Event loop
528 cx.spawn(async move |terminal, cx| {
529 while let Some(event) = self.events_rx.next().await {
530 terminal.update(cx, |terminal, cx| {
531 //Process the first event immediately for lowered latency
532 terminal.process_event(event, cx);
533 })?;
534
535 'outer: loop {
536 let mut events = Vec::new();
537 let mut timer = cx
538 .background_executor()
539 .timer(Duration::from_millis(4))
540 .fuse();
541 let mut wakeup = false;
542 loop {
543 futures::select_biased! {
544 _ = timer => break,
545 event = self.events_rx.next() => {
546 if let Some(event) = event {
547 if matches!(event, AlacTermEvent::Wakeup) {
548 wakeup = true;
549 } else {
550 events.push(event);
551 }
552
553 if events.len() > 100 {
554 break;
555 }
556 } else {
557 break;
558 }
559 },
560 }
561 }
562
563 if events.is_empty() && !wakeup {
564 smol::future::yield_now().await;
565 break 'outer;
566 }
567
568 terminal.update(cx, |this, cx| {
569 if wakeup {
570 this.process_event(AlacTermEvent::Wakeup, cx);
571 }
572
573 for event in events {
574 this.process_event(event, cx);
575 }
576 })?;
577 smol::future::yield_now().await;
578 }
579 }
580
581 anyhow::Ok(())
582 })
583 .detach();
584
585 self.terminal
586 }
587}
588
589#[derive(Debug, Clone, Deserialize, Serialize)]
590pub struct IndexedCell {
591 pub point: AlacPoint,
592 pub cell: Cell,
593}
594
595impl Deref for IndexedCell {
596 type Target = Cell;
597
598 #[inline]
599 fn deref(&self) -> &Cell {
600 &self.cell
601 }
602}
603
604// TODO: Un-pub
605#[derive(Clone)]
606pub struct TerminalContent {
607 pub cells: Vec<IndexedCell>,
608 pub mode: TermMode,
609 pub display_offset: usize,
610 pub selection_text: Option<String>,
611 pub selection: Option<SelectionRange>,
612 pub cursor: RenderableCursor,
613 pub cursor_char: char,
614 pub terminal_bounds: TerminalBounds,
615 pub last_hovered_word: Option<HoveredWord>,
616 pub scrolled_to_top: bool,
617 pub scrolled_to_bottom: bool,
618}
619
620#[derive(Debug, Clone, Eq, PartialEq)]
621pub struct HoveredWord {
622 pub word: String,
623 pub word_match: RangeInclusive<AlacPoint>,
624 pub id: usize,
625}
626
627impl Default for TerminalContent {
628 fn default() -> Self {
629 TerminalContent {
630 cells: Default::default(),
631 mode: Default::default(),
632 display_offset: Default::default(),
633 selection_text: Default::default(),
634 selection: Default::default(),
635 cursor: RenderableCursor {
636 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
637 point: AlacPoint::new(Line(0), Column(0)),
638 },
639 cursor_char: Default::default(),
640 terminal_bounds: Default::default(),
641 last_hovered_word: None,
642 scrolled_to_top: false,
643 scrolled_to_bottom: false,
644 }
645 }
646}
647
648#[derive(PartialEq, Eq)]
649pub enum SelectionPhase {
650 Selecting,
651 Ended,
652}
653
654pub struct Terminal {
655 pty_tx: Notifier,
656 completion_tx: Sender<Option<ExitStatus>>,
657 term: Arc<FairMutex<Term<ZedListener>>>,
658 term_config: Config,
659 events: VecDeque<InternalEvent>,
660 /// This is only used for mouse mode cell change detection
661 last_mouse: Option<(AlacPoint, AlacDirection)>,
662 pub matches: Vec<RangeInclusive<AlacPoint>>,
663 pub last_content: TerminalContent,
664 pub selection_head: Option<AlacPoint>,
665 pub breadcrumb_text: String,
666 pub pty_info: PtyProcessInfo,
667 title_override: Option<SharedString>,
668 pub python_venv_directory: Option<PathBuf>,
669 scroll_px: Pixels,
670 next_link_id: usize,
671 selection_phase: SelectionPhase,
672 hyperlink_regex_searches: RegexSearches,
673 task: Option<TaskState>,
674 vi_mode_enabled: bool,
675 is_ssh_terminal: bool,
676 last_mouse_move_time: Instant,
677 last_hyperlink_search_position: Option<Point<Pixels>>,
678 #[cfg(windows)]
679 shell_program: Option<String>,
680}
681
682pub struct TaskState {
683 pub id: TaskId,
684 pub full_label: String,
685 pub label: String,
686 pub command_label: String,
687 pub status: TaskStatus,
688 pub completion_rx: Receiver<Option<ExitStatus>>,
689 pub hide: HideStrategy,
690 pub show_summary: bool,
691 pub show_command: bool,
692 pub show_rerun: bool,
693}
694
695/// A status of the current terminal tab's task.
696#[derive(Debug, Clone, Copy, PartialEq, Eq)]
697pub enum TaskStatus {
698 /// The task had been started, but got cancelled or somehow otherwise it did not
699 /// report its exit code before the terminal event loop was shut down.
700 Unknown,
701 /// The task is started and running currently.
702 Running,
703 /// After the start, the task stopped running and reported its error code back.
704 Completed { success: bool },
705}
706
707impl TaskStatus {
708 fn register_terminal_exit(&mut self) {
709 if self == &Self::Running {
710 *self = Self::Unknown;
711 }
712 }
713
714 fn register_task_exit(&mut self, error_code: i32) {
715 *self = TaskStatus::Completed {
716 success: error_code == 0,
717 };
718 }
719}
720
721impl Terminal {
722 fn process_event(&mut self, event: AlacTermEvent, cx: &mut Context<Self>) {
723 match event {
724 AlacTermEvent::Title(title) => {
725 // ignore default shell program title change as windows always sends those events
726 // and it would end up showing the shell executable path in breadcrumbs
727 #[cfg(windows)]
728 {
729 if self
730 .shell_program
731 .as_ref()
732 .map(|e| *e == title)
733 .unwrap_or(false)
734 {
735 return;
736 }
737 }
738
739 self.breadcrumb_text = title;
740 cx.emit(Event::BreadcrumbsChanged);
741 }
742 AlacTermEvent::ResetTitle => {
743 self.breadcrumb_text = String::new();
744 cx.emit(Event::BreadcrumbsChanged);
745 }
746 AlacTermEvent::ClipboardStore(_, data) => {
747 cx.write_to_clipboard(ClipboardItem::new_string(data))
748 }
749 AlacTermEvent::ClipboardLoad(_, format) => {
750 self.write_to_pty(
751 match &cx.read_from_clipboard().and_then(|item| item.text()) {
752 // The terminal only supports pasting strings, not images.
753 Some(text) => format(text),
754 _ => format(""),
755 }
756 .into_bytes(),
757 )
758 }
759 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.into_bytes()),
760 AlacTermEvent::TextAreaSizeRequest(format) => {
761 self.write_to_pty(format(self.last_content.terminal_bounds.into()).into_bytes())
762 }
763 AlacTermEvent::CursorBlinkingChange => {
764 let terminal = self.term.lock();
765 let blinking = terminal.cursor_style().blinking;
766 cx.emit(Event::BlinkChanged(blinking));
767 }
768 AlacTermEvent::Bell => {
769 cx.emit(Event::Bell);
770 }
771 AlacTermEvent::Exit => self.register_task_finished(None, cx),
772 AlacTermEvent::MouseCursorDirty => {
773 //NOOP, Handled in render
774 }
775 AlacTermEvent::Wakeup => {
776 cx.emit(Event::Wakeup);
777
778 if self.pty_info.has_changed() {
779 cx.emit(Event::TitleChanged);
780 }
781 }
782 AlacTermEvent::ColorRequest(index, format) => {
783 // It's important that the color request is processed here to retain relative order
784 // with other PTY writes. Otherwise applications might witness out-of-order
785 // responses to requests. For example: An application sending `OSC 11 ; ? ST`
786 // (color request) followed by `CSI c` (request device attributes) would receive
787 // the response to `CSI c` first.
788 // Instead of locking, we could store the colors in `self.last_content`. But then
789 // we might respond with out of date value if a "set color" sequence is immediately
790 // followed by a color request sequence.
791 let color = self.term.lock().colors()[index]
792 .unwrap_or_else(|| to_alac_rgb(get_color_at_index(index, cx.theme().as_ref())));
793 self.write_to_pty(format(color).into_bytes());
794 }
795 AlacTermEvent::ChildExit(error_code) => {
796 self.register_task_finished(Some(error_code), cx);
797 }
798 }
799 }
800
801 pub fn selection_started(&self) -> bool {
802 self.selection_phase == SelectionPhase::Selecting
803 }
804
805 fn process_terminal_event(
806 &mut self,
807 event: &InternalEvent,
808 term: &mut Term<ZedListener>,
809 window: &mut Window,
810 cx: &mut Context<Self>,
811 ) {
812 match event {
813 &InternalEvent::Resize(mut new_bounds) => {
814 new_bounds.bounds.size.height =
815 cmp::max(new_bounds.line_height, new_bounds.height());
816 new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
817
818 self.last_content.terminal_bounds = new_bounds;
819
820 self.pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
821
822 term.resize(new_bounds);
823 }
824 InternalEvent::Clear => {
825 // Clear back buffer
826 term.clear_screen(ClearMode::Saved);
827
828 let cursor = term.grid().cursor.point;
829
830 // Clear the lines above
831 term.grid_mut().reset_region(..cursor.line);
832
833 // Copy the current line up
834 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
835 .iter()
836 .cloned()
837 .enumerate()
838 .collect::<Vec<(usize, Cell)>>();
839
840 for (i, cell) in line {
841 term.grid_mut()[Line(0)][Column(i)] = cell;
842 }
843
844 // Reset the cursor
845 term.grid_mut().cursor.point =
846 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
847 let new_cursor = term.grid().cursor.point;
848
849 // Clear the lines below the new cursor
850 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
851 term.grid_mut().reset_region((new_cursor.line + 1)..);
852 }
853
854 cx.emit(Event::Wakeup);
855 }
856 InternalEvent::Scroll(scroll) => {
857 term.scroll_display(*scroll);
858 self.refresh_hovered_word(window);
859
860 if self.vi_mode_enabled {
861 match *scroll {
862 AlacScroll::Delta(delta) => {
863 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
864 }
865 AlacScroll::PageUp => {
866 let lines = term.screen_lines() as i32;
867 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
868 }
869 AlacScroll::PageDown => {
870 let lines = -(term.screen_lines() as i32);
871 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
872 }
873 AlacScroll::Top => {
874 let point = AlacPoint::new(term.topmost_line(), Column(0));
875 term.vi_mode_cursor = ViModeCursor::new(point);
876 }
877 AlacScroll::Bottom => {
878 let point = AlacPoint::new(term.bottommost_line(), Column(0));
879 term.vi_mode_cursor = ViModeCursor::new(point);
880 }
881 }
882 if let Some(mut selection) = term.selection.take() {
883 let point = term.vi_mode_cursor.point;
884 selection.update(point, AlacDirection::Right);
885 term.selection = Some(selection);
886
887 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
888 if let Some(selection_text) = term.selection_to_string() {
889 cx.write_to_primary(ClipboardItem::new_string(selection_text));
890 }
891
892 self.selection_head = Some(point);
893 cx.emit(Event::SelectionsChanged)
894 }
895 }
896 }
897 InternalEvent::SetSelection(selection) => {
898 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
899
900 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
901 if let Some(selection_text) = term.selection_to_string() {
902 cx.write_to_primary(ClipboardItem::new_string(selection_text));
903 }
904
905 if let Some((_, head)) = selection {
906 self.selection_head = Some(*head);
907 }
908 cx.emit(Event::SelectionsChanged)
909 }
910 InternalEvent::UpdateSelection(position) => {
911 if let Some(mut selection) = term.selection.take() {
912 let (point, side) = grid_point_and_side(
913 *position,
914 self.last_content.terminal_bounds,
915 term.grid().display_offset(),
916 );
917
918 selection.update(point, side);
919 term.selection = Some(selection);
920
921 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
922 if let Some(selection_text) = term.selection_to_string() {
923 cx.write_to_primary(ClipboardItem::new_string(selection_text));
924 }
925
926 self.selection_head = Some(point);
927 cx.emit(Event::SelectionsChanged)
928 }
929 }
930
931 InternalEvent::Copy(keep_selection) => {
932 if let Some(txt) = term.selection_to_string() {
933 cx.write_to_clipboard(ClipboardItem::new_string(txt));
934 if !keep_selection.unwrap_or_else(|| {
935 let settings = TerminalSettings::get_global(cx);
936 settings.keep_selection_on_copy
937 }) {
938 self.events.push_back(InternalEvent::SetSelection(None));
939 }
940 }
941 }
942 InternalEvent::ScrollToAlacPoint(point) => {
943 term.scroll_to_point(*point);
944 self.refresh_hovered_word(window);
945 }
946 InternalEvent::ToggleViMode => {
947 self.vi_mode_enabled = !self.vi_mode_enabled;
948 term.toggle_vi_mode();
949 }
950 InternalEvent::ViMotion(motion) => {
951 term.vi_motion(*motion);
952 }
953 InternalEvent::FindHyperlink(position, open) => {
954 let prev_hovered_word = self.last_content.last_hovered_word.take();
955
956 let point = grid_point(
957 *position,
958 self.last_content.terminal_bounds,
959 term.grid().display_offset(),
960 )
961 .grid_clamp(term, Boundary::Grid);
962
963 match terminal_hyperlinks::find_from_grid_point(
964 term,
965 point,
966 &mut self.hyperlink_regex_searches,
967 ) {
968 Some((maybe_url_or_path, is_url, url_match)) => {
969 let target = if is_url {
970 // Treat "file://" URLs like file paths to ensure
971 // that line numbers at the end of the path are
972 // handled correctly.
973 // file://{path} should be urldecoded, returning a urldecoded {path}
974 if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
975 let decoded_path = urlencoding::decode(path)
976 .map(|decoded| decoded.into_owned())
977 .unwrap_or(path.to_owned());
978
979 MaybeNavigationTarget::PathLike(PathLikeTarget {
980 maybe_path: decoded_path,
981 terminal_dir: self.working_directory(),
982 })
983 } else {
984 MaybeNavigationTarget::Url(maybe_url_or_path.clone())
985 }
986 } else {
987 MaybeNavigationTarget::PathLike(PathLikeTarget {
988 maybe_path: maybe_url_or_path.clone(),
989 terminal_dir: self.working_directory(),
990 })
991 };
992 if *open {
993 cx.emit(Event::Open(target));
994 } else {
995 self.update_selected_word(
996 prev_hovered_word,
997 url_match,
998 maybe_url_or_path,
999 target,
1000 cx,
1001 );
1002 }
1003 }
1004 None => {
1005 cx.emit(Event::NewNavigationTarget(None));
1006 }
1007 }
1008 }
1009 }
1010 }
1011
1012 fn update_selected_word(
1013 &mut self,
1014 prev_word: Option<HoveredWord>,
1015 word_match: RangeInclusive<AlacPoint>,
1016 word: String,
1017 navigation_target: MaybeNavigationTarget,
1018 cx: &mut Context<Self>,
1019 ) {
1020 if let Some(prev_word) = prev_word {
1021 if prev_word.word == word && prev_word.word_match == word_match {
1022 self.last_content.last_hovered_word = Some(HoveredWord {
1023 word,
1024 word_match,
1025 id: prev_word.id,
1026 });
1027 return;
1028 }
1029 }
1030
1031 self.last_content.last_hovered_word = Some(HoveredWord {
1032 word,
1033 word_match,
1034 id: self.next_link_id(),
1035 });
1036 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1037 cx.notify()
1038 }
1039
1040 fn next_link_id(&mut self) -> usize {
1041 let res = self.next_link_id;
1042 self.next_link_id = self.next_link_id.wrapping_add(1);
1043 res
1044 }
1045
1046 pub fn last_content(&self) -> &TerminalContent {
1047 &self.last_content
1048 }
1049
1050 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1051 self.term_config.default_cursor_style = cursor_shape.into();
1052 self.term.lock().set_options(self.term_config.clone());
1053 }
1054
1055 pub fn total_lines(&self) -> usize {
1056 let term = self.term.clone();
1057 let terminal = term.lock_unfair();
1058 terminal.total_lines()
1059 }
1060
1061 pub fn viewport_lines(&self) -> usize {
1062 let term = self.term.clone();
1063 let terminal = term.lock_unfair();
1064 terminal.screen_lines()
1065 }
1066
1067 //To test:
1068 //- Activate match on terminal (scrolling and selection)
1069 //- Editor search snapping behavior
1070
1071 pub fn activate_match(&mut self, index: usize) {
1072 if let Some(search_match) = self.matches.get(index).cloned() {
1073 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1074
1075 self.events
1076 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1077 }
1078 }
1079
1080 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1081 let matches_to_select = self
1082 .matches
1083 .iter()
1084 .filter(|self_match| matches.contains(self_match))
1085 .cloned()
1086 .collect::<Vec<_>>();
1087 for match_to_select in matches_to_select {
1088 self.set_selection(Some((
1089 make_selection(&match_to_select),
1090 *match_to_select.end(),
1091 )));
1092 }
1093 }
1094
1095 pub fn select_all(&mut self) {
1096 let term = self.term.lock();
1097 let start = AlacPoint::new(term.topmost_line(), Column(0));
1098 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1099 drop(term);
1100 self.set_selection(Some((make_selection(&(start..=end)), end)));
1101 }
1102
1103 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1104 self.events
1105 .push_back(InternalEvent::SetSelection(selection));
1106 }
1107
1108 pub fn copy(&mut self, keep_selection: Option<bool>) {
1109 self.events.push_back(InternalEvent::Copy(keep_selection));
1110 }
1111
1112 pub fn clear(&mut self) {
1113 self.events.push_back(InternalEvent::Clear)
1114 }
1115
1116 pub fn scroll_line_up(&mut self) {
1117 self.events
1118 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1119 }
1120
1121 pub fn scroll_up_by(&mut self, lines: usize) {
1122 self.events
1123 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1124 }
1125
1126 pub fn scroll_line_down(&mut self) {
1127 self.events
1128 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1129 }
1130
1131 pub fn scroll_down_by(&mut self, lines: usize) {
1132 self.events
1133 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1134 }
1135
1136 pub fn scroll_page_up(&mut self) {
1137 self.events
1138 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1139 }
1140
1141 pub fn scroll_page_down(&mut self) {
1142 self.events
1143 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1144 }
1145
1146 pub fn scroll_to_top(&mut self) {
1147 self.events
1148 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1149 }
1150
1151 pub fn scroll_to_bottom(&mut self) {
1152 self.events
1153 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1154 }
1155
1156 pub fn scrolled_to_top(&self) -> bool {
1157 self.last_content.scrolled_to_top
1158 }
1159
1160 pub fn scrolled_to_bottom(&self) -> bool {
1161 self.last_content.scrolled_to_bottom
1162 }
1163
1164 ///Resize the terminal and the PTY.
1165 pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1166 if self.last_content.terminal_bounds != new_bounds {
1167 self.events.push_back(InternalEvent::Resize(new_bounds))
1168 }
1169 }
1170
1171 ///Write the Input payload to the tty.
1172 fn write_to_pty(&self, input: impl Into<Cow<'static, [u8]>>) {
1173 self.pty_tx.notify(input.into());
1174 }
1175
1176 pub fn input(&mut self, input: impl Into<Cow<'static, [u8]>>) {
1177 self.events
1178 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1179 self.events.push_back(InternalEvent::SetSelection(None));
1180
1181 self.write_to_pty(input);
1182 }
1183
1184 pub fn toggle_vi_mode(&mut self) {
1185 self.events.push_back(InternalEvent::ToggleViMode);
1186 }
1187
1188 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1189 if !self.vi_mode_enabled {
1190 return;
1191 }
1192
1193 let key: Cow<'_, str> = if keystroke.modifiers.shift {
1194 Cow::Owned(keystroke.key.to_uppercase())
1195 } else {
1196 Cow::Borrowed(keystroke.key.as_str())
1197 };
1198
1199 let motion: Option<ViMotion> = match key.as_ref() {
1200 "h" | "left" => Some(ViMotion::Left),
1201 "j" | "down" => Some(ViMotion::Down),
1202 "k" | "up" => Some(ViMotion::Up),
1203 "l" | "right" => Some(ViMotion::Right),
1204 "w" => Some(ViMotion::WordRight),
1205 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1206 "e" => Some(ViMotion::WordRightEnd),
1207 "%" => Some(ViMotion::Bracket),
1208 "$" => Some(ViMotion::Last),
1209 "0" => Some(ViMotion::First),
1210 "^" => Some(ViMotion::FirstOccupied),
1211 "H" => Some(ViMotion::High),
1212 "M" => Some(ViMotion::Middle),
1213 "L" => Some(ViMotion::Low),
1214 _ => None,
1215 };
1216
1217 if let Some(motion) = motion {
1218 let cursor = self.last_content.cursor.point;
1219 let cursor_pos = Point {
1220 x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1221 y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1222 };
1223 self.events
1224 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1225 self.events.push_back(InternalEvent::ViMotion(motion));
1226 return;
1227 }
1228
1229 let scroll_motion = match key.as_ref() {
1230 "g" => Some(AlacScroll::Top),
1231 "G" => Some(AlacScroll::Bottom),
1232 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1233 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1234 "d" if keystroke.modifiers.control => {
1235 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1236 Some(AlacScroll::Delta(-amount))
1237 }
1238 "u" if keystroke.modifiers.control => {
1239 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1240 Some(AlacScroll::Delta(amount))
1241 }
1242 _ => None,
1243 };
1244
1245 if let Some(scroll_motion) = scroll_motion {
1246 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1247 return;
1248 }
1249
1250 match key.as_ref() {
1251 "v" => {
1252 let point = self.last_content.cursor.point;
1253 let selection_type = SelectionType::Simple;
1254 let side = AlacDirection::Right;
1255 let selection = Selection::new(selection_type, point, side);
1256 self.events
1257 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1258 return;
1259 }
1260
1261 "escape" => {
1262 self.events.push_back(InternalEvent::SetSelection(None));
1263 return;
1264 }
1265
1266 "y" => {
1267 self.copy(Some(false));
1268 return;
1269 }
1270
1271 "i" => {
1272 self.scroll_to_bottom();
1273 self.toggle_vi_mode();
1274 return;
1275 }
1276 _ => {}
1277 }
1278 }
1279
1280 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1281 if self.vi_mode_enabled {
1282 self.vi_motion(keystroke);
1283 return true;
1284 }
1285
1286 // Keep default terminal behavior
1287 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1288 if let Some(esc) = esc {
1289 match esc {
1290 Cow::Borrowed(string) => self.input(string.as_bytes()),
1291 Cow::Owned(string) => self.input(string.into_bytes()),
1292 };
1293 true
1294 } else {
1295 false
1296 }
1297 }
1298
1299 pub fn try_modifiers_change(
1300 &mut self,
1301 modifiers: &Modifiers,
1302 window: &Window,
1303 cx: &mut Context<Self>,
1304 ) {
1305 if self
1306 .last_content
1307 .terminal_bounds
1308 .bounds
1309 .contains(&window.mouse_position())
1310 && modifiers.secondary()
1311 {
1312 self.refresh_hovered_word(window);
1313 }
1314 cx.notify();
1315 }
1316
1317 ///Paste text into the terminal
1318 pub fn paste(&mut self, text: &str) {
1319 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1320 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1321 } else {
1322 text.replace("\r\n", "\r").replace('\n', "\r")
1323 };
1324
1325 self.input(paste_text.into_bytes());
1326 }
1327
1328 pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1329 let term = self.term.clone();
1330 let mut terminal = term.lock_unfair();
1331 //Note that the ordering of events matters for event processing
1332 while let Some(e) = self.events.pop_front() {
1333 self.process_terminal_event(&e, &mut terminal, window, cx)
1334 }
1335
1336 self.last_content = Self::make_content(&terminal, &self.last_content);
1337 }
1338
1339 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1340 let content = term.renderable_content();
1341
1342 // Pre-allocate with estimated size to reduce reallocations
1343 let estimated_size = content.display_iter.size_hint().0;
1344 let mut cells = Vec::with_capacity(estimated_size);
1345
1346 cells.extend(content.display_iter.map(|ic| IndexedCell {
1347 point: ic.point,
1348 cell: ic.cell.clone(),
1349 }));
1350
1351 let selection_text = if content.selection.is_some() {
1352 term.selection_to_string()
1353 } else {
1354 None
1355 };
1356
1357 TerminalContent {
1358 cells,
1359 mode: content.mode,
1360 display_offset: content.display_offset,
1361 selection_text,
1362 selection: content.selection,
1363 cursor: content.cursor,
1364 cursor_char: term.grid()[content.cursor.point].c,
1365 terminal_bounds: last_content.terminal_bounds,
1366 last_hovered_word: last_content.last_hovered_word.clone(),
1367 scrolled_to_top: content.display_offset == term.history_size(),
1368 scrolled_to_bottom: content.display_offset == 0,
1369 }
1370 }
1371
1372 pub fn get_content(&self) -> String {
1373 let term = self.term.lock_unfair();
1374 let start = AlacPoint::new(term.topmost_line(), Column(0));
1375 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1376 term.bounds_to_string(start, end)
1377 }
1378
1379 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1380 let term = self.term.clone();
1381 let terminal = term.lock_unfair();
1382 let grid = terminal.grid();
1383 let mut lines = Vec::new();
1384
1385 let mut current_line = grid.bottommost_line().0;
1386 let topmost_line = grid.topmost_line().0;
1387
1388 while current_line >= topmost_line && lines.len() < n {
1389 let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1390 let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1391
1392 if let Some(line) = self.process_line(logical_line) {
1393 lines.push(line);
1394 }
1395
1396 // Move to the line above the start of the current logical line
1397 current_line = logical_line_start - 1;
1398 }
1399
1400 lines.reverse();
1401 lines
1402 }
1403
1404 fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1405 let mut line_start = current;
1406 while line_start > topmost {
1407 let prev_line = Line(line_start - 1);
1408 let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1409 if !last_cell.flags.contains(Flags::WRAPLINE) {
1410 break;
1411 }
1412 line_start -= 1;
1413 }
1414 line_start
1415 }
1416
1417 fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1418 let mut logical_line = String::new();
1419 for row in start..=end {
1420 let grid_row = &grid[Line(row)];
1421 logical_line.push_str(&row_to_string(grid_row));
1422 }
1423 logical_line
1424 }
1425
1426 fn process_line(&self, line: String) -> Option<String> {
1427 let trimmed = line.trim_end().to_string();
1428 if !trimmed.is_empty() {
1429 Some(trimmed)
1430 } else {
1431 None
1432 }
1433 }
1434
1435 pub fn focus_in(&self) {
1436 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1437 self.write_to_pty("\x1b[I".as_bytes());
1438 }
1439 }
1440
1441 pub fn focus_out(&mut self) {
1442 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1443 self.write_to_pty("\x1b[O".as_bytes());
1444 }
1445 }
1446
1447 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1448 match self.last_mouse {
1449 Some((old_point, old_side)) => {
1450 if old_point == point && old_side == side {
1451 false
1452 } else {
1453 self.last_mouse = Some((point, side));
1454 true
1455 }
1456 }
1457 None => {
1458 self.last_mouse = Some((point, side));
1459 true
1460 }
1461 }
1462 }
1463
1464 pub fn mouse_mode(&self, shift: bool) -> bool {
1465 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1466 }
1467
1468 pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1469 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1470 if self.mouse_mode(e.modifiers.shift) {
1471 let (point, side) = grid_point_and_side(
1472 position,
1473 self.last_content.terminal_bounds,
1474 self.last_content.display_offset,
1475 );
1476
1477 if self.mouse_changed(point, side) {
1478 if let Some(bytes) =
1479 mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1480 {
1481 self.pty_tx.notify(bytes);
1482 }
1483 }
1484 } else if e.modifiers.secondary() {
1485 self.word_from_position(e.position);
1486 }
1487 cx.notify();
1488 }
1489
1490 fn word_from_position(&mut self, position: Point<Pixels>) {
1491 if self.selection_phase == SelectionPhase::Selecting {
1492 self.last_content.last_hovered_word = None;
1493 } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1494 // Throttle hyperlink searches to avoid excessive processing
1495 let now = Instant::now();
1496 let should_search = if let Some(last_pos) = self.last_hyperlink_search_position {
1497 // Only search if mouse moved significantly or enough time passed
1498 let distance_moved =
1499 ((position.x - last_pos.x).abs() + (position.y - last_pos.y).abs()) > px(5.0);
1500 let time_elapsed = now.duration_since(self.last_mouse_move_time).as_millis() > 100;
1501 distance_moved || time_elapsed
1502 } else {
1503 true
1504 };
1505
1506 if should_search {
1507 self.last_mouse_move_time = now;
1508 self.last_hyperlink_search_position = Some(position);
1509 self.events.push_back(InternalEvent::FindHyperlink(
1510 position - self.last_content.terminal_bounds.bounds.origin,
1511 false,
1512 ));
1513 }
1514 } else {
1515 self.last_content.last_hovered_word = None;
1516 }
1517 }
1518
1519 pub fn select_word_at_event_position(&mut self, e: &MouseDownEvent) {
1520 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1521 let (point, side) = grid_point_and_side(
1522 position,
1523 self.last_content.terminal_bounds,
1524 self.last_content.display_offset,
1525 );
1526 let selection = Selection::new(SelectionType::Semantic, point, side);
1527 self.events
1528 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1529 }
1530
1531 pub fn mouse_drag(
1532 &mut self,
1533 e: &MouseMoveEvent,
1534 region: Bounds<Pixels>,
1535 cx: &mut Context<Self>,
1536 ) {
1537 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1538 if !self.mouse_mode(e.modifiers.shift) {
1539 self.selection_phase = SelectionPhase::Selecting;
1540 // Alacritty has the same ordering, of first updating the selection
1541 // then scrolling 15ms later
1542 self.events
1543 .push_back(InternalEvent::UpdateSelection(position));
1544
1545 // Doesn't make sense to scroll the alt screen
1546 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1547 let scroll_lines = match self.drag_line_delta(e, region) {
1548 Some(value) => value,
1549 None => return,
1550 };
1551
1552 self.events
1553 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1554 }
1555
1556 cx.notify();
1557 }
1558 }
1559
1560 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1561 let top = region.origin.y;
1562 let bottom = region.bottom_left().y;
1563
1564 let scroll_lines = if e.position.y < top {
1565 let scroll_delta = (top - e.position.y).pow(1.1);
1566 (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1567 } else if e.position.y > bottom {
1568 let scroll_delta = -((e.position.y - bottom).pow(1.1));
1569 (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1570 } else {
1571 return None;
1572 };
1573
1574 Some(scroll_lines.clamp(-3, 3))
1575 }
1576
1577 pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1578 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1579 let point = grid_point(
1580 position,
1581 self.last_content.terminal_bounds,
1582 self.last_content.display_offset,
1583 );
1584
1585 if self.mouse_mode(e.modifiers.shift) {
1586 if let Some(bytes) =
1587 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1588 {
1589 self.pty_tx.notify(bytes);
1590 }
1591 } else {
1592 match e.button {
1593 MouseButton::Left => {
1594 let (point, side) = grid_point_and_side(
1595 position,
1596 self.last_content.terminal_bounds,
1597 self.last_content.display_offset,
1598 );
1599
1600 let selection_type = match e.click_count {
1601 0 => return, //This is a release
1602 1 => Some(SelectionType::Simple),
1603 2 => Some(SelectionType::Semantic),
1604 3 => Some(SelectionType::Lines),
1605 _ => None,
1606 };
1607
1608 if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1609 self.events
1610 .push_back(InternalEvent::UpdateSelection(position));
1611 return;
1612 }
1613
1614 let selection = selection_type
1615 .map(|selection_type| Selection::new(selection_type, point, side));
1616
1617 if let Some(sel) = selection {
1618 self.events
1619 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1620 }
1621 }
1622 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1623 MouseButton::Middle => {
1624 if let Some(item) = _cx.read_from_primary() {
1625 let text = item.text().unwrap_or_default().to_string();
1626 self.input(text.into_bytes());
1627 }
1628 }
1629 _ => {}
1630 }
1631 }
1632 }
1633
1634 pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1635 let setting = TerminalSettings::get_global(cx);
1636
1637 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1638 if self.mouse_mode(e.modifiers.shift) {
1639 let point = grid_point(
1640 position,
1641 self.last_content.terminal_bounds,
1642 self.last_content.display_offset,
1643 );
1644
1645 if let Some(bytes) =
1646 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1647 {
1648 self.pty_tx.notify(bytes);
1649 }
1650 } else {
1651 if e.button == MouseButton::Left && setting.copy_on_select {
1652 self.copy(Some(true));
1653 }
1654
1655 //Hyperlinks
1656 if self.selection_phase == SelectionPhase::Ended {
1657 let mouse_cell_index =
1658 content_index_for_mouse(position, &self.last_content.terminal_bounds);
1659 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1660 cx.open_url(link.uri());
1661 } else if e.modifiers.secondary() {
1662 self.events
1663 .push_back(InternalEvent::FindHyperlink(position, true));
1664 }
1665 }
1666 }
1667
1668 self.selection_phase = SelectionPhase::Ended;
1669 self.last_mouse = None;
1670 }
1671
1672 ///Scroll the terminal
1673 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1674 let mouse_mode = self.mouse_mode(e.shift);
1675
1676 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1677 if mouse_mode {
1678 let point = grid_point(
1679 e.position - self.last_content.terminal_bounds.bounds.origin,
1680 self.last_content.terminal_bounds,
1681 self.last_content.display_offset,
1682 );
1683
1684 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1685 {
1686 for scroll in scrolls {
1687 self.pty_tx.notify(scroll);
1688 }
1689 };
1690 } else if self
1691 .last_content
1692 .mode
1693 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1694 && !e.shift
1695 {
1696 self.pty_tx.notify(alt_scroll(scroll_lines))
1697 } else if scroll_lines != 0 {
1698 let scroll = AlacScroll::Delta(scroll_lines);
1699
1700 self.events.push_back(InternalEvent::Scroll(scroll));
1701 }
1702 }
1703 }
1704
1705 fn refresh_hovered_word(&mut self, window: &Window) {
1706 self.word_from_position(window.mouse_position());
1707 }
1708
1709 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1710 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1711 let line_height = self.last_content.terminal_bounds.line_height;
1712 match e.touch_phase {
1713 /* Reset scroll state on started */
1714 TouchPhase::Started => {
1715 self.scroll_px = px(0.);
1716 None
1717 }
1718 /* Calculate the appropriate scroll lines */
1719 TouchPhase::Moved => {
1720 let old_offset = (self.scroll_px / line_height) as i32;
1721
1722 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1723
1724 let new_offset = (self.scroll_px / line_height) as i32;
1725
1726 // Whenever we hit the edges, reset our stored scroll to 0
1727 // so we can respond to changes in direction quickly
1728 self.scroll_px %= self.last_content.terminal_bounds.height();
1729
1730 Some(new_offset - old_offset)
1731 }
1732 TouchPhase::Ended => None,
1733 }
1734 }
1735
1736 pub fn find_matches(
1737 &self,
1738 mut searcher: RegexSearch,
1739 cx: &Context<Self>,
1740 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1741 let term = self.term.clone();
1742 cx.background_spawn(async move {
1743 let term = term.lock();
1744
1745 all_search_matches(&term, &mut searcher).collect()
1746 })
1747 }
1748
1749 pub fn working_directory(&self) -> Option<PathBuf> {
1750 if self.is_ssh_terminal {
1751 // We can't yet reliably detect the working directory of a shell on the
1752 // SSH host. Until we can do that, it doesn't make sense to display
1753 // the working directory on the client and persist that.
1754 None
1755 } else {
1756 self.client_side_working_directory()
1757 }
1758 }
1759
1760 /// Returns the working directory of the process that's connected to the PTY.
1761 /// That means it returns the working directory of the local shell or program
1762 /// that's running inside the terminal.
1763 ///
1764 /// This does *not* return the working directory of the shell that runs on the
1765 /// remote host, in case Zed is connected to a remote host.
1766 fn client_side_working_directory(&self) -> Option<PathBuf> {
1767 self.pty_info
1768 .current
1769 .as_ref()
1770 .map(|process| process.cwd.clone())
1771 }
1772
1773 pub fn title(&self, truncate: bool) -> String {
1774 const MAX_CHARS: usize = 25;
1775 match &self.task {
1776 Some(task_state) => {
1777 if truncate {
1778 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1779 } else {
1780 task_state.full_label.clone()
1781 }
1782 }
1783 None => self
1784 .title_override
1785 .as_ref()
1786 .map(|title_override| title_override.to_string())
1787 .unwrap_or_else(|| {
1788 self.pty_info
1789 .current
1790 .as_ref()
1791 .map(|fpi| {
1792 let process_file = fpi
1793 .cwd
1794 .file_name()
1795 .map(|name| name.to_string_lossy().to_string())
1796 .unwrap_or_default();
1797
1798 let argv = fpi.argv.as_slice();
1799 let process_name = format!(
1800 "{}{}",
1801 fpi.name,
1802 if !argv.is_empty() {
1803 format!(" {}", (argv[1..]).join(" "))
1804 } else {
1805 "".to_string()
1806 }
1807 );
1808 let (process_file, process_name) = if truncate {
1809 (
1810 truncate_and_trailoff(&process_file, MAX_CHARS),
1811 truncate_and_trailoff(&process_name, MAX_CHARS),
1812 )
1813 } else {
1814 (process_file, process_name)
1815 };
1816 format!("{process_file} — {process_name}")
1817 })
1818 .unwrap_or_else(|| "Terminal".to_string())
1819 }),
1820 }
1821 }
1822
1823 pub fn kill_active_task(&mut self) {
1824 if let Some(task) = self.task() {
1825 if task.status == TaskStatus::Running {
1826 self.pty_info.kill_current_process();
1827 }
1828 }
1829 }
1830
1831 pub fn task(&self) -> Option<&TaskState> {
1832 self.task.as_ref()
1833 }
1834
1835 pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
1836 if let Some(task) = self.task() {
1837 if task.status == TaskStatus::Running {
1838 let completion_receiver = task.completion_rx.clone();
1839 return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
1840 } else if let Ok(status) = task.completion_rx.try_recv() {
1841 return Task::ready(status);
1842 }
1843 }
1844 Task::ready(None)
1845 }
1846
1847 fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
1848 let e: Option<ExitStatus> = error_code.map(|code| {
1849 #[cfg(unix)]
1850 {
1851 return std::os::unix::process::ExitStatusExt::from_raw(code);
1852 }
1853 #[cfg(windows)]
1854 {
1855 return std::os::windows::process::ExitStatusExt::from_raw(code as u32);
1856 }
1857 });
1858
1859 self.completion_tx.try_send(e).ok();
1860 let task = match &mut self.task {
1861 Some(task) => task,
1862 None => {
1863 if error_code.is_none() {
1864 cx.emit(Event::CloseTerminal);
1865 }
1866 return;
1867 }
1868 };
1869 if task.status != TaskStatus::Running {
1870 return;
1871 }
1872 match error_code {
1873 Some(error_code) => {
1874 task.status.register_task_exit(error_code);
1875 }
1876 None => {
1877 task.status.register_terminal_exit();
1878 }
1879 };
1880
1881 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1882 let mut lines_to_show = Vec::new();
1883 if task.show_summary {
1884 lines_to_show.push(task_line.as_str());
1885 }
1886 if task.show_command {
1887 lines_to_show.push(command_line.as_str());
1888 }
1889
1890 if !lines_to_show.is_empty() {
1891 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1892 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1893 // when Zed task finishes and no more output is made.
1894 // After the task summary is output once, no more text is appended to the terminal.
1895 unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1896 }
1897
1898 match task.hide {
1899 HideStrategy::Never => {}
1900 HideStrategy::Always => {
1901 cx.emit(Event::CloseTerminal);
1902 }
1903 HideStrategy::OnSuccess => {
1904 if finished_successfully {
1905 cx.emit(Event::CloseTerminal);
1906 }
1907 }
1908 }
1909 }
1910
1911 pub fn vi_mode_enabled(&self) -> bool {
1912 self.vi_mode_enabled
1913 }
1914}
1915
1916// Helper function to convert a grid row to a string
1917pub fn row_to_string(row: &Row<Cell>) -> String {
1918 row[..Column(row.len())]
1919 .iter()
1920 .map(|cell| cell.c)
1921 .collect::<String>()
1922}
1923
1924const TASK_DELIMITER: &str = "⏵ ";
1925fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1926 let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1927 let (success, task_line) = match error_code {
1928 Some(0) => (
1929 true,
1930 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
1931 ),
1932 Some(error_code) => (
1933 false,
1934 format!(
1935 "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
1936 ),
1937 ),
1938 None => (
1939 false,
1940 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
1941 ),
1942 };
1943 let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1944 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1945 (success, task_line, command_line)
1946}
1947
1948/// Appends a stringified task summary to the terminal, after its output.
1949///
1950/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1951/// New text being added to the terminal here, uses "less public" APIs,
1952/// which are not maintaining the entire terminal state intact.
1953///
1954///
1955/// The library
1956///
1957/// * does not increment inner grid cursor's _lines_ on `input` calls
1958/// (but displaying the lines correctly and incrementing cursor's columns)
1959///
1960/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1961///
1962/// * does not alter grid state after `newline` call
1963/// so its `bottommost_line` is always the same additions, and
1964/// the cursor's `point` is not updated to the new line and column values
1965///
1966/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1967/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1968///
1969/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1970/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1971/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1972/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1973unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1974 term.newline();
1975 term.grid_mut().cursor.point.column = Column(0);
1976 for line in text_lines {
1977 for c in line.chars() {
1978 term.input(c);
1979 }
1980 term.newline();
1981 term.grid_mut().cursor.point.column = Column(0);
1982 }
1983}
1984
1985impl Drop for Terminal {
1986 fn drop(&mut self) {
1987 self.pty_tx.0.send(Msg::Shutdown).ok();
1988 }
1989}
1990
1991impl EventEmitter<Event> for Terminal {}
1992
1993fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1994 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1995 selection.update(*range.end(), AlacDirection::Right);
1996 selection
1997}
1998
1999fn all_search_matches<'a, T>(
2000 term: &'a Term<T>,
2001 regex: &'a mut RegexSearch,
2002) -> impl Iterator<Item = Match> + 'a {
2003 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
2004 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
2005 RegexIter::new(start, end, AlacDirection::Right, term, regex)
2006}
2007
2008fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
2009 let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
2010 let clamped_col = min(col, terminal_bounds.columns() - 1);
2011 let row = (pos.y / terminal_bounds.line_height()).round() as usize;
2012 let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
2013 clamped_row * terminal_bounds.columns() + clamped_col
2014}
2015
2016/// Converts an 8 bit ANSI color to its GPUI equivalent.
2017/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
2018/// Other than that use case, should only be called with values in the `[0,255]` range
2019pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
2020 let colors = theme.colors();
2021
2022 match index {
2023 // 0-15 are the same as the named colors above
2024 0 => colors.terminal_ansi_black,
2025 1 => colors.terminal_ansi_red,
2026 2 => colors.terminal_ansi_green,
2027 3 => colors.terminal_ansi_yellow,
2028 4 => colors.terminal_ansi_blue,
2029 5 => colors.terminal_ansi_magenta,
2030 6 => colors.terminal_ansi_cyan,
2031 7 => colors.terminal_ansi_white,
2032 8 => colors.terminal_ansi_bright_black,
2033 9 => colors.terminal_ansi_bright_red,
2034 10 => colors.terminal_ansi_bright_green,
2035 11 => colors.terminal_ansi_bright_yellow,
2036 12 => colors.terminal_ansi_bright_blue,
2037 13 => colors.terminal_ansi_bright_magenta,
2038 14 => colors.terminal_ansi_bright_cyan,
2039 15 => colors.terminal_ansi_bright_white,
2040 // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
2041 // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
2042 16..=231 => {
2043 let (r, g, b) = rgb_for_index(index as u8);
2044 rgba_color(
2045 if r == 0 { 0 } else { r * 40 + 55 },
2046 if g == 0 { 0 } else { g * 40 + 55 },
2047 if b == 0 { 0 } else { b * 40 + 55 },
2048 )
2049 }
2050 // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
2051 232..=255 => {
2052 let i = index as u8 - 232; // Align index to 0..24
2053 let value = i * 10 + 8;
2054 rgba_color(value, value, value)
2055 }
2056 // For compatibility with the alacritty::Colors interface
2057 // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
2058 256 => colors.terminal_foreground,
2059 257 => colors.terminal_background,
2060 258 => theme.players().local().cursor,
2061 259 => colors.terminal_ansi_dim_black,
2062 260 => colors.terminal_ansi_dim_red,
2063 261 => colors.terminal_ansi_dim_green,
2064 262 => colors.terminal_ansi_dim_yellow,
2065 263 => colors.terminal_ansi_dim_blue,
2066 264 => colors.terminal_ansi_dim_magenta,
2067 265 => colors.terminal_ansi_dim_cyan,
2068 266 => colors.terminal_ansi_dim_white,
2069 267 => colors.terminal_bright_foreground,
2070 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2071
2072 _ => black(),
2073 }
2074}
2075
2076/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2077/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2078///
2079/// Wikipedia gives a formula for calculating the index for a given color:
2080///
2081/// ```
2082/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2083/// ```
2084///
2085/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2086fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2087 debug_assert!((16..=231).contains(&i));
2088 let i = i - 16;
2089 let r = (i - (i % 36)) / 36;
2090 let g = ((i % 36) - (i % 6)) / 6;
2091 let b = (i % 36) % 6;
2092 (r, g, b)
2093}
2094
2095pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2096 Rgba {
2097 r: (r as f32 / 255.),
2098 g: (g as f32 / 255.),
2099 b: (b as f32 / 255.),
2100 a: 1.,
2101 }
2102 .into()
2103}
2104
2105#[cfg(test)]
2106mod tests {
2107 use alacritty_terminal::{
2108 index::{Column, Line, Point as AlacPoint},
2109 term::cell::Cell,
2110 };
2111 use gpui::{Pixels, Point, bounds, point, size};
2112 use rand::{Rng, distributions::Alphanumeric, rngs::ThreadRng, thread_rng};
2113
2114 use crate::{
2115 IndexedCell, TerminalBounds, TerminalContent, content_index_for_mouse, rgb_for_index,
2116 };
2117
2118 #[test]
2119 fn test_rgb_for_index() {
2120 // Test every possible value in the color cube.
2121 for i in 16..=231 {
2122 let (r, g, b) = rgb_for_index(i);
2123 assert_eq!(i, 16 + 36 * r + 6 * g + b);
2124 }
2125 }
2126
2127 #[test]
2128 fn test_mouse_to_cell_test() {
2129 let mut rng = thread_rng();
2130 const ITERATIONS: usize = 10;
2131 const PRECISION: usize = 1000;
2132
2133 for _ in 0..ITERATIONS {
2134 let viewport_cells = rng.gen_range(15..20);
2135 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2136
2137 let size = crate::TerminalBounds {
2138 cell_width: Pixels::from(cell_size),
2139 line_height: Pixels::from(cell_size),
2140 bounds: bounds(
2141 Point::default(),
2142 size(
2143 Pixels::from(cell_size * (viewport_cells as f32)),
2144 Pixels::from(cell_size * (viewport_cells as f32)),
2145 ),
2146 ),
2147 };
2148
2149 let cells = get_cells(size, &mut rng);
2150 let content = convert_cells_to_content(size, &cells);
2151
2152 for row in 0..(viewport_cells - 1) {
2153 let row = row as usize;
2154 for col in 0..(viewport_cells - 1) {
2155 let col = col as usize;
2156
2157 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2158 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2159
2160 let mouse_pos = point(
2161 Pixels::from(col as f32 * cell_size + col_offset),
2162 Pixels::from(row as f32 * cell_size + row_offset),
2163 );
2164
2165 let content_index =
2166 content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2167 let mouse_cell = content.cells[content_index].c;
2168 let real_cell = cells[row][col];
2169
2170 assert_eq!(mouse_cell, real_cell);
2171 }
2172 }
2173 }
2174 }
2175
2176 #[test]
2177 fn test_mouse_to_cell_clamp() {
2178 let mut rng = thread_rng();
2179
2180 let size = crate::TerminalBounds {
2181 cell_width: Pixels::from(10.),
2182 line_height: Pixels::from(10.),
2183 bounds: bounds(
2184 Point::default(),
2185 size(Pixels::from(100.), Pixels::from(100.)),
2186 ),
2187 };
2188
2189 let cells = get_cells(size, &mut rng);
2190 let content = convert_cells_to_content(size, &cells);
2191
2192 assert_eq!(
2193 content.cells[content_index_for_mouse(
2194 point(Pixels::from(-10.), Pixels::from(-10.)),
2195 &content.terminal_bounds,
2196 )]
2197 .c,
2198 cells[0][0]
2199 );
2200 assert_eq!(
2201 content.cells[content_index_for_mouse(
2202 point(Pixels::from(1000.), Pixels::from(1000.)),
2203 &content.terminal_bounds,
2204 )]
2205 .c,
2206 cells[9][9]
2207 );
2208 }
2209
2210 fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2211 let mut cells = Vec::new();
2212
2213 for _ in 0..((size.height() / size.line_height()) as usize) {
2214 let mut row_vec = Vec::new();
2215 for _ in 0..((size.width() / size.cell_width()) as usize) {
2216 let cell_char = rng.sample(Alphanumeric) as char;
2217 row_vec.push(cell_char)
2218 }
2219 cells.push(row_vec)
2220 }
2221
2222 cells
2223 }
2224
2225 fn convert_cells_to_content(
2226 terminal_bounds: TerminalBounds,
2227 cells: &[Vec<char>],
2228 ) -> TerminalContent {
2229 let mut ic = Vec::new();
2230
2231 for (index, row) in cells.iter().enumerate() {
2232 for (cell_index, cell_char) in row.iter().enumerate() {
2233 ic.push(IndexedCell {
2234 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2235 cell: Cell {
2236 c: *cell_char,
2237 ..Default::default()
2238 },
2239 });
2240 }
2241 }
2242
2243 TerminalContent {
2244 cells: ic,
2245 terminal_bounds,
2246 ..Default::default()
2247 }
2248 }
2249}