terminal.rs

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