terminal.rs

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