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