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