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