terminal.rs

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