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                // First kill the foreground process group (the command running in the shell)
2150                info.kill_current_process();
2151                // Then kill the shell itself so that the terminal exits properly
2152                // and wait_for_completed_task can complete
2153                info.kill_child_process();
2154            }
2155        }
2156    }
2157
2158    pub fn pid(&self) -> Option<sysinfo::Pid> {
2159        match &self.terminal_type {
2160            TerminalType::Pty { info, .. } => info.pid(),
2161            TerminalType::DisplayOnly => None,
2162        }
2163    }
2164
2165    pub fn pid_getter(&self) -> Option<&ProcessIdGetter> {
2166        match &self.terminal_type {
2167            TerminalType::Pty { info, .. } => Some(info.pid_getter()),
2168            TerminalType::DisplayOnly => None,
2169        }
2170    }
2171
2172    pub fn task(&self) -> Option<&TaskState> {
2173        self.task.as_ref()
2174    }
2175
2176    pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
2177        if let Some(task) = self.task() {
2178            if task.status == TaskStatus::Running {
2179                let completion_receiver = task.completion_rx.clone();
2180                return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
2181            } else if let Ok(status) = task.completion_rx.try_recv() {
2182                return Task::ready(status);
2183            }
2184        }
2185        Task::ready(None)
2186    }
2187
2188    fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
2189        let e: Option<ExitStatus> = error_code.map(|code| {
2190            #[cfg(unix)]
2191            {
2192                std::os::unix::process::ExitStatusExt::from_raw(code)
2193            }
2194            #[cfg(windows)]
2195            {
2196                std::os::windows::process::ExitStatusExt::from_raw(code as u32)
2197            }
2198        });
2199
2200        if let Some(tx) = &self.completion_tx {
2201            tx.try_send(e).ok();
2202        }
2203        if let Some(e) = e {
2204            self.child_exited = Some(e);
2205        }
2206        let task = match &mut self.task {
2207            Some(task) => task,
2208            None => {
2209                if self.child_exited.is_none_or(|e| e.code() == Some(0)) {
2210                    cx.emit(Event::CloseTerminal);
2211                }
2212                return;
2213            }
2214        };
2215        if task.status != TaskStatus::Running {
2216            return;
2217        }
2218        match error_code {
2219            Some(error_code) => {
2220                task.status.register_task_exit(error_code);
2221            }
2222            None => {
2223                task.status.register_terminal_exit();
2224            }
2225        };
2226
2227        let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
2228        let mut lines_to_show = Vec::new();
2229        if task.spawned_task.show_summary {
2230            lines_to_show.push(task_line.as_str());
2231        }
2232        if task.spawned_task.show_command {
2233            lines_to_show.push(command_line.as_str());
2234        }
2235
2236        if !lines_to_show.is_empty() {
2237            // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
2238            // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
2239            // when Zed task finishes and no more output is made.
2240            // After the task summary is output once, no more text is appended to the terminal.
2241            unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
2242        }
2243
2244        match task.spawned_task.hide {
2245            HideStrategy::Never => {}
2246            HideStrategy::Always => {
2247                cx.emit(Event::CloseTerminal);
2248            }
2249            HideStrategy::OnSuccess => {
2250                if finished_successfully {
2251                    cx.emit(Event::CloseTerminal);
2252                }
2253            }
2254        }
2255    }
2256
2257    pub fn vi_mode_enabled(&self) -> bool {
2258        self.vi_mode_enabled
2259    }
2260
2261    pub fn clone_builder(&self, cx: &App, cwd: Option<PathBuf>) -> Task<Result<TerminalBuilder>> {
2262        let working_directory = self.working_directory().or_else(|| cwd);
2263        TerminalBuilder::new(
2264            working_directory,
2265            None,
2266            self.template.shell.clone(),
2267            self.template.env.clone(),
2268            self.template.cursor_shape,
2269            self.template.alternate_scroll,
2270            self.template.max_scroll_history_lines,
2271            self.template.path_hyperlink_regexes.clone(),
2272            self.template.path_hyperlink_timeout_ms,
2273            self.is_remote_terminal,
2274            self.template.window_id,
2275            None,
2276            cx,
2277            self.activation_script.clone(),
2278        )
2279    }
2280}
2281
2282// Helper function to convert a grid row to a string
2283pub fn row_to_string(row: &Row<Cell>) -> String {
2284    row[..Column(row.len())]
2285        .iter()
2286        .map(|cell| cell.c)
2287        .collect::<String>()
2288}
2289
2290const TASK_DELIMITER: &str = "";
2291fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
2292    let escaped_full_label = task
2293        .spawned_task
2294        .full_label
2295        .replace("\r\n", "\r")
2296        .replace('\n', "\r");
2297    let success = error_code == Some(0);
2298    let task_line = match error_code {
2299        Some(0) => format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
2300        Some(error_code) => format!(
2301            "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
2302        ),
2303        None => format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
2304    };
2305    let escaped_command_label = task
2306        .spawned_task
2307        .command_label
2308        .replace("\r\n", "\r")
2309        .replace('\n', "\r");
2310    let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
2311    (success, task_line, command_line)
2312}
2313
2314/// Appends a stringified task summary to the terminal, after its output.
2315///
2316/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
2317/// New text being added to the terminal here, uses "less public" APIs,
2318/// which are not maintaining the entire terminal state intact.
2319///
2320///
2321/// The library
2322///
2323/// * does not increment inner grid cursor's _lines_ on `input` calls
2324///   (but displaying the lines correctly and incrementing cursor's columns)
2325///
2326/// * ignores `\n` and \r` character input, requiring the `newline` call instead
2327///
2328/// * does not alter grid state after `newline` call
2329///   so its `bottommost_line` is always the same additions, and
2330///   the cursor's `point` is not updated to the new line and column values
2331///
2332/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
2333///   Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
2334///
2335/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
2336/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
2337/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
2338/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
2339unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
2340    term.newline();
2341    term.grid_mut().cursor.point.column = Column(0);
2342    for line in text_lines {
2343        for c in line.chars() {
2344            term.input(c);
2345        }
2346        term.newline();
2347        term.grid_mut().cursor.point.column = Column(0);
2348    }
2349}
2350
2351impl Drop for Terminal {
2352    fn drop(&mut self) {
2353        if let TerminalType::Pty { pty_tx, info } = &mut self.terminal_type {
2354            info.kill_child_process();
2355            pty_tx.0.send(Msg::Shutdown).ok();
2356        }
2357    }
2358}
2359
2360impl EventEmitter<Event> for Terminal {}
2361
2362fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
2363    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
2364    selection.update(*range.end(), AlacDirection::Right);
2365    selection
2366}
2367
2368fn all_search_matches<'a, T>(
2369    term: &'a Term<T>,
2370    regex: &'a mut RegexSearch,
2371) -> impl Iterator<Item = Match> + 'a {
2372    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
2373    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
2374    RegexIter::new(start, end, AlacDirection::Right, term, regex)
2375}
2376
2377fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
2378    let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
2379    let clamped_col = min(col, terminal_bounds.columns() - 1);
2380    let row = (pos.y / terminal_bounds.line_height()).round() as usize;
2381    let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
2382    clamped_row * terminal_bounds.columns() + clamped_col
2383}
2384
2385/// Converts an 8 bit ANSI color to its GPUI equivalent.
2386/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
2387/// Other than that use case, should only be called with values in the `[0,255]` range
2388pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
2389    let colors = theme.colors();
2390
2391    match index {
2392        // 0-15 are the same as the named colors above
2393        0 => colors.terminal_ansi_black,
2394        1 => colors.terminal_ansi_red,
2395        2 => colors.terminal_ansi_green,
2396        3 => colors.terminal_ansi_yellow,
2397        4 => colors.terminal_ansi_blue,
2398        5 => colors.terminal_ansi_magenta,
2399        6 => colors.terminal_ansi_cyan,
2400        7 => colors.terminal_ansi_white,
2401        8 => colors.terminal_ansi_bright_black,
2402        9 => colors.terminal_ansi_bright_red,
2403        10 => colors.terminal_ansi_bright_green,
2404        11 => colors.terminal_ansi_bright_yellow,
2405        12 => colors.terminal_ansi_bright_blue,
2406        13 => colors.terminal_ansi_bright_magenta,
2407        14 => colors.terminal_ansi_bright_cyan,
2408        15 => colors.terminal_ansi_bright_white,
2409        // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
2410        // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
2411        16..=231 => {
2412            let (r, g, b) = rgb_for_index(index as u8);
2413            rgba_color(
2414                if r == 0 { 0 } else { r * 40 + 55 },
2415                if g == 0 { 0 } else { g * 40 + 55 },
2416                if b == 0 { 0 } else { b * 40 + 55 },
2417            )
2418        }
2419        // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
2420        232..=255 => {
2421            let i = index as u8 - 232; // Align index to 0..24
2422            let value = i * 10 + 8;
2423            rgba_color(value, value, value)
2424        }
2425        // For compatibility with the alacritty::Colors interface
2426        // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
2427        256 => colors.terminal_foreground,
2428        257 => colors.terminal_background,
2429        258 => theme.players().local().cursor,
2430        259 => colors.terminal_ansi_dim_black,
2431        260 => colors.terminal_ansi_dim_red,
2432        261 => colors.terminal_ansi_dim_green,
2433        262 => colors.terminal_ansi_dim_yellow,
2434        263 => colors.terminal_ansi_dim_blue,
2435        264 => colors.terminal_ansi_dim_magenta,
2436        265 => colors.terminal_ansi_dim_cyan,
2437        266 => colors.terminal_ansi_dim_white,
2438        267 => colors.terminal_bright_foreground,
2439        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2440
2441        _ => black(),
2442    }
2443}
2444
2445/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2446///
2447/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2448///
2449/// Wikipedia gives a formula for calculating the index for a given color:
2450///
2451/// ```text
2452/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2453/// ```
2454///
2455/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2456fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2457    debug_assert!((16..=231).contains(&i));
2458    let i = i - 16;
2459    let r = (i - (i % 36)) / 36;
2460    let g = ((i % 36) - (i % 6)) / 6;
2461    let b = (i % 36) % 6;
2462    (r, g, b)
2463}
2464
2465pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2466    Rgba {
2467        r: (r as f32 / 255.),
2468        g: (g as f32 / 255.),
2469        b: (b as f32 / 255.),
2470        a: 1.,
2471    }
2472    .into()
2473}
2474
2475#[cfg(test)]
2476mod tests {
2477    use std::time::Duration;
2478
2479    use super::*;
2480    use crate::{
2481        IndexedCell, TerminalBounds, TerminalBuilder, TerminalContent, content_index_for_mouse,
2482        rgb_for_index,
2483    };
2484    use alacritty_terminal::{
2485        index::{Column, Line, Point as AlacPoint},
2486        term::cell::Cell,
2487    };
2488    use collections::HashMap;
2489    use gpui::{
2490        Entity, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
2491        Point, TestAppContext, bounds, point, size, smol_timeout,
2492    };
2493    use rand::{Rng, distr, rngs::ThreadRng};
2494    use smol::channel::Receiver;
2495    use task::{Shell, ShellBuilder};
2496
2497    /// Helper to build a test terminal running a shell command.
2498    /// Returns the terminal entity and a receiver for the completion signal.
2499    async fn build_test_terminal(
2500        cx: &mut TestAppContext,
2501        command: &str,
2502        args: &[&str],
2503    ) -> (Entity<Terminal>, Receiver<Option<ExitStatus>>) {
2504        let (completion_tx, completion_rx) = smol::channel::unbounded();
2505        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
2506        let (program, args) =
2507            ShellBuilder::new(&Shell::System, false).build(Some(command.to_owned()), &args);
2508        let builder = cx
2509            .update(|cx| {
2510                TerminalBuilder::new(
2511                    None,
2512                    None,
2513                    task::Shell::WithArguments {
2514                        program,
2515                        args,
2516                        title_override: None,
2517                    },
2518                    HashMap::default(),
2519                    CursorShape::default(),
2520                    AlternateScroll::On,
2521                    None,
2522                    vec![],
2523                    0,
2524                    false,
2525                    0,
2526                    Some(completion_tx),
2527                    cx,
2528                    vec![],
2529                )
2530            })
2531            .await
2532            .unwrap();
2533        let terminal = cx.new(|cx| builder.subscribe(cx));
2534        (terminal, completion_rx)
2535    }
2536
2537    fn init_ctrl_click_hyperlink_test(cx: &mut TestAppContext, output: &[u8]) -> Entity<Terminal> {
2538        cx.update(|cx| {
2539            let settings_store = settings::SettingsStore::test(cx);
2540            cx.set_global(settings_store);
2541        });
2542
2543        let terminal = cx.new(|cx| {
2544            TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2545                .unwrap()
2546                .subscribe(cx)
2547        });
2548
2549        terminal.update(cx, |terminal, cx| {
2550            terminal.write_output(output, cx);
2551        });
2552
2553        cx.run_until_parked();
2554
2555        terminal.update(cx, |terminal, _cx| {
2556            let term_lock = terminal.term.lock();
2557            terminal.last_content = Terminal::make_content(&term_lock, &terminal.last_content);
2558            drop(term_lock);
2559
2560            let terminal_bounds = TerminalBounds::new(
2561                px(20.0),
2562                px(10.0),
2563                bounds(point(px(0.0), px(0.0)), size(px(400.0), px(400.0))),
2564            );
2565            terminal.last_content.terminal_bounds = terminal_bounds;
2566            terminal.events.clear();
2567        });
2568
2569        terminal
2570    }
2571
2572    fn ctrl_mouse_down_at(
2573        terminal: &mut Terminal,
2574        position: Point<Pixels>,
2575        cx: &mut Context<Terminal>,
2576    ) {
2577        let mouse_down = MouseDownEvent {
2578            button: MouseButton::Left,
2579            position,
2580            modifiers: Modifiers::secondary_key(),
2581            click_count: 1,
2582            first_mouse: true,
2583        };
2584        terminal.mouse_down(&mouse_down, cx);
2585    }
2586
2587    fn ctrl_mouse_move_to(
2588        terminal: &mut Terminal,
2589        position: Point<Pixels>,
2590        cx: &mut Context<Terminal>,
2591    ) {
2592        let terminal_bounds = terminal.last_content.terminal_bounds.bounds;
2593        let drag_event = MouseMoveEvent {
2594            position,
2595            pressed_button: Some(MouseButton::Left),
2596            modifiers: Modifiers::secondary_key(),
2597        };
2598        terminal.mouse_drag(&drag_event, terminal_bounds, cx);
2599    }
2600
2601    fn ctrl_mouse_up_at(
2602        terminal: &mut Terminal,
2603        position: Point<Pixels>,
2604        cx: &mut Context<Terminal>,
2605    ) {
2606        let mouse_up = MouseUpEvent {
2607            button: MouseButton::Left,
2608            position,
2609            modifiers: Modifiers::secondary_key(),
2610            click_count: 1,
2611        };
2612        terminal.mouse_up(&mouse_up, cx);
2613    }
2614
2615    #[gpui::test]
2616    async fn test_basic_terminal(cx: &mut TestAppContext) {
2617        cx.executor().allow_parking();
2618
2619        let (terminal, completion_rx) = build_test_terminal(cx, "echo", &["hello"]).await;
2620        assert_eq!(
2621            completion_rx.recv().await.unwrap(),
2622            Some(ExitStatus::default())
2623        );
2624        assert_eq!(
2625            terminal.update(cx, |term, _| term.get_content()).trim(),
2626            "hello"
2627        );
2628
2629        // Inject additional output directly into the emulator (display-only path)
2630        terminal.update(cx, |term, cx| {
2631            term.write_output(b"\nfrom_injection", cx);
2632        });
2633
2634        let content_after = terminal.update(cx, |term, _| term.get_content());
2635        assert!(
2636            content_after.contains("from_injection"),
2637            "expected injected output to appear, got: {content_after}"
2638        );
2639    }
2640
2641    // TODO should be tested on Linux too, but does not work there well
2642    #[cfg(target_os = "macos")]
2643    #[gpui::test(iterations = 10)]
2644    async fn test_terminal_eof(cx: &mut TestAppContext) {
2645        cx.executor().allow_parking();
2646
2647        let (completion_tx, completion_rx) = smol::channel::unbounded();
2648        let builder = cx
2649            .update(|cx| {
2650                TerminalBuilder::new(
2651                    None,
2652                    None,
2653                    task::Shell::System,
2654                    HashMap::default(),
2655                    CursorShape::default(),
2656                    AlternateScroll::On,
2657                    None,
2658                    vec![],
2659                    0,
2660                    false,
2661                    0,
2662                    Some(completion_tx),
2663                    cx,
2664                    Vec::new(),
2665                )
2666            })
2667            .await
2668            .unwrap();
2669        // Build an empty command, which will result in a tty shell spawned.
2670        let terminal = cx.new(|cx| builder.subscribe(cx));
2671
2672        let (event_tx, event_rx) = smol::channel::unbounded::<Event>();
2673        cx.update(|cx| {
2674            cx.subscribe(&terminal, move |_, e, _| {
2675                event_tx.send_blocking(e.clone()).unwrap();
2676            })
2677        })
2678        .detach();
2679        cx.background_spawn(async move {
2680            assert_eq!(
2681                completion_rx.recv().await.unwrap(),
2682                Some(ExitStatus::default()),
2683                "EOF should result in the tty shell exiting successfully",
2684            );
2685        })
2686        .detach();
2687
2688        let first_event = event_rx.recv().await.expect("No wakeup event received");
2689
2690        terminal.update(cx, |terminal, _| {
2691            let success = terminal.try_keystroke(&Keystroke::parse("ctrl-c").unwrap(), false);
2692            assert!(success, "Should have registered ctrl-c sequence");
2693        });
2694        terminal.update(cx, |terminal, _| {
2695            let success = terminal.try_keystroke(&Keystroke::parse("ctrl-d").unwrap(), false);
2696            assert!(success, "Should have registered ctrl-d sequence");
2697        });
2698
2699        let mut all_events = vec![first_event];
2700        while let Ok(Ok(new_event)) = smol_timeout(Duration::from_secs(1), event_rx.recv()).await {
2701            all_events.push(new_event.clone());
2702            if new_event == Event::CloseTerminal {
2703                break;
2704            }
2705        }
2706        assert!(
2707            all_events.contains(&Event::CloseTerminal),
2708            "EOF command sequence should have triggered a TTY terminal exit, but got events: {all_events:?}",
2709        );
2710    }
2711
2712    #[gpui::test(iterations = 10)]
2713    async fn test_terminal_no_exit_on_spawn_failure(cx: &mut TestAppContext) {
2714        cx.executor().allow_parking();
2715
2716        let (completion_tx, completion_rx) = smol::channel::unbounded();
2717        let (program, args) = ShellBuilder::new(&Shell::System, false)
2718            .build(Some("asdasdasdasd".to_owned()), &["@@@@@".to_owned()]);
2719        let builder = cx
2720            .update(|cx| {
2721                TerminalBuilder::new(
2722                    None,
2723                    None,
2724                    task::Shell::WithArguments {
2725                        program,
2726                        args,
2727                        title_override: None,
2728                    },
2729                    HashMap::default(),
2730                    CursorShape::default(),
2731                    AlternateScroll::On,
2732                    None,
2733                    Vec::new(),
2734                    0,
2735                    false,
2736                    0,
2737                    Some(completion_tx),
2738                    cx,
2739                    Vec::new(),
2740                )
2741            })
2742            .await
2743            .unwrap();
2744        let terminal = cx.new(|cx| builder.subscribe(cx));
2745
2746        let (event_tx, event_rx) = smol::channel::unbounded::<Event>();
2747        cx.update(|cx| {
2748            cx.subscribe(&terminal, move |_, e, _| {
2749                event_tx.send_blocking(e.clone()).unwrap();
2750            })
2751        })
2752        .detach();
2753        let completion_check_task = cx.background_spawn(async move {
2754            // The channel may be closed if the terminal is dropped before sending
2755            // the completion signal, which can happen with certain task scheduling orders.
2756            let exit_status = completion_rx.recv().await.ok().flatten();
2757            if let Some(exit_status) = exit_status {
2758                assert!(
2759                    !exit_status.success(),
2760                    "Wrong shell command should result in a failure"
2761                );
2762                #[cfg(target_os = "windows")]
2763                assert_eq!(exit_status.code(), Some(1));
2764                #[cfg(not(target_os = "windows"))]
2765                assert_eq!(exit_status.code(), None);
2766            }
2767        });
2768
2769        let mut all_events = Vec::new();
2770        while let Ok(Ok(new_event)) =
2771            smol_timeout(Duration::from_millis(500), event_rx.recv()).await
2772        {
2773            all_events.push(new_event.clone());
2774        }
2775
2776        assert!(
2777            !all_events
2778                .iter()
2779                .any(|event| event == &Event::CloseTerminal),
2780            "Wrong shell command should update the title but not should not close the terminal to show the error message, but got events: {all_events:?}",
2781        );
2782
2783        completion_check_task.await;
2784    }
2785
2786    #[test]
2787    fn test_rgb_for_index() {
2788        // Test every possible value in the color cube.
2789        for i in 16..=231 {
2790            let (r, g, b) = rgb_for_index(i);
2791            assert_eq!(i, 16 + 36 * r + 6 * g + b);
2792        }
2793    }
2794
2795    #[test]
2796    fn test_mouse_to_cell_test() {
2797        let mut rng = rand::rng();
2798        const ITERATIONS: usize = 10;
2799        const PRECISION: usize = 1000;
2800
2801        for _ in 0..ITERATIONS {
2802            let viewport_cells = rng.random_range(15..20);
2803            let cell_size =
2804                rng.random_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2805
2806            let size = crate::TerminalBounds {
2807                cell_width: Pixels::from(cell_size),
2808                line_height: Pixels::from(cell_size),
2809                bounds: bounds(
2810                    Point::default(),
2811                    size(
2812                        Pixels::from(cell_size * (viewport_cells as f32)),
2813                        Pixels::from(cell_size * (viewport_cells as f32)),
2814                    ),
2815                ),
2816            };
2817
2818            let cells = get_cells(size, &mut rng);
2819            let content = convert_cells_to_content(size, &cells);
2820
2821            for row in 0..(viewport_cells - 1) {
2822                let row = row as usize;
2823                for col in 0..(viewport_cells - 1) {
2824                    let col = col as usize;
2825
2826                    let row_offset = rng.random_range(0..PRECISION) as f32 / PRECISION as f32;
2827                    let col_offset = rng.random_range(0..PRECISION) as f32 / PRECISION as f32;
2828
2829                    let mouse_pos = point(
2830                        Pixels::from(col as f32 * cell_size + col_offset),
2831                        Pixels::from(row as f32 * cell_size + row_offset),
2832                    );
2833
2834                    let content_index =
2835                        content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2836                    let mouse_cell = content.cells[content_index].c;
2837                    let real_cell = cells[row][col];
2838
2839                    assert_eq!(mouse_cell, real_cell);
2840                }
2841            }
2842        }
2843    }
2844
2845    #[test]
2846    fn test_mouse_to_cell_clamp() {
2847        let mut rng = rand::rng();
2848
2849        let size = crate::TerminalBounds {
2850            cell_width: Pixels::from(10.),
2851            line_height: Pixels::from(10.),
2852            bounds: bounds(
2853                Point::default(),
2854                size(Pixels::from(100.), Pixels::from(100.)),
2855            ),
2856        };
2857
2858        let cells = get_cells(size, &mut rng);
2859        let content = convert_cells_to_content(size, &cells);
2860
2861        assert_eq!(
2862            content.cells[content_index_for_mouse(
2863                point(Pixels::from(-10.), Pixels::from(-10.)),
2864                &content.terminal_bounds,
2865            )]
2866            .c,
2867            cells[0][0]
2868        );
2869        assert_eq!(
2870            content.cells[content_index_for_mouse(
2871                point(Pixels::from(1000.), Pixels::from(1000.)),
2872                &content.terminal_bounds,
2873            )]
2874            .c,
2875            cells[9][9]
2876        );
2877    }
2878
2879    fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2880        let mut cells = Vec::new();
2881
2882        for _ in 0..((size.height() / size.line_height()) as usize) {
2883            let mut row_vec = Vec::new();
2884            for _ in 0..((size.width() / size.cell_width()) as usize) {
2885                let cell_char = rng.sample(distr::Alphanumeric) as char;
2886                row_vec.push(cell_char)
2887            }
2888            cells.push(row_vec)
2889        }
2890
2891        cells
2892    }
2893
2894    fn convert_cells_to_content(
2895        terminal_bounds: TerminalBounds,
2896        cells: &[Vec<char>],
2897    ) -> TerminalContent {
2898        let mut ic = Vec::new();
2899
2900        for (index, row) in cells.iter().enumerate() {
2901            for (cell_index, cell_char) in row.iter().enumerate() {
2902                ic.push(IndexedCell {
2903                    point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2904                    cell: Cell {
2905                        c: *cell_char,
2906                        ..Default::default()
2907                    },
2908                });
2909            }
2910        }
2911
2912        TerminalContent {
2913            cells: ic,
2914            terminal_bounds,
2915            ..Default::default()
2916        }
2917    }
2918
2919    #[gpui::test]
2920    async fn test_write_output_converts_lf_to_crlf(cx: &mut TestAppContext) {
2921        let terminal = cx.new(|cx| {
2922            TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2923                .unwrap()
2924                .subscribe(cx)
2925        });
2926
2927        // Test simple LF conversion
2928        terminal.update(cx, |terminal, cx| {
2929            terminal.write_output(b"line1\nline2\n", cx);
2930        });
2931
2932        // Get the content by directly accessing the term
2933        let content = terminal.update(cx, |terminal, _cx| {
2934            let term = terminal.term.lock_unfair();
2935            Terminal::make_content(&term, &terminal.last_content)
2936        });
2937
2938        // If LF is properly converted to CRLF, each line should start at column 0
2939        // The diagonal staircase bug would cause increasing column positions
2940
2941        // Get the cells and check that lines start at column 0
2942        let cells = &content.cells;
2943        let mut line1_col0 = false;
2944        let mut line2_col0 = false;
2945
2946        for cell in cells {
2947            if cell.c == 'l' && cell.point.column.0 == 0 {
2948                if cell.point.line.0 == 0 && !line1_col0 {
2949                    line1_col0 = true;
2950                } else if cell.point.line.0 == 1 && !line2_col0 {
2951                    line2_col0 = true;
2952                }
2953            }
2954        }
2955
2956        assert!(line1_col0, "First line should start at column 0");
2957        assert!(line2_col0, "Second line should start at column 0");
2958    }
2959
2960    #[gpui::test]
2961    async fn test_write_output_preserves_existing_crlf(cx: &mut TestAppContext) {
2962        let terminal = cx.new(|cx| {
2963            TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2964                .unwrap()
2965                .subscribe(cx)
2966        });
2967
2968        // Test that existing CRLF doesn't get doubled
2969        terminal.update(cx, |terminal, cx| {
2970            terminal.write_output(b"line1\r\nline2\r\n", cx);
2971        });
2972
2973        // Get the content by directly accessing the term
2974        let content = terminal.update(cx, |terminal, _cx| {
2975            let term = terminal.term.lock_unfair();
2976            Terminal::make_content(&term, &terminal.last_content)
2977        });
2978
2979        let cells = &content.cells;
2980
2981        // Check that both lines start at column 0
2982        let mut found_lines_at_column_0 = 0;
2983        for cell in cells {
2984            if cell.c == 'l' && cell.point.column.0 == 0 {
2985                found_lines_at_column_0 += 1;
2986            }
2987        }
2988
2989        assert!(
2990            found_lines_at_column_0 >= 2,
2991            "Both lines should start at column 0"
2992        );
2993    }
2994
2995    #[gpui::test]
2996    async fn test_write_output_preserves_bare_cr(cx: &mut TestAppContext) {
2997        let terminal = cx.new(|cx| {
2998            TerminalBuilder::new_display_only(CursorShape::default(), AlternateScroll::On, None, 0)
2999                .unwrap()
3000                .subscribe(cx)
3001        });
3002
3003        // Test that bare CR (without LF) is preserved
3004        terminal.update(cx, |terminal, cx| {
3005            terminal.write_output(b"hello\rworld", cx);
3006        });
3007
3008        // Get the content by directly accessing the term
3009        let content = terminal.update(cx, |terminal, _cx| {
3010            let term = terminal.term.lock_unfair();
3011            Terminal::make_content(&term, &terminal.last_content)
3012        });
3013
3014        let cells = &content.cells;
3015
3016        // Check that we have "world" at the beginning of the line
3017        let mut text = String::new();
3018        for cell in cells.iter().take(5) {
3019            if cell.point.line.0 == 0 {
3020                text.push(cell.c);
3021            }
3022        }
3023
3024        assert!(
3025            text.starts_with("world"),
3026            "Bare CR should allow overwriting: got '{}'",
3027            text
3028        );
3029    }
3030
3031    #[gpui::test]
3032    async fn test_hyperlink_ctrl_click_same_position(cx: &mut TestAppContext) {
3033        let terminal = init_ctrl_click_hyperlink_test(cx, b"Visit https://zed.dev/ for more\r\n");
3034
3035        terminal.update(cx, |terminal, cx| {
3036            let click_position = point(px(80.0), px(10.0));
3037            ctrl_mouse_down_at(terminal, click_position, cx);
3038            ctrl_mouse_up_at(terminal, click_position, cx);
3039
3040            assert!(
3041                terminal
3042                    .events
3043                    .iter()
3044                    .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, true))),
3045                "Should have ProcessHyperlink event when ctrl+clicking on same hyperlink position"
3046            );
3047        });
3048    }
3049
3050    #[gpui::test]
3051    async fn test_hyperlink_ctrl_click_drag_outside_bounds(cx: &mut TestAppContext) {
3052        let terminal = init_ctrl_click_hyperlink_test(
3053            cx,
3054            b"Visit https://zed.dev/ for more\r\nThis is another line\r\n",
3055        );
3056
3057        terminal.update(cx, |terminal, cx| {
3058            let down_position = point(px(80.0), px(10.0));
3059            let up_position = point(px(10.0), px(50.0));
3060
3061            ctrl_mouse_down_at(terminal, down_position, cx);
3062            ctrl_mouse_move_to(terminal, up_position, cx);
3063            ctrl_mouse_up_at(terminal, up_position, cx);
3064
3065            assert!(
3066                !terminal
3067                    .events
3068                    .iter()
3069                    .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, _))),
3070                "Should NOT have ProcessHyperlink event when dragging outside the hyperlink"
3071            );
3072        });
3073    }
3074
3075    #[gpui::test]
3076    async fn test_hyperlink_ctrl_click_drag_within_bounds(cx: &mut TestAppContext) {
3077        let terminal = init_ctrl_click_hyperlink_test(cx, b"Visit https://zed.dev/ for more\r\n");
3078
3079        terminal.update(cx, |terminal, cx| {
3080            let down_position = point(px(70.0), px(10.0));
3081            let up_position = point(px(130.0), px(10.0));
3082
3083            ctrl_mouse_down_at(terminal, down_position, cx);
3084            ctrl_mouse_move_to(terminal, up_position, cx);
3085            ctrl_mouse_up_at(terminal, up_position, cx);
3086
3087            assert!(
3088                terminal
3089                    .events
3090                    .iter()
3091                    .any(|event| matches!(event, InternalEvent::ProcessHyperlink(_, true))),
3092                "Should have ProcessHyperlink event when dragging within hyperlink bounds"
3093            );
3094        });
3095    }
3096
3097    /// Test that kill_active_task properly terminates both the foreground process
3098    /// and the shell, allowing wait_for_completed_task to complete and output to be captured.
3099    #[cfg(unix)]
3100    #[gpui::test]
3101    async fn test_kill_active_task_completes_and_captures_output(cx: &mut TestAppContext) {
3102        cx.executor().allow_parking();
3103
3104        // Run a command that prints output then sleeps for a long time
3105        // The echo ensures we have output to capture before killing
3106        let (terminal, completion_rx) =
3107            build_test_terminal(cx, "echo", &["test_output_before_kill; sleep 60"]).await;
3108
3109        // Wait a bit for the echo to execute and produce output
3110        smol::Timer::after(Duration::from_millis(200)).await;
3111
3112        // Kill the active task
3113        terminal.update(cx, |term, _cx| {
3114            term.kill_active_task();
3115        });
3116
3117        // wait_for_completed_task should complete within a reasonable time (not hang)
3118        let completion_result = smol_timeout(Duration::from_secs(5), completion_rx.recv()).await;
3119        assert!(
3120            completion_result.is_ok(),
3121            "wait_for_completed_task should complete after kill_active_task, but it timed out"
3122        );
3123
3124        // The exit status should indicate the process was killed (not a clean exit)
3125        let exit_status = completion_result.unwrap().unwrap();
3126        assert!(
3127            exit_status.is_some(),
3128            "Should have received an exit status after killing"
3129        );
3130
3131        // Verify that output captured before killing is still available
3132        let content = terminal.update(cx, |term, _| term.get_content());
3133        assert!(
3134            content.contains("test_output_before_kill"),
3135            "Output from before kill should be captured, got: {content}"
3136        );
3137    }
3138
3139    /// Test that kill_active_task on a task that's not running is a no-op
3140    #[gpui::test]
3141    async fn test_kill_active_task_on_completed_task_is_noop(cx: &mut TestAppContext) {
3142        cx.executor().allow_parking();
3143
3144        // Run a command that exits immediately
3145        let (terminal, completion_rx) = build_test_terminal(cx, "echo", &["done"]).await;
3146
3147        // Wait for the command to complete naturally
3148        let exit_status = smol_timeout(Duration::from_secs(5), completion_rx.recv())
3149            .await
3150            .expect("Command should complete")
3151            .expect("Should receive exit status");
3152        assert_eq!(exit_status, Some(ExitStatus::default()));
3153
3154        // Now try to kill - should be a no-op since task already completed
3155        terminal.update(cx, |term, _cx| {
3156            term.kill_active_task();
3157        });
3158
3159        // Content should still be there
3160        let content = terminal.update(cx, |term, _| term.get_content());
3161        assert!(
3162            content.contains("done"),
3163            "Output should still be present after no-op kill, got: {content}"
3164        );
3165    }
3166
3167    mod perf {
3168        use super::super::*;
3169        use gpui::{
3170            Entity, Point, ScrollDelta, ScrollWheelEvent, TestAppContext, VisualContext,
3171            VisualTestContext, point,
3172        };
3173        use util::default;
3174        use util_macros::perf;
3175
3176        async fn init_scroll_perf_test(
3177            cx: &mut TestAppContext,
3178        ) -> (Entity<Terminal>, &mut VisualTestContext) {
3179            cx.update(|cx| {
3180                let settings_store = settings::SettingsStore::test(cx);
3181                cx.set_global(settings_store);
3182            });
3183
3184            cx.executor().allow_parking();
3185
3186            let window = cx.add_empty_window();
3187            let builder = window
3188                .update(|window, cx| {
3189                    let settings = TerminalSettings::get_global(cx);
3190                    let test_path_hyperlink_timeout_ms = 100;
3191                    TerminalBuilder::new(
3192                        None,
3193                        None,
3194                        task::Shell::System,
3195                        HashMap::default(),
3196                        CursorShape::default(),
3197                        AlternateScroll::On,
3198                        None,
3199                        settings.path_hyperlink_regexes.clone(),
3200                        test_path_hyperlink_timeout_ms,
3201                        false,
3202                        window.window_handle().window_id().as_u64(),
3203                        None,
3204                        cx,
3205                        vec![],
3206                    )
3207                })
3208                .await
3209                .unwrap();
3210            let terminal = window.new(|cx| builder.subscribe(cx));
3211
3212            terminal.update(window, |term, cx| {
3213                term.write_output("long line ".repeat(1000).as_bytes(), cx);
3214            });
3215
3216            (terminal, window)
3217        }
3218
3219        #[perf]
3220        #[gpui::test]
3221        async fn scroll_long_line_benchmark(cx: &mut TestAppContext) {
3222            let (terminal, window) = init_scroll_perf_test(cx).await;
3223            let wobble = point(FIND_HYPERLINK_THROTTLE_PX, px(0.0));
3224            let mut scroll_by = |lines: i32| {
3225                window.update_window_entity(&terminal, |terminal, window, cx| {
3226                    let bounds = terminal.last_content.terminal_bounds.bounds;
3227                    let center = bounds.origin + bounds.center();
3228                    let position = center + wobble * lines as f32;
3229
3230                    terminal.mouse_move(
3231                        &MouseMoveEvent {
3232                            position,
3233                            ..default()
3234                        },
3235                        cx,
3236                    );
3237
3238                    terminal.scroll_wheel(
3239                        &ScrollWheelEvent {
3240                            position,
3241                            delta: ScrollDelta::Lines(Point::new(0.0, lines as f32)),
3242                            ..default()
3243                        },
3244                        1.0,
3245                    );
3246
3247                    assert!(
3248                        terminal
3249                            .events
3250                            .iter()
3251                            .any(|event| matches!(event, InternalEvent::Scroll(_))),
3252                        "Should have Scroll event when scrolling within terminal bounds"
3253                    );
3254                    terminal.sync(window, cx);
3255                });
3256            };
3257
3258            for _ in 0..20000 {
3259                scroll_by(1);
3260                scroll_by(-1);
3261            }
3262        }
3263    }
3264}