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