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