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