terminal.rs

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