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