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