terminal.rs

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