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