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