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