terminal.rs

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