1pub mod mappings;
2
3pub use alacritty_terminal;
4
5mod pty_info;
6mod terminal_hyperlinks;
7pub mod terminal_settings;
8
9use alacritty_terminal::{
10 Term,
11 event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
12 event_loop::{EventLoop, Msg, Notifier},
13 grid::{Dimensions, Grid, Row, Scroll as AlacScroll},
14 index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
15 selection::{Selection, SelectionRange, SelectionType},
16 sync::FairMutex,
17 term::{
18 Config, RenderableCursor, TermMode,
19 cell::{Cell, Flags},
20 search::{Match, RegexIter, RegexSearch},
21 },
22 tty::{self},
23 vi_mode::{ViModeCursor, ViMotion},
24 vte::ansi::{
25 ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
26 },
27};
28use anyhow::{Context as _, Result, bail};
29use log::trace;
30
31use futures::{
32 FutureExt,
33 channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded},
34};
35
36use itertools::Itertools as _;
37use mappings::mouse::{
38 alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
39 scroll_report,
40};
41
42use collections::{HashMap, VecDeque};
43use futures::StreamExt;
44use pty_info::{ProcessIdGetter, PtyProcessInfo};
45use serde::{Deserialize, Serialize};
46use settings::Settings;
47use smol::channel::{Receiver, Sender};
48use task::{HideStrategy, Shell, SpawnInTerminal};
49use terminal_hyperlinks::RegexSearches;
50use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
51use theme::{ActiveTheme, Theme};
52use urlencoding;
53use util::truncate_and_trailoff;
54
55use std::{
56 borrow::Cow,
57 cmp::{self, min},
58 fmt::Display,
59 ops::{Deref, RangeInclusive},
60 path::PathBuf,
61 process::ExitStatus,
62 sync::Arc,
63 time::Instant,
64};
65use thiserror::Error;
66
67use gpui::{
68 App, AppContext as _, Bounds, ClipboardItem, Context, EventEmitter, Hsla, Keystroke, Modifiers,
69 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, Rgba,
70 ScrollWheelEvent, Size, Task, TouchPhase, Window, actions, black, px,
71};
72
73use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
74
75actions!(
76 terminal,
77 [
78 /// Clears the terminal screen.
79 Clear,
80 /// Copies selected text to the clipboard.
81 Copy,
82 /// Pastes from the clipboard.
83 Paste,
84 /// Shows the character palette for special characters.
85 ShowCharacterPalette,
86 /// Searches for text in the terminal.
87 SearchTest,
88 /// Scrolls up by one line.
89 ScrollLineUp,
90 /// Scrolls down by one line.
91 ScrollLineDown,
92 /// Scrolls up by one page.
93 ScrollPageUp,
94 /// Scrolls down by one page.
95 ScrollPageDown,
96 /// Scrolls up by half a page.
97 ScrollHalfPageUp,
98 /// Scrolls down by half a page.
99 ScrollHalfPageDown,
100 /// Scrolls to the top of the terminal buffer.
101 ScrollToTop,
102 /// Scrolls to the bottom of the terminal buffer.
103 ScrollToBottom,
104 /// Toggles vi mode in the terminal.
105 ToggleViMode,
106 /// Selects all text in the terminal.
107 SelectAll,
108 ]
109);
110
111const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
112const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
113const DEBUG_CELL_WIDTH: Pixels = px(5.);
114const DEBUG_LINE_HEIGHT: Pixels = px(5.);
115
116/// Inserts Zed-specific environment variables for terminal sessions.
117/// Used by both local terminals and remote terminals (via SSH).
118pub fn insert_zed_terminal_env(
119 env: &mut HashMap<String, String>,
120 version: &impl std::fmt::Display,
121) {
122 env.insert("ZED_TERM".to_string(), "true".to_string());
123 env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
124 env.insert("TERM".to_string(), "xterm-256color".to_string());
125 env.insert("COLORTERM".to_string(), "truecolor".to_string());
126 env.insert("TERM_PROGRAM_VERSION".to_string(), version.to_string());
127}
128
129///Upward flowing events, for changing the title and such
130#[derive(Clone, Debug, PartialEq, Eq)]
131pub enum Event {
132 TitleChanged,
133 BreadcrumbsChanged,
134 CloseTerminal,
135 Bell,
136 Wakeup,
137 BlinkChanged(bool),
138 SelectionsChanged,
139 NewNavigationTarget(Option<MaybeNavigationTarget>),
140 Open(MaybeNavigationTarget),
141}
142
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub struct PathLikeTarget {
145 /// File system path, absolute or relative, existing or not.
146 /// Might have line and column number(s) attached as `file.rs:1:23`
147 pub maybe_path: String,
148 /// Current working directory of the terminal
149 pub terminal_dir: Option<PathBuf>,
150}
151
152/// A string inside terminal, potentially useful as a URI that can be opened.
153#[derive(Clone, Debug, PartialEq, Eq)]
154pub enum MaybeNavigationTarget {
155 /// HTTP, git, etc. string determined by the `URL_REGEX` regex.
156 Url(String),
157 /// File system path, absolute or relative, existing or not.
158 /// Might have line and column number(s) attached as `file.rs:1:23`
159 PathLike(PathLikeTarget),
160}
161
162#[derive(Clone)]
163enum InternalEvent {
164 Resize(TerminalBounds),
165 Clear,
166 // FocusNextMatch,
167 Scroll(AlacScroll),
168 ScrollToAlacPoint(AlacPoint),
169 SetSelection(Option<(Selection, AlacPoint)>),
170 UpdateSelection(Point<Pixels>),
171 FindHyperlink(Point<Pixels>, bool),
172 ProcessHyperlink((String, bool, Match), bool),
173 // Whether keep selection when copy
174 Copy(Option<bool>),
175 // Vi mode events
176 ToggleViMode,
177 ViMotion(ViMotion),
178 MoveViCursorToAlacPoint(AlacPoint),
179}
180
181///A translation struct for Alacritty to communicate with us from their event loop
182#[derive(Clone)]
183pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
184
185impl EventListener for ZedListener {
186 fn send_event(&self, event: AlacTermEvent) {
187 self.0.unbounded_send(event).ok();
188 }
189}
190
191#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
192pub struct TerminalBounds {
193 pub cell_width: Pixels,
194 pub line_height: Pixels,
195 pub bounds: Bounds<Pixels>,
196}
197
198impl TerminalBounds {
199 pub fn new(line_height: Pixels, cell_width: Pixels, bounds: Bounds<Pixels>) -> Self {
200 TerminalBounds {
201 cell_width,
202 line_height,
203 bounds,
204 }
205 }
206
207 pub fn num_lines(&self) -> usize {
208 (self.bounds.size.height / self.line_height).floor() as usize
209 }
210
211 pub fn num_columns(&self) -> usize {
212 (self.bounds.size.width / self.cell_width).floor() as usize
213 }
214
215 pub fn height(&self) -> Pixels {
216 self.bounds.size.height
217 }
218
219 pub fn width(&self) -> Pixels {
220 self.bounds.size.width
221 }
222
223 pub fn cell_width(&self) -> Pixels {
224 self.cell_width
225 }
226
227 pub fn line_height(&self) -> Pixels {
228 self.line_height
229 }
230}
231
232impl Default for TerminalBounds {
233 fn default() -> Self {
234 TerminalBounds::new(
235 DEBUG_LINE_HEIGHT,
236 DEBUG_CELL_WIDTH,
237 Bounds {
238 origin: Point::default(),
239 size: Size {
240 width: DEBUG_TERMINAL_WIDTH,
241 height: DEBUG_TERMINAL_HEIGHT,
242 },
243 },
244 )
245 }
246}
247
248impl From<TerminalBounds> for WindowSize {
249 fn from(val: TerminalBounds) -> Self {
250 WindowSize {
251 num_lines: val.num_lines() as u16,
252 num_cols: val.num_columns() as u16,
253 cell_width: f32::from(val.cell_width()) as u16,
254 cell_height: f32::from(val.line_height()) as u16,
255 }
256 }
257}
258
259impl Dimensions for TerminalBounds {
260 /// Note: this is supposed to be for the back buffer's length,
261 /// but we exclusively use it to resize the terminal, which does not
262 /// use this method. We still have to implement it for the trait though,
263 /// hence, this comment.
264 fn total_lines(&self) -> usize {
265 self.screen_lines()
266 }
267
268 fn screen_lines(&self) -> usize {
269 self.num_lines()
270 }
271
272 fn columns(&self) -> usize {
273 self.num_columns()
274 }
275}
276
277#[derive(Error, Debug)]
278pub struct TerminalError {
279 pub directory: Option<PathBuf>,
280 pub program: Option<String>,
281 pub args: Option<Vec<String>>,
282 pub title_override: Option<String>,
283 pub source: std::io::Error,
284}
285
286impl TerminalError {
287 pub fn fmt_directory(&self) -> String {
288 self.directory
289 .clone()
290 .map(|path| {
291 match path
292 .into_os_string()
293 .into_string()
294 .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
295 {
296 Ok(s) => s,
297 Err(s) => s,
298 }
299 })
300 .unwrap_or_else(|| "<none specified>".to_string())
301 }
302
303 pub fn fmt_shell(&self) -> String {
304 if let Some(title_override) = &self.title_override {
305 format!(
306 "{} {} ({})",
307 self.program.as_deref().unwrap_or("<system defined shell>"),
308 self.args.as_ref().into_iter().flatten().format(" "),
309 title_override
310 )
311 } else {
312 format!(
313 "{} {}",
314 self.program.as_deref().unwrap_or("<system defined shell>"),
315 self.args.as_ref().into_iter().flatten().format(" ")
316 )
317 }
318 }
319}
320
321impl Display for TerminalError {
322 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323 let dir_string: String = self.fmt_directory();
324 let shell = self.fmt_shell();
325
326 write!(
327 f,
328 "Working directory: {} Shell command: `{}`, IOError: {}",
329 dir_string, shell, self.source
330 )
331 }
332}
333
334// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
335const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
336pub const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
337
338pub struct TerminalBuilder {
339 terminal: Terminal,
340 events_rx: UnboundedReceiver<AlacTermEvent>,
341}
342
343impl TerminalBuilder {
344 pub fn new_display_only(
345 cursor_shape: CursorShape,
346 alternate_scroll: AlternateScroll,
347 max_scroll_history_lines: Option<usize>,
348 window_id: u64,
349 ) -> Result<TerminalBuilder> {
350 // Create a display-only terminal (no actual PTY).
351 let default_cursor_style = AlacCursorStyle::from(cursor_shape);
352 let scrolling_history = max_scroll_history_lines
353 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
354 .min(MAX_SCROLL_HISTORY_LINES);
355 let config = Config {
356 scrolling_history,
357 default_cursor_style,
358 ..Config::default()
359 };
360
361 let (events_tx, events_rx) = unbounded();
362 let mut term = Term::new(
363 config.clone(),
364 &TerminalBounds::default(),
365 ZedListener(events_tx),
366 );
367
368 if let AlternateScroll::Off = alternate_scroll {
369 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
370 }
371
372 let term = Arc::new(FairMutex::new(term));
373
374 let terminal = Terminal {
375 task: None,
376 terminal_type: TerminalType::DisplayOnly,
377 completion_tx: None,
378 term,
379 term_config: config,
380 title_override: None,
381 events: VecDeque::with_capacity(10),
382 last_content: Default::default(),
383 last_mouse: None,
384 matches: Vec::new(),
385
386 selection_head: None,
387 breadcrumb_text: String::new(),
388 scroll_px: px(0.),
389 next_link_id: 0,
390 selection_phase: SelectionPhase::Ended,
391 hyperlink_regex_searches: RegexSearches::default(),
392 vi_mode_enabled: false,
393 is_remote_terminal: false,
394 last_mouse_move_time: Instant::now(),
395 last_hyperlink_search_position: None,
396 mouse_down_hyperlink: None,
397 #[cfg(windows)]
398 shell_program: None,
399 activation_script: Vec::new(),
400 template: CopyTemplate {
401 shell: Shell::System,
402 env: HashMap::default(),
403 cursor_shape,
404 alternate_scroll,
405 max_scroll_history_lines,
406 path_hyperlink_regexes: Vec::default(),
407 path_hyperlink_timeout_ms: 0,
408 window_id,
409 },
410 child_exited: None,
411 event_loop_task: Task::ready(Ok(())),
412 };
413
414 Ok(TerminalBuilder {
415 terminal,
416 events_rx,
417 })
418 }
419
420 pub fn new(
421 working_directory: Option<PathBuf>,
422 task: Option<TaskState>,
423 shell: Shell,
424 mut env: HashMap<String, String>,
425 cursor_shape: CursorShape,
426 alternate_scroll: AlternateScroll,
427 max_scroll_history_lines: Option<usize>,
428 path_hyperlink_regexes: Vec<String>,
429 path_hyperlink_timeout_ms: u64,
430 is_remote_terminal: bool,
431 window_id: u64,
432 completion_tx: Option<Sender<Option<ExitStatus>>>,
433 cx: &App,
434 activation_script: Vec<String>,
435 ) -> Task<Result<TerminalBuilder>> {
436 let version = release_channel::AppVersion::global(cx);
437 let fut = async move {
438 // Remove SHLVL so the spawned shell initializes it to 1, matching
439 // the behavior of standalone terminal emulators like iTerm2/Kitty/Alacritty.
440 env.remove("SHLVL");
441
442 // If the parent environment doesn't have a locale set
443 // (As is the case when launched from a .app on MacOS),
444 // and the Project doesn't have a locale set, then
445 // set a fallback for our child environment to use.
446 if std::env::var("LANG").is_err() {
447 env.entry("LANG".to_string())
448 .or_insert_with(|| "en_US.UTF-8".to_string());
449 }
450
451 insert_zed_terminal_env(&mut env, &version);
452
453 #[derive(Default)]
454 struct ShellParams {
455 program: String,
456 args: Option<Vec<String>>,
457 title_override: Option<String>,
458 }
459
460 impl ShellParams {
461 fn new(
462 program: String,
463 args: Option<Vec<String>>,
464 title_override: Option<String>,
465 ) -> Self {
466 log::debug!("Using {program} as shell");
467 Self {
468 program,
469 args,
470 title_override,
471 }
472 }
473 }
474
475 let shell_params = match shell.clone() {
476 Shell::System => {
477 if cfg!(windows) {
478 Some(ShellParams::new(
479 util::shell::get_windows_system_shell(),
480 None,
481 None,
482 ))
483 } else {
484 None
485 }
486 }
487 Shell::Program(program) => Some(ShellParams::new(program, None, None)),
488 Shell::WithArguments {
489 program,
490 args,
491 title_override,
492 } => Some(ShellParams::new(program, Some(args), title_override)),
493 };
494 let terminal_title_override =
495 shell_params.as_ref().and_then(|e| e.title_override.clone());
496
497 #[cfg(windows)]
498 let shell_program = shell_params.as_ref().map(|params| {
499 use util::ResultExt;
500
501 Self::resolve_path(¶ms.program)
502 .log_err()
503 .unwrap_or(params.program.clone())
504 });
505
506 // Note: when remoting, this shell_kind will scrutinize `ssh` or
507 // `wsl.exe` as a shell and fall back to posix or powershell based on
508 // the compilation target. This is fine right now due to the restricted
509 // way we use the return value, but would become incorrect if we
510 // supported remoting into windows.
511 let shell_kind = shell.shell_kind(cfg!(windows));
512
513 let pty_options = {
514 let alac_shell = shell_params.as_ref().map(|params| {
515 alacritty_terminal::tty::Shell::new(
516 params.program.clone(),
517 params.args.clone().unwrap_or_default(),
518 )
519 });
520
521 alacritty_terminal::tty::Options {
522 shell: alac_shell,
523 working_directory: working_directory.clone(),
524 drain_on_exit: true,
525 env: env.clone().into_iter().collect(),
526 #[cfg(windows)]
527 escape_args: shell_kind.tty_escape_args(),
528 }
529 };
530
531 let default_cursor_style = AlacCursorStyle::from(cursor_shape);
532 let scrolling_history = if task.is_some() {
533 // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
534 // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
535 // cause excessive memory usage over time.
536 MAX_SCROLL_HISTORY_LINES
537 } else {
538 max_scroll_history_lines
539 .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
540 .min(MAX_SCROLL_HISTORY_LINES)
541 };
542 let config = Config {
543 scrolling_history,
544 default_cursor_style,
545 ..Config::default()
546 };
547
548 //Setup the pty...
549 let pty = match tty::new(&pty_options, TerminalBounds::default().into(), window_id) {
550 Ok(pty) => pty,
551 Err(error) => {
552 bail!(TerminalError {
553 directory: working_directory,
554 program: shell_params.as_ref().map(|params| params.program.clone()),
555 args: shell_params.as_ref().and_then(|params| params.args.clone()),
556 title_override: terminal_title_override,
557 source: error,
558 });
559 }
560 };
561
562 //Spawn a task so the Alacritty EventLoop can communicate with us
563 //TODO: Remove with a bounded sender which can be dispatched on &self
564 let (events_tx, events_rx) = unbounded();
565 //Set up the terminal...
566 let mut term = Term::new(
567 config.clone(),
568 &TerminalBounds::default(),
569 ZedListener(events_tx.clone()),
570 );
571
572 //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
573 if let AlternateScroll::Off = alternate_scroll {
574 term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
575 }
576
577 let term = Arc::new(FairMutex::new(term));
578
579 let pty_info = PtyProcessInfo::new(&pty);
580
581 //And connect them together
582 let event_loop = EventLoop::new(
583 term.clone(),
584 ZedListener(events_tx),
585 pty,
586 pty_options.drain_on_exit,
587 false,
588 )
589 .context("failed to create event loop")?;
590
591 let pty_tx = event_loop.channel();
592 let _io_thread = event_loop.spawn(); // DANGER
593
594 let no_task = task.is_none();
595 let terminal = Terminal {
596 task,
597 terminal_type: TerminalType::Pty {
598 pty_tx: Notifier(pty_tx),
599 info: pty_info,
600 },
601 completion_tx,
602 term,
603 term_config: config,
604 title_override: terminal_title_override,
605 events: VecDeque::with_capacity(10), //Should never get this high.
606 last_content: Default::default(),
607 last_mouse: None,
608 matches: Vec::new(),
609
610 selection_head: None,
611 breadcrumb_text: String::new(),
612 scroll_px: px(0.),
613 next_link_id: 0,
614 selection_phase: SelectionPhase::Ended,
615 hyperlink_regex_searches: RegexSearches::new(
616 &path_hyperlink_regexes,
617 path_hyperlink_timeout_ms,
618 ),
619 vi_mode_enabled: false,
620 is_remote_terminal,
621 last_mouse_move_time: Instant::now(),
622 last_hyperlink_search_position: None,
623 mouse_down_hyperlink: None,
624 #[cfg(windows)]
625 shell_program,
626 activation_script: activation_script.clone(),
627 template: CopyTemplate {
628 shell,
629 env,
630 cursor_shape,
631 alternate_scroll,
632 max_scroll_history_lines,
633 path_hyperlink_regexes,
634 path_hyperlink_timeout_ms,
635 window_id,
636 },
637 child_exited: None,
638 event_loop_task: Task::ready(Ok(())),
639 };
640
641 if !activation_script.is_empty() && no_task {
642 for activation_script in activation_script {
643 terminal.write_to_pty(activation_script.into_bytes());
644 // Simulate enter key press
645 // NOTE(PowerShell): using `\r\n` will put PowerShell in a continuation mode (infamous >> character)
646 // and generally mess up the rendering.
647 terminal.write_to_pty(b"\x0d");
648 }
649 // In order to clear the screen at this point, we have two options:
650 // 1. We can send a shell-specific command such as "clear" or "cls"
651 // 2. We can "echo" a marker message that we will then catch when handling a Wakeup event
652 // and clear the screen using `terminal.clear()` method
653 // We cannot issue a `terminal.clear()` command at this point as alacritty is evented
654 // and while we have sent the activation script to the pty, it will be executed asynchronously.
655 // Therefore, we somehow need to wait for the activation script to finish executing before we
656 // can proceed with clearing the screen.
657 terminal.write_to_pty(shell_kind.clear_screen_command().as_bytes());
658 // Simulate enter key press
659 terminal.write_to_pty(b"\x0d");
660 }
661
662 Ok(TerminalBuilder {
663 terminal,
664 events_rx,
665 })
666 };
667 // the thread we spawn things on has an effect on signal handling
668 if !cfg!(target_os = "windows") {
669 cx.spawn(async move |_| fut.await)
670 } else {
671 cx.background_spawn(fut)
672 }
673 }
674
675 pub fn subscribe(mut self, cx: &Context<Terminal>) -> Terminal {
676 //Event loop
677 self.terminal.event_loop_task = cx.spawn(async move |terminal, cx| {
678 while let Some(event) = self.events_rx.next().await {
679 terminal.update(cx, |terminal, cx| {
680 //Process the first event immediately for lowered latency
681 terminal.process_event(event, cx);
682 })?;
683
684 'outer: loop {
685 let mut events = Vec::new();
686
687 #[cfg(any(test, feature = "test-support"))]
688 let mut timer = cx.background_executor().simulate_random_delay().fuse();
689 #[cfg(not(any(test, feature = "test-support")))]
690 let mut timer = cx
691 .background_executor()
692 .timer(std::time::Duration::from_millis(4))
693 .fuse();
694
695 let mut wakeup = false;
696 loop {
697 futures::select_biased! {
698 _ = timer => break,
699 event = self.events_rx.next() => {
700 if let Some(event) = event {
701 if matches!(event, AlacTermEvent::Wakeup) {
702 wakeup = true;
703 } else {
704 events.push(event);
705 }
706
707 if events.len() > 100 {
708 break;
709 }
710 } else {
711 break;
712 }
713 },
714 }
715 }
716
717 if events.is_empty() && !wakeup {
718 smol::future::yield_now().await;
719 break 'outer;
720 }
721
722 terminal.update(cx, |this, cx| {
723 if wakeup {
724 this.process_event(AlacTermEvent::Wakeup, cx);
725 }
726
727 for event in events {
728 this.process_event(event, cx);
729 }
730 })?;
731 smol::future::yield_now().await;
732 }
733 }
734 anyhow::Ok(())
735 });
736 self.terminal
737 }
738
739 #[cfg(windows)]
740 fn resolve_path(path: &str) -> Result<String> {
741 use windows::Win32::Storage::FileSystem::SearchPathW;
742 use windows::core::HSTRING;
743
744 let path = if path.starts_with(r"\\?\") || !path.contains(&['/', '\\']) {
745 path.to_string()
746 } else {
747 r"\\?\".to_string() + path
748 };
749
750 let required_length = unsafe { SearchPathW(None, &HSTRING::from(&path), None, None, None) };
751 let mut buf = vec![0u16; required_length as usize];
752 let size = unsafe { SearchPathW(None, &HSTRING::from(&path), None, Some(&mut buf), None) };
753
754 Ok(String::from_utf16(&buf[..size as usize])?)
755 }
756}
757
758#[derive(Debug, Clone, Deserialize, Serialize)]
759pub struct IndexedCell {
760 pub point: AlacPoint,
761 pub cell: Cell,
762}
763
764impl Deref for IndexedCell {
765 type Target = Cell;
766
767 #[inline]
768 fn deref(&self) -> &Cell {
769 &self.cell
770 }
771}
772
773// TODO: Un-pub
774#[derive(Clone)]
775pub struct TerminalContent {
776 pub cells: Vec<IndexedCell>,
777 pub mode: TermMode,
778 pub display_offset: usize,
779 pub selection_text: Option<String>,
780 pub selection: Option<SelectionRange>,
781 pub cursor: RenderableCursor,
782 pub cursor_char: char,
783 pub terminal_bounds: TerminalBounds,
784 pub last_hovered_word: Option<HoveredWord>,
785 pub scrolled_to_top: bool,
786 pub scrolled_to_bottom: bool,
787}
788
789#[derive(Debug, Clone, Eq, PartialEq)]
790pub struct HoveredWord {
791 pub word: String,
792 pub word_match: RangeInclusive<AlacPoint>,
793 pub id: usize,
794}
795
796impl Default for TerminalContent {
797 fn default() -> Self {
798 TerminalContent {
799 cells: Default::default(),
800 mode: Default::default(),
801 display_offset: Default::default(),
802 selection_text: Default::default(),
803 selection: Default::default(),
804 cursor: RenderableCursor {
805 shape: alacritty_terminal::vte::ansi::CursorShape::Block,
806 point: AlacPoint::new(Line(0), Column(0)),
807 },
808 cursor_char: Default::default(),
809 terminal_bounds: Default::default(),
810 last_hovered_word: None,
811 scrolled_to_top: false,
812 scrolled_to_bottom: false,
813 }
814 }
815}
816
817#[derive(PartialEq, Eq)]
818pub enum SelectionPhase {
819 Selecting,
820 Ended,
821}
822
823enum TerminalType {
824 Pty {
825 pty_tx: Notifier,
826 info: PtyProcessInfo,
827 },
828 DisplayOnly,
829}
830
831pub struct Terminal {
832 terminal_type: TerminalType,
833 completion_tx: Option<Sender<Option<ExitStatus>>>,
834 term: Arc<FairMutex<Term<ZedListener>>>,
835 term_config: Config,
836 events: VecDeque<InternalEvent>,
837 /// This is only used for mouse mode cell change detection
838 last_mouse: Option<(AlacPoint, AlacDirection)>,
839 pub matches: Vec<RangeInclusive<AlacPoint>>,
840 pub last_content: TerminalContent,
841 pub selection_head: Option<AlacPoint>,
842
843 pub breadcrumb_text: String,
844 title_override: Option<String>,
845 scroll_px: Pixels,
846 next_link_id: usize,
847 selection_phase: SelectionPhase,
848 hyperlink_regex_searches: RegexSearches,
849 task: Option<TaskState>,
850 vi_mode_enabled: bool,
851 is_remote_terminal: bool,
852 last_mouse_move_time: Instant,
853 last_hyperlink_search_position: Option<Point<Pixels>>,
854 mouse_down_hyperlink: Option<(String, bool, Match)>,
855 #[cfg(windows)]
856 shell_program: Option<String>,
857 template: CopyTemplate,
858 activation_script: Vec<String>,
859 child_exited: Option<ExitStatus>,
860 event_loop_task: Task<Result<(), anyhow::Error>>,
861}
862
863struct CopyTemplate {
864 shell: Shell,
865 env: HashMap<String, String>,
866 cursor_shape: CursorShape,
867 alternate_scroll: AlternateScroll,
868 max_scroll_history_lines: Option<usize>,
869 path_hyperlink_regexes: Vec<String>,
870 path_hyperlink_timeout_ms: u64,
871 window_id: u64,
872}
873
874#[derive(Debug)]
875pub struct TaskState {
876 pub status: TaskStatus,
877 pub completion_rx: Receiver<Option<ExitStatus>>,
878 pub spawned_task: SpawnInTerminal,
879}
880
881/// A status of the current terminal tab's task.
882#[derive(Debug, Clone, Copy, PartialEq, Eq)]
883pub enum TaskStatus {
884 /// The task had been started, but got cancelled or somehow otherwise it did not
885 /// report its exit code before the terminal event loop was shut down.
886 Unknown,
887 /// The task is started and running currently.
888 Running,
889 /// After the start, the task stopped running and reported its error code back.
890 Completed { success: bool },
891}
892
893impl TaskStatus {
894 fn register_terminal_exit(&mut self) {
895 if self == &Self::Running {
896 *self = Self::Unknown;
897 }
898 }
899
900 fn register_task_exit(&mut self, error_code: i32) {
901 *self = TaskStatus::Completed {
902 success: error_code == 0,
903 };
904 }
905}
906
907const FIND_HYPERLINK_THROTTLE_PX: Pixels = px(5.0);
908
909impl Terminal {
910 fn process_event(&mut self, event: AlacTermEvent, cx: &mut Context<Self>) {
911 match event {
912 AlacTermEvent::Title(title) => {
913 // ignore default shell program title change as windows always sends those events
914 // and it would end up showing the shell executable path in breadcrumbs
915 #[cfg(windows)]
916 {
917 if self
918 .shell_program
919 .as_ref()
920 .map(|e| *e == title)
921 .unwrap_or(false)
922 {
923 return;
924 }
925 }
926
927 self.breadcrumb_text = title;
928 cx.emit(Event::BreadcrumbsChanged);
929 }
930 AlacTermEvent::ResetTitle => {
931 self.breadcrumb_text = String::new();
932 cx.emit(Event::BreadcrumbsChanged);
933 }
934 AlacTermEvent::ClipboardStore(_, data) => {
935 cx.write_to_clipboard(ClipboardItem::new_string(data))
936 }
937 AlacTermEvent::ClipboardLoad(_, format) => {
938 self.write_to_pty(
939 match &cx.read_from_clipboard().and_then(|item| item.text()) {
940 // The terminal only supports pasting strings, not images.
941 Some(text) => format(text),
942 _ => format(""),
943 }
944 .into_bytes(),
945 )
946 }
947 AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.into_bytes()),
948 AlacTermEvent::TextAreaSizeRequest(format) => {
949 self.write_to_pty(format(self.last_content.terminal_bounds.into()).into_bytes())
950 }
951 AlacTermEvent::CursorBlinkingChange => {
952 let terminal = self.term.lock();
953 let blinking = terminal.cursor_style().blinking;
954 cx.emit(Event::BlinkChanged(blinking));
955 }
956 AlacTermEvent::Bell => {
957 cx.emit(Event::Bell);
958 }
959 AlacTermEvent::Exit => self.register_task_finished(Some(9), cx),
960 AlacTermEvent::MouseCursorDirty => {
961 //NOOP, Handled in render
962 }
963 AlacTermEvent::Wakeup => {
964 cx.emit(Event::Wakeup);
965
966 if let TerminalType::Pty { info, .. } = &mut self.terminal_type {
967 if info.has_changed() {
968 cx.emit(Event::TitleChanged);
969 }
970 }
971 }
972 AlacTermEvent::ColorRequest(index, format) => {
973 // It's important that the color request is processed here to retain relative order
974 // with other PTY writes. Otherwise applications might witness out-of-order
975 // responses to requests. For example: An application sending `OSC 11 ; ? ST`
976 // (color request) followed by `CSI c` (request device attributes) would receive
977 // the response to `CSI c` first.
978 // Instead of locking, we could store the colors in `self.last_content`. But then
979 // we might respond with out of date value if a "set color" sequence is immediately
980 // followed by a color request sequence.
981 let color = self.term.lock().colors()[index]
982 .unwrap_or_else(|| to_alac_rgb(get_color_at_index(index, cx.theme().as_ref())));
983 self.write_to_pty(format(color).into_bytes());
984 }
985 AlacTermEvent::ChildExit(error_code) => {
986 self.register_task_finished(Some(error_code), cx);
987 }
988 }
989 }
990
991 pub fn selection_started(&self) -> bool {
992 self.selection_phase == SelectionPhase::Selecting
993 }
994
995 fn process_terminal_event(
996 &mut self,
997 event: &InternalEvent,
998 term: &mut Term<ZedListener>,
999 window: &mut Window,
1000 cx: &mut Context<Self>,
1001 ) {
1002 match event {
1003 &InternalEvent::Resize(mut new_bounds) => {
1004 trace!("Resizing: new_bounds={new_bounds:?}");
1005 new_bounds.bounds.size.height =
1006 cmp::max(new_bounds.line_height, new_bounds.height());
1007 new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
1008
1009 self.last_content.terminal_bounds = new_bounds;
1010
1011 if let TerminalType::Pty { pty_tx, .. } = &self.terminal_type {
1012 pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
1013 }
1014
1015 term.resize(new_bounds);
1016 // If there are matches we need to emit a wake up event to
1017 // invalidate the matches and recalculate their locations
1018 // in the new terminal layout
1019 if !self.matches.is_empty() {
1020 cx.emit(Event::Wakeup);
1021 }
1022 }
1023 InternalEvent::Clear => {
1024 trace!("Clearing");
1025 // Clear back buffer
1026 term.clear_screen(ClearMode::Saved);
1027
1028 let cursor = term.grid().cursor.point;
1029
1030 // Clear the lines above
1031 term.grid_mut().reset_region(..cursor.line);
1032
1033 // Copy the current line up
1034 let line = term.grid()[cursor.line][..Column(term.grid().columns())]
1035 .iter()
1036 .cloned()
1037 .enumerate()
1038 .collect::<Vec<(usize, Cell)>>();
1039
1040 for (i, cell) in line {
1041 term.grid_mut()[Line(0)][Column(i)] = cell;
1042 }
1043
1044 // Reset the cursor
1045 term.grid_mut().cursor.point =
1046 AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
1047 let new_cursor = term.grid().cursor.point;
1048
1049 // Clear the lines below the new cursor
1050 if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
1051 term.grid_mut().reset_region((new_cursor.line + 1)..);
1052 }
1053
1054 cx.emit(Event::Wakeup);
1055 }
1056 InternalEvent::Scroll(scroll) => {
1057 trace!("Scrolling: scroll={scroll:?}");
1058 term.scroll_display(*scroll);
1059 self.refresh_hovered_word(window);
1060
1061 if self.vi_mode_enabled {
1062 match *scroll {
1063 AlacScroll::Delta(delta) => {
1064 term.vi_mode_cursor = term.vi_mode_cursor.scroll(term, delta);
1065 }
1066 AlacScroll::PageUp => {
1067 let lines = term.screen_lines() as i32;
1068 term.vi_mode_cursor = term.vi_mode_cursor.scroll(term, lines);
1069 }
1070 AlacScroll::PageDown => {
1071 let lines = -(term.screen_lines() as i32);
1072 term.vi_mode_cursor = term.vi_mode_cursor.scroll(term, lines);
1073 }
1074 AlacScroll::Top => {
1075 let point = AlacPoint::new(term.topmost_line(), Column(0));
1076 term.vi_mode_cursor = ViModeCursor::new(point);
1077 }
1078 AlacScroll::Bottom => {
1079 let point = AlacPoint::new(term.bottommost_line(), Column(0));
1080 term.vi_mode_cursor = ViModeCursor::new(point);
1081 }
1082 }
1083 if let Some(mut selection) = term.selection.take() {
1084 let point = term.vi_mode_cursor.point;
1085 selection.update(point, AlacDirection::Right);
1086 term.selection = Some(selection);
1087
1088 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1089 if let Some(selection_text) = term.selection_to_string() {
1090 cx.write_to_primary(ClipboardItem::new_string(selection_text));
1091 }
1092
1093 self.selection_head = Some(point);
1094 cx.emit(Event::SelectionsChanged)
1095 }
1096 }
1097 }
1098 InternalEvent::SetSelection(selection) => {
1099 trace!("Setting selection: selection={selection:?}");
1100 term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
1101
1102 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1103 if let Some(selection_text) = term.selection_to_string() {
1104 cx.write_to_primary(ClipboardItem::new_string(selection_text));
1105 }
1106
1107 if let Some((_, head)) = selection {
1108 self.selection_head = Some(*head);
1109 }
1110 cx.emit(Event::SelectionsChanged)
1111 }
1112 InternalEvent::UpdateSelection(position) => {
1113 trace!("Updating selection: position={position:?}");
1114 if let Some(mut selection) = term.selection.take() {
1115 let (point, side) = grid_point_and_side(
1116 *position,
1117 self.last_content.terminal_bounds,
1118 term.grid().display_offset(),
1119 );
1120
1121 selection.update(point, side);
1122 term.selection = Some(selection);
1123
1124 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1125 if let Some(selection_text) = term.selection_to_string() {
1126 cx.write_to_primary(ClipboardItem::new_string(selection_text));
1127 }
1128
1129 self.selection_head = Some(point);
1130 cx.emit(Event::SelectionsChanged)
1131 }
1132 }
1133
1134 InternalEvent::Copy(keep_selection) => {
1135 trace!("Copying selection: keep_selection={keep_selection:?}");
1136 if let Some(txt) = term.selection_to_string() {
1137 cx.write_to_clipboard(ClipboardItem::new_string(txt));
1138 if !keep_selection.unwrap_or_else(|| {
1139 let settings = TerminalSettings::get_global(cx);
1140 settings.keep_selection_on_copy
1141 }) {
1142 self.events.push_back(InternalEvent::SetSelection(None));
1143 }
1144 }
1145 }
1146 InternalEvent::ScrollToAlacPoint(point) => {
1147 trace!("Scrolling to point: point={point:?}");
1148 term.scroll_to_point(*point);
1149 self.refresh_hovered_word(window);
1150 }
1151 InternalEvent::MoveViCursorToAlacPoint(point) => {
1152 trace!("Move vi cursor to point: point={point:?}");
1153 term.vi_goto_point(*point);
1154 self.refresh_hovered_word(window);
1155 }
1156 InternalEvent::ToggleViMode => {
1157 trace!("Toggling vi mode");
1158 self.vi_mode_enabled = !self.vi_mode_enabled;
1159 term.toggle_vi_mode();
1160 }
1161 InternalEvent::ViMotion(motion) => {
1162 trace!("Performing vi motion: motion={motion:?}");
1163 term.vi_motion(*motion);
1164 }
1165 InternalEvent::FindHyperlink(position, open) => {
1166 trace!("Finding hyperlink at position: position={position:?}, open={open:?}");
1167
1168 let point = grid_point(
1169 *position,
1170 self.last_content.terminal_bounds,
1171 term.grid().display_offset(),
1172 )
1173 .grid_clamp(term, Boundary::Grid);
1174
1175 match terminal_hyperlinks::find_from_grid_point(
1176 term,
1177 point,
1178 &mut self.hyperlink_regex_searches,
1179 ) {
1180 Some(hyperlink) => {
1181 self.process_hyperlink(hyperlink, *open, cx);
1182 }
1183 None => {
1184 cx.emit(Event::NewNavigationTarget(None));
1185 }
1186 }
1187 }
1188 InternalEvent::ProcessHyperlink(hyperlink, open) => {
1189 self.process_hyperlink(hyperlink.clone(), *open, cx);
1190 }
1191 }
1192 }
1193
1194 fn process_hyperlink(
1195 &mut self,
1196 hyperlink: (String, bool, Match),
1197 open: bool,
1198 cx: &mut Context<Self>,
1199 ) {
1200 let (maybe_url_or_path, is_url, url_match) = hyperlink;
1201 let prev_hovered_word = self.last_content.last_hovered_word.take();
1202
1203 let target = if is_url {
1204 if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
1205 let decoded_path = urlencoding::decode(path)
1206 .map(|decoded| decoded.into_owned())
1207 .unwrap_or(path.to_owned());
1208
1209 MaybeNavigationTarget::PathLike(PathLikeTarget {
1210 maybe_path: decoded_path,
1211 terminal_dir: self.working_directory(),
1212 })
1213 } else {
1214 MaybeNavigationTarget::Url(maybe_url_or_path.clone())
1215 }
1216 } else {
1217 MaybeNavigationTarget::PathLike(PathLikeTarget {
1218 maybe_path: maybe_url_or_path.clone(),
1219 terminal_dir: self.working_directory(),
1220 })
1221 };
1222
1223 if open {
1224 cx.emit(Event::Open(target));
1225 } else {
1226 self.update_selected_word(prev_hovered_word, url_match, maybe_url_or_path, target, cx);
1227 }
1228 }
1229
1230 fn update_selected_word(
1231 &mut self,
1232 prev_word: Option<HoveredWord>,
1233 word_match: RangeInclusive<AlacPoint>,
1234 word: String,
1235 navigation_target: MaybeNavigationTarget,
1236 cx: &mut Context<Self>,
1237 ) {
1238 if let Some(prev_word) = prev_word
1239 && prev_word.word == word
1240 && prev_word.word_match == word_match
1241 {
1242 self.last_content.last_hovered_word = Some(HoveredWord {
1243 word,
1244 word_match,
1245 id: prev_word.id,
1246 });
1247 return;
1248 }
1249
1250 self.last_content.last_hovered_word = Some(HoveredWord {
1251 word,
1252 word_match,
1253 id: self.next_link_id(),
1254 });
1255 cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1256 cx.notify()
1257 }
1258
1259 fn next_link_id(&mut self) -> usize {
1260 let res = self.next_link_id;
1261 self.next_link_id = self.next_link_id.wrapping_add(1);
1262 res
1263 }
1264
1265 pub fn last_content(&self) -> &TerminalContent {
1266 &self.last_content
1267 }
1268
1269 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1270 self.term_config.default_cursor_style = cursor_shape.into();
1271 self.term.lock().set_options(self.term_config.clone());
1272 }
1273
1274 pub fn write_output(&mut self, bytes: &[u8], cx: &mut Context<Self>) {
1275 // Inject bytes directly into the terminal emulator and refresh the UI.
1276 // This bypasses the PTY/event loop for display-only terminals.
1277 //
1278 // We first convert LF to CRLF, to get the expected line wrapping in Alacritty.
1279 // When output comes from piped commands (not a PTY) such as codex-acp, and that
1280 // output only contains LF (\n) without a CR (\r) after it, such as the output
1281 // of the `ls` command when running outside a PTY, Alacritty moves the cursor
1282 // cursor down a line but does not move it back to the initial column. This makes
1283 // the rendered output look ridiculous. To prevent this, we insert a CR (\r) before
1284 // each LF that didn't already have one. (Alacritty doesn't have a setting for this.)
1285 let mut converted = Vec::with_capacity(bytes.len());
1286 let mut prev_byte = 0u8;
1287 for &byte in bytes {
1288 if byte == b'\n' && prev_byte != b'\r' {
1289 converted.push(b'\r');
1290 }
1291 converted.push(byte);
1292 prev_byte = byte;
1293 }
1294
1295 let mut processor = alacritty_terminal::vte::ansi::Processor::<
1296 alacritty_terminal::vte::ansi::StdSyncHandler,
1297 >::new();
1298 {
1299 let mut term = self.term.lock();
1300 processor.advance(&mut *term, &converted);
1301 }
1302 cx.emit(Event::Wakeup);
1303 }
1304
1305 pub fn total_lines(&self) -> usize {
1306 self.term.lock_unfair().total_lines()
1307 }
1308
1309 pub fn viewport_lines(&self) -> usize {
1310 self.term.lock_unfair().screen_lines()
1311 }
1312
1313 //To test:
1314 //- Activate match on terminal (scrolling and selection)
1315 //- Editor search snapping behavior
1316
1317 pub fn activate_match(&mut self, index: usize) {
1318 if let Some(search_match) = self.matches.get(index).cloned() {
1319 self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1320 if self.vi_mode_enabled {
1321 self.events
1322 .push_back(InternalEvent::MoveViCursorToAlacPoint(*search_match.end()));
1323 } else {
1324 self.events
1325 .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1326 }
1327 }
1328 }
1329
1330 pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1331 let matches_to_select = self
1332 .matches
1333 .iter()
1334 .filter(|self_match| matches.contains(self_match))
1335 .cloned()
1336 .collect::<Vec<_>>();
1337 for match_to_select in matches_to_select {
1338 self.set_selection(Some((
1339 make_selection(&match_to_select),
1340 *match_to_select.end(),
1341 )));
1342 }
1343 }
1344
1345 pub fn select_all(&mut self) {
1346 let term = self.term.lock();
1347 let start = AlacPoint::new(term.topmost_line(), Column(0));
1348 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1349 drop(term);
1350 self.set_selection(Some((make_selection(&(start..=end)), end)));
1351 }
1352
1353 fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1354 self.events
1355 .push_back(InternalEvent::SetSelection(selection));
1356 }
1357
1358 pub fn copy(&mut self, keep_selection: Option<bool>) {
1359 self.events.push_back(InternalEvent::Copy(keep_selection));
1360 }
1361
1362 pub fn clear(&mut self) {
1363 self.events.push_back(InternalEvent::Clear)
1364 }
1365
1366 pub fn scroll_line_up(&mut self) {
1367 self.events
1368 .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1369 }
1370
1371 pub fn scroll_up_by(&mut self, lines: usize) {
1372 self.events
1373 .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1374 }
1375
1376 pub fn scroll_line_down(&mut self) {
1377 self.events
1378 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1379 }
1380
1381 pub fn scroll_down_by(&mut self, lines: usize) {
1382 self.events
1383 .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1384 }
1385
1386 pub fn scroll_page_up(&mut self) {
1387 self.events
1388 .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1389 }
1390
1391 pub fn scroll_page_down(&mut self) {
1392 self.events
1393 .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1394 }
1395
1396 pub fn scroll_to_top(&mut self) {
1397 self.events
1398 .push_back(InternalEvent::Scroll(AlacScroll::Top));
1399 }
1400
1401 pub fn scroll_to_bottom(&mut self) {
1402 self.events
1403 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1404 }
1405
1406 pub fn scrolled_to_top(&self) -> bool {
1407 self.last_content.scrolled_to_top
1408 }
1409
1410 pub fn scrolled_to_bottom(&self) -> bool {
1411 self.last_content.scrolled_to_bottom
1412 }
1413
1414 ///Resize the terminal and the PTY.
1415 pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1416 if self.last_content.terminal_bounds != new_bounds {
1417 self.events.push_back(InternalEvent::Resize(new_bounds))
1418 }
1419 }
1420
1421 /// Write the Input payload to the PTY, if applicable.
1422 /// (This is a no-op for display-only terminals.)
1423 fn write_to_pty(&self, input: impl Into<Cow<'static, [u8]>>) {
1424 if let TerminalType::Pty { pty_tx, .. } = &self.terminal_type {
1425 let input = input.into();
1426 if log::log_enabled!(log::Level::Debug) {
1427 if let Ok(str) = str::from_utf8(&input) {
1428 log::debug!("Writing to PTY: {:?}", str);
1429 } else {
1430 log::debug!("Writing to PTY: {:?}", input);
1431 }
1432 }
1433 pty_tx.notify(input);
1434 }
1435 }
1436
1437 pub fn input(&mut self, input: impl Into<Cow<'static, [u8]>>) {
1438 self.events
1439 .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1440 self.events.push_back(InternalEvent::SetSelection(None));
1441
1442 self.write_to_pty(input);
1443 }
1444
1445 pub fn toggle_vi_mode(&mut self) {
1446 self.events.push_back(InternalEvent::ToggleViMode);
1447 }
1448
1449 pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1450 if !self.vi_mode_enabled {
1451 return;
1452 }
1453
1454 let key: Cow<'_, str> = if keystroke.modifiers.shift {
1455 Cow::Owned(keystroke.key.to_uppercase())
1456 } else {
1457 Cow::Borrowed(keystroke.key.as_str())
1458 };
1459
1460 let motion: Option<ViMotion> = match key.as_ref() {
1461 "h" | "left" => Some(ViMotion::Left),
1462 "j" | "down" => Some(ViMotion::Down),
1463 "k" | "up" => Some(ViMotion::Up),
1464 "l" | "right" => Some(ViMotion::Right),
1465 "w" => Some(ViMotion::WordRight),
1466 "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1467 "e" => Some(ViMotion::WordRightEnd),
1468 "%" => Some(ViMotion::Bracket),
1469 "$" => Some(ViMotion::Last),
1470 "0" => Some(ViMotion::First),
1471 "^" => Some(ViMotion::FirstOccupied),
1472 "H" => Some(ViMotion::High),
1473 "M" => Some(ViMotion::Middle),
1474 "L" => Some(ViMotion::Low),
1475 _ => None,
1476 };
1477
1478 if let Some(motion) = motion {
1479 let cursor = self.last_content.cursor.point;
1480 let cursor_pos = Point {
1481 x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1482 y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1483 };
1484 self.events
1485 .push_back(InternalEvent::UpdateSelection(cursor_pos));
1486 self.events.push_back(InternalEvent::ViMotion(motion));
1487 return;
1488 }
1489
1490 let scroll_motion = match key.as_ref() {
1491 "g" => Some(AlacScroll::Top),
1492 "G" => Some(AlacScroll::Bottom),
1493 "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1494 "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1495 "d" if keystroke.modifiers.control => {
1496 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1497 Some(AlacScroll::Delta(-amount))
1498 }
1499 "u" if keystroke.modifiers.control => {
1500 let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1501 Some(AlacScroll::Delta(amount))
1502 }
1503 _ => None,
1504 };
1505
1506 if let Some(scroll_motion) = scroll_motion {
1507 self.events.push_back(InternalEvent::Scroll(scroll_motion));
1508 return;
1509 }
1510
1511 match key.as_ref() {
1512 "v" => {
1513 let point = self.last_content.cursor.point;
1514 let selection_type = SelectionType::Simple;
1515 let side = AlacDirection::Right;
1516 let selection = Selection::new(selection_type, point, side);
1517 self.events
1518 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1519 }
1520
1521 "escape" => {
1522 self.events.push_back(InternalEvent::SetSelection(None));
1523 }
1524
1525 "y" => {
1526 self.copy(Some(false));
1527 }
1528
1529 "i" => {
1530 self.scroll_to_bottom();
1531 self.toggle_vi_mode();
1532 }
1533 _ => {}
1534 }
1535 }
1536
1537 pub fn try_keystroke(&mut self, keystroke: &Keystroke, option_as_meta: bool) -> bool {
1538 if self.vi_mode_enabled {
1539 self.vi_motion(keystroke);
1540 return true;
1541 }
1542
1543 // Keep default terminal behavior
1544 let esc = to_esc_str(keystroke, &self.last_content.mode, option_as_meta);
1545 if let Some(esc) = esc {
1546 match esc {
1547 Cow::Borrowed(string) => self.input(string.as_bytes()),
1548 Cow::Owned(string) => self.input(string.into_bytes()),
1549 };
1550 true
1551 } else {
1552 false
1553 }
1554 }
1555
1556 pub fn try_modifiers_change(
1557 &mut self,
1558 modifiers: &Modifiers,
1559 window: &Window,
1560 cx: &mut Context<Self>,
1561 ) {
1562 if self
1563 .last_content
1564 .terminal_bounds
1565 .bounds
1566 .contains(&window.mouse_position())
1567 && modifiers.secondary()
1568 {
1569 self.refresh_hovered_word(window);
1570 }
1571 cx.notify();
1572 }
1573
1574 ///Paste text into the terminal
1575 pub fn paste(&mut self, text: &str) {
1576 let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1577 format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1578 } else {
1579 text.replace("\r\n", "\r").replace('\n', "\r")
1580 };
1581
1582 self.input(paste_text.into_bytes());
1583 }
1584
1585 pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1586 let term = self.term.clone();
1587 let mut terminal = term.lock_unfair();
1588 //Note that the ordering of events matters for event processing
1589 while let Some(e) = self.events.pop_front() {
1590 self.process_terminal_event(&e, &mut terminal, window, cx)
1591 }
1592
1593 self.last_content = Self::make_content(&terminal, &self.last_content);
1594 }
1595
1596 fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1597 let content = term.renderable_content();
1598
1599 // Pre-allocate with estimated size to reduce reallocations
1600 let estimated_size = content.display_iter.size_hint().0;
1601 let mut cells = Vec::with_capacity(estimated_size);
1602
1603 cells.extend(content.display_iter.map(|ic| IndexedCell {
1604 point: ic.point,
1605 cell: ic.cell.clone(),
1606 }));
1607
1608 let selection_text = if content.selection.is_some() {
1609 term.selection_to_string()
1610 } else {
1611 None
1612 };
1613
1614 TerminalContent {
1615 cells,
1616 mode: content.mode,
1617 display_offset: content.display_offset,
1618 selection_text,
1619 selection: content.selection,
1620 cursor: content.cursor,
1621 cursor_char: term.grid()[content.cursor.point].c,
1622 terminal_bounds: last_content.terminal_bounds,
1623 last_hovered_word: last_content.last_hovered_word.clone(),
1624 scrolled_to_top: content.display_offset == term.history_size(),
1625 scrolled_to_bottom: content.display_offset == 0,
1626 }
1627 }
1628
1629 pub fn get_content(&self) -> String {
1630 let term = self.term.lock_unfair();
1631 let start = AlacPoint::new(term.topmost_line(), Column(0));
1632 let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1633 term.bounds_to_string(start, end)
1634 }
1635
1636 pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1637 let term = self.term.clone();
1638 let terminal = term.lock_unfair();
1639 let grid = terminal.grid();
1640 let mut lines = Vec::new();
1641
1642 let mut current_line = grid.bottommost_line().0;
1643 let topmost_line = grid.topmost_line().0;
1644
1645 while current_line >= topmost_line && lines.len() < n {
1646 let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1647 let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1648
1649 if let Some(line) = self.process_line(logical_line) {
1650 lines.push(line);
1651 }
1652
1653 // Move to the line above the start of the current logical line
1654 current_line = logical_line_start - 1;
1655 }
1656
1657 lines.reverse();
1658 lines
1659 }
1660
1661 fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1662 let mut line_start = current;
1663 while line_start > topmost {
1664 let prev_line = Line(line_start - 1);
1665 let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1666 if !last_cell.flags.contains(Flags::WRAPLINE) {
1667 break;
1668 }
1669 line_start -= 1;
1670 }
1671 line_start
1672 }
1673
1674 fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1675 let mut logical_line = String::new();
1676 for row in start..=end {
1677 let grid_row = &grid[Line(row)];
1678 logical_line.push_str(&row_to_string(grid_row));
1679 }
1680 logical_line
1681 }
1682
1683 fn process_line(&self, line: String) -> Option<String> {
1684 let trimmed = line.trim_end().to_string();
1685 if !trimmed.is_empty() {
1686 Some(trimmed)
1687 } else {
1688 None
1689 }
1690 }
1691
1692 pub fn focus_in(&self) {
1693 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1694 self.write_to_pty("\x1b[I".as_bytes());
1695 }
1696 }
1697
1698 pub fn focus_out(&mut self) {
1699 if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1700 self.write_to_pty("\x1b[O".as_bytes());
1701 }
1702 }
1703
1704 pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1705 match self.last_mouse {
1706 Some((old_point, old_side)) => {
1707 if old_point == point && old_side == side {
1708 false
1709 } else {
1710 self.last_mouse = Some((point, side));
1711 true
1712 }
1713 }
1714 None => {
1715 self.last_mouse = Some((point, side));
1716 true
1717 }
1718 }
1719 }
1720
1721 pub fn mouse_mode(&self, shift: bool) -> bool {
1722 self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1723 }
1724
1725 pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1726 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1727 if self.mouse_mode(e.modifiers.shift) {
1728 let (point, side) = grid_point_and_side(
1729 position,
1730 self.last_content.terminal_bounds,
1731 self.last_content.display_offset,
1732 );
1733
1734 if self.mouse_changed(point, side)
1735 && let Some(bytes) =
1736 mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1737 {
1738 self.write_to_pty(bytes);
1739 }
1740 } else {
1741 self.schedule_find_hyperlink(e.modifiers, e.position);
1742 }
1743 cx.notify();
1744 }
1745
1746 fn schedule_find_hyperlink(&mut self, modifiers: Modifiers, position: Point<Pixels>) {
1747 if self.selection_phase == SelectionPhase::Selecting
1748 || !modifiers.secondary()
1749 || !self.last_content.terminal_bounds.bounds.contains(&position)
1750 {
1751 self.last_content.last_hovered_word = None;
1752 return;
1753 }
1754
1755 // Throttle hyperlink searches to avoid excessive processing
1756 let now = Instant::now();
1757 if self
1758 .last_hyperlink_search_position
1759 .map_or(true, |last_pos| {
1760 // Only search if mouse moved significantly or enough time passed
1761 let distance_moved = ((position.x - last_pos.x).abs()
1762 + (position.y - last_pos.y).abs())
1763 > FIND_HYPERLINK_THROTTLE_PX;
1764 let time_elapsed = now.duration_since(self.last_mouse_move_time).as_millis() > 100;
1765 distance_moved || time_elapsed
1766 })
1767 {
1768 self.last_mouse_move_time = now;
1769 self.last_hyperlink_search_position = Some(position);
1770 self.events.push_back(InternalEvent::FindHyperlink(
1771 position - self.last_content.terminal_bounds.bounds.origin,
1772 false,
1773 ));
1774 }
1775 }
1776
1777 pub fn select_word_at_event_position(&mut self, e: &MouseDownEvent) {
1778 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1779 let (point, side) = grid_point_and_side(
1780 position,
1781 self.last_content.terminal_bounds,
1782 self.last_content.display_offset,
1783 );
1784 let selection = Selection::new(SelectionType::Semantic, point, side);
1785 self.events
1786 .push_back(InternalEvent::SetSelection(Some((selection, point))));
1787 }
1788
1789 pub fn mouse_drag(
1790 &mut self,
1791 e: &MouseMoveEvent,
1792 region: Bounds<Pixels>,
1793 cx: &mut Context<Self>,
1794 ) {
1795 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1796 if !self.mouse_mode(e.modifiers.shift) {
1797 if let Some((.., hyperlink_range)) = &self.mouse_down_hyperlink {
1798 let point = grid_point(
1799 position,
1800 self.last_content.terminal_bounds,
1801 self.last_content.display_offset,
1802 );
1803
1804 if !hyperlink_range.contains(&point) {
1805 self.mouse_down_hyperlink = None;
1806 } else {
1807 return;
1808 }
1809 }
1810
1811 self.selection_phase = SelectionPhase::Selecting;
1812 // Alacritty has the same ordering, of first updating the selection
1813 // then scrolling 15ms later
1814 self.events
1815 .push_back(InternalEvent::UpdateSelection(position));
1816
1817 // Doesn't make sense to scroll the alt screen
1818 if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1819 let scroll_lines = match self.drag_line_delta(e, region) {
1820 Some(value) => value,
1821 None => return,
1822 };
1823
1824 self.events
1825 .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1826 }
1827
1828 cx.notify();
1829 }
1830 }
1831
1832 fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1833 let top = region.origin.y;
1834 let bottom = region.bottom_left().y;
1835
1836 let scroll_lines = if e.position.y < top {
1837 let scroll_delta = (top - e.position.y).pow(1.1);
1838 (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1839 } else if e.position.y > bottom {
1840 let scroll_delta = -((e.position.y - bottom).pow(1.1));
1841 (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1842 } else {
1843 return None;
1844 };
1845
1846 Some(scroll_lines.clamp(-3, 3))
1847 }
1848
1849 pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1850 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1851 let point = grid_point(
1852 position,
1853 self.last_content.terminal_bounds,
1854 self.last_content.display_offset,
1855 );
1856
1857 if e.button == MouseButton::Left
1858 && e.modifiers.secondary()
1859 && !self.mouse_mode(e.modifiers.shift)
1860 {
1861 let term_lock = self.term.lock();
1862 self.mouse_down_hyperlink = terminal_hyperlinks::find_from_grid_point(
1863 &term_lock,
1864 point,
1865 &mut self.hyperlink_regex_searches,
1866 );
1867 drop(term_lock);
1868
1869 if self.mouse_down_hyperlink.is_some() {
1870 return;
1871 }
1872 }
1873
1874 if self.mouse_mode(e.modifiers.shift) {
1875 if let Some(bytes) =
1876 mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1877 {
1878 self.write_to_pty(bytes);
1879 }
1880 } else {
1881 match e.button {
1882 MouseButton::Left => {
1883 let (point, side) = grid_point_and_side(
1884 position,
1885 self.last_content.terminal_bounds,
1886 self.last_content.display_offset,
1887 );
1888
1889 let selection_type = match e.click_count {
1890 0 => return, //This is a release
1891 1 => Some(SelectionType::Simple),
1892 2 => Some(SelectionType::Semantic),
1893 3 => Some(SelectionType::Lines),
1894 _ => None,
1895 };
1896
1897 if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1898 self.events
1899 .push_back(InternalEvent::UpdateSelection(position));
1900 return;
1901 }
1902
1903 let selection = selection_type
1904 .map(|selection_type| Selection::new(selection_type, point, side));
1905
1906 if let Some(sel) = selection {
1907 self.events
1908 .push_back(InternalEvent::SetSelection(Some((sel, point))));
1909 }
1910 }
1911 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1912 MouseButton::Middle => {
1913 if let Some(item) = _cx.read_from_primary() {
1914 let text = item.text().unwrap_or_default();
1915 self.input(text.into_bytes());
1916 }
1917 }
1918 _ => {}
1919 }
1920 }
1921 }
1922
1923 pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1924 let setting = TerminalSettings::get_global(cx);
1925
1926 let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1927 if self.mouse_mode(e.modifiers.shift) {
1928 let point = grid_point(
1929 position,
1930 self.last_content.terminal_bounds,
1931 self.last_content.display_offset,
1932 );
1933
1934 if let Some(bytes) =
1935 mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1936 {
1937 self.write_to_pty(bytes);
1938 }
1939 } else {
1940 if e.button == MouseButton::Left && setting.copy_on_select {
1941 self.copy(Some(true));
1942 }
1943
1944 if let Some(mouse_down_hyperlink) = self.mouse_down_hyperlink.take() {
1945 let point = grid_point(
1946 position,
1947 self.last_content.terminal_bounds,
1948 self.last_content.display_offset,
1949 );
1950
1951 if let Some(mouse_up_hyperlink) = {
1952 let term_lock = self.term.lock();
1953 terminal_hyperlinks::find_from_grid_point(
1954 &term_lock,
1955 point,
1956 &mut self.hyperlink_regex_searches,
1957 )
1958 } {
1959 if mouse_down_hyperlink == mouse_up_hyperlink {
1960 self.events
1961 .push_back(InternalEvent::ProcessHyperlink(mouse_up_hyperlink, true));
1962 self.selection_phase = SelectionPhase::Ended;
1963 self.last_mouse = None;
1964 return;
1965 }
1966 }
1967 }
1968
1969 //Hyperlinks
1970 if self.selection_phase == SelectionPhase::Ended {
1971 let mouse_cell_index =
1972 content_index_for_mouse(position, &self.last_content.terminal_bounds);
1973 if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1974 cx.open_url(link.uri());
1975 } else if e.modifiers.secondary() {
1976 self.events
1977 .push_back(InternalEvent::FindHyperlink(position, true));
1978 }
1979 }
1980 }
1981
1982 self.selection_phase = SelectionPhase::Ended;
1983 self.last_mouse = None;
1984 }
1985
1986 ///Scroll the terminal
1987 pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, scroll_multiplier: f32) {
1988 let mouse_mode = self.mouse_mode(e.shift);
1989 let scroll_multiplier = if mouse_mode { 1. } else { scroll_multiplier };
1990
1991 if let Some(scroll_lines) = self.determine_scroll_lines(e, scroll_multiplier)
1992 && scroll_lines != 0
1993 {
1994 if mouse_mode {
1995 let point = grid_point(
1996 e.position - self.last_content.terminal_bounds.bounds.origin,
1997 self.last_content.terminal_bounds,
1998 self.last_content.display_offset,
1999 );
2000
2001 if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
2002 {
2003 for scroll in scrolls {
2004 self.write_to_pty(scroll);
2005 }
2006 };
2007 } else if self
2008 .last_content
2009 .mode
2010 .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
2011 && !e.shift
2012 {
2013 self.write_to_pty(alt_scroll(scroll_lines));
2014 } else {
2015 let scroll = AlacScroll::Delta(scroll_lines);
2016
2017 self.events.push_back(InternalEvent::Scroll(scroll));
2018 }
2019 }
2020 }
2021
2022 fn refresh_hovered_word(&mut self, window: &Window) {
2023 self.schedule_find_hyperlink(window.modifiers(), window.mouse_position());
2024 }
2025
2026 fn determine_scroll_lines(
2027 &mut self,
2028 e: &ScrollWheelEvent,
2029 scroll_multiplier: f32,
2030 ) -> Option<i32> {
2031 let line_height = self.last_content.terminal_bounds.line_height;
2032 match e.touch_phase {
2033 /* Reset scroll state on started */
2034 TouchPhase::Started => {
2035 self.scroll_px = px(0.);
2036 None
2037 }
2038 /* Calculate the appropriate scroll lines */
2039 TouchPhase::Moved => {
2040 let old_offset = (self.scroll_px / line_height) as i32;
2041
2042 self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
2043
2044 let new_offset = (self.scroll_px / line_height) as i32;
2045
2046 // Whenever we hit the edges, reset our stored scroll to 0
2047 // so we can respond to changes in direction quickly
2048 self.scroll_px %= self.last_content.terminal_bounds.height();
2049
2050 Some(new_offset - old_offset)
2051 }
2052 TouchPhase::Ended => None,
2053 }
2054 }
2055
2056 pub fn find_matches(
2057 &self,
2058 mut searcher: RegexSearch,
2059 cx: &Context<Self>,
2060 ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
2061 let term = self.term.clone();
2062 cx.background_spawn(async move {
2063 let term = term.lock();
2064
2065 all_search_matches(&term, &mut searcher).collect()
2066 })
2067 }
2068
2069 pub fn working_directory(&self) -> Option<PathBuf> {
2070 if self.is_remote_terminal {
2071 // We can't yet reliably detect the working directory of a shell on the
2072 // SSH host. Until we can do that, it doesn't make sense to display
2073 // the working directory on the client and persist that.
2074 None
2075 } else {
2076 self.client_side_working_directory()
2077 }
2078 }
2079
2080 /// Returns the working directory of the process that's connected to the PTY.
2081 /// That means it returns the working directory of the local shell or program
2082 /// that's running inside the terminal.
2083 ///
2084 /// This does *not* return the working directory of the shell that runs on the
2085 /// remote host, in case Zed is connected to a remote host.
2086 fn client_side_working_directory(&self) -> Option<PathBuf> {
2087 match &self.terminal_type {
2088 TerminalType::Pty { info, .. } => {
2089 info.current.as_ref().map(|process| process.cwd.clone())
2090 }
2091 TerminalType::DisplayOnly => None,
2092 }
2093 }
2094
2095 pub fn title(&self, truncate: bool) -> String {
2096 const MAX_CHARS: usize = 25;
2097 match &self.task {
2098 Some(task_state) => {
2099 if truncate {
2100 truncate_and_trailoff(&task_state.spawned_task.label, MAX_CHARS)
2101 } else {
2102 task_state.spawned_task.full_label.clone()
2103 }
2104 }
2105 None => self
2106 .title_override
2107 .as_ref()
2108 .map(|title_override| title_override.to_string())
2109 .unwrap_or_else(|| match &self.terminal_type {
2110 TerminalType::Pty { info, .. } => info
2111 .current
2112 .as_ref()
2113 .map(|fpi| {
2114 let process_file = fpi
2115 .cwd
2116 .file_name()
2117 .map(|name| name.to_string_lossy().into_owned())
2118 .unwrap_or_default();
2119
2120 let argv = fpi.argv.as_slice();
2121 let process_name = format!(
2122 "{}{}",
2123 fpi.name,
2124 if !argv.is_empty() {
2125 format!(" {}", (argv[1..]).join(" "))
2126 } else {
2127 "".to_string()
2128 }
2129 );
2130 let (process_file, process_name) = if truncate {
2131 (
2132 truncate_and_trailoff(&process_file, MAX_CHARS),
2133 truncate_and_trailoff(&process_name, MAX_CHARS),
2134 )
2135 } else {
2136 (process_file, process_name)
2137 };
2138 format!("{process_file} — {process_name}")
2139 })
2140 .unwrap_or_else(|| "Terminal".to_string()),
2141 TerminalType::DisplayOnly => "Terminal".to_string(),
2142 }),
2143 }
2144 }
2145
2146 pub fn kill_active_task(&mut self) {
2147 if let Some(task) = self.task()
2148 && task.status == TaskStatus::Running
2149 {
2150 if let TerminalType::Pty { info, .. } = &mut self.terminal_type {
2151 // First kill the foreground process group (the command running in the shell)
2152 info.kill_current_process();
2153 // Then kill the shell itself so that the terminal exits properly
2154 // and wait_for_completed_task can complete
2155 info.kill_child_process();
2156 }
2157 }
2158 }
2159
2160 pub fn pid(&self) -> Option<sysinfo::Pid> {
2161 match &self.terminal_type {
2162 TerminalType::Pty { info, .. } => info.pid(),
2163 TerminalType::DisplayOnly => None,
2164 }
2165 }
2166
2167 pub fn pid_getter(&self) -> Option<&ProcessIdGetter> {
2168 match &self.terminal_type {
2169 TerminalType::Pty { info, .. } => Some(info.pid_getter()),
2170 TerminalType::DisplayOnly => None,
2171 }
2172 }
2173
2174 pub fn task(&self) -> Option<&TaskState> {
2175 self.task.as_ref()
2176 }
2177
2178 pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
2179 if let Some(task) = self.task() {
2180 if task.status == TaskStatus::Running {
2181 let completion_receiver = task.completion_rx.clone();
2182 return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
2183 } else if let Ok(status) = task.completion_rx.try_recv() {
2184 return Task::ready(status);
2185 }
2186 }
2187 Task::ready(None)
2188 }
2189
2190 fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
2191 let e: Option<ExitStatus> = error_code.map(|code| {
2192 #[cfg(unix)]
2193 {
2194 std::os::unix::process::ExitStatusExt::from_raw(code)
2195 }
2196 #[cfg(windows)]
2197 {
2198 std::os::windows::process::ExitStatusExt::from_raw(code as u32)
2199 }
2200 });
2201
2202 if let Some(tx) = &self.completion_tx {
2203 tx.try_send(e).ok();
2204 }
2205 if let Some(e) = e {
2206 self.child_exited = Some(e);
2207 }
2208 let task = match &mut self.task {
2209 Some(task) => task,
2210 None => {
2211 if self.child_exited.is_none_or(|e| e.code() == Some(0)) {
2212 cx.emit(Event::CloseTerminal);
2213 }
2214 return;
2215 }
2216 };
2217 if task.status != TaskStatus::Running {
2218 return;
2219 }
2220 match error_code {
2221 Some(error_code) => {
2222 task.status.register_task_exit(error_code);
2223 }
2224 None => {
2225 task.status.register_terminal_exit();
2226 }
2227 };
2228
2229 let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
2230 let mut lines_to_show = Vec::new();
2231 if task.spawned_task.show_summary {
2232 lines_to_show.push(task_line.as_str());
2233 }
2234 if task.spawned_task.show_command {
2235 lines_to_show.push(command_line.as_str());
2236 }
2237
2238 if !lines_to_show.is_empty() {
2239 // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
2240 // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
2241 // when Zed task finishes and no more output is made.
2242 // After the task summary is output once, no more text is appended to the terminal.
2243 unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
2244 }
2245
2246 match task.spawned_task.hide {
2247 HideStrategy::Never => {}
2248 HideStrategy::Always => {
2249 cx.emit(Event::CloseTerminal);
2250 }
2251 HideStrategy::OnSuccess => {
2252 if finished_successfully {
2253 cx.emit(Event::CloseTerminal);
2254 }
2255 }
2256 }
2257 }
2258
2259 pub fn vi_mode_enabled(&self) -> bool {
2260 self.vi_mode_enabled
2261 }
2262
2263 pub fn clone_builder(&self, cx: &App, cwd: Option<PathBuf>) -> Task<Result<TerminalBuilder>> {
2264 let working_directory = self.working_directory().or_else(|| cwd);
2265 TerminalBuilder::new(
2266 working_directory,
2267 None,
2268 self.template.shell.clone(),
2269 self.template.env.clone(),
2270 self.template.cursor_shape,
2271 self.template.alternate_scroll,
2272 self.template.max_scroll_history_lines,
2273 self.template.path_hyperlink_regexes.clone(),
2274 self.template.path_hyperlink_timeout_ms,
2275 self.is_remote_terminal,
2276 self.template.window_id,
2277 None,
2278 cx,
2279 self.activation_script.clone(),
2280 )
2281 }
2282}
2283
2284// Helper function to convert a grid row to a string
2285pub fn row_to_string(row: &Row<Cell>) -> String {
2286 row[..Column(row.len())]
2287 .iter()
2288 .map(|cell| cell.c)
2289 .collect::<String>()
2290}
2291
2292const TASK_DELIMITER: &str = "⏵ ";
2293fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
2294 let escaped_full_label = task
2295 .spawned_task
2296 .full_label
2297 .replace("\r\n", "\r")
2298 .replace('\n', "\r");
2299 let success = error_code == Some(0);
2300 let task_line = match error_code {
2301 Some(0) => format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
2302 Some(error_code) => format!(
2303 "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
2304 ),
2305 None => format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
2306 };
2307 let escaped_command_label = task
2308 .spawned_task
2309 .command_label
2310 .replace("\r\n", "\r")
2311 .replace('\n', "\r");
2312 let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
2313 (success, task_line, command_line)
2314}
2315
2316/// Appends a stringified task summary to the terminal, after its output.
2317///
2318/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
2319/// New text being added to the terminal here, uses "less public" APIs,
2320/// which are not maintaining the entire terminal state intact.
2321///
2322///
2323/// The library
2324///
2325/// * does not increment inner grid cursor's _lines_ on `input` calls
2326/// (but displaying the lines correctly and incrementing cursor's columns)
2327///
2328/// * ignores `\n` and \r` character input, requiring the `newline` call instead
2329///
2330/// * does not alter grid state after `newline` call
2331/// so its `bottommost_line` is always the same additions, and
2332/// the cursor's `point` is not updated to the new line and column values
2333///
2334/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
2335/// Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
2336///
2337/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
2338/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
2339/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
2340/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
2341unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
2342 term.newline();
2343 term.grid_mut().cursor.point.column = Column(0);
2344 for line in text_lines {
2345 for c in line.chars() {
2346 term.input(c);
2347 }
2348 term.newline();
2349 term.grid_mut().cursor.point.column = Column(0);
2350 }
2351}
2352
2353impl Drop for Terminal {
2354 fn drop(&mut self) {
2355 if let TerminalType::Pty { pty_tx, info } = &mut self.terminal_type {
2356 info.kill_child_process();
2357 pty_tx.0.send(Msg::Shutdown).ok();
2358 }
2359 }
2360}
2361
2362impl EventEmitter<Event> for Terminal {}
2363
2364fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
2365 let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
2366 selection.update(*range.end(), AlacDirection::Right);
2367 selection
2368}
2369
2370fn all_search_matches<'a, T>(
2371 term: &'a Term<T>,
2372 regex: &'a mut RegexSearch,
2373) -> impl Iterator<Item = Match> + 'a {
2374 let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
2375 let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
2376 RegexIter::new(start, end, AlacDirection::Right, term, regex)
2377}
2378
2379fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
2380 let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
2381 let clamped_col = min(col, terminal_bounds.columns() - 1);
2382 let row = (pos.y / terminal_bounds.line_height()).round() as usize;
2383 let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
2384 clamped_row * terminal_bounds.columns() + clamped_col
2385}
2386
2387/// Converts an 8 bit ANSI color to its GPUI equivalent.
2388/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
2389/// Other than that use case, should only be called with values in the `[0,255]` range
2390pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
2391 let colors = theme.colors();
2392
2393 match index {
2394 // 0-15 are the same as the named colors above
2395 0 => colors.terminal_ansi_black,
2396 1 => colors.terminal_ansi_red,
2397 2 => colors.terminal_ansi_green,
2398 3 => colors.terminal_ansi_yellow,
2399 4 => colors.terminal_ansi_blue,
2400 5 => colors.terminal_ansi_magenta,
2401 6 => colors.terminal_ansi_cyan,
2402 7 => colors.terminal_ansi_white,
2403 8 => colors.terminal_ansi_bright_black,
2404 9 => colors.terminal_ansi_bright_red,
2405 10 => colors.terminal_ansi_bright_green,
2406 11 => colors.terminal_ansi_bright_yellow,
2407 12 => colors.terminal_ansi_bright_blue,
2408 13 => colors.terminal_ansi_bright_magenta,
2409 14 => colors.terminal_ansi_bright_cyan,
2410 15 => colors.terminal_ansi_bright_white,
2411 // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
2412 // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
2413 16..=231 => {
2414 let (r, g, b) = rgb_for_index(index as u8);
2415 rgba_color(
2416 if r == 0 { 0 } else { r * 40 + 55 },
2417 if g == 0 { 0 } else { g * 40 + 55 },
2418 if b == 0 { 0 } else { b * 40 + 55 },
2419 )
2420 }
2421 // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
2422 232..=255 => {
2423 let i = index as u8 - 232; // Align index to 0..24
2424 let value = i * 10 + 8;
2425 rgba_color(value, value, value)
2426 }
2427 // For compatibility with the alacritty::Colors interface
2428 // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
2429 256 => colors.terminal_foreground,
2430 257 => colors.terminal_background,
2431 258 => theme.players().local().cursor,
2432 259 => colors.terminal_ansi_dim_black,
2433 260 => colors.terminal_ansi_dim_red,
2434 261 => colors.terminal_ansi_dim_green,
2435 262 => colors.terminal_ansi_dim_yellow,
2436 263 => colors.terminal_ansi_dim_blue,
2437 264 => colors.terminal_ansi_dim_magenta,
2438 265 => colors.terminal_ansi_dim_cyan,
2439 266 => colors.terminal_ansi_dim_white,
2440 267 => colors.terminal_bright_foreground,
2441 268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2442
2443 _ => black(),
2444 }
2445}
2446
2447/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2448///
2449/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2450///
2451/// Wikipedia gives a formula for calculating the index for a given color:
2452///
2453/// ```text
2454/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2455/// ```
2456///
2457/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2458fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2459 debug_assert!((16..=231).contains(&i));
2460 let i = i - 16;
2461 let r = (i - (i % 36)) / 36;
2462 let g = ((i % 36) - (i % 6)) / 6;
2463 let b = (i % 36) % 6;
2464 (r, g, b)
2465}
2466
2467pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2468 Rgba {
2469 r: (r as f32 / 255.),
2470 g: (g as f32 / 255.),
2471 b: (b as f32 / 255.),
2472 a: 1.,
2473 }
2474 .into()
2475}
2476
2477#[cfg(test)]
2478mod tests {
2479 use std::time::Duration;
2480
2481 use super::*;
2482 use crate::{
2483 IndexedCell, TerminalBounds, TerminalBuilder, TerminalContent, content_index_for_mouse,
2484 rgb_for_index,
2485 };
2486 use alacritty_terminal::{
2487 index::{Column, Line, Point as AlacPoint},
2488 term::cell::Cell,
2489 };
2490 use collections::HashMap;
2491 use gpui::{
2492 Entity, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
2493 Point, TestAppContext, bounds, point, size,
2494 };
2495 use parking_lot::Mutex;
2496 use rand::{Rng, distr, rngs::ThreadRng};
2497 use smol::channel::Receiver;
2498 use task::{Shell, ShellBuilder};
2499
2500 /// Helper to build a test terminal running a shell command.
2501 /// Returns the terminal entity and a receiver for the completion signal.
2502 async fn build_test_terminal(
2503 cx: &mut TestAppContext,
2504 command: &str,
2505 args: &[&str],
2506 ) -> (Entity<Terminal>, Receiver<Option<ExitStatus>>) {
2507 let (completion_tx, completion_rx) = smol::channel::unbounded();
2508 let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
2509 let (program, args) =
2510 ShellBuilder::new(&Shell::System, false).build(Some(command.to_owned()), &args);
2511 let builder = cx
2512 .update(|cx| {
2513 TerminalBuilder::new(
2514 None,
2515 None,
2516 task::Shell::WithArguments {
2517 program,
2518 args,
2519 title_override: None,
2520 },
2521 HashMap::default(),
2522 CursorShape::default(),
2523 AlternateScroll::On,
2524 None,
2525 vec![],
2526 0,
2527 false,
2528 0,
2529 Some(completion_tx),
2530 cx,
2531 vec![],
2532 )
2533 })
2534 .await
2535 .unwrap();
2536 let terminal = cx.new(|cx| builder.subscribe(cx));
2537 (terminal, completion_rx)
2538 }
2539
2540 fn init_ctrl_click_hyperlink_test(cx: &mut TestAppContext, output: &[u8]) -> Entity<Terminal> {
2541 cx.update(|cx| {
2542 let settings_store = settings::SettingsStore::test(cx);
2543 cx.set_global(settings_store);
2544 });
2545
2546 let terminal = cx.new(|cx| {
2547 TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2548 .unwrap()
2549 .subscribe(cx)
2550 });
2551
2552 terminal.update(cx, |terminal, cx| {
2553 terminal.write_output(output, cx);
2554 });
2555
2556 cx.run_until_parked();
2557
2558 terminal.update(cx, |terminal, _cx| {
2559 let term_lock = terminal.term.lock();
2560 terminal.last_content = Terminal::make_content(&term_lock, &terminal.last_content);
2561 drop(term_lock);
2562
2563 let terminal_bounds = TerminalBounds::new(
2564 px(20.0),
2565 px(10.0),
2566 bounds(point(px(0.0), px(0.0)), size(px(400.0), px(400.0))),
2567 );
2568 terminal.last_content.terminal_bounds = terminal_bounds;
2569 terminal.events.clear();
2570 });
2571
2572 terminal
2573 }
2574
2575 fn ctrl_mouse_down_at(
2576 terminal: &mut Terminal,
2577 position: Point<Pixels>,
2578 cx: &mut Context<Terminal>,
2579 ) {
2580 let mouse_down = MouseDownEvent {
2581 button: MouseButton::Left,
2582 position,
2583 modifiers: Modifiers::secondary_key(),
2584 click_count: 1,
2585 first_mouse: true,
2586 };
2587 terminal.mouse_down(&mouse_down, cx);
2588 }
2589
2590 fn ctrl_mouse_move_to(
2591 terminal: &mut Terminal,
2592 position: Point<Pixels>,
2593 cx: &mut Context<Terminal>,
2594 ) {
2595 let terminal_bounds = terminal.last_content.terminal_bounds.bounds;
2596 let drag_event = MouseMoveEvent {
2597 position,
2598 pressed_button: Some(MouseButton::Left),
2599 modifiers: Modifiers::secondary_key(),
2600 };
2601 terminal.mouse_drag(&drag_event, terminal_bounds, cx);
2602 }
2603
2604 fn ctrl_mouse_up_at(
2605 terminal: &mut Terminal,
2606 position: Point<Pixels>,
2607 cx: &mut Context<Terminal>,
2608 ) {
2609 let mouse_up = MouseUpEvent {
2610 button: MouseButton::Left,
2611 position,
2612 modifiers: Modifiers::secondary_key(),
2613 click_count: 1,
2614 };
2615 terminal.mouse_up(&mouse_up, cx);
2616 }
2617
2618 #[gpui::test]
2619 async fn test_basic_terminal(cx: &mut TestAppContext) {
2620 cx.executor().allow_parking();
2621
2622 let (terminal, completion_rx) = build_test_terminal(cx, "echo", &["hello"]).await;
2623 assert_eq!(
2624 completion_rx.recv().await.unwrap(),
2625 Some(ExitStatus::default())
2626 );
2627 assert_eq!(
2628 terminal.update(cx, |term, _| term.get_content()).trim(),
2629 "hello"
2630 );
2631
2632 // Inject additional output directly into the emulator (display-only path)
2633 terminal.update(cx, |term, cx| {
2634 term.write_output(b"\nfrom_injection", cx);
2635 });
2636
2637 let content_after = terminal.update(cx, |term, _| term.get_content());
2638 assert!(
2639 content_after.contains("from_injection"),
2640 "expected injected output to appear, got: {content_after}"
2641 );
2642 }
2643
2644 // TODO should be tested on Linux too, but does not work there well
2645 #[cfg(target_os = "macos")]
2646 #[gpui::test(iterations = 10)]
2647 async fn test_terminal_eof(cx: &mut TestAppContext) {
2648 cx.executor().allow_parking();
2649
2650 let (completion_tx, completion_rx) = smol::channel::unbounded();
2651 let builder = cx
2652 .update(|cx| {
2653 TerminalBuilder::new(
2654 None,
2655 None,
2656 task::Shell::System,
2657 HashMap::default(),
2658 CursorShape::default(),
2659 AlternateScroll::On,
2660 None,
2661 vec![],
2662 0,
2663 false,
2664 0,
2665 Some(completion_tx),
2666 cx,
2667 Vec::new(),
2668 )
2669 })
2670 .await
2671 .unwrap();
2672 // Build an empty command, which will result in a tty shell spawned.
2673 let terminal = cx.new(|cx| builder.subscribe(cx));
2674
2675 let (event_tx, event_rx) = smol::channel::unbounded::<Event>();
2676 cx.update(|cx| {
2677 cx.subscribe(&terminal, move |_, e, _| {
2678 event_tx.send_blocking(e.clone()).unwrap();
2679 })
2680 })
2681 .detach();
2682 cx.background_spawn(async move {
2683 assert_eq!(
2684 completion_rx.recv().await.unwrap(),
2685 Some(ExitStatus::default()),
2686 "EOF should result in the tty shell exiting successfully",
2687 );
2688 })
2689 .detach();
2690
2691 let first_event = event_rx.recv().await.expect("No wakeup event received");
2692
2693 terminal.update(cx, |terminal, _| {
2694 let success = terminal.try_keystroke(&Keystroke::parse("ctrl-c").unwrap(), false);
2695 assert!(success, "Should have registered ctrl-c sequence");
2696 });
2697 terminal.update(cx, |terminal, _| {
2698 let success = terminal.try_keystroke(&Keystroke::parse("ctrl-d").unwrap(), false);
2699 assert!(success, "Should have registered ctrl-d sequence");
2700 });
2701
2702 let mut all_events = vec![first_event];
2703 while let Ok(new_event) = event_rx.recv().await {
2704 all_events.push(new_event.clone());
2705 if new_event == Event::CloseTerminal {
2706 break;
2707 }
2708 }
2709 assert!(
2710 all_events.contains(&Event::CloseTerminal),
2711 "EOF command sequence should have triggered a TTY terminal exit, but got events: {all_events:?}",
2712 );
2713 }
2714
2715 #[gpui::test(iterations = 10)]
2716 async fn test_terminal_no_exit_on_spawn_failure(cx: &mut TestAppContext) {
2717 cx.executor().allow_parking();
2718
2719 let (completion_tx, completion_rx) = smol::channel::unbounded();
2720 let (program, args) = ShellBuilder::new(&Shell::System, false)
2721 .build(Some("asdasdasdasd".to_owned()), &["@@@@@".to_owned()]);
2722 let builder = cx
2723 .update(|cx| {
2724 TerminalBuilder::new(
2725 None,
2726 None,
2727 task::Shell::WithArguments {
2728 program,
2729 args,
2730 title_override: None,
2731 },
2732 HashMap::default(),
2733 CursorShape::default(),
2734 AlternateScroll::On,
2735 None,
2736 Vec::new(),
2737 0,
2738 false,
2739 0,
2740 Some(completion_tx),
2741 cx,
2742 Vec::new(),
2743 )
2744 })
2745 .await
2746 .unwrap();
2747 let terminal = cx.new(|cx| builder.subscribe(cx));
2748
2749 let all_events: Arc<Mutex<Vec<Event>>> = Arc::new(Mutex::new(Vec::new()));
2750 cx.update({
2751 let all_events = all_events.clone();
2752 |cx| {
2753 cx.subscribe(&terminal, move |_, e, _| {
2754 all_events.lock().push(e.clone());
2755 })
2756 }
2757 })
2758 .detach();
2759 let completion_check_task = cx.background_spawn(async move {
2760 // The channel may be closed if the terminal is dropped before sending
2761 // the completion signal, which can happen with certain task scheduling orders.
2762 let exit_status = completion_rx.recv().await.ok().flatten();
2763 if let Some(exit_status) = exit_status {
2764 assert!(
2765 !exit_status.success(),
2766 "Wrong shell command should result in a failure"
2767 );
2768 #[cfg(target_os = "windows")]
2769 assert_eq!(exit_status.code(), Some(1));
2770 #[cfg(not(target_os = "windows"))]
2771 assert_eq!(exit_status.code(), None);
2772 }
2773 });
2774
2775 completion_check_task.await;
2776 cx.executor().timer(Duration::from_millis(500)).await;
2777
2778 assert!(
2779 !all_events
2780 .lock()
2781 .iter()
2782 .any(|event| event == &Event::CloseTerminal),
2783 "Wrong shell command should update the title but not should not close the terminal to show the error message, but got events: {all_events:?}",
2784 );
2785 }
2786
2787 #[test]
2788 fn test_rgb_for_index() {
2789 // Test every possible value in the color cube.
2790 for i in 16..=231 {
2791 let (r, g, b) = rgb_for_index(i);
2792 assert_eq!(i, 16 + 36 * r + 6 * g + b);
2793 }
2794 }
2795
2796 #[test]
2797 fn test_mouse_to_cell_test() {
2798 let mut rng = rand::rng();
2799 const ITERATIONS: usize = 10;
2800 const PRECISION: usize = 1000;
2801
2802 for _ in 0..ITERATIONS {
2803 let viewport_cells = rng.random_range(15..20);
2804 let cell_size =
2805 rng.random_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2806
2807 let size = crate::TerminalBounds {
2808 cell_width: Pixels::from(cell_size),
2809 line_height: Pixels::from(cell_size),
2810 bounds: bounds(
2811 Point::default(),
2812 size(
2813 Pixels::from(cell_size * (viewport_cells as f32)),
2814 Pixels::from(cell_size * (viewport_cells as f32)),
2815 ),
2816 ),
2817 };
2818
2819 let cells = get_cells(size, &mut rng);
2820 let content = convert_cells_to_content(size, &cells);
2821
2822 for row in 0..(viewport_cells - 1) {
2823 let row = row as usize;
2824 for col in 0..(viewport_cells - 1) {
2825 let col = col as usize;
2826
2827 let row_offset = rng.random_range(0..PRECISION) as f32 / PRECISION as f32;
2828 let col_offset = rng.random_range(0..PRECISION) as f32 / PRECISION as f32;
2829
2830 let mouse_pos = point(
2831 Pixels::from(col as f32 * cell_size + col_offset),
2832 Pixels::from(row as f32 * cell_size + row_offset),
2833 );
2834
2835 let content_index =
2836 content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2837 let mouse_cell = content.cells[content_index].c;
2838 let real_cell = cells[row][col];
2839
2840 assert_eq!(mouse_cell, real_cell);
2841 }
2842 }
2843 }
2844 }
2845
2846 #[test]
2847 fn test_mouse_to_cell_clamp() {
2848 let mut rng = rand::rng();
2849
2850 let size = crate::TerminalBounds {
2851 cell_width: Pixels::from(10.),
2852 line_height: Pixels::from(10.),
2853 bounds: bounds(
2854 Point::default(),
2855 size(Pixels::from(100.), Pixels::from(100.)),
2856 ),
2857 };
2858
2859 let cells = get_cells(size, &mut rng);
2860 let content = convert_cells_to_content(size, &cells);
2861
2862 assert_eq!(
2863 content.cells[content_index_for_mouse(
2864 point(Pixels::from(-10.), Pixels::from(-10.)),
2865 &content.terminal_bounds,
2866 )]
2867 .c,
2868 cells[0][0]
2869 );
2870 assert_eq!(
2871 content.cells[content_index_for_mouse(
2872 point(Pixels::from(1000.), Pixels::from(1000.)),
2873 &content.terminal_bounds,
2874 )]
2875 .c,
2876 cells[9][9]
2877 );
2878 }
2879
2880 fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2881 let mut cells = Vec::new();
2882
2883 for _ in 0..((size.height() / size.line_height()) as usize) {
2884 let mut row_vec = Vec::new();
2885 for _ in 0..((size.width() / size.cell_width()) as usize) {
2886 let cell_char = rng.sample(distr::Alphanumeric) as char;
2887 row_vec.push(cell_char)
2888 }
2889 cells.push(row_vec)
2890 }
2891
2892 cells
2893 }
2894
2895 fn convert_cells_to_content(
2896 terminal_bounds: TerminalBounds,
2897 cells: &[Vec<char>],
2898 ) -> TerminalContent {
2899 let mut ic = Vec::new();
2900
2901 for (index, row) in cells.iter().enumerate() {
2902 for (cell_index, cell_char) in row.iter().enumerate() {
2903 ic.push(IndexedCell {
2904 point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2905 cell: Cell {
2906 c: *cell_char,
2907 ..Default::default()
2908 },
2909 });
2910 }
2911 }
2912
2913 TerminalContent {
2914 cells: ic,
2915 terminal_bounds,
2916 ..Default::default()
2917 }
2918 }
2919
2920 #[gpui::test]
2921 async fn test_write_output_converts_lf_to_crlf(cx: &mut TestAppContext) {
2922 let terminal = cx.new(|cx| {
2923 TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2924 .unwrap()
2925 .subscribe(cx)
2926 });
2927
2928 // Test simple LF conversion
2929 terminal.update(cx, |terminal, cx| {
2930 terminal.write_output(b"line1\nline2\n", cx);
2931 });
2932
2933 // Get the content by directly accessing the term
2934 let content = terminal.update(cx, |terminal, _cx| {
2935 let term = terminal.term.lock_unfair();
2936 Terminal::make_content(&term, &terminal.last_content)
2937 });
2938
2939 // If LF is properly converted to CRLF, each line should start at column 0
2940 // The diagonal staircase bug would cause increasing column positions
2941
2942 // Get the cells and check that lines start at column 0
2943 let cells = &content.cells;
2944 let mut line1_col0 = false;
2945 let mut line2_col0 = false;
2946
2947 for cell in cells {
2948 if cell.c == 'l' && cell.point.column.0 == 0 {
2949 if cell.point.line.0 == 0 && !line1_col0 {
2950 line1_col0 = true;
2951 } else if cell.point.line.0 == 1 && !line2_col0 {
2952 line2_col0 = true;
2953 }
2954 }
2955 }
2956
2957 assert!(line1_col0, "First line should start at column 0");
2958 assert!(line2_col0, "Second line should start at column 0");
2959 }
2960
2961 #[gpui::test]
2962 async fn test_write_output_preserves_existing_crlf(cx: &mut TestAppContext) {
2963 let terminal = cx.new(|cx| {
2964 TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2965 .unwrap()
2966 .subscribe(cx)
2967 });
2968
2969 // Test that existing CRLF doesn't get doubled
2970 terminal.update(cx, |terminal, cx| {
2971 terminal.write_output(b"line1\r\nline2\r\n", cx);
2972 });
2973
2974 // Get the content by directly accessing the term
2975 let content = terminal.update(cx, |terminal, _cx| {
2976 let term = terminal.term.lock_unfair();
2977 Terminal::make_content(&term, &terminal.last_content)
2978 });
2979
2980 let cells = &content.cells;
2981
2982 // Check that both lines start at column 0
2983 let mut found_lines_at_column_0 = 0;
2984 for cell in cells {
2985 if cell.c == 'l' && cell.point.column.0 == 0 {
2986 found_lines_at_column_0 += 1;
2987 }
2988 }
2989
2990 assert!(
2991 found_lines_at_column_0 >= 2,
2992 "Both lines should start at column 0"
2993 );
2994 }
2995
2996 #[gpui::test]
2997 async fn test_write_output_preserves_bare_cr(cx: &mut TestAppContext) {
2998 let terminal = cx.new(|cx| {
2999 TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
3000 .unwrap()
3001 .subscribe(cx)
3002 });
3003
3004 // Test that bare CR (without LF) is preserved
3005 terminal.update(cx, |terminal, cx| {
3006 terminal.write_output(b"hello\rworld", cx);
3007 });
3008
3009 // Get the content by directly accessing the term
3010 let content = terminal.update(cx, |terminal, _cx| {
3011 let term = terminal.term.lock_unfair();
3012 Terminal::make_content(&term, &terminal.last_content)
3013 });
3014
3015 let cells = &content.cells;
3016
3017 // Check that we have "world" at the beginning of the line
3018 let mut text = String::new();
3019 for cell in cells.iter().take(5) {
3020 if cell.point.line.0 == 0 {
3021 text.push(cell.c);
3022 }
3023 }
3024
3025 assert!(
3026 text.starts_with("world"),
3027 "Bare CR should allow overwriting: got '{}'",
3028 text
3029 );
3030 }
3031
3032 #[gpui::test]
3033 async fn test_hyperlink_ctrl_click_same_position(cx: &mut TestAppContext) {
3034 let terminal = init_ctrl_click_hyperlink_test(cx, b"Visit https://zed.dev/ for more\r\n");
3035
3036 terminal.update(cx, |terminal, cx| {
3037 let click_position = point(px(80.0), px(10.0));
3038 ctrl_mouse_down_at(terminal, click_position, cx);
3039 ctrl_mouse_up_at(terminal, click_position, cx);
3040
3041 assert!(
3042 terminal
3043 .events
3044 .iter()
3045 .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, true))),
3046 "Should have ProcessHyperlink event when ctrl+clicking on same hyperlink position"
3047 );
3048 });
3049 }
3050
3051 #[gpui::test]
3052 async fn test_hyperlink_ctrl_click_drag_outside_bounds(cx: &mut TestAppContext) {
3053 let terminal = init_ctrl_click_hyperlink_test(
3054 cx,
3055 b"Visit https://zed.dev/ for more\r\nThis is another line\r\n",
3056 );
3057
3058 terminal.update(cx, |terminal, cx| {
3059 let down_position = point(px(80.0), px(10.0));
3060 let up_position = point(px(10.0), px(50.0));
3061
3062 ctrl_mouse_down_at(terminal, down_position, cx);
3063 ctrl_mouse_move_to(terminal, up_position, cx);
3064 ctrl_mouse_up_at(terminal, up_position, cx);
3065
3066 assert!(
3067 !terminal
3068 .events
3069 .iter()
3070 .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, _))),
3071 "Should NOT have ProcessHyperlink event when dragging outside the hyperlink"
3072 );
3073 });
3074 }
3075
3076 #[gpui::test]
3077 async fn test_hyperlink_ctrl_click_drag_within_bounds(cx: &mut TestAppContext) {
3078 let terminal = init_ctrl_click_hyperlink_test(cx, b"Visit https://zed.dev/ for more\r\n");
3079
3080 terminal.update(cx, |terminal, cx| {
3081 let down_position = point(px(70.0), px(10.0));
3082 let up_position = point(px(130.0), px(10.0));
3083
3084 ctrl_mouse_down_at(terminal, down_position, cx);
3085 ctrl_mouse_move_to(terminal, up_position, cx);
3086 ctrl_mouse_up_at(terminal, up_position, cx);
3087
3088 assert!(
3089 terminal
3090 .events
3091 .iter()
3092 .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, true))),
3093 "Should have ProcessHyperlink event when dragging within hyperlink bounds"
3094 );
3095 });
3096 }
3097
3098 /// Test that kill_active_task properly terminates both the foreground process
3099 /// and the shell, allowing wait_for_completed_task to complete and output to be captured.
3100 #[cfg(unix)]
3101 #[gpui::test]
3102 async fn test_kill_active_task_completes_and_captures_output(cx: &mut TestAppContext) {
3103 cx.executor().allow_parking();
3104
3105 // Run a command that prints output then sleeps for a long time
3106 // The echo ensures we have output to capture before killing
3107 let (terminal, completion_rx) =
3108 build_test_terminal(cx, "echo", &["test_output_before_kill; sleep 60"]).await;
3109
3110 // Wait a bit for the echo to execute and produce output
3111 cx.background_executor
3112 .timer(Duration::from_millis(200))
3113 .await;
3114
3115 // Kill the active task
3116 terminal.update(cx, |term, _cx| {
3117 term.kill_active_task();
3118 });
3119
3120 // wait_for_completed_task should complete within a reasonable time (not hang)
3121 let completion_result = completion_rx.recv().await;
3122 assert!(
3123 completion_result.is_ok(),
3124 "wait_for_completed_task should complete after kill_active_task, but it timed out"
3125 );
3126
3127 // The exit status should indicate the process was killed (not a clean exit)
3128 let exit_status = completion_result.unwrap();
3129 assert!(
3130 exit_status.is_some(),
3131 "Should have received an exit status after killing"
3132 );
3133
3134 // Verify that output captured before killing is still available
3135 let content = terminal.update(cx, |term, _| term.get_content());
3136 assert!(
3137 content.contains("test_output_before_kill"),
3138 "Output from before kill should be captured, got: {content}"
3139 );
3140 }
3141
3142 /// Test that kill_active_task on a task that's not running is a no-op
3143 #[gpui::test]
3144 async fn test_kill_active_task_on_completed_task_is_noop(cx: &mut TestAppContext) {
3145 cx.executor().allow_parking();
3146
3147 // Run a command that exits immediately
3148 let (terminal, completion_rx) = build_test_terminal(cx, "echo", &["done"]).await;
3149
3150 // Wait for the command to complete naturally
3151 let exit_status = completion_rx
3152 .recv()
3153 .await
3154 .expect("Should receive exit status");
3155 assert_eq!(exit_status, Some(ExitStatus::default()));
3156
3157 // Now try to kill - should be a no-op since task already completed
3158 terminal.update(cx, |term, _cx| {
3159 term.kill_active_task();
3160 });
3161
3162 // Content should still be there
3163 let content = terminal.update(cx, |term, _| term.get_content());
3164 assert!(
3165 content.contains("done"),
3166 "Output should still be present after no-op kill, got: {content}"
3167 );
3168 }
3169
3170 mod perf {
3171 use super::super::*;
3172 use gpui::{
3173 Entity, Point, ScrollDelta, ScrollWheelEvent, TestAppContext, VisualContext,
3174 VisualTestContext, point,
3175 };
3176 use util::default;
3177 use util_macros::perf;
3178
3179 async fn init_scroll_perf_test(
3180 cx: &mut TestAppContext,
3181 ) -> (Entity<Terminal>, &mut VisualTestContext) {
3182 cx.update(|cx| {
3183 let settings_store = settings::SettingsStore::test(cx);
3184 cx.set_global(settings_store);
3185 });
3186
3187 cx.executor().allow_parking();
3188
3189 let window = cx.add_empty_window();
3190 let builder = window
3191 .update(|window, cx| {
3192 let settings = TerminalSettings::get_global(cx);
3193 let test_path_hyperlink_timeout_ms = 100;
3194 TerminalBuilder::new(
3195 None,
3196 None,
3197 task::Shell::System,
3198 HashMap::default(),
3199 CursorShape::default(),
3200 AlternateScroll::On,
3201 None,
3202 settings.path_hyperlink_regexes.clone(),
3203 test_path_hyperlink_timeout_ms,
3204 false,
3205 window.window_handle().window_id().as_u64(),
3206 None,
3207 cx,
3208 vec![],
3209 )
3210 })
3211 .await
3212 .unwrap();
3213 let terminal = window.new(|cx| builder.subscribe(cx));
3214
3215 terminal.update(window, |term, cx| {
3216 term.write_output("long line ".repeat(1000).as_bytes(), cx);
3217 });
3218
3219 (terminal, window)
3220 }
3221
3222 #[perf]
3223 #[gpui::test]
3224 async fn scroll_long_line_benchmark(cx: &mut TestAppContext) {
3225 let (terminal, window) = init_scroll_perf_test(cx).await;
3226 let wobble = point(FIND_HYPERLINK_THROTTLE_PX, px(0.0));
3227 let mut scroll_by = |lines: i32| {
3228 window.update_window_entity(&terminal, |terminal, window, cx| {
3229 let bounds = terminal.last_content.terminal_bounds.bounds;
3230 let center = bounds.origin + bounds.center();
3231 let position = center + wobble * lines as f32;
3232
3233 terminal.mouse_move(
3234 &MouseMoveEvent {
3235 position,
3236 ..default()
3237 },
3238 cx,
3239 );
3240
3241 terminal.scroll_wheel(
3242 &ScrollWheelEvent {
3243 position,
3244 delta: ScrollDelta::Lines(Point::new(0.0, lines as f32)),
3245 ..default()
3246 },
3247 1.0,
3248 );
3249
3250 assert!(
3251 terminal
3252 .events
3253 .iter()
3254 .any(|event| matches!(event, InternalEvent::Scroll(_))),
3255 "Should have Scroll event when scrolling within terminal bounds"
3256 );
3257 terminal.sync(window, cx);
3258 });
3259 };
3260
3261 for _ in 0..20000 {
3262 scroll_by(1);
3263 scroll_by(-1);
3264 }
3265 }
3266 }
3267}