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("(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(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            found_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    found_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::Cursor);
 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 = regex_match_at(term, point, &URL_REGEX).is_some();
 879
 880                    Some((maybe_url_or_path, is_url, word_match))
 881                } else {
 882                    None
 883                };
 884
 885                self.found_word = found_word.is_some();
 886                if let Some((maybe_url_or_path, is_url, url_match)) = found_word {
 887                    if *open {
 888                        let target = if is_url {
 889                            MaybeNavigationTarget::Url(maybe_url_or_path)
 890                        } else {
 891                            MaybeNavigationTarget::PathLike(maybe_url_or_path)
 892                        };
 893                        cx.emit(Event::Open(target));
 894                    } else {
 895                        self.update_selected_word(
 896                            prev_hovered_word,
 897                            url_match,
 898                            maybe_url_or_path,
 899                            is_url,
 900                            cx,
 901                        );
 902                    }
 903                }
 904            }
 905        }
 906    }
 907
 908    fn update_selected_word(
 909        &mut self,
 910        prev_word: Option<HoveredWord>,
 911        word_match: RangeInclusive<Point>,
 912        word: String,
 913        is_url: bool,
 914        cx: &mut ModelContext<Self>,
 915    ) {
 916        if let Some(prev_word) = prev_word {
 917            if prev_word.word == word && prev_word.word_match == word_match {
 918                self.last_content.last_hovered_word = Some(HoveredWord {
 919                    word,
 920                    word_match,
 921                    id: prev_word.id,
 922                });
 923                return;
 924            }
 925        }
 926
 927        self.last_content.last_hovered_word = Some(HoveredWord {
 928            word: word.clone(),
 929            word_match,
 930            id: self.next_link_id(),
 931        });
 932        let navigation_target = if is_url {
 933            MaybeNavigationTarget::Url(word)
 934        } else {
 935            MaybeNavigationTarget::PathLike(word)
 936        };
 937        cx.emit(Event::NewNavigationTarget(navigation_target));
 938    }
 939
 940    fn next_link_id(&mut self) -> usize {
 941        let res = self.next_link_id;
 942        self.next_link_id = self.next_link_id.wrapping_add(1);
 943        res
 944    }
 945
 946    pub fn last_content(&self) -> &TerminalContent {
 947        &self.last_content
 948    }
 949
 950    //To test:
 951    //- Activate match on terminal (scrolling and selection)
 952    //- Editor search snapping behavior
 953
 954    pub fn activate_match(&mut self, index: usize) {
 955        if let Some(search_match) = self.matches.get(index).cloned() {
 956            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 957
 958            self.events
 959                .push_back(InternalEvent::ScrollToPoint(*search_match.start()));
 960        }
 961    }
 962
 963    pub fn select_matches(&mut self, matches: Vec<RangeInclusive<Point>>) {
 964        let matches_to_select = self
 965            .matches
 966            .iter()
 967            .filter(|self_match| matches.contains(self_match))
 968            .cloned()
 969            .collect::<Vec<_>>();
 970        for match_to_select in matches_to_select {
 971            self.set_selection(Some((
 972                make_selection(&match_to_select),
 973                *match_to_select.end(),
 974            )));
 975        }
 976    }
 977
 978    fn set_selection(&mut self, selection: Option<(Selection, Point)>) {
 979        self.events
 980            .push_back(InternalEvent::SetSelection(selection));
 981    }
 982
 983    pub fn copy(&mut self) {
 984        self.events.push_back(InternalEvent::Copy);
 985    }
 986
 987    pub fn clear(&mut self) {
 988        self.events.push_back(InternalEvent::Clear)
 989    }
 990
 991    ///Resize the terminal and the PTY.
 992    pub fn set_size(&mut self, new_size: TerminalSize) {
 993        self.events.push_back(InternalEvent::Resize(new_size))
 994    }
 995
 996    ///Write the Input payload to the tty.
 997    fn write_to_pty(&self, input: String) {
 998        self.pty_tx.notify(input.into_bytes());
 999    }
