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