terminal.rs

   1pub mod mappings;
   2pub use alacritty_terminal;
   3pub mod terminal_settings;
   4
   5use alacritty_terminal::{
   6    ansi::{ClearMode, Handler},
   7    config::{Config, Program, PtyConfig, Scrolling},
   8    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
   9    event_loop::{EventLoop, Msg, Notifier},
  10    grid::{Dimensions, Scroll as AlacScroll},
  11    index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
  12    selection::{Selection, SelectionRange, SelectionType},
  13    sync::FairMutex,
  14    term::{
  15        cell::Cell,
  16        color::Rgb,
  17        search::{Match, RegexIter, RegexSearch},
  18        RenderableCursor, TermMode,
  19    },
  20    tty::{self, setup_env},
  21    Term,
  22};
  23use anyhow::{bail, Result};
  24
  25use futures::{
  26    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
  27    FutureExt,
  28};
  29
  30use mappings::mouse::{
  31    alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
  32    scroll_report,
  33};
  34
  35use procinfo::LocalProcessInfo;
  36use serde::{Deserialize, Serialize};
  37use settings::Settings;
  38use terminal_settings::{AlternateScroll, Shell, TerminalBlink, TerminalSettings};
  39use theme::{ActiveTheme, Theme};
  40use util::truncate_and_trailoff;
  41
  42use std::{
  43    cmp::{self, min},
  44    collections::{HashMap, VecDeque},
  45    fmt::Display,
  46    ops::{Deref, Index, RangeInclusive},
  47    os::unix::prelude::AsRawFd,
  48    path::PathBuf,
  49    sync::Arc,
  50    time::Duration,
  51};
  52use thiserror::Error;
  53
  54use gpui::{
  55    actions, black, px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla,
  56    Keystroke, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
  57    Pixels, Point, Rgba, ScrollWheelEvent, Size, Task, TouchPhase,
  58};
  59
  60use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
  61use lazy_static::lazy_static;
  62
  63actions!(
  64    terminal,
  65    [Clear, Copy, Paste, ShowCharacterPalette, SearchTest,]
  66);
  67
  68///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  69///Scroll multiplier that is set to 3 by default. This will be removed when I
  70///Implement scroll bars.
  71const SCROLL_MULTIPLIER: f32 = 4.;
  72const MAX_SEARCH_LINES: usize = 100;
  73const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
  74const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
  75const DEBUG_CELL_WIDTH: Pixels = px(5.);
  76const DEBUG_LINE_HEIGHT: Pixels = px(5.);
  77
  78lazy_static! {
  79    // Regex Copied from alacritty's ui_config.rs and modified its declaration slightly:
  80    // * avoid Rust-specific escaping.
  81    // * use more strict regex for `file://` protocol matching: original regex has `file:` inside, but we want to avoid matching `some::file::module` strings.
  82    static ref URL_REGEX: RegexSearch = RegexSearch::new(r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`]+"#).unwrap();
  83
  84    static ref WORD_REGEX: RegexSearch = RegexSearch::new(r#"[\w.\[\]:/@\-~]+"#).unwrap();
  85}
  86
  87///Upward flowing events, for changing the title and such
  88#[derive(Clone, Debug)]
  89pub enum Event {
  90    TitleChanged,
  91    BreadcrumbsChanged,
  92    CloseTerminal,
  93    Bell,
  94    Wakeup,
  95    BlinkChanged,
  96    SelectionsChanged,
  97    NewNavigationTarget(Option<MaybeNavigationTarget>),
  98    Open(MaybeNavigationTarget),
  99}
 100
 101/// A string inside terminal, potentially useful as a URI that can be opened.
 102#[derive(Clone, Debug)]
 103pub enum MaybeNavigationTarget {
 104    /// HTTP, git, etc. string determined by the [`URL_REGEX`] regex.
 105    Url(String),
 106    /// File system path, absolute or relative, existing or not.
 107    /// Might have line and column number(s) attached as `file.rs:1:23`
 108    PathLike(String),
 109}
 110
 111#[derive(Clone)]
 112enum InternalEvent {
 113    ColorRequest(usize, Arc<dyn Fn(Rgb) -> String + Sync + Send + 'static>),
 114    Resize(TerminalSize),
 115    Clear,
 116    // FocusNextMatch,
 117    Scroll(AlacScroll),
 118    ScrollToAlacPoint(AlacPoint),
 119    SetSelection(Option<(Selection, AlacPoint)>),
 120    UpdateSelection(Point<Pixels>),
 121    // Adjusted mouse position, should open
 122    FindHyperlink(Point<Pixels>, bool),
 123    Copy,
 124}
 125
 126///A translation struct for Alacritty to communicate with us from their event loop
 127#[derive(Clone)]
 128pub struct ZedListener(UnboundedSender<AlacTermEvent>);
 129
 130impl EventListener for ZedListener {
 131    fn send_event(&self, event: AlacTermEvent) {
 132        self.0.unbounded_send(event).ok();
 133    }
 134}
 135
 136pub fn init(cx: &mut AppContext) {
 137    TerminalSettings::register(cx);
 138}
 139
 140#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
 141pub struct TerminalSize {
 142    pub cell_width: Pixels,
 143    pub line_height: Pixels,
 144    pub size: Size<Pixels>,
 145}
 146
 147impl TerminalSize {
 148    pub fn new(line_height: Pixels, cell_width: Pixels, size: Size<Pixels>) -> Self {
 149        TerminalSize {
 150            cell_width,
 151            line_height,
 152            size,
 153        }
 154    }
 155
 156    pub fn num_lines(&self) -> usize {
 157        f32::from((self.size.height / self.line_height).floor()) as usize
 158    }
 159
 160    pub fn num_columns(&self) -> usize {
 161        f32::from((self.size.width / self.cell_width).floor()) as usize
 162    }
 163
 164    pub fn height(&self) -> Pixels {
 165        self.size.height
 166    }
 167
 168    pub fn width(&self) -> Pixels {
 169        self.size.width
 170    }
 171
 172    pub fn cell_width(&self) -> Pixels {
 173        self.cell_width
 174    }
 175
 176    pub fn line_height(&self) -> Pixels {
 177        self.line_height
 178    }
 179}
 180impl Default for TerminalSize {
 181    fn default() -> Self {
 182        TerminalSize::new(
 183            DEBUG_LINE_HEIGHT,
 184            DEBUG_CELL_WIDTH,
 185            Size {
 186                width: DEBUG_TERMINAL_WIDTH,
 187                height: DEBUG_TERMINAL_HEIGHT,
 188            },
 189        )
 190    }
 191}
 192
 193impl From<TerminalSize> for WindowSize {
 194    fn from(val: TerminalSize) -> Self {
 195        WindowSize {
 196            num_lines: val.num_lines() as u16,
 197            num_cols: val.num_columns() as u16,
 198            cell_width: f32::from(val.cell_width()) as u16,
 199            cell_height: f32::from(val.line_height()) as u16,
 200        }
 201    }
 202}
 203
 204impl Dimensions for TerminalSize {
 205    /// Note: this is supposed to be for the back buffer's length,
 206    /// but we exclusively use it to resize the terminal, which does not
 207    /// use this method. We still have to implement it for the trait though,
 208    /// hence, this comment.
 209    fn total_lines(&self) -> usize {
 210        self.screen_lines()
 211    }
 212
 213    fn screen_lines(&self) -> usize {
 214        self.num_lines()
 215    }
 216
 217    fn columns(&self) -> usize {
 218        self.num_columns()
 219    }
 220}
 221
 222#[derive(Error, Debug)]
 223pub struct TerminalError {
 224    pub directory: Option<PathBuf>,
 225    pub shell: Shell,
 226    pub source: std::io::Error,
 227}
 228
 229impl TerminalError {
 230    pub fn fmt_directory(&self) -> String {
 231        self.directory
 232            .clone()
 233            .map(|path| {
 234                match path
 235                    .into_os_string()
 236                    .into_string()
 237                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 238                {
 239                    Ok(s) => s,
 240                    Err(s) => s,
 241                }
 242            })
 243            .unwrap_or_else(|| {
 244                let default_dir =
 245                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
 246                match default_dir {
 247                    Some(dir) => format!("<none specified, using home directory> {}", dir),
 248                    None => "<none specified, could not find home directory>".to_string(),
 249                }
 250            })
 251    }
 252
 253    pub fn shell_to_string(&self) -> String {
 254        match &self.shell {
 255            Shell::System => "<system shell>".to_string(),
 256            Shell::Program(p) => p.to_string(),
 257            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 258        }
 259    }
 260
 261    pub fn fmt_shell(&self) -> String {
 262        match &self.shell {
 263            Shell::System => "<system defined shell>".to_string(),
 264            Shell::Program(s) => s.to_string(),
 265            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 266        }
 267    }
 268}
 269
 270impl Display for TerminalError {
 271    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 272        let dir_string: String = self.fmt_directory();
 273        let shell = self.fmt_shell();
 274
 275        write!(
 276            f,
 277            "Working directory: {} Shell command: `{}`, IOError: {}",
 278            dir_string, shell, self.source
 279        )
 280    }
 281}
 282
 283pub struct TerminalBuilder {
 284    terminal: Terminal,
 285    events_rx: UnboundedReceiver<AlacTermEvent>,
 286}
 287
 288impl TerminalBuilder {
 289    pub fn new(
 290        working_directory: Option<PathBuf>,
 291        shell: Shell,
 292        mut env: HashMap<String, String>,
 293        blink_settings: Option<TerminalBlink>,
 294        alternate_scroll: AlternateScroll,
 295        window: AnyWindowHandle,
 296    ) -> Result<TerminalBuilder> {
 297        let pty_config = {
 298            let alac_shell = match shell.clone() {
 299                Shell::System => None,
 300                Shell::Program(program) => Some(Program::Just(program)),
 301                Shell::WithArguments { program, args } => Some(Program::WithArgs { program, args }),
 302            };
 303
 304            PtyConfig {
 305                shell: alac_shell,
 306                working_directory: working_directory.clone(),
 307                hold: false,
 308            }
 309        };
 310
 311        //TODO: Properly set the current locale,
 312        env.insert("LC_ALL".to_string(), "en_US.UTF-8".to_string());
 313        env.insert("ZED_TERM".to_string(), true.to_string());
 314
 315        let alac_scrolling = Scrolling::default();
 316        // alac_scrolling.set_history((BACK_BUFFER_SIZE * 2) as u32);
 317
 318        let config = Config {
 319            pty_config: pty_config.clone(),
 320            env,
 321            scrolling: alac_scrolling,
 322            ..Default::default()
 323        };
 324
 325        setup_env(&config);
 326
 327        //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
 328        //TODO: Remove with a bounded sender which can be dispatched on &self
 329        let (events_tx, events_rx) = unbounded();
 330        //Set up the terminal...
 331        let mut term = Term::new(
 332            &config,
 333            &TerminalSize::default(),
 334            ZedListener(events_tx.clone()),
 335        );
 336
 337        //Start off blinking if we need to
 338        if let Some(TerminalBlink::On) = blink_settings {
 339            term.set_mode(alacritty_terminal::ansi::Mode::BlinkingCursor)
 340        }
 341
 342        //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
 343        if let AlternateScroll::Off = alternate_scroll {
 344            term.unset_mode(alacritty_terminal::ansi::Mode::AlternateScroll)
 345        }
 346
 347        let term = Arc::new(FairMutex::new(term));
 348
 349        //Setup the pty...
 350        let pty = match tty::new(
 351            &pty_config,
 352            TerminalSize::default().into(),
 353            window.window_id().as_u64(),
 354        ) {
 355            Ok(pty) => pty,
 356            Err(error) => {
 357                bail!(TerminalError {
 358                    directory: working_directory,
 359                    shell,
 360                    source: error,
 361                });
 362            }
 363        };
 364
 365        let fd = pty.file().as_raw_fd();
 366        let shell_pid = pty.child().id();
 367
 368        //And connect them together
 369        let event_loop = EventLoop::new(
 370            term.clone(),
 371            ZedListener(events_tx.clone()),
 372            pty,
 373            pty_config.hold,
 374            false,
 375        );
 376
 377        //Kick things off
 378        let pty_tx = event_loop.channel();
 379        let _io_thread = event_loop.spawn();
 380
 381        let terminal = Terminal {
 382            pty_tx: Notifier(pty_tx),
 383            term,
 384            events: VecDeque::with_capacity(10), //Should never get this high.
 385            last_content: Default::default(),
 386            last_mouse: None,
 387            matches: Vec::new(),
 388            selection_head: None,
 389            shell_fd: fd as u32,
 390            shell_pid,
 391            foreground_process_info: None,
 392            breadcrumb_text: String::new(),
 393            scroll_px: px(0.),
 394            last_mouse_position: None,
 395            next_link_id: 0,
 396            selection_phase: SelectionPhase::Ended,
 397            cmd_pressed: false,
 398            hovered_word: false,
 399        };
 400
 401        Ok(TerminalBuilder {
 402            terminal,
 403            events_rx,
 404        })
 405    }
 406
 407    pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
 408        //Event loop
 409        cx.spawn(|this, mut cx| async move {
 410            use futures::StreamExt;
 411
 412            while let Some(event) = self.events_rx.next().await {
 413                this.update(&mut cx, |this, cx| {
 414                    //Process the first event immediately for lowered latency
 415                    this.process_event(&event, cx);
 416                })?;
 417
 418                'outer: loop {
 419                    let mut events = vec![];
 420                    let mut timer = cx
 421                        .background_executor()
 422                        .timer(Duration::from_millis(4))
 423                        .fuse();
 424                    let mut wakeup = false;
 425                    loop {
 426                        futures::select_biased! {
 427                            _ = timer => break,
 428                            event = self.events_rx.next() => {
 429                                if let Some(event) = event {
 430                                    if matches!(event, AlacTermEvent::Wakeup) {
 431                                        wakeup = true;
 432                                    } else {
 433                                        events.push(event);
 434                                    }
 435
 436                                    if events.len() > 100 {
 437                                        break;
 438                                    }
 439                                } else {
 440                                    break;
 441                                }
 442                            },
 443                        }
 444                    }
 445
 446                    if events.is_empty() && wakeup == false {
 447                        smol::future::yield_now().await;
 448                        break 'outer;
 449                    } else {
 450                        this.update(&mut cx, |this, cx| {
 451                            if wakeup {
 452                                this.process_event(&AlacTermEvent::Wakeup, cx);
 453                            }
 454
 455                            for event in events {
 456                                this.process_event(&event, cx);
 457                            }
 458                        })?;
 459                        smol::future::yield_now().await;
 460                    }
 461                }
 462            }
 463
 464            anyhow::Ok(())
 465        })
 466        .detach();
 467
 468        self.terminal
 469    }
 470}
 471
 472#[derive(Debug, Clone, Deserialize, Serialize)]
 473pub struct IndexedCell {
 474    pub point: AlacPoint,
 475    pub cell: Cell,
 476}
 477
 478impl Deref for IndexedCell {
 479    type Target = Cell;
 480
 481    #[inline]
 482    fn deref(&self) -> &Cell {
 483        &self.cell
 484    }
 485}
 486
 487// TODO: Un-pub
 488#[derive(Clone)]
 489pub struct TerminalContent {
 490    pub cells: Vec<IndexedCell>,
 491    pub mode: TermMode,
 492    pub display_offset: usize,
 493    pub selection_text: Option<String>,
 494    pub selection: Option<SelectionRange>,
 495    pub cursor: RenderableCursor,
 496    pub cursor_char: char,
 497    pub size: TerminalSize,
 498    pub last_hovered_word: Option<HoveredWord>,
 499}
 500
 501#[derive(Clone)]
 502pub struct HoveredWord {
 503    pub word: String,
 504    pub word_match: RangeInclusive<AlacPoint>,
 505    pub id: usize,
 506}
 507
 508impl Default for TerminalContent {
 509    fn default() -> Self {
 510        TerminalContent {
 511            cells: Default::default(),
 512            mode: Default::default(),
 513            display_offset: Default::default(),
 514            selection_text: Default::default(),
 515            selection: Default::default(),
 516            cursor: RenderableCursor {
 517                shape: alacritty_terminal::ansi::CursorShape::Block,
 518                point: AlacPoint::new(Line(0), Column(0)),
 519            },
 520            cursor_char: Default::default(),
 521            size: Default::default(),
 522            last_hovered_word: None,
 523        }
 524    }
 525}
 526
 527#[derive(PartialEq, Eq)]
 528pub enum SelectionPhase {
 529    Selecting,
 530    Ended,
 531}
 532
 533pub struct Terminal {
 534    pty_tx: Notifier,
 535    term: Arc<FairMutex<Term<ZedListener>>>,
 536    events: VecDeque<InternalEvent>,
 537    /// This is only used for mouse mode cell change detection
 538    last_mouse: Option<(AlacPoint, AlacDirection)>,
 539    /// This is only used for terminal hovered word checking
 540    last_mouse_position: Option<Point<Pixels>>,
 541    pub matches: Vec<RangeInclusive<AlacPoint>>,
 542    pub last_content: TerminalContent,
 543    pub selection_head: Option<AlacPoint>,
 544    pub breadcrumb_text: String,
 545    shell_pid: u32,
 546    shell_fd: u32,
 547    pub foreground_process_info: Option<LocalProcessInfo>,
 548    scroll_px: Pixels,
 549    next_link_id: usize,
 550    selection_phase: SelectionPhase,
 551    cmd_pressed: bool,
 552    hovered_word: bool,
 553}
 554
 555impl Terminal {
 556    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
 557        match event {
 558            AlacTermEvent::Title(title) => {
 559                self.breadcrumb_text = title.to_string();
 560                cx.emit(Event::BreadcrumbsChanged);
 561            }
 562            AlacTermEvent::ResetTitle => {
 563                self.breadcrumb_text = String::new();
 564                cx.emit(Event::BreadcrumbsChanged);
 565            }
 566            AlacTermEvent::ClipboardStore(_, data) => {
 567                cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
 568            }
 569            AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
 570                &cx.read_from_clipboard()
 571                    .map(|ci| ci.text().to_string())
 572                    .unwrap_or_else(|| "".to_string()),
 573            )),
 574            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 575            AlacTermEvent::TextAreaSizeRequest(format) => {
 576                self.write_to_pty(format(self.last_content.size.into()))
 577            }
 578            AlacTermEvent::CursorBlinkingChange => {
 579                cx.emit(Event::BlinkChanged);
 580            }
 581            AlacTermEvent::Bell => {
 582                cx.emit(Event::Bell);
 583            }
 584            AlacTermEvent::Exit => cx.emit(Event::CloseTerminal),
 585            AlacTermEvent::MouseCursorDirty => {
 586                //NOOP, Handled in render
 587            }
 588            AlacTermEvent::Wakeup => {
 589                cx.emit(Event::Wakeup);
 590
 591                if self.update_process_info() {
 592                    cx.emit(Event::TitleChanged);
 593                }
 594            }
 595            AlacTermEvent::ColorRequest(idx, fun_ptr) => {
 596                self.events
 597                    .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
 598            }
 599        }
 600    }
 601
 602    pub fn selection_started(&self) -> bool {
 603        self.selection_phase == SelectionPhase::Selecting
 604    }
 605
 606    /// Updates the cached process info, returns whether the Zed-relevant info has changed
 607    fn update_process_info(&mut self) -> bool {
 608        let mut pid = unsafe { libc::tcgetpgrp(self.shell_fd as i32) };
 609        if pid < 0 {
 610            pid = self.shell_pid as i32;
 611        }
 612
 613        if let Some(process_info) = LocalProcessInfo::with_root_pid(pid as u32) {
 614            let res = self
 615                .foreground_process_info
 616                .as_ref()
 617                .map(|old_info| {
 618                    process_info.cwd != old_info.cwd || process_info.name != old_info.name
 619                })
 620                .unwrap_or(true);
 621
 622            self.foreground_process_info = Some(process_info.clone());
 623
 624            res
 625        } else {
 626            false
 627        }
 628    }
 629
 630    ///Takes events from Alacritty and translates them to behavior on this view
 631    fn process_terminal_event(
 632        &mut self,
 633        event: &InternalEvent,
 634        term: &mut Term<ZedListener>,
 635        cx: &mut ModelContext<Self>,
 636    ) {
 637        match event {
 638            InternalEvent::ColorRequest(index, format) => {
 639                let color = term.colors()[*index].unwrap_or_else(|| {
 640                    to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
 641                });
 642                self.write_to_pty(format(color))
 643            }
 644            InternalEvent::Resize(mut new_size) => {
 645                new_size.size.height = cmp::max(new_size.line_height, new_size.height());
 646                new_size.size.width = cmp::max(new_size.cell_width, new_size.width());
 647
 648                self.last_content.size = new_size.clone();
 649
 650                self.pty_tx.0.send(Msg::Resize(new_size.into())).ok();
 651
 652                term.resize(new_size);
 653            }
 654            InternalEvent::Clear => {
 655                // Clear back buffer
 656                term.clear_screen(ClearMode::Saved);
 657
 658                let cursor = term.grid().cursor.point;
 659
 660                // Clear the lines above
 661                term.grid_mut().reset_region(..cursor.line);
 662
 663                // Copy the current line up
 664                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 665                    .iter()
 666                    .cloned()
 667                    .enumerate()
 668                    .collect::<Vec<(usize, Cell)>>();
 669
 670                for (i, cell) in line {
 671                    term.grid_mut()[Line(0)][Column(i)] = cell;
 672                }
 673
 674                // Reset the cursor
 675                term.grid_mut().cursor.point =
 676                    AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
 677                let new_cursor = term.grid().cursor.point;
 678
 679                // Clear the lines below the new cursor
 680                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 681                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 682                }
 683
 684                cx.emit(Event::Wakeup);
 685            }
 686            InternalEvent::Scroll(scroll) => {
 687                term.scroll_display(*scroll);
 688                self.refresh_hovered_word();
 689            }
 690            InternalEvent::SetSelection(selection) => {
 691                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 692
 693                if let Some((_, head)) = selection {
 694                    self.selection_head = Some(*head);
 695                }
 696                cx.emit(Event::SelectionsChanged)
 697            }
 698            InternalEvent::UpdateSelection(position) => {
 699                if let Some(mut selection) = term.selection.take() {
 700                    let (point, side) = grid_point_and_side(
 701                        *position,
 702                        self.last_content.size,
 703                        term.grid().display_offset(),
 704                    );
 705
 706                    selection.update(point, side);
 707                    term.selection = Some(selection);
 708
 709                    self.selection_head = Some(point);
 710                    cx.emit(Event::SelectionsChanged)
 711                }
 712            }
 713
 714            InternalEvent::Copy => {
 715                if let Some(txt) = term.selection_to_string() {
 716                    cx.write_to_clipboard(ClipboardItem::new(txt))
 717                }
 718            }
 719            InternalEvent::ScrollToAlacPoint(point) => {
 720                term.scroll_to_point(*point);
 721                self.refresh_hovered_word();
 722            }
 723            InternalEvent::FindHyperlink(position, open) => {
 724                let prev_hovered_word = self.last_content.last_hovered_word.take();
 725
 726                let point = grid_point(
 727                    *position,
 728                    self.last_content.size,
 729                    term.grid().display_offset(),
 730                )
 731                .grid_clamp(term, Boundary::Grid);
 732
 733                let link = term.grid().index(point).hyperlink();
 734                let found_word = if link.is_some() {
 735                    let mut min_index = point;
 736                    loop {
 737                        let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
 738                        if new_min_index == min_index {
 739                            break;
 740                        } else if term.grid().index(new_min_index).hyperlink() != link {
 741                            break;
 742                        } else {
 743                            min_index = new_min_index
 744                        }
 745                    }
 746
 747                    let mut max_index = point;
 748                    loop {
 749                        let new_max_index = max_index.add(term, Boundary::Cursor, 1);
 750                        if new_max_index == max_index {
 751                            break;
 752                        } else if term.grid().index(new_max_index).hyperlink() != link {
 753                            break;
 754                        } else {
 755                            max_index = new_max_index
 756                        }
 757                    }
 758
 759                    let url = link.unwrap().uri().to_owned();
 760                    let url_match = min_index..=max_index;
 761
 762                    Some((url, true, url_match))
 763                } else if let Some(word_match) = regex_match_at(term, point, &WORD_REGEX) {
 764                    let maybe_url_or_path =
 765                        term.bounds_to_string(*word_match.start(), *word_match.end());
 766                    let original_match = word_match.clone();
 767                    let (sanitized_match, sanitized_word) =
 768                        if maybe_url_or_path.starts_with('[') && maybe_url_or_path.ends_with(']') {
 769                            (
 770                                Match::new(
 771                                    word_match.start().add(term, Boundary::Cursor, 1),
 772                                    word_match.end().sub(term, Boundary::Cursor, 1),
 773                                ),
 774                                maybe_url_or_path[1..maybe_url_or_path.len() - 1].to_owned(),
 775                            )
 776                        } else {
 777                            (word_match, maybe_url_or_path)
 778                        };
 779
 780                    let is_url = match regex_match_at(term, point, &URL_REGEX) {
 781                        Some(url_match) => {
 782                            // `]` is a valid symbol in the `file://` URL, so the regex match will include it
 783                            // consider that when ensuring that the URL match is the same as the original word
 784                            if sanitized_match != original_match {
 785                                url_match.start() == sanitized_match.start()
 786                                    && url_match.end() == original_match.end()
 787                            } else {
 788                                url_match == sanitized_match
 789                            }
 790                        }
 791                        None => false,
 792                    };
 793                    Some((sanitized_word, is_url, sanitized_match))
 794                } else {
 795                    None
 796                };
 797
 798                match found_word {
 799                    Some((maybe_url_or_path, is_url, url_match)) => {
 800                        if *open {
 801                            let target = if is_url {
 802                                MaybeNavigationTarget::Url(maybe_url_or_path)
 803                            } else {
 804                                MaybeNavigationTarget::PathLike(maybe_url_or_path)
 805                            };
 806                            cx.emit(Event::Open(target));
 807                        } else {
 808                            self.update_selected_word(
 809                                prev_hovered_word,
 810                                url_match,
 811                                maybe_url_or_path,
 812                                is_url,
 813                                cx,
 814                            );
 815                        }
 816                        self.hovered_word = true;
 817                    }
 818                    None => {
 819                        if self.hovered_word {
 820                            cx.emit(Event::NewNavigationTarget(None));
 821                        }
 822                        self.hovered_word = false;
 823                    }
 824                }
 825            }
 826        }
 827    }
 828
 829    fn update_selected_word(
 830        &mut self,
 831        prev_word: Option<HoveredWord>,
 832        word_match: RangeInclusive<AlacPoint>,
 833        word: String,
 834        is_url: bool,
 835        cx: &mut ModelContext<Self>,
 836    ) {
 837        if let Some(prev_word) = prev_word {
 838            if prev_word.word == word && prev_word.word_match == word_match {
 839                self.last_content.last_hovered_word = Some(HoveredWord {
 840                    word,
 841                    word_match,
 842                    id: prev_word.id,
 843                });
 844                return;
 845            }
 846        }
 847
 848        self.last_content.last_hovered_word = Some(HoveredWord {
 849            word: word.clone(),
 850            word_match,
 851            id: self.next_link_id(),
 852        });
 853        let navigation_target = if is_url {
 854            MaybeNavigationTarget::Url(word)
 855        } else {
 856            MaybeNavigationTarget::PathLike(word)
 857        };
 858        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
 859    }
 860
 861    fn next_link_id(&mut self) -> usize {
 862        let res = self.next_link_id;
 863        self.next_link_id = self.next_link_id.wrapping_add(1);
 864        res
 865    }
 866
 867    pub fn last_content(&self) -> &TerminalContent {
 868        &self.last_content
 869    }
 870
 871    //To test:
 872    //- Activate match on terminal (scrolling and selection)
 873    //- Editor search snapping behavior
 874
 875    pub fn activate_match(&mut self, index: usize) {
 876        if let Some(search_match) = self.matches.get(index).cloned() {
 877            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 878
 879            self.events
 880                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
 881        }
 882    }
 883
 884    pub fn select_matches(&mut self, matches: Vec<RangeInclusive<AlacPoint>>) {
 885        let matches_to_select = self
 886            .matches
 887            .iter()
 888            .filter(|self_match| matches.contains(self_match))
 889            .cloned()
 890            .collect::<Vec<_>>();
 891        for match_to_select in matches_to_select {
 892            self.set_selection(Some((
 893                make_selection(&match_to_select),
 894                *match_to_select.end(),
 895            )));
 896        }
 897    }
 898
 899    pub fn select_all(&mut self) {
 900        let term = self.term.lock();
 901        let start = AlacPoint::new(term.topmost_line(), Column(0));
 902        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
 903        drop(term);
 904        self.set_selection(Some((make_selection(&(start..=end)), end)));
 905    }
 906
 907    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
 908        self.events
 909            .push_back(InternalEvent::SetSelection(selection));
 910    }
 911
 912    pub fn copy(&mut self) {
 913        self.events.push_back(InternalEvent::Copy);
 914    }
 915
 916    pub fn clear(&mut self) {
 917        self.events.push_back(InternalEvent::Clear)
 918    }
 919
 920    ///Resize the terminal and the PTY.
 921    pub fn set_size(&mut self, new_size: TerminalSize) {
 922        self.events.push_back(InternalEvent::Resize(new_size))
 923    }
 924
 925    ///Write the Input payload to the tty.
 926    fn write_to_pty(&self, input: String) {
 927        self.pty_tx.notify(input.into_bytes());
 928    }
 929
 930    fn write_bytes_to_pty(&self, input: Vec<u8>) {
 931        self.pty_tx.notify(input);
 932    }
 933
 934    pub fn input(&mut self, input: String) {
 935        self.events
 936            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
 937        self.events.push_back(InternalEvent::SetSelection(None));
 938
 939        self.write_to_pty(input);
 940    }
 941
 942    pub fn input_bytes(&mut self, input: Vec<u8>) {
 943        self.events
 944            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
 945        self.events.push_back(InternalEvent::SetSelection(None));
 946
 947        self.write_bytes_to_pty(input);
 948    }
 949
 950    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
 951        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
 952        if let Some(esc) = esc {
 953            self.input(esc);
 954            true
 955        } else {
 956            false
 957        }
 958    }
 959
 960    pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
 961        let changed = self.cmd_pressed != modifiers.command;
 962        if !self.cmd_pressed && modifiers.command {
 963            self.refresh_hovered_word();
 964        }
 965        self.cmd_pressed = modifiers.command;
 966        changed
 967    }
 968
 969    ///Paste text into the terminal
 970    pub fn paste(&mut self, text: &str) {
 971        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
 972            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
 973        } else {
 974            text.replace("\r\n", "\r").replace('\n', "\r")
 975        };
 976
 977        self.input(paste_text);
 978    }
 979
 980    pub fn sync(&mut self, cx: &mut ModelContext<Self>) {
 981        let term = self.term.clone();
 982        let mut terminal = term.lock_unfair();
 983        //Note that the ordering of events matters for event processing
 984        while let Some(e) = self.events.pop_front() {
 985            self.process_terminal_event(&e, &mut terminal, cx)
 986        }
 987
 988        self.last_content = Self::make_content(&terminal, &self.last_content);
 989    }
 990
 991    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
 992        let content = term.renderable_content();
 993        TerminalContent {
 994            cells: content
 995                .display_iter
 996                //TODO: Add this once there's a way to retain empty lines
 997                // .filter(|ic| {
 998                //     !ic.flags.contains(Flags::HIDDEN)
 999                //         && !(ic.bg == Named(NamedColor::Background)
1000                //             && ic.c == ' '
1001                //             && !ic.flags.contains(Flags::INVERSE))
1002                // })
1003                .map(|ic| IndexedCell {
1004                    point: ic.point,
1005                    cell: ic.cell.clone(),
1006                })
1007                .collect::<Vec<IndexedCell>>(),
1008            mode: content.mode,
1009            display_offset: content.display_offset,
1010            selection_text: term.selection_to_string(),
1011            selection: content.selection,
1012            cursor: content.cursor,
1013            cursor_char: term.grid()[content.cursor.point].c,
1014            size: last_content.size,
1015            last_hovered_word: last_content.last_hovered_word.clone(),
1016        }
1017    }
1018
1019    pub fn focus_in(&self) {
1020        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1021            self.write_to_pty("\x1b[I".to_string());
1022        }
1023    }
1024
1025    pub fn focus_out(&mut self) {
1026        self.last_mouse_position = None;
1027        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1028            self.write_to_pty("\x1b[O".to_string());
1029        }
1030    }
1031
1032    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1033        match self.last_mouse {
1034            Some((old_point, old_side)) => {
1035                if old_point == point && old_side == side {
1036                    false
1037                } else {
1038                    self.last_mouse = Some((point, side));
1039                    true
1040                }
1041            }
1042            None => {
1043                self.last_mouse = Some((point, side));
1044                true
1045            }
1046        }
1047    }
1048
1049    pub fn mouse_mode(&self, shift: bool) -> bool {
1050        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1051    }
1052
1053    pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1054        let position = e.position - origin;
1055        self.last_mouse_position = Some(position);
1056        if self.mouse_mode(e.modifiers.shift) {
1057            let (point, side) = grid_point_and_side(
1058                position,
1059                self.last_content.size,
1060                self.last_content.display_offset,
1061            );
1062
1063            if self.mouse_changed(point, side) {
1064                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1065                    self.pty_tx.notify(bytes);
1066                }
1067            }
1068        } else if self.cmd_pressed {
1069            self.word_from_position(Some(position));
1070        }
1071    }
1072
1073    fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1074        if self.selection_phase == SelectionPhase::Selecting {
1075            self.last_content.last_hovered_word = None;
1076        } else if let Some(position) = position {
1077            self.events
1078                .push_back(InternalEvent::FindHyperlink(position, false));
1079        }
1080    }
1081
1082    pub fn mouse_drag(
1083        &mut self,
1084        e: &MouseMoveEvent,
1085        origin: Point<Pixels>,
1086        region: Bounds<Pixels>,
1087    ) {
1088        let position = e.position - origin;
1089        self.last_mouse_position = Some(position);
1090
1091        if !self.mouse_mode(e.modifiers.shift) {
1092            self.selection_phase = SelectionPhase::Selecting;
1093            // Alacritty has the same ordering, of first updating the selection
1094            // then scrolling 15ms later
1095            self.events
1096                .push_back(InternalEvent::UpdateSelection(position));
1097
1098            // Doesn't make sense to scroll the alt screen
1099            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1100                let scroll_delta = match self.drag_line_delta(e, region) {
1101                    Some(value) => value,
1102                    None => return,
1103                };
1104
1105                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1106
1107                self.events
1108                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1109            }
1110        }
1111    }
1112
1113    fn drag_line_delta(&mut self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1114        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1115        let top = region.origin.y + (self.last_content.size.line_height * 2.);
1116        let bottom = region.lower_left().y - (self.last_content.size.line_height * 2.);
1117        let scroll_delta = if e.position.y < top {
1118            (top - e.position.y).pow(1.1)
1119        } else if e.position.y > bottom {
1120            -((e.position.y - bottom).pow(1.1))
1121        } else {
1122            return None; //Nothing to do
1123        };
1124        Some(scroll_delta)
1125    }
1126
1127    pub fn mouse_down(&mut self, e: &MouseDownEvent, origin: Point<Pixels>) {
1128        let position = e.position - origin;
1129        let point = grid_point(
1130            position,
1131            self.last_content.size,
1132            self.last_content.display_offset,
1133        );
1134
1135        if self.mouse_mode(e.modifiers.shift) {
1136            if let Some(bytes) =
1137                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1138            {
1139                self.pty_tx.notify(bytes);
1140            }
1141        } else if e.button == MouseButton::Left {
1142            let position = e.position - origin;
1143            let (point, side) = grid_point_and_side(
1144                position,
1145                self.last_content.size,
1146                self.last_content.display_offset,
1147            );
1148
1149            let selection_type = match e.click_count {
1150                0 => return, //This is a release
1151                1 => Some(SelectionType::Simple),
1152                2 => Some(SelectionType::Semantic),
1153                3 => Some(SelectionType::Lines),
1154                _ => None,
1155            };
1156
1157            let selection =
1158                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1159
1160            if let Some(sel) = selection {
1161                self.events
1162                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
1163            }
1164        }
1165    }
1166
1167    pub fn mouse_up(
1168        &mut self,
1169        e: &MouseUpEvent,
1170        origin: Point<Pixels>,
1171        cx: &mut ModelContext<Self>,
1172    ) {
1173        let setting = TerminalSettings::get_global(cx);
1174
1175        let position = e.position - origin;
1176        if self.mouse_mode(e.modifiers.shift) {
1177            let point = grid_point(
1178                position,
1179                self.last_content.size,
1180                self.last_content.display_offset,
1181            );
1182
1183            if let Some(bytes) =
1184                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1185            {
1186                self.pty_tx.notify(bytes);
1187            }
1188        } else {
1189            if e.button == MouseButton::Left && setting.copy_on_select {
1190                self.copy();
1191            }
1192
1193            //Hyperlinks
1194            if self.selection_phase == SelectionPhase::Ended {
1195                let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1196                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1197                    cx.open_url(link.uri());
1198                } else if self.cmd_pressed {
1199                    self.events
1200                        .push_back(InternalEvent::FindHyperlink(position, true));
1201                }
1202            }
1203        }
1204
1205        self.selection_phase = SelectionPhase::Ended;
1206        self.last_mouse = None;
1207    }
1208
1209    ///Scroll the terminal
1210    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Point<Pixels>) {
1211        let mouse_mode = self.mouse_mode(e.shift);
1212
1213        if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1214            if mouse_mode {
1215                let point = grid_point(
1216                    e.position - origin,
1217                    self.last_content.size,
1218                    self.last_content.display_offset,
1219                );
1220
1221                if let Some(scrolls) =
1222                    scroll_report(point, scroll_lines as i32, e, self.last_content.mode)
1223                {
1224                    for scroll in scrolls {
1225                        self.pty_tx.notify(scroll);
1226                    }
1227                };
1228            } else if self
1229                .last_content
1230                .mode
1231                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1232                && !e.shift
1233            {
1234                self.pty_tx.notify(alt_scroll(scroll_lines))
1235            } else {
1236                if scroll_lines != 0 {
1237                    let scroll = AlacScroll::Delta(scroll_lines);
1238
1239                    self.events.push_back(InternalEvent::Scroll(scroll));
1240                }
1241            }
1242        }
1243    }
1244
1245    fn refresh_hovered_word(&mut self) {
1246        self.word_from_position(self.last_mouse_position);
1247    }
1248
1249    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1250        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1251        let line_height = self.last_content.size.line_height;
1252        match e.touch_phase {
1253            /* Reset scroll state on started */
1254            TouchPhase::Started => {
1255                self.scroll_px = px(0.);
1256                None
1257            }
1258            /* Calculate the appropriate scroll lines */
1259            TouchPhase::Moved => {
1260                let old_offset = (self.scroll_px / line_height) as i32;
1261
1262                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1263
1264                let new_offset = (self.scroll_px / line_height) as i32;
1265
1266                // Whenever we hit the edges, reset our stored scroll to 0
1267                // so we can respond to changes in direction quickly
1268                self.scroll_px %= self.last_content.size.height();
1269
1270                Some(new_offset - old_offset)
1271            }
1272            TouchPhase::Ended => None,
1273        }
1274    }
1275
1276    pub fn find_matches(
1277        &mut self,
1278        searcher: RegexSearch,
1279        cx: &mut ModelContext<Self>,
1280    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1281        let term = self.term.clone();
1282        cx.background_executor().spawn(async move {
1283            let term = term.lock();
1284
1285            all_search_matches(&term, &searcher).collect()
1286        })
1287    }
1288
1289    pub fn title(&self, truncate: bool) -> String {
1290        self.foreground_process_info
1291            .as_ref()
1292            .map(|fpi| {
1293                let process_file = fpi
1294                    .cwd
1295                    .file_name()
1296                    .map(|name| name.to_string_lossy().to_string())
1297                    .unwrap_or_default();
1298                let process_name = format!(
1299                    "{}{}",
1300                    fpi.name,
1301                    if fpi.argv.len() >= 1 {
1302                        format!(" {}", (fpi.argv[1..]).join(" "))
1303                    } else {
1304                        "".to_string()
1305                    }
1306                );
1307                let (process_file, process_name) = if truncate {
1308                    (
1309                        truncate_and_trailoff(&process_file, 25),
1310                        truncate_and_trailoff(&process_name, 25),
1311                    )
1312                } else {
1313                    (process_file, process_name)
1314                };
1315                format!("{process_file}{process_name}")
1316            })
1317            .unwrap_or_else(|| "Terminal".to_string())
1318    }
1319
1320    pub fn can_navigate_to_selected_word(&self) -> bool {
1321        self.cmd_pressed && self.hovered_word
1322    }
1323}
1324
1325impl Drop for Terminal {
1326    fn drop(&mut self) {
1327        self.pty_tx.0.send(Msg::Shutdown).ok();
1328    }
1329}
1330
1331impl EventEmitter<Event> for Terminal {}
1332
1333/// Based on alacritty/src/display/hint.rs > regex_match_at
1334/// Retrieve the match, if the specified point is inside the content matching the regex.
1335fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &RegexSearch) -> Option<Match> {
1336    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1337}
1338
1339/// Copied from alacritty/src/display/hint.rs:
1340/// Iterate over all visible regex matches.
1341pub fn visible_regex_match_iter<'a, T>(
1342    term: &'a Term<T>,
1343    regex: &'a RegexSearch,
1344) -> impl Iterator<Item = Match> + 'a {
1345    let viewport_start = Line(-(term.grid().display_offset() as i32));
1346    let viewport_end = viewport_start + term.bottommost_line();
1347    let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1348    let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1349    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1350    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1351
1352    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1353        .skip_while(move |rm| rm.end().line < viewport_start)
1354        .take_while(move |rm| rm.start().line <= viewport_end)
1355}
1356
1357fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1358    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1359    selection.update(*range.end(), AlacDirection::Right);
1360    selection
1361}
1362
1363fn all_search_matches<'a, T>(
1364    term: &'a Term<T>,
1365    regex: &'a RegexSearch,
1366) -> impl Iterator<Item = Match> + 'a {
1367    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1368    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1369    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1370}
1371
1372fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1373    let col = (pos.x / size.cell_width()).round() as usize;
1374    let clamped_col = min(col, size.columns() - 1);
1375    let row = (pos.y / size.line_height()).round() as usize;
1376    let clamped_row = min(row, size.screen_lines() - 1);
1377    clamped_row * size.columns() + clamped_col
1378}
1379
1380/// Converts an 8 bit ANSI color to it's GPUI equivalent.
1381/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1382/// Other than that use case, should only be called with values in the [0,255] range
1383pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1384    let colors = theme.colors();
1385
1386    match index {
1387        // 0-15 are the same as the named colors above
1388        0 => colors.terminal_ansi_black,
1389        1 => colors.terminal_ansi_red,
1390        2 => colors.terminal_ansi_green,
1391        3 => colors.terminal_ansi_yellow,
1392        4 => colors.terminal_ansi_blue,
1393        5 => colors.terminal_ansi_magenta,
1394        6 => colors.terminal_ansi_cyan,
1395        7 => colors.terminal_ansi_white,
1396        8 => colors.terminal_ansi_bright_black,
1397        9 => colors.terminal_ansi_bright_red,
1398        10 => colors.terminal_ansi_bright_green,
1399        11 => colors.terminal_ansi_bright_yellow,
1400        12 => colors.terminal_ansi_bright_blue,
1401        13 => colors.terminal_ansi_bright_magenta,
1402        14 => colors.terminal_ansi_bright_cyan,
1403        15 => colors.terminal_ansi_bright_white,
1404        // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1405        16..=231 => {
1406            let (r, g, b) = rgb_for_index(&(index as u8)); // Split the index into it's ANSI-RGB components
1407            let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1408            rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1409        }
1410        // 232-255 are a 24 step grayscale from black to white
1411        232..=255 => {
1412            let i = index as u8 - 232; // Align index to 0..24
1413            let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1414            rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1415        }
1416        // For compatibility with the alacritty::Colors interface
1417        256 => colors.text,
1418        257 => colors.background,
1419        258 => theme.players().local().cursor,
1420        259 => colors.terminal_ansi_dim_black,
1421        260 => colors.terminal_ansi_dim_red,
1422        261 => colors.terminal_ansi_dim_green,
1423        262 => colors.terminal_ansi_dim_yellow,
1424        263 => colors.terminal_ansi_dim_blue,
1425        264 => colors.terminal_ansi_dim_magenta,
1426        265 => colors.terminal_ansi_dim_cyan,
1427        266 => colors.terminal_ansi_dim_white,
1428        267 => colors.terminal_bright_foreground,
1429        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1430
1431        _ => black(),
1432    }
1433}
1434
1435/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1436/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1437///
1438/// Wikipedia gives a formula for calculating the index for a given color:
1439///
1440/// ```
1441/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1442/// ```
1443///
1444/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1445fn rgb_for_index(i: &u8) -> (u8, u8, u8) {
1446    debug_assert!((&16..=&231).contains(&i));
1447    let i = i - 16;
1448    let r = (i - (i % 36)) / 36;
1449    let g = ((i % 36) - (i % 6)) / 6;
1450    let b = (i % 36) % 6;
1451    (r, g, b)
1452}
1453
1454pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1455    Rgba {
1456        r: (r as f32 / 255.) as f32,
1457        g: (g as f32 / 255.) as f32,
1458        b: (b as f32 / 255.) as f32,
1459        a: 1.,
1460    }
1461    .into()
1462}
1463
1464#[cfg(test)]
1465mod tests {
1466    use alacritty_terminal::{
1467        index::{Column, Line, Point as AlacPoint},
1468        term::cell::Cell,
1469    };
1470    use gpui::{point, size, Pixels};
1471    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1472
1473    use crate::{
1474        content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
1475    };
1476
1477    #[test]
1478    fn test_rgb_for_index() {
1479        //Test every possible value in the color cube
1480        for i in 16..=231 {
1481            let (r, g, b) = rgb_for_index(&(i as u8));
1482            assert_eq!(i, 16 + 36 * r + 6 * g + b);
1483        }
1484    }
1485
1486    #[test]
1487    fn test_mouse_to_cell_test() {
1488        let mut rng = thread_rng();
1489        const ITERATIONS: usize = 10;
1490        const PRECISION: usize = 1000;
1491
1492        for _ in 0..ITERATIONS {
1493            let viewport_cells = rng.gen_range(15..20);
1494            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1495
1496            let size = crate::TerminalSize {
1497                cell_width: Pixels::from(cell_size),
1498                line_height: Pixels::from(cell_size),
1499                size: size(
1500                    Pixels::from(cell_size * (viewport_cells as f32)),
1501                    Pixels::from(cell_size * (viewport_cells as f32)),
1502                ),
1503            };
1504
1505            let cells = get_cells(size, &mut rng);
1506            let content = convert_cells_to_content(size, &cells);
1507
1508            for row in 0..(viewport_cells - 1) {
1509                let row = row as usize;
1510                for col in 0..(viewport_cells - 1) {
1511                    let col = col as usize;
1512
1513                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1514                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1515
1516                    let mouse_pos = point(
1517                        Pixels::from(col as f32 * cell_size + col_offset),
1518                        Pixels::from(row as f32 * cell_size + row_offset),
1519                    );
1520
1521                    let content_index = content_index_for_mouse(mouse_pos, &content.size);
1522                    let mouse_cell = content.cells[content_index].c;
1523                    let real_cell = cells[row][col];
1524
1525                    assert_eq!(mouse_cell, real_cell);
1526                }
1527            }
1528        }
1529    }
1530
1531    #[test]
1532    fn test_mouse_to_cell_clamp() {
1533        let mut rng = thread_rng();
1534
1535        let size = crate::TerminalSize {
1536            cell_width: Pixels::from(10.),
1537            line_height: Pixels::from(10.),
1538            size: size(Pixels::from(100.), Pixels::from(100.)),
1539        };
1540
1541        let cells = get_cells(size, &mut rng);
1542        let content = convert_cells_to_content(size, &cells);
1543
1544        assert_eq!(
1545            content.cells[content_index_for_mouse(
1546                point(Pixels::from(-10.), Pixels::from(-10.)),
1547                &content.size
1548            )]
1549            .c,
1550            cells[0][0]
1551        );
1552        assert_eq!(
1553            content.cells[content_index_for_mouse(
1554                point(Pixels::from(1000.), Pixels::from(1000.)),
1555                &content.size
1556            )]
1557            .c,
1558            cells[9][9]
1559        );
1560    }
1561
1562    fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1563        let mut cells = Vec::new();
1564
1565        for _ in 0..(f32::from(size.height() / size.line_height()) as usize) {
1566            let mut row_vec = Vec::new();
1567            for _ in 0..(f32::from(size.width() / size.cell_width()) as usize) {
1568                let cell_char = rng.sample(Alphanumeric) as char;
1569                row_vec.push(cell_char)
1570            }
1571            cells.push(row_vec)
1572        }
1573
1574        cells
1575    }
1576
1577    fn convert_cells_to_content(size: TerminalSize, cells: &Vec<Vec<char>>) -> TerminalContent {
1578        let mut ic = Vec::new();
1579
1580        for row in 0..cells.len() {
1581            for col in 0..cells[row].len() {
1582                let cell_char = cells[row][col];
1583                ic.push(IndexedCell {
1584                    point: AlacPoint::new(Line(row as i32), Column(col)),
1585                    cell: Cell {
1586                        c: cell_char,
1587                        ..Default::default()
1588                    },
1589                });
1590            }
1591        }
1592
1593        TerminalContent {
1594            cells: ic,
1595            size,
1596            ..Default::default()
1597        }
1598    }
1599}