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            }
 904            InternalEvent::ScrollToAlacPoint(point) => {
 905                term.scroll_to_point(*point);
 906                self.refresh_hovered_word(window);
 907            }
 908            InternalEvent::ToggleViMode => {
 909                self.vi_mode_enabled = !self.vi_mode_enabled;
 910                term.toggle_vi_mode();
 911            }
 912            InternalEvent::ViMotion(motion) => {
 913                term.vi_motion(*motion);
 914            }
 915            InternalEvent::FindHyperlink(position, open) => {
 916                let prev_hovered_word = self.last_content.last_hovered_word.take();
 917
 918                let point = grid_point(
 919                    *position,
 920                    self.last_content.terminal_bounds,
 921                    term.grid().display_offset(),
 922                )
 923                .grid_clamp(term, Boundary::Grid);
 924
 925                match terminal_hyperlinks::find_from_grid_point(
 926                    term,
 927                    point,
 928                    &mut self.hyperlink_regex_searches,
 929                ) {
 930                    Some((maybe_url_or_path, is_url, url_match)) => {
 931                        let target = if is_url {
 932                            // Treat "file://" URLs like file paths to ensure
 933                            // that line numbers at the end of the path are
 934                            // handled correctly.
 935                            // file://{path} should be urldecoded, returning a urldecoded {path}
 936                            if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
 937                                let decoded_path = urlencoding::decode(path)
 938                                    .map(|decoded| decoded.into_owned())
 939                                    .unwrap_or(path.to_owned());
 940
 941                                MaybeNavigationTarget::PathLike(PathLikeTarget {
 942                                    maybe_path: decoded_path,
 943                                    terminal_dir: self.working_directory(),
 944                                })
 945                            } else {
 946                                MaybeNavigationTarget::Url(maybe_url_or_path.clone())
 947                            }
 948                        } else {
 949                            MaybeNavigationTarget::PathLike(PathLikeTarget {
 950                                maybe_path: maybe_url_or_path.clone(),
 951                                terminal_dir: self.working_directory(),
 952                            })
 953                        };
 954                        if *open {
 955                            cx.emit(Event::Open(target));
 956                        } else {
 957                            self.update_selected_word(
 958                                prev_hovered_word,
 959                                url_match,
 960                                maybe_url_or_path,
 961                                target,
 962                                cx,
 963                            );
 964                        }
 965                    }
 966                    None => {
 967                        cx.emit(Event::NewNavigationTarget(None));
 968                    }
 969                }
 970            }
 971        }
 972    }
 973
 974    fn update_selected_word(
 975        &mut self,
 976        prev_word: Option<HoveredWord>,
 977        word_match: RangeInclusive<AlacPoint>,
 978        word: String,
 979        navigation_target: MaybeNavigationTarget,
 980        cx: &mut Context<Self>,
 981    ) {
 982        if let Some(prev_word) = prev_word {
 983            if prev_word.word == word && prev_word.word_match == word_match {
 984                self.last_content.last_hovered_word = Some(HoveredWord {
 985                    word,
 986                    word_match,
 987                    id: prev_word.id,
 988                });
 989                return;
 990            }
 991        }
 992
 993        self.last_content.last_hovered_word = Some(HoveredWord {
 994            word,
 995            word_match,
 996            id: self.next_link_id(),
 997        });
 998        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
 999        cx.notify()
1000    }
1001
1002    fn next_link_id(&mut self) -> usize {
1003        let res = self.next_link_id;
1004        self.next_link_id = self.next_link_id.wrapping_add(1);
1005        res
1006    }
1007
1008    pub fn last_content(&self) -> &TerminalContent {
1009        &self.last_content
1010    }
1011
1012    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1013        self.term_config.default_cursor_style = cursor_shape.into();
1014        self.term.lock().set_options(self.term_config.clone());
1015    }
1016
1017    pub fn total_lines(&self) -> usize {
1018        let term = self.term.clone();
1019        let terminal = term.lock_unfair();
1020        terminal.total_lines()
1021    }
1022
1023    pub fn viewport_lines(&self) -> usize {
1024        let term = self.term.clone();
1025        let terminal = term.lock_unfair();
1026        terminal.screen_lines()
1027    }
1028
1029    //To test:
1030    //- Activate match on terminal (scrolling and selection)
1031    //- Editor search snapping behavior
1032
1033    pub fn activate_match(&mut self, index: usize) {
1034        if let Some(search_match) = self.matches.get(index).cloned() {
1035            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1036
1037            self.events
1038                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1039        }
1040    }
1041
1042    pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1043        let matches_to_select = self
1044            .matches
1045            .iter()
1046            .filter(|self_match| matches.contains(self_match))
1047            .cloned()
1048            .collect::<Vec<_>>();
1049        for match_to_select in matches_to_select {
1050            self.set_selection(Some((
1051                make_selection(&match_to_select),
1052                *match_to_select.end(),
1053            )));
1054        }
1055    }
1056
1057    pub fn select_all(&mut self) {
1058        let term = self.term.lock();
1059        let start = AlacPoint::new(term.topmost_line(), Column(0));
1060        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1061        drop(term);
1062        self.set_selection(Some((make_selection(&(start..=end)), end)));
1063    }
1064
1065    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1066        self.events
1067            .push_back(InternalEvent::SetSelection(selection));
1068    }
1069
1070    pub fn copy(&mut self) {
1071        self.events.push_back(InternalEvent::Copy);
1072    }
1073
1074    pub fn clear(&mut self) {
1075        self.events.push_back(InternalEvent::Clear)
1076    }
1077
1078    pub fn scroll_line_up(&mut self) {
1079        self.events
1080            .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1081    }
1082
1083    pub fn scroll_up_by(&mut self, lines: usize) {
1084        self.events
1085            .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1086    }
1087
1088    pub fn scroll_line_down(&mut self) {
1089        self.events
1090            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1091    }
1092
1093    pub fn scroll_down_by(&mut self, lines: usize) {
1094        self.events
1095            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1096    }
1097
1098    pub fn scroll_page_up(&mut self) {
1099        self.events
1100            .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1101    }
1102
1103    pub fn scroll_page_down(&mut self) {
1104        self.events
1105            .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1106    }
1107
1108    pub fn scroll_to_top(&mut self) {
1109        self.events
1110            .push_back(InternalEvent::Scroll(AlacScroll::Top));
1111    }
1112
1113    pub fn scroll_to_bottom(&mut self) {
1114        self.events
1115            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1116    }
1117
1118    pub fn scrolled_to_top(&self) -> bool {
1119        self.last_content.scrolled_to_top
1120    }
1121
1122    pub fn scrolled_to_bottom(&self) -> bool {
1123        self.last_content.scrolled_to_bottom
1124    }
1125
1126    ///Resize the terminal and the PTY.
1127    pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1128        if self.last_content.terminal_bounds != new_bounds {
1129            self.events.push_back(InternalEvent::Resize(new_bounds))
1130        }
1131    }
1132
1133    ///Write the Input payload to the tty.
1134    fn write_to_pty(&self, input: impl Into<Cow<'static, [u8]>>) {
1135        self.pty_tx.notify(input.into());
1136    }
1137
1138    pub fn input(&mut self, input: impl Into<Cow<'static, [u8]>>) {
1139        self.events
1140            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1141        self.events.push_back(InternalEvent::SetSelection(None));
1142
1143        self.write_to_pty(input);
1144    }
1145
1146    pub fn toggle_vi_mode(&mut self) {
1147        self.events.push_back(InternalEvent::ToggleViMode);
1148    }
1149
1150    pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1151        if !self.vi_mode_enabled {
1152            return;
1153        }
1154
1155        let key: Cow<'_, str> = if keystroke.modifiers.shift {
1156            Cow::Owned(keystroke.key.to_uppercase())
1157        } else {
1158            Cow::Borrowed(keystroke.key.as_str())
1159        };
1160
1161        let motion: Option<ViMotion> = match key.as_ref() {
1162            "h" | "left" => Some(ViMotion::Left),
1163            "j" | "down" => Some(ViMotion::Down),
1164            "k" | "up" => Some(ViMotion::Up),
1165            "l" | "right" => Some(ViMotion::Right),
1166            "w" => Some(ViMotion::WordRight),
1167            "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1168            "e" => Some(ViMotion::WordRightEnd),
1169            "%" => Some(ViMotion::Bracket),
1170            "$" => Some(ViMotion::Last),
1171            "0" => Some(ViMotion::First),
1172            "^" => Some(ViMotion::FirstOccupied),
1173            "H" => Some(ViMotion::High),
1174            "M" => Some(ViMotion::Middle),
1175            "L" => Some(ViMotion::Low),
1176            _ => None,
1177        };
1178
1179        if let Some(motion) = motion {
1180            let cursor = self.last_content.cursor.point;
1181            let cursor_pos = Point {
1182                x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1183                y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1184            };
1185            self.events
1186                .push_back(InternalEvent::UpdateSelection(cursor_pos));
1187            self.events.push_back(InternalEvent::ViMotion(motion));
1188            return;
1189        }
1190
1191        let scroll_motion = match key.as_ref() {
1192            "g" => Some(AlacScroll::Top),
1193            "G" => Some(AlacScroll::Bottom),
1194            "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1195            "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1196            "d" if keystroke.modifiers.control => {
1197                let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1198                Some(AlacScroll::Delta(-amount))
1199            }
1200            "u" if keystroke.modifiers.control => {
1201                let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1202                Some(AlacScroll::Delta(amount))
1203            }
1204            _ => None,
1205        };
1206
1207        if let Some(scroll_motion) = scroll_motion {
1208            self.events.push_back(InternalEvent::Scroll(scroll_motion));
1209            return;
1210        }
1211
1212        match key.as_ref() {
1213            "v" => {
1214                let point = self.last_content.cursor.point;
1215                let selection_type = SelectionType::Simple;
1216                let side = AlacDirection::Right;
1217                let selection = Selection::new(selection_type, point, side);
1218                self.events
1219                    .push_back(InternalEvent::SetSelection(Some((selection, point))));
1220                return;
1221            }
1222
1223            "escape" => {
1224                self.events.push_back(InternalEvent::SetSelection(None));
1225                return;
1226            }
1227
1228            "y" => {
1229                self.events.push_back(InternalEvent::Copy);
1230                self.events.push_back(InternalEvent::SetSelection(None));
1231                return;
1232            }
1233
1234            "i" => {
1235                self.scroll_to_bottom();
1236                self.toggle_vi_mode();
1237                return;
1238            }
1239            _ => {}
1240        }
1241    }
1242
1243    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1244        if self.vi_mode_enabled {
1245            self.vi_motion(keystroke);
1246            return true;
1247        }
1248
1249        // Keep default terminal behavior
1250        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1251        if let Some(esc) = esc {
1252            match esc {
1253                Cow::Borrowed(string) => self.input(string.as_bytes()),
1254                Cow::Owned(string) => self.input(string.into_bytes()),
1255            };
1256            true
1257        } else {
1258            false
1259        }
1260    }
1261
1262    pub fn try_modifiers_change(
1263        &mut self,
1264        modifiers: &Modifiers,
1265        window: &Window,
1266        cx: &mut Context<Self>,
1267    ) {
1268        if self
1269            .last_content
1270            .terminal_bounds
1271            .bounds
1272            .contains(&window.mouse_position())
1273            && modifiers.secondary()
1274        {
1275            self.refresh_hovered_word(window);
1276        }
1277        cx.notify();
1278    }
1279
1280    ///Paste text into the terminal
1281    pub fn paste(&mut self, text: &str) {
1282        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1283            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1284        } else {
1285            text.replace("\r\n", "\r").replace('\n', "\r")
1286        };
1287
1288        self.input(paste_text.into_bytes());
1289    }
1290
1291    pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1292        let term = self.term.clone();
1293        let mut terminal = term.lock_unfair();
1294        //Note that the ordering of events matters for event processing
1295        while let Some(e) = self.events.pop_front() {
1296            self.process_terminal_event(&e, &mut terminal, window, cx)
1297        }
1298
1299        self.last_content = Self::make_content(&terminal, &self.last_content);
1300    }
1301
1302    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1303        let content = term.renderable_content();
1304        TerminalContent {
1305            cells: content
1306                .display_iter
1307                //TODO: Add this once there's a way to retain empty lines
1308                // .filter(|ic| {
1309                //     !ic.flags.contains(Flags::HIDDEN)
1310                //         && !(ic.bg == Named(NamedColor::Background)
1311                //             && ic.c == ' '
1312                //             && !ic.flags.contains(Flags::INVERSE))
1313                // })
1314                .map(|ic| IndexedCell {
1315                    point: ic.point,
1316                    cell: ic.cell.clone(),
1317                })
1318                .collect::<Vec<IndexedCell>>(),
1319            mode: content.mode,
1320            display_offset: content.display_offset,
1321            selection_text: term.selection_to_string(),
1322            selection: content.selection,
1323            cursor: content.cursor,
1324            cursor_char: term.grid()[content.cursor.point].c,
1325            terminal_bounds: last_content.terminal_bounds,
1326            last_hovered_word: last_content.last_hovered_word.clone(),
1327            scrolled_to_top: content.display_offset == term.history_size(),
1328            scrolled_to_bottom: content.display_offset == 0,
1329        }
1330    }
1331
1332    pub fn get_content(&self) -> String {
1333        let term = self.term.lock_unfair();
1334        let start = AlacPoint::new(term.topmost_line(), Column(0));
1335        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1336        term.bounds_to_string(start, end)
1337    }
1338
1339    pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1340        let term = self.term.clone();
1341        let terminal = term.lock_unfair();
1342        let grid = terminal.grid();
1343        let mut lines = Vec::new();
1344
1345        let mut current_line = grid.bottommost_line().0;
1346        let topmost_line = grid.topmost_line().0;
1347
1348        while current_line >= topmost_line && lines.len() < n {
1349            let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1350            let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1351
1352            if let Some(line) = self.process_line(logical_line) {
1353                lines.push(line);
1354            }
1355
1356            // Move to the line above the start of the current logical line
1357            current_line = logical_line_start - 1;
1358        }
1359
1360        lines.reverse();
1361        lines
1362    }
1363
1364    fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1365        let mut line_start = current;
1366        while line_start > topmost {
1367            let prev_line = Line(line_start - 1);
1368            let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1369            if !last_cell.flags.contains(Flags::WRAPLINE) {
1370                break;
1371            }
1372            line_start -= 1;
1373        }
1374        line_start
1375    }
1376
1377    fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1378        let mut logical_line = String::new();
1379        for row in start..=end {
1380            let grid_row = &grid[Line(row)];
1381            logical_line.push_str(&row_to_string(grid_row));
1382        }
1383        logical_line
1384    }
1385
1386    fn process_line(&self, line: String) -> Option<String> {
1387        let trimmed = line.trim_end().to_string();
1388        if !trimmed.is_empty() {
1389            Some(trimmed)
1390        } else {
1391            None
1392        }
1393    }
1394
1395    pub fn focus_in(&self) {
1396        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1397            self.write_to_pty("\x1b[I".as_bytes());
1398        }
1399    }
1400
1401    pub fn focus_out(&mut self) {
1402        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1403            self.write_to_pty("\x1b[O".as_bytes());
1404        }
1405    }
1406
1407    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1408        match self.last_mouse {
1409            Some((old_point, old_side)) => {
1410                if old_point == point && old_side == side {
1411                    false
1412                } else {
1413                    self.last_mouse = Some((point, side));
1414                    true
1415                }
1416            }
1417            None => {
1418                self.last_mouse = Some((point, side));
1419                true
1420            }
1421        }
1422    }
1423
1424    pub fn mouse_mode(&self, shift: bool) -> bool {
1425        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1426    }
1427
1428    pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1429        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1430        if self.mouse_mode(e.modifiers.shift) {
1431            let (point, side) = grid_point_and_side(
1432                position,
1433                self.last_content.terminal_bounds,
1434                self.last_content.display_offset,
1435            );
1436
1437            if self.mouse_changed(point, side) {
1438                if let Some(bytes) =
1439                    mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1440                {
1441                    self.pty_tx.notify(bytes);
1442                }
1443            }
1444        } else if e.modifiers.secondary() {
1445            self.word_from_position(e.position);
1446        }
1447        cx.notify();
1448    }
1449
1450    fn word_from_position(&mut self, position: Point<Pixels>) {
1451        if self.selection_phase == SelectionPhase::Selecting {
1452            self.last_content.last_hovered_word = None;
1453        } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1454            self.events.push_back(InternalEvent::FindHyperlink(
1455                position - self.last_content.terminal_bounds.bounds.origin,
1456                false,
1457            ));
1458        } else {
1459            self.last_content.last_hovered_word = None;
1460        }
1461    }
1462
1463    pub fn select_word_at_event_position(&mut self, e: &MouseDownEvent) {
1464        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1465        let (point, side) = grid_point_and_side(
1466            position,
1467            self.last_content.terminal_bounds,
1468            self.last_content.display_offset,
1469        );
1470        let selection = Selection::new(SelectionType::Semantic, point, side);
1471        self.events
1472            .push_back(InternalEvent::SetSelection(Some((selection, point))));
1473    }
1474
1475    pub fn mouse_drag(
1476        &mut self,
1477        e: &MouseMoveEvent,
1478        region: Bounds<Pixels>,
1479        cx: &mut Context<Self>,
1480    ) {
1481        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1482        if !self.mouse_mode(e.modifiers.shift) {
1483            self.selection_phase = SelectionPhase::Selecting;
1484            // Alacritty has the same ordering, of first updating the selection
1485            // then scrolling 15ms later
1486            self.events
1487                .push_back(InternalEvent::UpdateSelection(position));
1488
1489            // Doesn't make sense to scroll the alt screen
1490            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1491                let scroll_lines = match self.drag_line_delta(e, region) {
1492                    Some(value) => value,
1493                    None => return,
1494                };
1495
1496                self.events
1497                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1498            }
1499
1500            cx.notify();
1501        }
1502    }
1503
1504    fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1505        let top = region.origin.y;
1506        let bottom = region.bottom_left().y;
1507
1508        let scroll_lines = if e.position.y < top {
1509            let scroll_delta = (top - e.position.y).pow(1.1);
1510            (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1511        } else if e.position.y > bottom {
1512            let scroll_delta = -((e.position.y - bottom).pow(1.1));
1513            (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1514        } else {
1515            return None;
1516        };
1517
1518        Some(scroll_lines.clamp(-3, 3))
1519    }
1520
1521    pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1522        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1523        let point = grid_point(
1524            position,
1525            self.last_content.terminal_bounds,
1526            self.last_content.display_offset,
1527        );
1528
1529        if self.mouse_mode(e.modifiers.shift) {
1530            if let Some(bytes) =
1531                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1532            {
1533                self.pty_tx.notify(bytes);
1534            }
1535        } else {
1536            match e.button {
1537                MouseButton::Left => {
1538                    let (point, side) = grid_point_and_side(
1539                        position,
1540                        self.last_content.terminal_bounds,
1541                        self.last_content.display_offset,
1542                    );
1543
1544                    let selection_type = match e.click_count {
1545                        0 => return, //This is a release
1546                        1 => Some(SelectionType::Simple),
1547                        2 => Some(SelectionType::Semantic),
1548                        3 => Some(SelectionType::Lines),
1549                        _ => None,
1550                    };
1551
1552                    if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1553                        self.events
1554                            .push_back(InternalEvent::UpdateSelection(position));
1555                        return;
1556                    }
1557
1558                    let selection = selection_type
1559                        .map(|selection_type| Selection::new(selection_type, point, side));
1560
1561                    if let Some(sel) = selection {
1562                        self.events
1563                            .push_back(InternalEvent::SetSelection(Some((sel, point))));
1564                    }
1565                }
1566                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1567                MouseButton::Middle => {
1568                    if let Some(item) = _cx.read_from_primary() {
1569                        let text = item.text().unwrap_or_default().to_string();
1570                        self.input(text.into_bytes());
1571                    }
1572                }
1573                _ => {}
1574            }
1575        }
1576    }
1577
1578    pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1579        let setting = TerminalSettings::get_global(cx);
1580
1581        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1582        if self.mouse_mode(e.modifiers.shift) {
1583            let point = grid_point(
1584                position,
1585                self.last_content.terminal_bounds,
1586                self.last_content.display_offset,
1587            );
1588
1589            if let Some(bytes) =
1590                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1591            {
1592                self.pty_tx.notify(bytes);
1593            }
1594        } else {
1595            if e.button == MouseButton::Left && setting.copy_on_select {
1596                self.copy();
1597            }
1598
1599            //Hyperlinks
1600            if self.selection_phase == SelectionPhase::Ended {
1601                let mouse_cell_index =
1602                    content_index_for_mouse(position, &self.last_content.terminal_bounds);
1603                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1604                    cx.open_url(link.uri());
1605                } else if e.modifiers.secondary() {
1606                    self.events
1607                        .push_back(InternalEvent::FindHyperlink(position, true));
1608                }
1609            }
1610        }
1611
1612        self.selection_phase = SelectionPhase::Ended;
1613        self.last_mouse = None;
1614    }
1615
1616    ///Scroll the terminal
1617    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1618        let mouse_mode = self.mouse_mode(e.shift);
1619
1620        if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1621            if mouse_mode {
1622                let point = grid_point(
1623                    e.position - self.last_content.terminal_bounds.bounds.origin,
1624                    self.last_content.terminal_bounds,
1625                    self.last_content.display_offset,
1626                );
1627
1628                if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1629                {
1630                    for scroll in scrolls {
1631                        self.pty_tx.notify(scroll);
1632                    }
1633                };
1634            } else if self
1635                .last_content
1636                .mode
1637                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1638                && !e.shift
1639            {
1640                self.pty_tx.notify(alt_scroll(scroll_lines))
1641            } else if scroll_lines != 0 {
1642                let scroll = AlacScroll::Delta(scroll_lines);
1643
1644                self.events.push_back(InternalEvent::Scroll(scroll));
1645            }
1646        }
1647    }
1648
1649    fn refresh_hovered_word(&mut self, window: &Window) {
1650        self.word_from_position(window.mouse_position());
1651    }
1652
1653    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1654        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1655        let line_height = self.last_content.terminal_bounds.line_height;
1656        match e.touch_phase {
1657            /* Reset scroll state on started */
1658            TouchPhase::Started => {
1659                self.scroll_px = px(0.);
1660                None
1661            }
1662            /* Calculate the appropriate scroll lines */
1663            TouchPhase::Moved => {
1664                let old_offset = (self.scroll_px / line_height) as i32;
1665
1666                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1667
1668                let new_offset = (self.scroll_px / line_height) as i32;
1669
1670                // Whenever we hit the edges, reset our stored scroll to 0
1671                // so we can respond to changes in direction quickly
1672                self.scroll_px %= self.last_content.terminal_bounds.height();
1673
1674                Some(new_offset - old_offset)
1675            }
1676            TouchPhase::Ended => None,
1677        }
1678    }
1679
1680    pub fn find_matches(
1681        &self,
1682        mut searcher: RegexSearch,
1683        cx: &Context<Self>,
1684    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1685        let term = self.term.clone();
1686        cx.background_spawn(async move {
1687            let term = term.lock();
1688
1689            all_search_matches(&term, &mut searcher).collect()
1690        })
1691    }
1692
1693    pub fn working_directory(&self) -> Option<PathBuf> {
1694        if self.is_ssh_terminal {
1695            // We can't yet reliably detect the working directory of a shell on the
1696            // SSH host. Until we can do that, it doesn't make sense to display
1697            // the working directory on the client and persist that.
1698            None
1699        } else {
1700            self.client_side_working_directory()
1701        }
1702    }
1703
1704    /// Returns the working directory of the process that's connected to the PTY.
1705    /// That means it returns the working directory of the local shell or program
1706    /// that's running inside the terminal.
1707    ///
1708    /// This does *not* return the working directory of the shell that runs on the
1709    /// remote host, in case Zed is connected to a remote host.
1710    fn client_side_working_directory(&self) -> Option<PathBuf> {
1711        self.pty_info
1712            .current
1713            .as_ref()
1714            .map(|process| process.cwd.clone())
1715    }
1716
1717    pub fn title(&self, truncate: bool) -> String {
1718        const MAX_CHARS: usize = 25;
1719        match &self.task {
1720            Some(task_state) => {
1721                if truncate {
1722                    truncate_and_trailoff(&task_state.label, MAX_CHARS)
1723                } else {
1724                    task_state.full_label.clone()
1725                }
1726            }
1727            None => self
1728                .title_override
1729                .as_ref()
1730                .map(|title_override| title_override.to_string())
1731                .unwrap_or_else(|| {
1732                    self.pty_info
1733                        .current
1734                        .as_ref()
1735                        .map(|fpi| {
1736                            let process_file = fpi
1737                                .cwd
1738                                .file_name()
1739                                .map(|name| name.to_string_lossy().to_string())
1740                                .unwrap_or_default();
1741
1742                            let argv = fpi.argv.as_slice();
1743                            let process_name = format!(
1744                                "{}{}",
1745                                fpi.name,
1746                                if !argv.is_empty() {
1747                                    format!(" {}", (argv[1..]).join(" "))
1748                                } else {
1749                                    "".to_string()
1750                                }
1751                            );
1752                            let (process_file, process_name) = if truncate {
1753                                (
1754                                    truncate_and_trailoff(&process_file, MAX_CHARS),
1755                                    truncate_and_trailoff(&process_name, MAX_CHARS),
1756                                )
1757                            } else {
1758                                (process_file, process_name)
1759                            };
1760                            format!("{process_file}{process_name}")
1761                        })
1762                        .unwrap_or_else(|| "Terminal".to_string())
1763                }),
1764        }
1765    }
1766
1767    pub fn task(&self) -> Option<&TaskState> {
1768        self.task.as_ref()
1769    }
1770
1771    pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
1772        if let Some(task) = self.task() {
1773            if task.status == TaskStatus::Running {
1774                let completion_receiver = task.completion_rx.clone();
1775                return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
1776            } else if let Ok(status) = task.completion_rx.try_recv() {
1777                return Task::ready(status);
1778            }
1779        }
1780        Task::ready(None)
1781    }
1782
1783    fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
1784        let e: Option<ExitStatus> = error_code.map(|code| {
1785            #[cfg(unix)]
1786            {
1787                return std::os::unix::process::ExitStatusExt::from_raw(code);
1788            }
1789            #[cfg(windows)]
1790            {
1791                return std::os::windows::process::ExitStatusExt::from_raw(code as u32);
1792            }
1793        });
1794
1795        self.completion_tx.try_send(e).ok();
1796        let task = match &mut self.task {
1797            Some(task) => task,
1798            None => {
1799                if error_code.is_none() {
1800                    cx.emit(Event::CloseTerminal);
1801                }
1802                return;
1803            }
1804        };
1805        if task.status != TaskStatus::Running {
1806            return;
1807        }
1808        match error_code {
1809            Some(error_code) => {
1810                task.status.register_task_exit(error_code);
1811            }
1812            None => {
1813                task.status.register_terminal_exit();
1814            }
1815        };
1816
1817        let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1818        let mut lines_to_show = Vec::new();
1819        if task.show_summary {
1820            lines_to_show.push(task_line.as_str());
1821        }
1822        if task.show_command {
1823            lines_to_show.push(command_line.as_str());
1824        }
1825
1826        if !lines_to_show.is_empty() {
1827            // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1828            // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1829            // when Zed task finishes and no more output is made.
1830            // After the task summary is output once, no more text is appended to the terminal.
1831            unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1832        }
1833
1834        match task.hide {
1835            HideStrategy::Never => {}
1836            HideStrategy::Always => {
1837                cx.emit(Event::CloseTerminal);
1838            }
1839            HideStrategy::OnSuccess => {
1840                if finished_successfully {
1841                    cx.emit(Event::CloseTerminal);
1842                }
1843            }
1844        }
1845    }
1846
1847    pub fn vi_mode_enabled(&self) -> bool {
1848        self.vi_mode_enabled
1849    }
1850}
1851
1852// Helper function to convert a grid row to a string
1853pub fn row_to_string(row: &Row<Cell>) -> String {
1854    row[..Column(row.len())]
1855        .iter()
1856        .map(|cell| cell.c)
1857        .collect::<String>()
1858}
1859
1860const TASK_DELIMITER: &str = "";
1861fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1862    let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1863    let (success, task_line) = match error_code {
1864        Some(0) => (
1865            true,
1866            format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
1867        ),
1868        Some(error_code) => (
1869            false,
1870            format!(
1871                "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
1872            ),
1873        ),
1874        None => (
1875            false,
1876            format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
1877        ),
1878    };
1879    let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1880    let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1881    (success, task_line, command_line)
1882}
1883
1884/// Appends a stringified task summary to the terminal, after its output.
1885///
1886/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1887/// New text being added to the terminal here, uses "less public" APIs,
1888/// which are not maintaining the entire terminal state intact.
1889///
1890///
1891/// The library
1892///
1893/// * does not increment inner grid cursor's _lines_ on `input` calls
1894///   (but displaying the lines correctly and incrementing cursor's columns)
1895///
1896/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1897///
1898/// * does not alter grid state after `newline` call
1899///   so its `bottommost_line` is always the same additions, and
1900///   the cursor's `point` is not updated to the new line and column values
1901///
1902/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1903///   Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1904///
1905/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1906/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1907/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1908/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1909unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1910    term.newline();
1911    term.grid_mut().cursor.point.column = Column(0);
1912    for line in text_lines {
1913        for c in line.chars() {
1914            term.input(c);
1915        }
1916        term.newline();
1917        term.grid_mut().cursor.point.column = Column(0);
1918    }
1919}
1920
1921impl Drop for Terminal {
1922    fn drop(&mut self) {
1923        self.pty_tx.0.send(Msg::Shutdown).ok();
1924    }
1925}
1926
1927impl EventEmitter<Event> for Terminal {}
1928
1929fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1930    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1931    selection.update(*range.end(), AlacDirection::Right);
1932    selection
1933}
1934
1935fn all_search_matches<'a, T>(
1936    term: &'a Term<T>,
1937    regex: &'a mut RegexSearch,
1938) -> impl Iterator<Item = Match> + 'a {
1939    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1940    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1941    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1942}
1943
1944fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
1945    let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
1946    let clamped_col = min(col, terminal_bounds.columns() - 1);
1947    let row = (pos.y / terminal_bounds.line_height()).round() as usize;
1948    let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
1949    clamped_row * terminal_bounds.columns() + clamped_col
1950}
1951
1952/// Converts an 8 bit ANSI color to its GPUI equivalent.
1953/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1954/// Other than that use case, should only be called with values in the `[0,255]` range
1955pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1956    let colors = theme.colors();
1957
1958    match index {
1959        // 0-15 are the same as the named colors above
1960        0 => colors.terminal_ansi_black,
1961        1 => colors.terminal_ansi_red,
1962        2 => colors.terminal_ansi_green,
1963        3 => colors.terminal_ansi_yellow,
1964        4 => colors.terminal_ansi_blue,
1965        5 => colors.terminal_ansi_magenta,
1966        6 => colors.terminal_ansi_cyan,
1967        7 => colors.terminal_ansi_white,
1968        8 => colors.terminal_ansi_bright_black,
1969        9 => colors.terminal_ansi_bright_red,
1970        10 => colors.terminal_ansi_bright_green,
1971        11 => colors.terminal_ansi_bright_yellow,
1972        12 => colors.terminal_ansi_bright_blue,
1973        13 => colors.terminal_ansi_bright_magenta,
1974        14 => colors.terminal_ansi_bright_cyan,
1975        15 => colors.terminal_ansi_bright_white,
1976        // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
1977        // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
1978        16..=231 => {
1979            let (r, g, b) = rgb_for_index(index as u8);
1980            rgba_color(
1981                if r == 0 { 0 } else { r * 40 + 55 },
1982                if g == 0 { 0 } else { g * 40 + 55 },
1983                if b == 0 { 0 } else { b * 40 + 55 },
1984            )
1985        }
1986        // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
1987        232..=255 => {
1988            let i = index as u8 - 232; // Align index to 0..24
1989            let value = i * 10 + 8;
1990            rgba_color(value, value, value)
1991        }
1992        // For compatibility with the alacritty::Colors interface
1993        // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
1994        256 => colors.terminal_foreground,
1995        257 => colors.terminal_background,
1996        258 => theme.players().local().cursor,
1997        259 => colors.terminal_ansi_dim_black,
1998        260 => colors.terminal_ansi_dim_red,
1999        261 => colors.terminal_ansi_dim_green,
2000        262 => colors.terminal_ansi_dim_yellow,
2001        263 => colors.terminal_ansi_dim_blue,
2002        264 => colors.terminal_ansi_dim_magenta,
2003        265 => colors.terminal_ansi_dim_cyan,
2004        266 => colors.terminal_ansi_dim_white,
2005        267 => colors.terminal_bright_foreground,
2006        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2007
2008        _ => black(),
2009    }
2010}
2011
2012/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2013/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2014///
2015/// Wikipedia gives a formula for calculating the index for a given color:
2016///
2017/// ```
2018/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2019/// ```
2020///
2021/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2022fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2023    debug_assert!((16..=231).contains(&i));
2024    let i = i - 16;
2025    let r = (i - (i % 36)) / 36;
2026    let g = ((i % 36) - (i % 6)) / 6;
2027    let b = (i % 36) % 6;
2028    (r, g, b)
2029}
2030
2031pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2032    Rgba {
2033        r: (r as f32 / 255.),
2034        g: (g as f32 / 255.),
2035        b: (b as f32 / 255.),
2036        a: 1.,
2037    }
2038    .into()
2039}
2040
2041#[cfg(test)]
2042mod tests {
2043    use alacritty_terminal::{
2044        index::{Column, Line, Point as AlacPoint},
2045        term::cell::Cell,
2046    };
2047    use gpui::{Pixels, Point, bounds, point, size};
2048    use rand::{Rng, distributions::Alphanumeric, rngs::ThreadRng, thread_rng};
2049
2050    use crate::{
2051        IndexedCell, TerminalBounds, TerminalContent, content_index_for_mouse, rgb_for_index,
2052    };
2053
2054    #[test]
2055    fn test_rgb_for_index() {
2056        // Test every possible value in the color cube.
2057        for i in 16..=231 {
2058            let (r, g, b) = rgb_for_index(i);
2059            assert_eq!(i, 16 + 36 * r + 6 * g + b);
2060        }
2061    }
2062
2063    #[test]
2064    fn test_mouse_to_cell_test() {
2065        let mut rng = thread_rng();
2066        const ITERATIONS: usize = 10;
2067        const PRECISION: usize = 1000;
2068
2069        for _ in 0..ITERATIONS {
2070            let viewport_cells = rng.gen_range(15..20);
2071            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2072
2073            let size = crate::TerminalBounds {
2074                cell_width: Pixels::from(cell_size),
2075                line_height: Pixels::from(cell_size),
2076                bounds: bounds(
2077                    Point::default(),
2078                    size(
2079                        Pixels::from(cell_size * (viewport_cells as f32)),
2080                        Pixels::from(cell_size * (viewport_cells as f32)),
2081                    ),
2082                ),
2083            };
2084
2085            let cells = get_cells(size, &mut rng);
2086            let content = convert_cells_to_content(size, &cells);
2087
2088            for row in 0..(viewport_cells - 1) {
2089                let row = row as usize;
2090                for col in 0..(viewport_cells - 1) {
2091                    let col = col as usize;
2092
2093                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2094                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2095
2096                    let mouse_pos = point(
2097                        Pixels::from(col as f32 * cell_size + col_offset),
2098                        Pixels::from(row as f32 * cell_size + row_offset),
2099                    );
2100
2101                    let content_index =
2102                        content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2103                    let mouse_cell = content.cells[content_index].c;
2104                    let real_cell = cells[row][col];
2105
2106                    assert_eq!(mouse_cell, real_cell);
2107                }
2108            }
2109        }
2110    }
2111
2112    #[test]
2113    fn test_mouse_to_cell_clamp() {
2114        let mut rng = thread_rng();
2115
2116        let size = crate::TerminalBounds {
2117            cell_width: Pixels::from(10.),
2118            line_height: Pixels::from(10.),
2119            bounds: bounds(
2120                Point::default(),
2121                size(Pixels::from(100.), Pixels::from(100.)),
2122            ),
2123        };
2124
2125        let cells = get_cells(size, &mut rng);
2126        let content = convert_cells_to_content(size, &cells);
2127
2128        assert_eq!(
2129            content.cells[content_index_for_mouse(
2130                point(Pixels::from(-10.), Pixels::from(-10.)),
2131                &content.terminal_bounds,
2132            )]
2133            .c,
2134            cells[0][0]
2135        );
2136        assert_eq!(
2137            content.cells[content_index_for_mouse(
2138                point(Pixels::from(1000.), Pixels::from(1000.)),
2139                &content.terminal_bounds,
2140            )]
2141            .c,
2142            cells[9][9]
2143        );
2144    }
2145
2146    fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2147        let mut cells = Vec::new();
2148
2149        for _ in 0..((size.height() / size.line_height()) as usize) {
2150            let mut row_vec = Vec::new();
2151            for _ in 0..((size.width() / size.cell_width()) as usize) {
2152                let cell_char = rng.sample(Alphanumeric) as char;
2153                row_vec.push(cell_char)
2154            }
2155            cells.push(row_vec)
2156        }
2157
2158        cells
2159    }
2160
2161    fn convert_cells_to_content(
2162        terminal_bounds: TerminalBounds,
2163        cells: &[Vec<char>],
2164    ) -> TerminalContent {
2165        let mut ic = Vec::new();
2166
2167        for (index, row) in cells.iter().enumerate() {
2168            for (cell_index, cell_char) in row.iter().enumerate() {
2169                ic.push(IndexedCell {
2170                    point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2171                    cell: Cell {
2172                        c: *cell_char,
2173                        ..Default::default()
2174                    },
2175                });
2176            }
2177        }
2178
2179        TerminalContent {
2180            cells: ic,
2181            terminal_bounds,
2182            ..Default::default()
2183        }
2184    }
2185}