terminal.rs

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