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