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