terminal.rs

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