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