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