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