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