1000
1001    pub fn input(&mut self, input: String) {
1002        self.events
1003            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1004        self.events.push_back(InternalEvent::SetSelection(None));
1005
1006        self.write_to_pty(input);
1007    }
1008
1009    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1010        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1011        if let Some(esc) = esc {
1012            self.input(esc);
1013            true
1014        } else {
1015            false
1016        }
1017    }
1018
1019    pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
1020        let changed = self.cmd_pressed != modifiers.cmd;
1021        self.cmd_pressed = modifiers.cmd;
1022        changed
1023    }
1024
1025    ///Paste text into the terminal
1026    pub fn paste(&mut self, text: &str) {
1027        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1028            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1029        } else {
1030            text.replace("\r\n", "\r").replace('\n', "\r")
1031        };
1032
1033        self.input(paste_text);
1034    }
1035
1036    pub fn try_sync(&mut self, cx: &mut ModelContext<Self>) {
1037        let term = self.term.clone();
1038
1039        let mut terminal = if let Some(term) = term.try_lock_unfair() {
1040            term
1041        } else if self.last_synced.elapsed().as_secs_f32() > 0.25 {
1042            term.lock_unfair() //It's been too long, force block
1043        } else if let None = self.sync_task {
1044            //Skip this frame
1045            let delay = cx.background().timer(Duration::from_millis(16));
1046            self.sync_task = Some(cx.spawn_weak(|weak_handle, mut cx| async move {
1047                delay.await;
1048                cx.update(|cx| {
1049                    if let Some(handle) = weak_handle.upgrade(cx) {
1050                        handle.update(cx, |terminal, cx| {
1051                            terminal.sync_task.take();
1052                            cx.notify();
1053                        });
1054                    }
1055                });
1056            }));
1057            return;
1058        } else {
1059            //No lock and delayed rendering already scheduled, nothing to do
1060            return;
1061        };
1062
1063        //Note that the ordering of events matters for event processing
1064        while let Some(e) = self.events.pop_front() {
1065            self.process_terminal_event(&e, &mut terminal, cx)
1066        }
1067
1068        self.last_content = Self::make_content(&terminal, &self.last_content);
1069        self.last_synced = Instant::now();
1070    }
1071
1072    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1073        let content = term.renderable_content();
1074        TerminalContent {
1075            cells: content
1076                .display_iter
1077                //TODO: Add this once there's a way to retain empty lines
1078                // .filter(|ic| {
1079                //     !ic.flags.contains(Flags::HIDDEN)
1080                //         && !(ic.bg == Named(NamedColor::Background)
1081                //             && ic.c == ' '
1082                //             && !ic.flags.contains(Flags::INVERSE))
1083                // })
1084                .map(|ic| IndexedCell {
1085                    point: ic.point,
1086                    cell: ic.cell.clone(),
1087                })
1088                .collect::<Vec<IndexedCell>>(),
1089            mode: content.mode,
1090            display_offset: content.display_offset,
1091            selection_text: term.selection_to_string(),
1092            selection: content.selection,
1093            cursor: content.cursor,
1094            cursor_char: term.grid()[content.cursor.point].c,
1095            size: last_content.size,
1096            last_hovered_word: last_content.last_hovered_word.clone(),
1097        }
1098    }
1099
1100    pub fn focus_in(&self) {
1101        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1102            self.write_to_pty("\x1b[I".to_string());
1103        }
1104    }
1105
1106    pub fn focus_out(&mut self) {
1107        self.last_mouse_position = None;
1108        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1109            self.write_to_pty("\x1b[O".to_string());
1110        }
1111    }
1112
1113    pub fn mouse_changed(&mut self, point: Point, side: AlacDirection) -> bool {
1114        match self.last_mouse {
1115            Some((old_point, old_side)) => {
1116                if old_point == point && old_side == side {
1117                    false
1118                } else {
1119                    self.last_mouse = Some((point, side));
1120                    true
1121                }
1122            }
1123            None => {
1124                self.last_mouse = Some((point, side));
1125                true
1126            }
1127        }
1128    }
1129
1130    pub fn mouse_mode(&self, shift: bool) -> bool {
1131        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1132    }
1133
1134    pub fn mouse_move(&mut self, e: &MouseMovedEvent, origin: Vector2F) {
1135        let position = e.position.sub(origin);
1136        self.last_mouse_position = Some(position);
1137        if self.mouse_mode(e.shift) {
1138            let point = grid_point(
1139                position,
1140                self.last_content.size,
1141                self.last_content.display_offset,
1142            );
1143            let side = mouse_side(position, self.last_content.size);
1144
1145            if self.mouse_changed(point, side) {
1146                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1147                    self.pty_tx.notify(bytes);
1148                }
1149            }
1150        } else if self.cmd_pressed {
1151            self.word_from_position(Some(position));
1152        }
1153    }
1154
1155    fn word_from_position(&mut self, position: Option<Vector2F>) {
1156        if self.selection_phase == SelectionPhase::Selecting {
1157            self.last_content.last_hovered_word = None;
1158        } else if let Some(position) = position {
1159            self.events
1160                .push_back(InternalEvent::FindHyperlink(position, false));
1161        }
1162    }
1163
1164    pub fn mouse_drag(&mut self, e: MouseDrag, origin: Vector2F) {
1165        let position = e.position.sub(origin);
1166        self.last_mouse_position = Some(position);
1167
1168        if !self.mouse_mode(e.shift) {
1169            self.selection_phase = SelectionPhase::Selecting;
1170            // Alacritty has the same ordering, of first updating the selection
1171            // then scrolling 15ms later
1172            self.events
1173                .push_back(InternalEvent::UpdateSelection(position));
1174
1175            // Doesn't make sense to scroll the alt screen
1176            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1177                let scroll_delta = match self.drag_line_delta(e) {
1178                    Some(value) => value,
1179                    None => return,
1180                };
1181
1182                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1183
1184                self.events
1185                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1186            }
1187        }
1188    }
1189
1190    fn drag_line_delta(&mut self, e: MouseDrag) -> Option<f32> {
1191        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1192        let top = e.region.origin_y() + (self.last_content.size.line_height * 2.);
1193        let bottom = e.region.lower_left().y() - (self.last_content.size.line_height * 2.);
1194        let scroll_delta = if e.position.y() < top {
1195            (top - e.position.y()).powf(1.1)
1196        } else if e.position.y() > bottom {
1197            -((e.position.y() - bottom).powf(1.1))
1198        } else {
1199            return None; //Nothing to do
1200        };
1201        Some(scroll_delta)
1202    }
1203
1204    pub fn mouse_down(&mut self, e: &MouseDown, origin: Vector2F) {
1205        let position = e.position.sub(origin);
1206        let point = grid_point(
1207            position,
1208            self.last_content.size,
1209            self.last_content.display_offset,
1210        );
1211
1212        if self.mouse_mode(e.shift) {
1213            if let Some(bytes) = mouse_button_report(point, e, true, self.last_content.mode) {
1214                self.pty_tx.notify(bytes);
1215            }
1216        } else if e.button == MouseButton::Left {
1217            let position = e.position.sub(origin);
1218            let point = grid_point(
1219                position,
1220                self.last_content.size,
1221                self.last_content.display_offset,
1222            );
1223
1224            // Use .opposite so that selection is inclusive of the cell clicked.
1225            let side = mouse_side(position, self.last_content.size);
1226
1227            let selection_type = match e.click_count {
1228                0 => return, //This is a release
1229                1 => Some(SelectionType::Simple),
1230                2 => Some(SelectionType::Semantic),
1231                3 => Some(SelectionType::Lines),
1232                _ => None,
1233            };
1234
1235            let selection =
1236                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1237
1238            if let Some(sel) = selection {
1239                self.events
1240                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
1241            }
1242        }
1243    }
1244
1245    pub fn mouse_up(&mut self, e: &MouseUp, origin: Vector2F, cx: &mut ModelContext<Self>) {
1246        let setting = settings::get::<TerminalSettings>(cx);
1247
1248        let position = e.position.sub(origin);
1249        if self.mouse_mode(e.shift) {
1250            let point = grid_point(
1251                position,
1252                self.last_content.size,
1253                self.last_content.display_offset,
1254            );
1255
1256            if let Some(bytes) = mouse_button_report(point, e, false, self.last_content.mode) {
1257                self.pty_tx.notify(bytes);
1258            }
1259        } else {
1260            if e.button == MouseButton::Left && setting.copy_on_select {
1261                self.copy();
1262            }
1263
1264            //Hyperlinks
1265            if self.selection_phase == SelectionPhase::Ended {
1266                let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1267                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1268                    cx.platform().open_url(link.uri());
1269                } else if self.cmd_pressed {
1270                    self.events
1271                        .push_back(InternalEvent::FindHyperlink(position, true));
1272                }
1273            }
1274        }
1275
1276        self.selection_phase = SelectionPhase::Ended;
1277        self.last_mouse = None;
1278    }
1279
1280    ///Scroll the terminal
1281    pub fn scroll_wheel(&mut self, e: MouseScrollWheel, origin: Vector2F) {
1282        let mouse_mode = self.mouse_mode(e.shift);
1283
1284        if let Some(scroll_lines) = self.determine_scroll_lines(&e, mouse_mode) {
1285            if mouse_mode {
1286                let point = grid_point(
1287                    e.position.sub(origin),
1288                    self.last_content.size,
1289                    self.last_content.display_offset,
1290                );
1291
1292                if let Some(scrolls) =
1293                    scroll_report(point, scroll_lines as i32, &e, self.last_content.mode)
1294                {
1295                    for scroll in scrolls {
1296                        self.pty_tx.notify(scroll);
1297                    }
1298                };
1299            } else if self
1300                .last_content
1301                .mode
1302                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1303                && !e.shift
1304            {
1305                self.pty_tx.notify(alt_scroll(scroll_lines))
1306            } else {
1307                if scroll_lines != 0 {
1308                    let scroll = AlacScroll::Delta(scroll_lines);
1309
1310                    self.events.push_back(InternalEvent::Scroll(scroll));
1311                }
1312            }
1313        }
1314    }
1315
1316    fn refresh_hovered_word(&mut self) {
1317        self.word_from_position(self.last_mouse_position);
1318    }
1319
1320    fn determine_scroll_lines(&mut self, e: &MouseScrollWheel, mouse_mode: bool) -> Option<i32> {
1321        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1322        let line_height = self.last_content.size.line_height;
1323        match e.phase {
1324            /* Reset scroll state on started */
1325            Some(TouchPhase::Started) => {
1326                self.scroll_px = 0.;
1327                None
1328            }
1329            /* Calculate the appropriate scroll lines */
1330            Some(gpui::platform::TouchPhase::Moved) => {
1331                let old_offset = (self.scroll_px / line_height) as i32;
1332
1333                self.scroll_px += e.delta.pixel_delta(line_height).y() * scroll_multiplier;
1334
1335                let new_offset = (self.scroll_px / line_height) as i32;
1336
1337                // Whenever we hit the edges, reset our stored scroll to 0
1338                // so we can respond to changes in direction quickly
1339                self.scroll_px %= self.last_content.size.height;
1340
1341                Some(new_offset - old_offset)
1342            }
1343            /* Fall back to delta / line_height */
1344            None => Some(
1345                ((e.delta.pixel_delta(line_height).y() * scroll_multiplier) / line_height) as i32,
1346            ),
1347            _ => None,
1348        }
1349    }
1350
1351    pub fn find_matches(
1352        &mut self,
1353        searcher: RegexSearch,
1354        cx: &mut ModelContext<Self>,
1355    ) -> Task<Vec<RangeInclusive<Point>>> {
1356        let term = self.term.clone();
1357        cx.background().spawn(async move {
1358            let term = term.lock();
1359
1360            all_search_matches(&term, &searcher).collect()
1361        })
1362    }
1363
1364    pub fn title(&self) -> String {
1365        self.foreground_process_info
1366            .as_ref()
1367            .map(|fpi| {
1368                format!(
1369                    "{}{}",
1370                    truncate_and_trailoff(
1371                        &fpi.cwd
1372                            .file_name()
1373                            .map(|name| name.to_string_lossy().to_string())
1374                            .unwrap_or_default(),
1375                        25
1376                    ),
1377                    truncate_and_trailoff(
1378                        &{
1379                            format!(
1380                                "{}{}",
1381                                fpi.name,
1382                                if fpi.argv.len() >= 1 {
1383                                    format!(" {}", (&fpi.argv[1..]).join(" "))
1384                                } else {
1385                                    "".to_string()
1386                                }
1387                            )
1388                        },
1389                        25
1390                    )
1391                )
1392            })
1393            .unwrap_or_else(|| "Terminal".to_string())
1394    }
1395
1396    pub fn can_navigate_to_selected_word(&self) -> bool {
1397        self.cmd_pressed && self.found_word
1398    }
1399}
1400
1401impl Drop for Terminal {
1402    fn drop(&mut self) {
1403        self.pty_tx.0.send(Msg::Shutdown).ok();
1404    }
1405}
1406
1407impl Entity for Terminal {
1408    type Event = Event;
1409}
1410
1411/// Based on alacritty/src/display/hint.rs > regex_match_at
1412/// Retrieve the match, if the specified point is inside the content matching the regex.
1413fn regex_match_at<T>(term: &Term<T>, point: Point, regex: &RegexSearch) -> Option<Match> {
1414    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1415}
1416
1417/// Copied from alacritty/src/display/hint.rs:
1418/// Iterate over all visible regex matches.
1419pub fn visible_regex_match_iter<'a, T>(
1420    term: &'a Term<T>,
1421    regex: &'a RegexSearch,
1422) -> impl Iterator<Item = Match> + 'a {
1423    let viewport_start = Line(-(term.grid().display_offset() as i32));
1424    let viewport_end = viewport_start + term.bottommost_line();
1425    let mut start = term.line_search_left(Point::new(viewport_start, Column(0)));
1426    let mut end = term.line_search_right(Point::new(viewport_end, Column(0)));
1427    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1428    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1429
1430    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1431        .skip_while(move |rm| rm.end().line < viewport_start)
1432        .take_while(move |rm| rm.start().line <= viewport_end)
1433}
1434
1435fn make_selection(range: &RangeInclusive<Point>) -> Selection {
1436    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1437    selection.update(*range.end(), AlacDirection::Right);
1438    selection
1439}
1440
1441fn all_search_matches<'a, T>(
1442    term: &'a Term<T>,
1443    regex: &'a RegexSearch,
1444) -> impl Iterator<Item = Match> + 'a {
1445    let start = Point::new(term.grid().topmost_line(), Column(0));
1446    let end = Point::new(term.grid().bottommost_line(), term.grid().last_column());
1447    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1448}
1449
1450fn content_index_for_mouse(pos: Vector2F, size: &TerminalSize) -> usize {
1451    let col = (pos.x() / size.cell_width()).round() as usize;
1452
1453    let clamped_col = min(col, size.columns() - 1);
1454
1455    let row = (pos.y() / size.line_height()).round() as usize;
1456
1457    let clamped_row = min(row, size.screen_lines() - 1);
1458
1459    clamped_row * size.columns() + clamped_col
1460}
1461
1462#[cfg(test)]
1463mod tests {
1464    use alacritty_terminal::{
1465        index::{Column, Line, Point},
1466        term::cell::Cell,
1467    };
1468    use gpui::geometry::vector::vec2f;
1469    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1470
1471    use crate::{content_index_for_mouse, IndexedCell, TerminalContent, TerminalSize};
1472
1473    #[test]
1474    fn test_mouse_to_cell_test() {
1475        let mut rng = thread_rng();
1476        const ITERATIONS: usize = 10;
1477        const PRECISION: usize = 1000;
1478
1479        for _ in 0..ITERATIONS {
1480            let viewport_cells = rng.gen_range(15..20);
1481            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1482
1483            let size = crate::TerminalSize {
1484                cell_width: cell_size,
1485                line_height: cell_size,
1486                height: cell_size * (viewport_cells as f32),
1487                width: cell_size * (viewport_cells as f32),
1488            };
1489
1490            let cells = get_cells(size, &mut rng);
1491            let content = convert_cells_to_content(size, &cells);
1492
1493            for row in 0..(viewport_cells - 1) {
1494                let row = row as usize;
1495                for col in 0..(viewport_cells - 1) {
1496                    let col = col as usize;
1497
1498                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1499                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1500
1501                    let mouse_pos = vec2f(
1502                        col as f32 * cell_size + col_offset,
1503                        row as f32 * cell_size + row_offset,
1504                    );
1505
1506                    let content_index = content_index_for_mouse(mouse_pos, &content.size);
1507                    let mouse_cell = content.cells[content_index].c;
1508                    let real_cell = cells[row][col];
1509
1510                    assert_eq!(mouse_cell, real_cell);
1511                }
1512            }
1513        }
1514    }
1515
1516    #[test]
1517    fn test_mouse_to_cell_clamp() {
1518        let mut rng = thread_rng();
1519
1520        let size = crate::TerminalSize {
1521            cell_width: 10.,
1522            line_height: 10.,
1523            height: 100.,
1524            width: 100.,
1525        };
1526
1527        let cells = get_cells(size, &mut rng);
1528        let content = convert_cells_to_content(size, &cells);
1529
1530        assert_eq!(
1531            content.cells[content_index_for_mouse(vec2f(-10., -10.), &content.size)].c,
1532            cells[0][0]
1533        );
1534        assert_eq!(
1535            content.cells[content_index_for_mouse(vec2f(1000., 1000.), &content.size)].c,
1536            cells[9][9]
1537        );
1538    }
1539
1540    fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1541        let mut cells = Vec::new();
1542
1543        for _ in 0..((size.height() / size.line_height()) as usize) {
1544            let mut row_vec = Vec::new();
1545            for _ in 0..((size.width() / size.cell_width()) as usize) {
1546                let cell_char = rng.sample(Alphanumeric) as char;
1547                row_vec.push(cell_char)
1548            }
1549            cells.push(row_vec)
1550        }
1551
1552        cells
1553    }
1554
1555    fn convert_cells_to_content(size: TerminalSize, cells: &Vec<Vec<char>>) -> TerminalContent {
1556        let mut ic = Vec::new();
1557
1558        for row in 0..cells.len() {
1559            for col in 0..cells[row].len() {
1560                let cell_char = cells[row][col];
1561                ic.push(IndexedCell {
1562                    point: Point::new(Line(row as i32), Column(col)),
1563                    cell: Cell {
1564                        c: cell_char,
1565                        ..Default::default()
1566                    },
1567                });
1568            }
1569        }
1570
1571        TerminalContent {
1572            cells: ic,
1573            size,
1574            ..Default::default()
1575        }
1576    }
1577}