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