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