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