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