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