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