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