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