terminal.rs

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