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