terminal.rs

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