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