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::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
538 #[cfg(any(test, feature = "test-support"))]
539 let mut timer = cx.background_executor().simulate_random_delay().fuse();
540 #[cfg(not(any(test, feature = "test-support")))]
541 let mut timer = cx
542 .background_executor()
543 .timer(std::time::Duration::from_millis(4))
544 .fuse();
545
546 let mut wakeup = false;
547 loop {
548 futures::select_biased! {
549 _ = timer => break,
550 event = self.events_rx.next() => {
551 if let Some(event) = event {
552 if matches!(event, AlacTermEvent::Wakeup) {
553 wakeup = true;
554 } else {
555 events.push(event);
556 }
557
558 if events.len() > 100 {
559 break;
560 }
561 } else {
562 break;
563 }
564 },
565 }
566 }
567
568 if events.is_empty() && !wakeup {
569 smol::future::yield_now().await;
570 break 'outer;
571 }
572
573 terminal.update(cx, |this, cx| {
574 if wakeup {
575 this.process_event(AlacTermEvent::Wakeup, cx);
576 }
577
578 for event in events {
579 this.process_event(event, cx);
580 }
581 })?;
582 smol::future::yield_now().await;
583 }
584 }
585
586 anyhow::Ok(())
587 })
588 .detach();
589
590 self.terminal
591 }
592}
593
594#[derive(Debug, Clone, Deserialize, Serialize)]
595pub struct IndexedCell {
596 pub point: AlacPoint,
597 pub cell: Cell,
598}
599
600impl Deref for IndexedCell {
601 type Target = Cell;
602
603 #[inline]
604 fn deref(&self) -> &Cell {
605 &self.cell
606 }
607}
608
609// TODO: Un-pub
610#[derive(Clone)]
611pub struct TerminalContent {
612 pub cells: Vec<IndexedCell>,
613 pub mode: TermMode,
614 pub display_offset: usize,
615 pub selection_text: Option<String>,
616 pub selection: Option<SelectionRange>,
617 pub cursor: RenderableCursor,
618 pub cursor_char: char,
619 pub terminal_bounds: TerminalBounds,
620 pub last_hovered_word: Option<HoveredWord>,
621 pub scrolled_to_top: bool,
622 pub scrolled_to_bottom: bool,
623}
624
625#[derive(Debug, Clone, Eq, PartialEq)]
626pub struct HoveredWord {
627 pub word: String,
628 pub word_match: RangeInclusive<AlacPoint>,
629 pub id: usize,
630}
631
632impl Default for TerminalContent {
633 fn default() -> Self {
634 TerminalContent {
635 cells: Default::default(),
636 mode: Default::default(),
637 display_offset: Default::default(),
638 selection_text: Default::default(),
639 selection: Default::default(),
640 cursor: RenderableCursor {
641 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
642 point: AlacPoint::new(Line(0), Column(0)),
643 },
644 cursor_char: Default::default(),
645 terminal_bounds: Default::default(),
646 last_hovered_word: None,
647 scrolled_to_top: false,
648 scrolled_to_bottom: false,
649 }
650 }
651}
652
653#[derive(PartialEq, Eq)]
654pub enum SelectionPhase {
655 Selecting,
656 Ended,
657}
658
659pub struct Terminal {
660 pty_tx: Notifier,
661 completion_tx: Sender<Option<ExitStatus>>,
662 term: Arc<FairMutex<Term<ZedListener>>>,
663 term_config: Config,
664 events: VecDeque<InternalEvent>,
665 /// This is only used for mouse mode cell change detection
666 last_mouse: Option<(AlacPoint, AlacDirection)>,
667 pub matches: Vec<RangeInclusive<AlacPoint>>,
668 pub last_content: TerminalContent,
669 pub selection_head: Option<AlacPoint>,
670 pub breadcrumb_text: String,
671 pub pty_info: PtyProcessInfo,
672 title_override: Option<SharedString>,
673 pub python_venv_directory: Option<PathBuf>,
674 scroll_px: Pixels,
675 next_link_id: usize,
676 selection_phase: SelectionPhase,
677 hyperlink_regex_searches: RegexSearches,
678 task: Option<TaskState>,
679 vi_mode_enabled: bool,
680 is_ssh_terminal: bool,
681 last_mouse_move_time: Instant,
682 last_hyperlink_search_position: Option<Point<Pixels>>,
683 #[cfg(windows)]
684 shell_program: Option<String>,
685}
686
687pub struct TaskState {
688 pub id: TaskId,
689 pub full_label: String,
690 pub label: String,
691 pub command_label: String,
692 pub status: TaskStatus,
693 pub completion_rx: Receiver<Option<ExitStatus>>,
694 pub hide: HideStrategy,
695 pub show_summary: bool,
696 pub show_command: bool,
697 pub show_rerun: bool,
698}
699
700/// A status of the current terminal tab's task.
701#[derive(Debug, Clone, Copy, PartialEq, Eq)]
702pub enum TaskStatus {
703 /// The task had been started, but got cancelled or somehow otherwise it did not
704 /// report its exit code before the terminal event loop was shut down.
705 Unknown,
706 /// The task is started and running currently.
707 Running,
708 /// After the start, the task stopped running and reported its error code back.
709 Completed { success: bool },
710}
711
712impl TaskStatus {
713 fn register_terminal_exit(&mut self) {
714 if self == &Self::Running {
715 *self = Self::Unknown;
716 }
717 }
718
719 fn register_task_exit(&mut self, error_code: i32) {
720 *self = TaskStatus::Completed {
721 success: error_code == 0,
722 };
723 }
724}
725
726impl Terminal {
727 fn process_event(&mut self, event: AlacTermEvent, cx: &mut Context<Self>) {
728 match event {
729 AlacTermEvent::Title(title) => {
730 // ignore default shell program title change as windows always sends those events
731 // and it would end up showing the shell executable path in breadcrumbs
732 #[cfg(windows)]
733 {
734 if self
735 .shell_program
736 .as_ref()
737 .map(|e| *e == title)
738 .unwrap_or(false)
739 {
740 return;
741 }
742 }
743
744 self.breadcrumb_text = title;
745 cx.emit(Event::BreadcrumbsChanged);
746 }
747 AlacTermEvent::ResetTitle => {
748 self.breadcrumb_text = String::new();
749 cx.emit(Event::BreadcrumbsChanged);
750 }
751 AlacTermEvent::ClipboardStore(_, data) => {
752 cx.write_to_clipboard(ClipboardItem::new_string(data))
753 }
754 AlacTermEvent::ClipboardLoad(_, format) => {
755 self.write_to_pty(
756 match &cx.read_from_clipboard().and_then(|item| item.text()) {
757 // The terminal only supports pasting strings, not images.
758 Some(text) => format(text),
759 _ => format(""),
760 }
761 .into_bytes(),
762 )
763 }
764 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.into_bytes()),
765 AlacTermEvent::TextAreaSizeRequest(format) => {
766 self.write_to_pty(format(self.last_content.terminal_bounds.into()).into_bytes())
767 }
768 AlacTermEvent::CursorBlinkingChange => {
769 let terminal = self.term.lock();
770 let blinking = terminal.cursor_style().blinking;
771 cx.emit(Event::BlinkChanged(blinking));
772 }
773 AlacTermEvent::Bell => {
774 cx.emit(Event::Bell);
775 }
776 AlacTermEvent::Exit => self.register_task_finished(None, cx),
777 AlacTermEvent::MouseCursorDirty => {
778 //NOOP, Handled in render
779 }
780 AlacTermEvent::Wakeup => {
781 cx.emit(Event::Wakeup);
782
783 if self.pty_info.has_changed() {
784 cx.emit(Event::TitleChanged);
785 }
786 }
787 AlacTermEvent::ColorRequest(index, format) => {
788 // It's important that the color request is processed here to retain relative order
789 // with other PTY writes. Otherwise applications might witness out-of-order
790 // responses to requests. For example: An application sending `OSC 11 ; ? ST`
791 // (color request) followed by `CSI c` (request device attributes) would receive
792 // the response to `CSI c` first.
793 // Instead of locking, we could store the colors in `self.last_content`. But then
794 // we might respond with out of date value if a "set color" sequence is immediately
795 // followed by a color request sequence.
796 let color = self.term.lock().colors()[index]
797 .unwrap_or_else(|| to_alac_rgb(get_color_at_index(index, cx.theme().as_ref())));
798 self.write_to_pty(format(color).into_bytes());
799 }
800 AlacTermEvent::ChildExit(error_code) => {
801 self.register_task_finished(Some(error_code), cx);
802 }
803 }
804 }
805
806 pub fn selection_started(&self) -> bool {
807 self.selection_phase == SelectionPhase::Selecting
808 }
809
810 fn process_terminal_event(
811 &mut self,
812 event: &InternalEvent,
813 term: &mut Term<ZedListener>,
814 window: &mut Window,
815 cx: &mut Context<Self>,
816 ) {
817 match event {
818 &InternalEvent::Resize(mut new_bounds) => {
819 new_bounds.bounds.size.height =
820 cmp::max(new_bounds.line_height, new_bounds.height());
821 new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
822
823 self.last_content.terminal_bounds = new_bounds;
824
825 self.pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
826
827 term.resize(new_bounds);
828 }
829 InternalEvent::Clear => {
830 // Clear back buffer
831 term.clear_screen(ClearMode::Saved);
832
833 let cursor = term.grid().cursor.point;
834
835 // Clear the lines above
836 term.grid_mut().reset_region(..cursor.line);
837
838 // Copy the current line up
839 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
840 .iter()
841 .cloned()
842 .enumerate()
843 .collect::<Vec<(usize, Cell)>>();
844
845 for (i, cell) in line {
846 term.grid_mut()[Line(0)][Column(i)] = cell;
847 }
848
849 // Reset the cursor
850 term.grid_mut().cursor.point =
851 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
852 let new_cursor = term.grid().cursor.point;
853
854 // Clear the lines below the new cursor
855 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
856 term.grid_mut().reset_region((new_cursor.line + 1)..);
857 }
858
859 cx.emit(Event::Wakeup);
860 }
861 InternalEvent::Scroll(scroll) => {
862 term.scroll_display(*scroll);
863 self.refresh_hovered_word(window);
864
865 if self.vi_mode_enabled {
866 match *scroll {
867 AlacScroll::Delta(delta) => {
868 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
869 }
870 AlacScroll::PageUp => {
871 let lines = term.screen_lines() as i32;
872 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
873 }
874 AlacScroll::PageDown => {
875 let lines = -(term.screen_lines() as i32);
876 term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
877 }
878 AlacScroll::Top => {
879 let point = AlacPoint::new(term.topmost_line(), Column(0));
880 term.vi_mode_cursor = ViModeCursor::new(point);
881 }
882 AlacScroll::Bottom => {
883 let point = AlacPoint::new(term.bottommost_line(), Column(0));
884 term.vi_mode_cursor = ViModeCursor::new(point);
885 }
886 }
887 if let Some(mut selection) = term.selection.take() {
888 let point = term.vi_mode_cursor.point;
889 selection.update(point, AlacDirection::Right);
890 term.selection = Some(selection);
891
892 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
893 if let Some(selection_text) = term.selection_to_string() {
894 cx.write_to_primary(ClipboardItem::new_string(selection_text));
895 }
896
897 self.selection_head = Some(point);
898 cx.emit(Event::SelectionsChanged)
899 }
900 }
901 }
902 InternalEvent::SetSelection(selection) => {
903 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
904
905 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
906 if let Some(selection_text) = term.selection_to_string() {
907 cx.write_to_primary(ClipboardItem::new_string(selection_text));
908 }
909
910 if let Some((_, head)) = selection {
911 self.selection_head = Some(*head);
912 }
913 cx.emit(Event::SelectionsChanged)
914 }
915 InternalEvent::UpdateSelection(position) => {
916 if let Some(mut selection) = term.selection.take() {
917 let (point, side) = grid_point_and_side(
918 *position,
919 self.last_content.terminal_bounds,
920 term.grid().display_offset(),
921 );
922
923 selection.update(point, side);
924 term.selection = Some(selection);
925
926 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
927 if let Some(selection_text) = term.selection_to_string() {
928 cx.write_to_primary(ClipboardItem::new_string(selection_text));
929 }
930
931 self.selection_head = Some(point);
932 cx.emit(Event::SelectionsChanged)
933 }
934 }
935
936 InternalEvent::Copy(keep_selection) => {
937 if let Some(txt) = term.selection_to_string() {
938 cx.write_to_clipboard(ClipboardItem::new_string(txt));
939 if !keep_selection.unwrap_or_else(|| {
940 let settings = TerminalSettings::get_global(cx);
941 settings.keep_selection_on_copy
942 }) {
943 self.events.push_back(InternalEvent::SetSelection(None));
944 }
945 }
946 }
947 InternalEvent::ScrollToAlacPoint(point) => {
948 term.scroll_to_point(*point);
949 self.refresh_hovered_word(window);
950 }
951 InternalEvent::ToggleViMode => {
952 self.vi_mode_enabled = !self.vi_mode_enabled;
953 term.toggle_vi_mode();
954 }
955 InternalEvent::ViMotion(motion) => {
956 term.vi_motion(*motion);
957 }
958 InternalEvent::FindHyperlink(position, open) => {
959 let prev_hovered_word = self.last_content.last_hovered_word.take();
960
961 let point = grid_point(
962 *position,
963 self.last_content.terminal_bounds,
964 term.grid().display_offset(),
965 )
966 .grid_clamp(term, Boundary::Grid);
967
968 match terminal_hyperlinks::find_from_grid_point(
969 term,
970 point,
971 &mut self.hyperlink_regex_searches,
972 ) {
973 Some((maybe_url_or_path, is_url, url_match)) => {
974 let target = if is_url {
975 // Treat "file://" URLs like file paths to ensure
976 // that line numbers at the end of the path are
977 // handled correctly.
978 // file://{path} should be urldecoded, returning a urldecoded {path}
979 if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
980 let decoded_path = urlencoding::decode(path)
981 .map(|decoded| decoded.into_owned())
982 .unwrap_or(path.to_owned());
983
984 MaybeNavigationTarget::PathLike(PathLikeTarget {
985 maybe_path: decoded_path,
986 terminal_dir: self.working_directory(),
987 })
988 } else {
989 MaybeNavigationTarget::Url(maybe_url_or_path.clone())
990 }
991 } else {
992 MaybeNavigationTarget::PathLike(PathLikeTarget {
993 maybe_path: maybe_url_or_path.clone(),
994 terminal_dir: self.working_directory(),
995 })
996 };
997 if *open {
998 cx.emit(Event::Open(target));
999 } else {
1000 self.update_selected_word(
1001 prev_hovered_word,
1002 url_match,
1003 maybe_url_or_path,
1004 target,
1005 cx,
1006 );
1007 }
1008 }
1009 None => {
1010 cx.emit(Event::NewNavigationTarget(None));
1011 }
1012 }
1013 }
1014 }
1015 }
1016
1017 fn update_selected_word(
1018 &mut self,
1019 prev_word: Option<HoveredWord>,
1020 word_match: RangeInclusive<AlacPoint>,
1021 word: String,
1022 navigation_target: MaybeNavigationTarget,
1023 cx: &mut Context<Self>,
1024 ) {
1025 if let Some(prev_word) = prev_word {
1026 if prev_word.word == word && prev_word.word_match == word_match {
1027 self.last_content.last_hovered_word = Some(HoveredWord {
1028 word,
1029 word_match,
1030 id: prev_word.id,
1031 });
1032 return;
1033 }
1034 }
1035
1036 self.last_content.last_hovered_word = Some(HoveredWord {
1037 word,
1038 word_match,
1039 id: self.next_link_id(),
1040 });
1041 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1042 cx.notify()
1043 }
1044
1045 fn next_link_id(&mut self) -> usize {
1046 let res = self.next_link_id;
1047 self.next_link_id = self.next_link_id.wrapping_add(1);
1048 res
1049 }
1050
1051 pub fn last_content(&self) -> &TerminalContent {
1052 &self.last_content
1053 }
1054
1055 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1056 self.term_config.default_cursor_style = cursor_shape.into();
1057 self.term.lock().set_options(self.term_config.clone());
1058 }
1059
1060 pub fn total_lines(&self) -> usize {
1061 let term = self.term.clone();
1062 let terminal = term.lock_unfair();
1063 terminal.total_lines()
1064 }
1065
1066 pub fn viewport_lines(&self) -> usize {
1067 let term = self.term.clone();
1068 let terminal = term.lock_unfair();
1069 terminal.screen_lines()
1070 }
1071
1072 //To test:
1073 //- Activate match on terminal (scrolling and selection)
1074 //- Editor search snapping behavior
1075
1076 pub fn activate_match(&mut self, index: usize) {
1077 if let Some(search_match) = self.matches.get(index).cloned() {
1078 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1079
1080 self.events
1081 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1082 }
1083 }
1084
1085 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1086 let matches_to_select = self
1087 .matches
1088 .iter()
1089 .filter(|self_match| matches.contains(self_match))
1090 .cloned()
1091 .collect::<Vec<_>>();
1092 for match_to_select in matches_to_select {
1093 self.set_selection(Some((
1094 make_selection(&match_to_select),
1095 *match_to_select.end(),
1096 )));
1097 }
1098 }
1099
1100 pub fn select_all(&mut self) {
1101 let term = self.term.lock();
1102 let start = AlacPoint::new(term.topmost_line(), Column(0));
1103 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1104 drop(term);
1105 self.set_selection(Some((make_selection(&(start..=end)), end)));
1106 }
1107
1108 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1109 self.events
1110 .push_back(InternalEvent::SetSelection(selection));
1111 }
1112
1113 pub fn copy(&mut self, keep_selection: Option<bool>) {
1114 self.events.push_back(InternalEvent::Copy(keep_selection));
1115 }
1116
1117 pub fn clear(&mut self) {
1118 self.events.push_back(InternalEvent::Clear)
1119 }
1120
1121 pub fn scroll_line_up(&mut self) {
1122 self.events
1123 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1124 }
1125
1126 pub fn scroll_up_by(&mut self, lines: usize) {
1127 self.events
1128 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1129 }
1130
1131 pub fn scroll_line_down(&mut self) {
1132 self.events
1133 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1134 }
1135
1136 pub fn scroll_down_by(&mut self, lines: usize) {
1137 self.events
1138 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1139 }
1140
1141 pub fn scroll_page_up(&mut self) {
1142 self.events
1143 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1144 }
1145
1146 pub fn scroll_page_down(&mut self) {
1147 self.events
1148 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1149 }
1150
1151 pub fn scroll_to_top(&mut self) {
1152 self.events
1153 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1154 }
1155
1156 pub fn scroll_to_bottom(&mut self) {
1157 self.events
1158 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1159 }
1160
1161 pub fn scrolled_to_top(&self) -> bool {
1162 self.last_content.scrolled_to_top
1163 }
1164
1165 pub fn scrolled_to_bottom(&self) -> bool {
1166 self.last_content.scrolled_to_bottom
1167 }
1168
1169 ///Resize the terminal and the PTY.
1170 pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1171 if self.last_content.terminal_bounds != new_bounds {
1172 self.events.push_back(InternalEvent::Resize(new_bounds))
1173 }
1174 }
1175
1176 ///Write the Input payload to the tty.
1177 fn write_to_pty(&self, input: impl Into<Cow<'static, [u8]>>) {
1178 self.pty_tx.notify(input.into());
1179 }
1180
1181 pub fn input(&mut self, input: impl Into<Cow<'static, [u8]>>) {
1182 self.events
1183 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1184 self.events.push_back(InternalEvent::SetSelection(None));
1185
1186 self.write_to_pty(input);
1187 }
1188
1189 pub fn toggle_vi_mode(&mut self) {
1190 self.events.push_back(InternalEvent::ToggleViMode);
1191 }
1192
1193 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1194 if !self.vi_mode_enabled {
1195 return;
1196 }
1197
1198 let key: Cow<'_, str> = if keystroke.modifiers.shift {
1199 Cow::Owned(keystroke.key.to_uppercase())
1200 } else {
1201 Cow::Borrowed(keystroke.key.as_str())
1202 };
1203
1204 let motion: Option<ViMotion> = match key.as_ref() {
1205 "h" | "left" => Some(ViMotion::Left),
1206 "j" | "down" => Some(ViMotion::Down),
1207 "k" | "up" => Some(ViMotion::Up),
1208 "l" | "right" => Some(ViMotion::Right),
1209 "w" => Some(ViMotion::WordRight),
1210 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1211 "e" => Some(ViMotion::WordRightEnd),
1212 "%" => Some(ViMotion::Bracket),
1213 "$" => Some(ViMotion::Last),
1214 "0" => Some(ViMotion::First),
1215 "^" => Some(ViMotion::FirstOccupied),
1216 "H" => Some(ViMotion::High),
1217 "M" => Some(ViMotion::Middle),
1218 "L" => Some(ViMotion::Low),
1219 _ => None,
1220 };
1221
1222 if let Some(motion) = motion {
1223 let cursor = self.last_content.cursor.point;
1224 let cursor_pos = Point {
1225 x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1226 y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1227 };
1228 self.events
1229 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1230 self.events.push_back(InternalEvent::ViMotion(motion));
1231 return;
1232 }
1233
1234 let scroll_motion = match key.as_ref() {
1235 "g" => Some(AlacScroll::Top),
1236 "G" => Some(AlacScroll::Bottom),
1237 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1238 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1239 "d" if keystroke.modifiers.control => {
1240 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1241 Some(AlacScroll::Delta(-amount))
1242 }
1243 "u" if keystroke.modifiers.control => {
1244 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1245 Some(AlacScroll::Delta(amount))
1246 }
1247 _ => None,
1248 };
1249
1250 if let Some(scroll_motion) = scroll_motion {
1251 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1252 return;
1253 }
1254
1255 match key.as_ref() {
1256 "v" => {
1257 let point = self.last_content.cursor.point;
1258 let selection_type = SelectionType::Simple;
1259 let side = AlacDirection::Right;
1260 let selection = Selection::new(selection_type, point, side);
1261 self.events
1262 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1263 return;
1264 }
1265
1266 "escape" => {
1267 self.events.push_back(InternalEvent::SetSelection(None));
1268 return;
1269 }
1270
1271 "y" => {
1272 self.copy(Some(false));
1273 return;
1274 }
1275
1276 "i" => {
1277 self.scroll_to_bottom();
1278 self.toggle_vi_mode();
1279 return;
1280 }
1281 _ => {}
1282 }
1283 }
1284
1285 pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1286 if self.vi_mode_enabled {
1287 self.vi_motion(keystroke);
1288 return true;
1289 }
1290
1291 // Keep default terminal behavior
1292 let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1293 if let Some(esc) = esc {
1294 match esc {
1295 Cow::Borrowed(string) => self.input(string.as_bytes()),
1296 Cow::Owned(string) => self.input(string.into_bytes()),
1297 };
1298 true
1299 } else {
1300 false
1301 }
1302 }
1303
1304 pub fn try_modifiers_change(
1305 &mut self,
1306 modifiers: &Modifiers,
1307 window: &Window,
1308 cx: &mut Context<Self>,
1309 ) {
1310 if self
1311 .last_content
1312 .terminal_bounds
1313 .bounds
1314 .contains(&window.mouse_position())
1315 && modifiers.secondary()
1316 {
1317 self.refresh_hovered_word(window);
1318 }
1319 cx.notify();
1320 }
1321
1322 ///Paste text into the terminal
1323 pub fn paste(&mut self, text: &str) {
1324 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1325 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1326 } else {
1327 text.replace("\r\n", "\r").replace('\n', "\r")
1328 };
1329
1330 self.input(paste_text.into_bytes());
1331 }
1332
1333 pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1334 let term = self.term.clone();
1335 let mut terminal = term.lock_unfair();
1336 //Note that the ordering of events matters for event processing
1337 while let Some(e) = self.events.pop_front() {
1338 self.process_terminal_event(&e, &mut terminal, window, cx)
1339 }
1340
1341 self.last_content = Self::make_content(&terminal, &self.last_content);
1342 }
1343
1344 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1345 let content = term.renderable_content();
1346
1347 // Pre-allocate with estimated size to reduce reallocations
1348 let estimated_size = content.display_iter.size_hint().0;
1349 let mut cells = Vec::with_capacity(estimated_size);
1350
1351 cells.extend(content.display_iter.map(|ic| IndexedCell {
1352 point: ic.point,
1353 cell: ic.cell.clone(),
1354 }));
1355
1356 let selection_text = if content.selection.is_some() {
1357 term.selection_to_string()
1358 } else {
1359 None
1360 };
1361
1362 TerminalContent {
1363 cells,
1364 mode: content.mode,
1365 display_offset: content.display_offset,
1366 selection_text,
1367 selection: content.selection,
1368 cursor: content.cursor,
1369 cursor_char: term.grid()[content.cursor.point].c,
1370 terminal_bounds: last_content.terminal_bounds,
1371 last_hovered_word: last_content.last_hovered_word.clone(),
1372 scrolled_to_top: content.display_offset == term.history_size(),
1373 scrolled_to_bottom: content.display_offset == 0,
1374 }
1375 }
1376
1377 pub fn get_content(&self) -> String {
1378 let term = self.term.lock_unfair();
1379 let start = AlacPoint::new(term.topmost_line(), Column(0));
1380 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1381 term.bounds_to_string(start, end)
1382 }
1383
1384 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1385 let term = self.term.clone();
1386 let terminal = term.lock_unfair();
1387 let grid = terminal.grid();
1388 let mut lines = Vec::new();
1389
1390 let mut current_line = grid.bottommost_line().0;
1391 let topmost_line = grid.topmost_line().0;
1392
1393 while current_line >= topmost_line && lines.len() < n {
1394 let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1395 let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1396
1397 if let Some(line) = self.process_line(logical_line) {
1398 lines.push(line);
1399 }
1400
1401 // Move to the line above the start of the current logical line
1402 current_line = logical_line_start - 1;
1403 }
1404
1405 lines.reverse();
1406 lines
1407 }
1408
1409 fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1410 let mut line_start = current;
1411 while line_start > topmost {
1412 let prev_line = Line(line_start - 1);
1413 let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1414 if !last_cell.flags.contains(Flags::WRAPLINE) {
1415 break;
1416 }
1417 line_start -= 1;
1418 }
1419 line_start
1420 }
1421
1422 fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1423 let mut logical_line = String::new();
1424 for row in start..=end {
1425 let grid_row = &grid[Line(row)];
1426 logical_line.push_str(&row_to_string(grid_row));
1427 }
1428 logical_line
1429 }
1430
1431 fn process_line(&self, line: String) -> Option<String> {
1432 let trimmed = line.trim_end().to_string();
1433 if !trimmed.is_empty() {
1434 Some(trimmed)
1435 } else {
1436 None
1437 }
1438 }
1439
1440 pub fn focus_in(&self) {
1441 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1442 self.write_to_pty("\x1b[I".as_bytes());
1443 }
1444 }
1445
1446 pub fn focus_out(&mut self) {
1447 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1448 self.write_to_pty("\x1b[O".as_bytes());
1449 }
1450 }
1451
1452 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1453 match self.last_mouse {
1454 Some((old_point, old_side)) => {
1455 if old_point == point && old_side == side {
1456 false
1457 } else {
1458 self.last_mouse = Some((point, side));
1459 true
1460 }
1461 }
1462 None => {
1463 self.last_mouse = Some((point, side));
1464 true
1465 }
1466 }
1467 }
1468
1469 pub fn mouse_mode(&self, shift: bool) -> bool {
1470 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1471 }
1472
1473 pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1474 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1475 if self.mouse_mode(e.modifiers.shift) {
1476 let (point, side) = grid_point_and_side(
1477 position,
1478 self.last_content.terminal_bounds,
1479 self.last_content.display_offset,
1480 );
1481
1482 if self.mouse_changed(point, side) {
1483 if let Some(bytes) =
1484 mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1485 {
1486 self.pty_tx.notify(bytes);
1487 }
1488 }
1489 } else if e.modifiers.secondary() {
1490 self.word_from_position(e.position);
1491 }
1492 cx.notify();
1493 }
1494
1495 fn word_from_position(&mut self, position: Point<Pixels>) {
1496 if self.selection_phase == SelectionPhase::Selecting {
1497 self.last_content.last_hovered_word = None;
1498 } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1499 // Throttle hyperlink searches to avoid excessive processing
1500 let now = Instant::now();
1501 let should_search = if let Some(last_pos) = self.last_hyperlink_search_position {
1502 // Only search if mouse moved significantly or enough time passed
1503 let distance_moved =
1504 ((position.x - last_pos.x).abs() + (position.y - last_pos.y).abs()) > px(5.0);
1505 let time_elapsed = now.duration_since(self.last_mouse_move_time).as_millis() > 100;
1506 distance_moved || time_elapsed
1507 } else {
1508 true
1509 };
1510
1511 if should_search {
1512 self.last_mouse_move_time = now;
1513 self.last_hyperlink_search_position = Some(position);
1514 self.events.push_back(InternalEvent::FindHyperlink(
1515 position - self.last_content.terminal_bounds.bounds.origin,
1516 false,
1517 ));
1518 }
1519 } else {
1520 self.last_content.last_hovered_word = None;
1521 }
1522 }
1523
1524 pub fn select_word_at_event_position(&mut self, e: &MouseDownEvent) {
1525 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1526 let (point, side) = grid_point_and_side(
1527 position,
1528 self.last_content.terminal_bounds,
1529 self.last_content.display_offset,
1530 );
1531 let selection = Selection::new(SelectionType::Semantic, point, side);
1532 self.events
1533 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1534 }
1535
1536 pub fn mouse_drag(
1537 &mut self,
1538 e: &MouseMoveEvent,
1539 region: Bounds<Pixels>,
1540 cx: &mut Context<Self>,
1541 ) {
1542 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1543 if !self.mouse_mode(e.modifiers.shift) {
1544 self.selection_phase = SelectionPhase::Selecting;
1545 // Alacritty has the same ordering, of first updating the selection
1546 // then scrolling 15ms later
1547 self.events
1548 .push_back(InternalEvent::UpdateSelection(position));
1549
1550 // Doesn't make sense to scroll the alt screen
1551 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1552 let scroll_lines = match self.drag_line_delta(e, region) {
1553 Some(value) => value,
1554 None => return,
1555 };
1556
1557 self.events
1558 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1559 }
1560
1561 cx.notify();
1562 }
1563 }
1564
1565 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1566 let top = region.origin.y;
1567 let bottom = region.bottom_left().y;
1568
1569 let scroll_lines = if e.position.y < top {
1570 let scroll_delta = (top - e.position.y).pow(1.1);
1571 (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1572 } else if e.position.y > bottom {
1573 let scroll_delta = -((e.position.y - bottom).pow(1.1));
1574 (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1575 } else {
1576 return None;
1577 };
1578
1579 Some(scroll_lines.clamp(-3, 3))
1580 }
1581
1582 pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1583 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1584 let point = grid_point(
1585 position,
1586 self.last_content.terminal_bounds,
1587 self.last_content.display_offset,
1588 );
1589
1590 if self.mouse_mode(e.modifiers.shift) {
1591 if let Some(bytes) =
1592 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1593 {
1594 self.pty_tx.notify(bytes);
1595 }
1596 } else {
1597 match e.button {
1598 MouseButton::Left => {
1599 let (point, side) = grid_point_and_side(
1600 position,
1601 self.last_content.terminal_bounds,
1602 self.last_content.display_offset,
1603 );
1604
1605 let selection_type = match e.click_count {
1606 0 => return, //This is a release
1607 1 => Some(SelectionType::Simple),
1608 2 => Some(SelectionType::Semantic),
1609 3 => Some(SelectionType::Lines),
1610 _ => None,
1611 };
1612
1613 if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1614 self.events
1615 .push_back(InternalEvent::UpdateSelection(position));
1616 return;
1617 }
1618
1619 let selection = selection_type
1620 .map(|selection_type| Selection::new(selection_type, point, side));
1621
1622 if let Some(sel) = selection {
1623 self.events
1624 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1625 }
1626 }
1627 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1628 MouseButton::Middle => {
1629 if let Some(item) = _cx.read_from_primary() {
1630 let text = item.text().unwrap_or_default().to_string();
1631 self.input(text.into_bytes());
1632 }
1633 }
1634 _ => {}
1635 }
1636 }
1637 }
1638
1639 pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1640 let setting = TerminalSettings::get_global(cx);
1641
1642 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1643 if self.mouse_mode(e.modifiers.shift) {
1644 let point = grid_point(
1645 position,
1646 self.last_content.terminal_bounds,
1647 self.last_content.display_offset,
1648 );
1649
1650 if let Some(bytes) =
1651 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1652 {
1653 self.pty_tx.notify(bytes);
1654 }
1655 } else {
1656 if e.button == MouseButton::Left && setting.copy_on_select {
1657 self.copy(Some(true));
1658 }
1659
1660 //Hyperlinks
1661 if self.selection_phase == SelectionPhase::Ended {
1662 let mouse_cell_index =
1663 content_index_for_mouse(position, &self.last_content.terminal_bounds);
1664 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1665 cx.open_url(link.uri());
1666 } else if e.modifiers.secondary() {
1667 self.events
1668 .push_back(InternalEvent::FindHyperlink(position, true));
1669 }
1670 }
1671 }
1672
1673 self.selection_phase = SelectionPhase::Ended;
1674 self.last_mouse = None;
1675 }
1676
1677 ///Scroll the terminal
1678 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1679 let mouse_mode = self.mouse_mode(e.shift);
1680
1681 if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1682 if mouse_mode {
1683 let point = grid_point(
1684 e.position - self.last_content.terminal_bounds.bounds.origin,
1685 self.last_content.terminal_bounds,
1686 self.last_content.display_offset,
1687 );
1688
1689 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1690 {
1691 for scroll in scrolls {
1692 self.pty_tx.notify(scroll);
1693 }
1694 };
1695 } else if self
1696 .last_content
1697 .mode
1698 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1699 && !e.shift
1700 {
1701 self.pty_tx.notify(alt_scroll(scroll_lines))
1702 } else if scroll_lines != 0 {
1703 let scroll = AlacScroll::Delta(scroll_lines);
1704
1705 self.events.push_back(InternalEvent::Scroll(scroll));
1706 }
1707 }
1708 }
1709
1710 fn refresh_hovered_word(&mut self, window: &Window) {
1711 self.word_from_position(window.mouse_position());
1712 }
1713
1714 fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1715 let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1716 let line_height = self.last_content.terminal_bounds.line_height;
1717 match e.touch_phase {
1718 /* Reset scroll state on started */
1719 TouchPhase::Started => {
1720 self.scroll_px = px(0.);
1721 None
1722 }
1723 /* Calculate the appropriate scroll lines */
1724 TouchPhase::Moved => {
1725 let old_offset = (self.scroll_px / line_height) as i32;
1726
1727 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1728
1729 let new_offset = (self.scroll_px / line_height) as i32;
1730
1731 // Whenever we hit the edges, reset our stored scroll to 0
1732 // so we can respond to changes in direction quickly
1733 self.scroll_px %= self.last_content.terminal_bounds.height();
1734
1735 Some(new_offset - old_offset)
1736 }
1737 TouchPhase::Ended => None,
1738 }
1739 }
1740
1741 pub fn find_matches(
1742 &self,
1743 mut searcher: RegexSearch,
1744 cx: &Context<Self>,
1745 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1746 let term = self.term.clone();
1747 cx.background_spawn(async move {
1748 let term = term.lock();
1749
1750 all_search_matches(&term, &mut searcher).collect()
1751 })
1752 }
1753
1754 pub fn working_directory(&self) -> Option<PathBuf> {
1755 if self.is_ssh_terminal {
1756 // We can't yet reliably detect the working directory of a shell on the
1757 // SSH host. Until we can do that, it doesn't make sense to display
1758 // the working directory on the client and persist that.
1759 None
1760 } else {
1761 self.client_side_working_directory()
1762 }
1763 }
1764
1765 /// Returns the working directory of the process that's connected to the PTY.
1766 /// That means it returns the working directory of the local shell or program
1767 /// that's running inside the terminal.
1768 ///
1769 /// This does *not* return the working directory of the shell that runs on the
1770 /// remote host, in case Zed is connected to a remote host.
1771 fn client_side_working_directory(&self) -> Option<PathBuf> {
1772 self.pty_info
1773 .current
1774 .as_ref()
1775 .map(|process| process.cwd.clone())
1776 }
1777
1778 pub fn title(&self, truncate: bool) -> String {
1779 const MAX_CHARS: usize = 25;
1780 match &self.task {
1781 Some(task_state) => {
1782 if truncate {
1783 truncate_and_trailoff(&task_state.label, MAX_CHARS)
1784 } else {
1785 task_state.full_label.clone()
1786 }
1787 }
1788 None => self
1789 .title_override
1790 .as_ref()
1791 .map(|title_override| title_override.to_string())
1792 .unwrap_or_else(|| {
1793 self.pty_info
1794 .current
1795 .as_ref()
1796 .map(|fpi| {
1797 let process_file = fpi
1798 .cwd
1799 .file_name()
1800 .map(|name| name.to_string_lossy().to_string())
1801 .unwrap_or_default();
1802
1803 let argv = fpi.argv.as_slice();
1804 let process_name = format!(
1805 "{}{}",
1806 fpi.name,
1807 if !argv.is_empty() {
1808 format!(" {}", (argv[1..]).join(" "))
1809 } else {
1810 "".to_string()
1811 }
1812 );
1813 let (process_file, process_name) = if truncate {
1814 (
1815 truncate_and_trailoff(&process_file, MAX_CHARS),
1816 truncate_and_trailoff(&process_name, MAX_CHARS),
1817 )
1818 } else {
1819 (process_file, process_name)
1820 };
1821 format!("{process_file} — {process_name}")
1822 })
1823 .unwrap_or_else(|| "Terminal".to_string())
1824 }),
1825 }
1826 }
1827
1828 pub fn kill_active_task(&mut self) {
1829 if let Some(task) = self.task() {
1830 if task.status == TaskStatus::Running {
1831 self.pty_info.kill_current_process();
1832 }
1833 }
1834 }
1835
1836 pub fn task(&self) -> Option<&TaskState> {
1837 self.task.as_ref()
1838 }
1839
1840 pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
1841 if let Some(task) = self.task() {
1842 if task.status == TaskStatus::Running {
1843 let completion_receiver = task.completion_rx.clone();
1844 return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
1845 } else if let Ok(status) = task.completion_rx.try_recv() {
1846 return Task::ready(status);
1847 }
1848 }
1849 Task::ready(None)
1850 }
1851
1852 fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
1853 let e: Option<ExitStatus> = error_code.map(|code| {
1854 #[cfg(unix)]
1855 {
1856 return std::os::unix::process::ExitStatusExt::from_raw(code);
1857 }
1858 #[cfg(windows)]
1859 {
1860 return std::os::windows::process::ExitStatusExt::from_raw(code as u32);
1861 }
1862 });
1863
1864 self.completion_tx.try_send(e).ok();
1865 let task = match &mut self.task {
1866 Some(task) => task,
1867 None => {
1868 if error_code.is_none() {
1869 cx.emit(Event::CloseTerminal);
1870 }
1871 return;
1872 }
1873 };
1874 if task.status != TaskStatus::Running {
1875 return;
1876 }
1877 match error_code {
1878 Some(error_code) => {
1879 task.status.register_task_exit(error_code);
1880 }
1881 None => {
1882 task.status.register_terminal_exit();
1883 }
1884 };
1885
1886 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1887 let mut lines_to_show = Vec::new();
1888 if task.show_summary {
1889 lines_to_show.push(task_line.as_str());
1890 }
1891 if task.show_command {
1892 lines_to_show.push(command_line.as_str());
1893 }
1894
1895 if !lines_to_show.is_empty() {
1896 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1897 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1898 // when Zed task finishes and no more output is made.
1899 // After the task summary is output once, no more text is appended to the terminal.
1900 unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1901 }
1902
1903 match task.hide {
1904 HideStrategy::Never => {}
1905 HideStrategy::Always => {
1906 cx.emit(Event::CloseTerminal);
1907 }
1908 HideStrategy::OnSuccess => {
1909 if finished_successfully {
1910 cx.emit(Event::CloseTerminal);
1911 }
1912 }
1913 }
1914 }
1915
1916 pub fn vi_mode_enabled(&self) -> bool {
1917 self.vi_mode_enabled
1918 }
1919}
1920
1921// Helper function to convert a grid row to a string
1922pub fn row_to_string(row: &Row<Cell>) -> String {
1923 row[..Column(row.len())]
1924 .iter()
1925 .map(|cell| cell.c)
1926 .collect::<String>()
1927}
1928
1929const TASK_DELIMITER: &str = "⏵ ";
1930fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1931 let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1932 let (success, task_line) = match error_code {
1933 Some(0) => (
1934 true,
1935 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
1936 ),
1937 Some(error_code) => (
1938 false,
1939 format!(
1940 "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
1941 ),
1942 ),
1943 None => (
1944 false,
1945 format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
1946 ),
1947 };
1948 let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1949 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1950 (success, task_line, command_line)
1951}
1952
1953/// Appends a stringified task summary to the terminal, after its output.
1954///
1955/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1956/// New text being added to the terminal here, uses "less public" APIs,
1957/// which are not maintaining the entire terminal state intact.
1958///
1959///
1960/// The library
1961///
1962/// * does not increment inner grid cursor's _lines_ on `input` calls
1963/// (but displaying the lines correctly and incrementing cursor's columns)
1964///
1965/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1966///
1967/// * does not alter grid state after `newline` call
1968/// so its `bottommost_line` is always the same additions, and
1969/// the cursor's `point` is not updated to the new line and column values
1970///
1971/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1972/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1973///
1974/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1975/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1976/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1977/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1978unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1979 term.newline();
1980 term.grid_mut().cursor.point.column = Column(0);
1981 for line in text_lines {
1982 for c in line.chars() {
1983 term.input(c);
1984 }
1985 term.newline();
1986 term.grid_mut().cursor.point.column = Column(0);
1987 }
1988}
1989
1990impl Drop for Terminal {
1991 fn drop(&mut self) {
1992 self.pty_tx.0.send(Msg::Shutdown).ok();
1993 }
1994}
1995
1996impl EventEmitter<Event> for Terminal {}
1997
1998fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1999 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
2000 selection.update(*range.end(), AlacDirection::Right);
2001 selection
2002}
2003
2004fn all_search_matches<'a, T>(
2005 term: &'a Term<T>,
2006 regex: &'a mut RegexSearch,
2007) -> impl Iterator<Item = Match> + 'a {
2008 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
2009 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
2010 RegexIter::new(start, end, AlacDirection::Right, term, regex)
2011}
2012
2013fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
2014 let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
2015 let clamped_col = min(col, terminal_bounds.columns() - 1);
2016 let row = (pos.y / terminal_bounds.line_height()).round() as usize;
2017 let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
2018 clamped_row * terminal_bounds.columns() + clamped_col
2019}
2020
2021/// Converts an 8 bit ANSI color to its GPUI equivalent.
2022/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
2023/// Other than that use case, should only be called with values in the `[0,255]` range
2024pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
2025 let colors = theme.colors();
2026
2027 match index {
2028 // 0-15 are the same as the named colors above
2029 0 => colors.terminal_ansi_black,
2030 1 => colors.terminal_ansi_red,
2031 2 => colors.terminal_ansi_green,
2032 3 => colors.terminal_ansi_yellow,
2033 4 => colors.terminal_ansi_blue,
2034 5 => colors.terminal_ansi_magenta,
2035 6 => colors.terminal_ansi_cyan,
2036 7 => colors.terminal_ansi_white,
2037 8 => colors.terminal_ansi_bright_black,
2038 9 => colors.terminal_ansi_bright_red,
2039 10 => colors.terminal_ansi_bright_green,
2040 11 => colors.terminal_ansi_bright_yellow,
2041 12 => colors.terminal_ansi_bright_blue,
2042 13 => colors.terminal_ansi_bright_magenta,
2043 14 => colors.terminal_ansi_bright_cyan,
2044 15 => colors.terminal_ansi_bright_white,
2045 // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
2046 // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
2047 16..=231 => {
2048 let (r, g, b) = rgb_for_index(index as u8);
2049 rgba_color(
2050 if r == 0 { 0 } else { r * 40 + 55 },
2051 if g == 0 { 0 } else { g * 40 + 55 },
2052 if b == 0 { 0 } else { b * 40 + 55 },
2053 )
2054 }
2055 // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
2056 232..=255 => {
2057 let i = index as u8 - 232; // Align index to 0..24
2058 let value = i * 10 + 8;
2059 rgba_color(value, value, value)
2060 }
2061 // For compatibility with the alacritty::Colors interface
2062 // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
2063 256 => colors.terminal_foreground,
2064 257 => colors.terminal_background,
2065 258 => theme.players().local().cursor,
2066 259 => colors.terminal_ansi_dim_black,
2067 260 => colors.terminal_ansi_dim_red,
2068 261 => colors.terminal_ansi_dim_green,
2069 262 => colors.terminal_ansi_dim_yellow,
2070 263 => colors.terminal_ansi_dim_blue,
2071 264 => colors.terminal_ansi_dim_magenta,
2072 265 => colors.terminal_ansi_dim_cyan,
2073 266 => colors.terminal_ansi_dim_white,
2074 267 => colors.terminal_bright_foreground,
2075 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2076
2077 _ => black(),
2078 }
2079}
2080
2081/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2082/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2083///
2084/// Wikipedia gives a formula for calculating the index for a given color:
2085///
2086/// ```
2087/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2088/// ```
2089///
2090/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2091fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2092 debug_assert!((16..=231).contains(&i));
2093 let i = i - 16;
2094 let r = (i - (i % 36)) / 36;
2095 let g = ((i % 36) - (i % 6)) / 6;
2096 let b = (i % 36) % 6;
2097 (r, g, b)
2098}
2099
2100pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2101 Rgba {
2102 r: (r as f32 / 255.),
2103 g: (g as f32 / 255.),
2104 b: (b as f32 / 255.),
2105 a: 1.,
2106 }
2107 .into()
2108}
2109
2110#[cfg(test)]
2111mod tests {
2112 use super::*;
2113 use crate::{
2114 IndexedCell, TerminalBounds, TerminalBuilder, TerminalContent, content_index_for_mouse,
2115 rgb_for_index,
2116 };
2117 use alacritty_terminal::{
2118 index::{Column, Line, Point as AlacPoint},
2119 term::cell::Cell,
2120 };
2121 use collections::HashMap;
2122 use gpui::{Pixels, Point, TestAppContext, bounds, point, size};
2123 use rand::{Rng, distributions::Alphanumeric, rngs::ThreadRng, thread_rng};
2124
2125 #[cfg_attr(windows, ignore = "TODO: fix on windows")]
2126 #[gpui::test]
2127 async fn test_basic_terminal(cx: &mut TestAppContext) {
2128 cx.executor().allow_parking();
2129
2130 let (completion_tx, completion_rx) = smol::channel::unbounded();
2131 let terminal = cx.new(|cx| {
2132 TerminalBuilder::new(
2133 None,
2134 None,
2135 None,
2136 task::Shell::WithArguments {
2137 program: "echo".into(),
2138 args: vec!["hello".into()],
2139 title_override: None,
2140 },
2141 HashMap::default(),
2142 CursorShape::default(),
2143 AlternateScroll::On,
2144 None,
2145 false,
2146 0,
2147 completion_tx,
2148 cx,
2149 )
2150 .unwrap()
2151 .subscribe(cx)
2152 });
2153 assert_eq!(
2154 completion_rx.recv().await.unwrap(),
2155 Some(ExitStatus::default())
2156 );
2157 assert_eq!(
2158 terminal.update(cx, |term, _| term.get_content()).trim(),
2159 "hello"
2160 );
2161 }
2162
2163 #[test]
2164 fn test_rgb_for_index() {
2165 // Test every possible value in the color cube.
2166 for i in 16..=231 {
2167 let (r, g, b) = rgb_for_index(i);
2168 assert_eq!(i, 16 + 36 * r + 6 * g + b);
2169 }
2170 }
2171
2172 #[test]
2173 fn test_mouse_to_cell_test() {
2174 let mut rng = thread_rng();
2175 const ITERATIONS: usize = 10;
2176 const PRECISION: usize = 1000;
2177
2178 for _ in 0..ITERATIONS {
2179 let viewport_cells = rng.gen_range(15..20);
2180 let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2181
2182 let size = crate::TerminalBounds {
2183 cell_width: Pixels::from(cell_size),
2184 line_height: Pixels::from(cell_size),
2185 bounds: bounds(
2186 Point::default(),
2187 size(
2188 Pixels::from(cell_size * (viewport_cells as f32)),
2189 Pixels::from(cell_size * (viewport_cells as f32)),
2190 ),
2191 ),
2192 };
2193
2194 let cells = get_cells(size, &mut rng);
2195 let content = convert_cells_to_content(size, &cells);
2196
2197 for row in 0..(viewport_cells - 1) {
2198 let row = row as usize;
2199 for col in 0..(viewport_cells - 1) {
2200 let col = col as usize;
2201
2202 let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2203 let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2204
2205 let mouse_pos = point(
2206 Pixels::from(col as f32 * cell_size + col_offset),
2207 Pixels::from(row as f32 * cell_size + row_offset),
2208 );
2209
2210 let content_index =
2211 content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2212 let mouse_cell = content.cells[content_index].c;
2213 let real_cell = cells[row][col];
2214
2215 assert_eq!(mouse_cell, real_cell);
2216 }
2217 }
2218 }
2219 }
2220
2221 #[test]
2222 fn test_mouse_to_cell_clamp() {
2223 let mut rng = thread_rng();
2224
2225 let size = crate::TerminalBounds {
2226 cell_width: Pixels::from(10.),
2227 line_height: Pixels::from(10.),
2228 bounds: bounds(
2229 Point::default(),
2230 size(Pixels::from(100.), Pixels::from(100.)),
2231 ),
2232 };
2233
2234 let cells = get_cells(size, &mut rng);
2235 let content = convert_cells_to_content(size, &cells);
2236
2237 assert_eq!(
2238 content.cells[content_index_for_mouse(
2239 point(Pixels::from(-10.), Pixels::from(-10.)),
2240 &content.terminal_bounds,
2241 )]
2242 .c,
2243 cells[0][0]
2244 );
2245 assert_eq!(
2246 content.cells[content_index_for_mouse(
2247 point(Pixels::from(1000.), Pixels::from(1000.)),
2248 &content.terminal_bounds,
2249 )]
2250 .c,
2251 cells[9][9]
2252 );
2253 }
2254
2255 fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2256 let mut cells = Vec::new();
2257
2258 for _ in 0..((size.height() / size.line_height()) as usize) {
2259 let mut row_vec = Vec::new();
2260 for _ in 0..((size.width() / size.cell_width()) as usize) {
2261 let cell_char = rng.sample(Alphanumeric) as char;
2262 row_vec.push(cell_char)
2263 }
2264 cells.push(row_vec)
2265 }
2266
2267 cells
2268 }
2269
2270 fn convert_cells_to_content(
2271 terminal_bounds: TerminalBounds,
2272 cells: &[Vec<char>],
2273 ) -> TerminalContent {
2274 let mut ic = Vec::new();
2275
2276 for (index, row) in cells.iter().enumerate() {
2277 for (cell_index, cell_char) in row.iter().enumerate() {
2278 ic.push(IndexedCell {
2279 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2280 cell: Cell {
2281 c: *cell_char,
2282 ..Default::default()
2283 },
2284 });
2285 }
2286 }
2287
2288 TerminalContent {
2289 cells: ic,
2290 terminal_bounds,
2291 ..Default::default()
2292 }
2293 }
2294}