terminal.rs

   1pub mod mappings;
   2
   3pub use alacritty_terminal;
   4
   5mod pty_info;
   6pub mod terminal_settings;
   7
   8use alacritty_terminal::{
   9    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
  10    event_loop::{EventLoop, Msg, Notifier},
  11    grid::{Dimensions, Scroll as AlacScroll},
  12    index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
  13    selection::{Selection, SelectionRange, SelectionType},
  14    sync::FairMutex,
  15    term::{
  16        cell::Cell,
  17        search::{Match, RegexIter, RegexSearch},
  18        Config, RenderableCursor, TermMode,
  19    },
  20    tty::{self},
  21    vi_mode::{ViModeCursor, ViMotion},
  22    vte::ansi::{
  23        ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
  24    },
  25    Term,
  26};
  27use anyhow::{bail, Result};
  28
  29use futures::{
  30    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
  31    FutureExt,
  32};
  33
  34use mappings::mouse::{
  35    alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
  36    scroll_report,
  37};
  38
  39use collections::{HashMap, VecDeque};
  40use futures::StreamExt;
  41use pty_info::PtyProcessInfo;
  42use serde::{Deserialize, Serialize};
  43use settings::Settings;
  44use smol::channel::{Receiver, Sender};
  45use task::{HideStrategy, Shell, TaskId};
  46use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
  47use theme::{ActiveTheme, Theme};
  48use util::{paths::home_dir, truncate_and_trailoff};
  49
  50use std::{
  51    cmp::{self, min},
  52    fmt::Display,
  53    ops::{Deref, Index, RangeInclusive},
  54    path::PathBuf,
  55    sync::Arc,
  56    time::Duration,
  57};
  58use thiserror::Error;
  59
  60use gpui::{
  61    actions, black, px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla,
  62    Keystroke, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
  63    Pixels, Point, Rgba, ScrollWheelEvent, SharedString, Size, Task, TouchPhase,
  64};
  65
  66use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
  67
  68actions!(
  69    terminal,
  70    [
  71        Clear,
  72        Copy,
  73        Paste,
  74        ShowCharacterPalette,
  75        SearchTest,
  76        ScrollLineUp,
  77        ScrollLineDown,
  78        ScrollPageUp,
  79        ScrollPageDown,
  80        ScrollToTop,
  81        ScrollToBottom,
  82        ToggleViMode,
  83    ]
  84);
  85
  86///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  87///Scroll multiplier that is set to 3 by default. This will be removed when I
  88///Implement scroll bars.
  89#[cfg(target_os = "macos")]
  90const SCROLL_MULTIPLIER: f32 = 4.;
  91#[cfg(not(target_os = "macos"))]
  92const SCROLL_MULTIPLIER: f32 = 1.;
  93const MAX_SEARCH_LINES: usize = 100;
  94const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
  95const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
  96const DEBUG_CELL_WIDTH: Pixels = px(5.);
  97const DEBUG_LINE_HEIGHT: Pixels = px(5.);
  98
  99///Upward flowing events, for changing the title and such
 100#[derive(Clone, Debug)]
 101pub enum Event {
 102    TitleChanged,
 103    BreadcrumbsChanged,
 104    CloseTerminal,
 105    Bell,
 106    Wakeup,
 107    BlinkChanged(bool),
 108    SelectionsChanged,
 109    NewNavigationTarget(Option<MaybeNavigationTarget>),
 110    Open(MaybeNavigationTarget),
 111}
 112
 113#[derive(Clone, Debug)]
 114pub struct PathLikeTarget {
 115    /// File system path, absolute or relative, existing or not.
 116    /// Might have line and column number(s) attached as `file.rs:1:23`
 117    pub maybe_path: String,
 118    /// Current working directory of the terminal
 119    pub terminal_dir: Option<PathBuf>,
 120}
 121
 122/// A string inside terminal, potentially useful as a URI that can be opened.
 123#[derive(Clone, Debug)]
 124pub enum MaybeNavigationTarget {
 125    /// HTTP, git, etc. string determined by the [`URL_REGEX`] regex.
 126    Url(String),
 127    /// File system path, absolute or relative, existing or not.
 128    /// Might have line and column number(s) attached as `file.rs:1:23`
 129    PathLike(PathLikeTarget),
 130}
 131
 132#[derive(Clone)]
 133enum InternalEvent {
 134    Resize(TerminalSize),
 135    Clear,
 136    // FocusNextMatch,
 137    Scroll(AlacScroll),
 138    ScrollToAlacPoint(AlacPoint),
 139    SetSelection(Option<(Selection, AlacPoint)>),
 140    UpdateSelection(Point<Pixels>),
 141    // Adjusted mouse position, should open
 142    FindHyperlink(Point<Pixels>, bool),
 143    Copy,
 144    // Vi mode events
 145    ToggleViMode,
 146    ViMotion(ViMotion),
 147}
 148
 149///A translation struct for Alacritty to communicate with us from their event loop
 150#[derive(Clone)]
 151pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
 152
 153impl EventListener for ZedListener {
 154    fn send_event(&self, event: AlacTermEvent) {
 155        self.0.unbounded_send(event).ok();
 156    }
 157}
 158
 159pub fn init(cx: &mut AppContext) {
 160    TerminalSettings::register(cx);
 161}
 162
 163#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
 164pub struct TerminalSize {
 165    pub cell_width: Pixels,
 166    pub line_height: Pixels,
 167    pub size: Size<Pixels>,
 168}
 169
 170impl TerminalSize {
 171    pub fn new(line_height: Pixels, cell_width: Pixels, size: Size<Pixels>) -> Self {
 172        TerminalSize {
 173            cell_width,
 174            line_height,
 175            size,
 176        }
 177    }
 178
 179    pub fn num_lines(&self) -> usize {
 180        (self.size.height / self.line_height).floor() as usize
 181    }
 182
 183    pub fn num_columns(&self) -> usize {
 184        (self.size.width / self.cell_width).floor() as usize
 185    }
 186
 187    pub fn height(&self) -> Pixels {
 188        self.size.height
 189    }
 190
 191    pub fn width(&self) -> Pixels {
 192        self.size.width
 193    }
 194
 195    pub fn cell_width(&self) -> Pixels {
 196        self.cell_width
 197    }
 198
 199    pub fn line_height(&self) -> Pixels {
 200        self.line_height
 201    }
 202}
 203
 204impl Default for TerminalSize {
 205    fn default() -> Self {
 206        TerminalSize::new(
 207            DEBUG_LINE_HEIGHT,
 208            DEBUG_CELL_WIDTH,
 209            Size {
 210                width: DEBUG_TERMINAL_WIDTH,
 211                height: DEBUG_TERMINAL_HEIGHT,
 212            },
 213        )
 214    }
 215}
 216
 217impl From<TerminalSize> for WindowSize {
 218    fn from(val: TerminalSize) -> Self {
 219        WindowSize {
 220            num_lines: val.num_lines() as u16,
 221            num_cols: val.num_columns() as u16,
 222            cell_width: f32::from(val.cell_width()) as u16,
 223            cell_height: f32::from(val.line_height()) as u16,
 224        }
 225    }
 226}
 227
 228impl Dimensions for TerminalSize {
 229    /// Note: this is supposed to be for the back buffer's length,
 230    /// but we exclusively use it to resize the terminal, which does not
 231    /// use this method. We still have to implement it for the trait though,
 232    /// hence, this comment.
 233    fn total_lines(&self) -> usize {
 234        self.screen_lines()
 235    }
 236
 237    fn screen_lines(&self) -> usize {
 238        self.num_lines()
 239    }
 240
 241    fn columns(&self) -> usize {
 242        self.num_columns()
 243    }
 244}
 245
 246#[derive(Error, Debug)]
 247pub struct TerminalError {
 248    pub directory: Option<PathBuf>,
 249    pub shell: Shell,
 250    pub source: std::io::Error,
 251}
 252
 253impl TerminalError {
 254    pub fn fmt_directory(&self) -> String {
 255        self.directory
 256            .clone()
 257            .map(|path| {
 258                match path
 259                    .into_os_string()
 260                    .into_string()
 261                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 262                {
 263                    Ok(s) => s,
 264                    Err(s) => s,
 265                }
 266            })
 267            .unwrap_or_else(|| {
 268                let default_dir =
 269                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
 270                match default_dir {
 271                    Some(dir) => format!("<none specified, using home directory> {}", dir),
 272                    None => "<none specified, could not find home directory>".to_string(),
 273                }
 274            })
 275    }
 276
 277    pub fn fmt_shell(&self) -> String {
 278        match &self.shell {
 279            Shell::System => "<system defined shell>".to_string(),
 280            Shell::Program(s) => s.to_string(),
 281            Shell::WithArguments {
 282                program,
 283                args,
 284                title_override,
 285            } => {
 286                if let Some(title_override) = title_override {
 287                    format!("{} {} ({})", program, args.join(" "), title_override)
 288                } else {
 289                    format!("{} {}", program, args.join(" "))
 290                }
 291            }
 292        }
 293    }
 294}
 295
 296impl Display for TerminalError {
 297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 298        let dir_string: String = self.fmt_directory();
 299        let shell = self.fmt_shell();
 300
 301        write!(
 302            f,
 303            "Working directory: {} Shell command: `{}`, IOError: {}",
 304            dir_string, shell, self.source
 305        )
 306    }
 307}
 308
 309// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
 310const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
 311const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
 312const URL_REGEX: &str = r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`]+"#;
 313// Optional suffix matches MSBuild diagnostic suffixes for path parsing in PathLikeWithPosition
 314// https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks
 315const WORD_REGEX: &str =
 316    r#"[\$\+\w.\[\]:/\\@\-~()]+(?:\((?:\d+|\d+,\d+)\))|[\$\+\w.\[\]:/\\@\-~()]+"#;
 317
 318pub struct TerminalBuilder {
 319    terminal: Terminal,
 320    events_rx: UnboundedReceiver<AlacTermEvent>,
 321}
 322
 323impl TerminalBuilder {
 324    #[allow(clippy::too_many_arguments)]
 325    pub fn new(
 326        working_directory: Option<PathBuf>,
 327        python_venv_directory: Option<PathBuf>,
 328        task: Option<TaskState>,
 329        shell: Shell,
 330        mut env: HashMap<String, String>,
 331        cursor_shape: CursorShape,
 332        alternate_scroll: AlternateScroll,
 333        max_scroll_history_lines: Option<usize>,
 334        is_ssh_terminal: bool,
 335        window: AnyWindowHandle,
 336        completion_tx: Sender<()>,
 337        cx: &AppContext,
 338    ) -> Result<TerminalBuilder> {
 339        // If the parent environment doesn't have a locale set
 340        // (As is the case when launched from a .app on MacOS),
 341        // and the Project doesn't have a locale set, then
 342        // set a fallback for our child environment to use.
 343        if std::env::var("LANG").is_err() {
 344            env.entry("LANG".to_string())
 345                .or_insert_with(|| "en_US.UTF-8".to_string());
 346        }
 347
 348        env.insert("ZED_TERM".to_string(), "true".to_string());
 349        env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
 350        env.insert(
 351            "TERM_PROGRAM_VERSION".to_string(),
 352            release_channel::AppVersion::global(cx).to_string(),
 353        );
 354
 355        let mut terminal_title_override = None;
 356
 357        let pty_options = {
 358            let alac_shell = match shell.clone() {
 359                Shell::System => None,
 360                Shell::Program(program) => {
 361                    Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
 362                }
 363                Shell::WithArguments {
 364                    program,
 365                    args,
 366                    title_override,
 367                } => {
 368                    terminal_title_override = title_override;
 369                    Some(alacritty_terminal::tty::Shell::new(program, args))
 370                }
 371            };
 372
 373            alacritty_terminal::tty::Options {
 374                shell: alac_shell,
 375                working_directory: working_directory
 376                    .clone()
 377                    .or_else(|| Some(home_dir().to_path_buf())),
 378                hold: false,
 379                env: env.into_iter().collect(),
 380            }
 381        };
 382
 383        // Setup Alacritty's env, which modifies the current process's environment
 384        alacritty_terminal::tty::setup_env();
 385
 386        let default_cursor_style = AlacCursorStyle::from(cursor_shape);
 387        let scrolling_history = if task.is_some() {
 388            // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
 389            // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
 390            // cause excessive memory usage over time.
 391            MAX_SCROLL_HISTORY_LINES
 392        } else {
 393            max_scroll_history_lines
 394                .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
 395                .min(MAX_SCROLL_HISTORY_LINES)
 396        };
 397        let config = Config {
 398            scrolling_history,
 399            default_cursor_style,
 400            ..Config::default()
 401        };
 402
 403        //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
 404        //TODO: Remove with a bounded sender which can be dispatched on &self
 405        let (events_tx, events_rx) = unbounded();
 406        //Set up the terminal...
 407        let mut term = Term::new(
 408            config.clone(),
 409            &TerminalSize::default(),
 410            ZedListener(events_tx.clone()),
 411        );
 412
 413        //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
 414        if let AlternateScroll::Off = alternate_scroll {
 415            term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
 416        }
 417
 418        let term = Arc::new(FairMutex::new(term));
 419
 420        //Setup the pty...
 421        let pty = match tty::new(
 422            &pty_options,
 423            TerminalSize::default().into(),
 424            window.window_id().as_u64(),
 425        ) {
 426            Ok(pty) => pty,
 427            Err(error) => {
 428                bail!(TerminalError {
 429                    directory: working_directory,
 430                    shell,
 431                    source: error,
 432                });
 433            }
 434        };
 435
 436        let pty_info = PtyProcessInfo::new(&pty);
 437
 438        //And connect them together
 439        let event_loop = EventLoop::new(
 440            term.clone(),
 441            ZedListener(events_tx.clone()),
 442            pty,
 443            pty_options.hold,
 444            false,
 445        )?;
 446
 447        //Kick things off
 448        let pty_tx = event_loop.channel();
 449        let _io_thread = event_loop.spawn(); // DANGER
 450
 451        let terminal = Terminal {
 452            task,
 453            pty_tx: Notifier(pty_tx),
 454            completion_tx,
 455            term,
 456            term_config: config,
 457            title_override: terminal_title_override,
 458            events: VecDeque::with_capacity(10), //Should never get this high.
 459            last_content: Default::default(),
 460            last_mouse: None,
 461            matches: Vec::new(),
 462            selection_head: None,
 463            pty_info,
 464            breadcrumb_text: String::new(),
 465            scroll_px: px(0.),
 466            last_mouse_position: None,
 467            next_link_id: 0,
 468            selection_phase: SelectionPhase::Ended,
 469            secondary_pressed: false,
 470            hovered_word: false,
 471            url_regex: RegexSearch::new(URL_REGEX).unwrap(),
 472            word_regex: RegexSearch::new(WORD_REGEX).unwrap(),
 473            vi_mode_enabled: false,
 474            is_ssh_terminal,
 475            python_venv_directory,
 476        };
 477
 478        Ok(TerminalBuilder {
 479            terminal,
 480            events_rx,
 481        })
 482    }
 483
 484    pub fn subscribe(mut self, cx: &ModelContext<Terminal>) -> Terminal {
 485        //Event loop
 486        cx.spawn(|terminal, mut cx| async move {
 487            while let Some(event) = self.events_rx.next().await {
 488                terminal.update(&mut cx, |terminal, cx| {
 489                    //Process the first event immediately for lowered latency
 490                    terminal.process_event(&event, cx);
 491                })?;
 492
 493                'outer: loop {
 494                    let mut events = Vec::new();
 495                    let mut timer = cx
 496                        .background_executor()
 497                        .timer(Duration::from_millis(4))
 498                        .fuse();
 499                    let mut wakeup = false;
 500                    loop {
 501                        futures::select_biased! {
 502                            _ = timer => break,
 503                            event = self.events_rx.next() => {
 504                                if let Some(event) = event {
 505                                    if matches!(event, AlacTermEvent::Wakeup) {
 506                                        wakeup = true;
 507                                    } else {
 508                                        events.push(event);
 509                                    }
 510
 511                                    if events.len() > 100 {
 512                                        break;
 513                                    }
 514                                } else {
 515                                    break;
 516                                }
 517                            },
 518                        }
 519                    }
 520
 521                    if events.is_empty() && !wakeup {
 522                        smol::future::yield_now().await;
 523                        break 'outer;
 524                    }
 525
 526                    terminal.update(&mut cx, |this, cx| {
 527                        if wakeup {
 528                            this.process_event(&AlacTermEvent::Wakeup, cx);
 529                        }
 530
 531                        for event in events {
 532                            this.process_event(&event, cx);
 533                        }
 534                    })?;
 535                    smol::future::yield_now().await;
 536                }
 537            }
 538
 539            anyhow::Ok(())
 540        })
 541        .detach();
 542
 543        self.terminal
 544    }
 545}
 546
 547#[derive(Debug, Clone, Deserialize, Serialize)]
 548pub struct IndexedCell {
 549    pub point: AlacPoint,
 550    pub cell: Cell,
 551}
 552
 553impl Deref for IndexedCell {
 554    type Target = Cell;
 555
 556    #[inline]
 557    fn deref(&self) -> &Cell {
 558        &self.cell
 559    }
 560}
 561
 562// TODO: Un-pub
 563#[derive(Clone)]
 564pub struct TerminalContent {
 565    pub cells: Vec<IndexedCell>,
 566    pub mode: TermMode,
 567    pub display_offset: usize,
 568    pub selection_text: Option<String>,
 569    pub selection: Option<SelectionRange>,
 570    pub cursor: RenderableCursor,
 571    pub cursor_char: char,
 572    pub size: TerminalSize,
 573    pub last_hovered_word: Option<HoveredWord>,
 574}
 575
 576#[derive(Clone)]
 577pub struct HoveredWord {
 578    pub word: String,
 579    pub word_match: RangeInclusive<AlacPoint>,
 580    pub id: usize,
 581}
 582
 583impl Default for TerminalContent {
 584    fn default() -> Self {
 585        TerminalContent {
 586            cells: Default::default(),
 587            mode: Default::default(),
 588            display_offset: Default::default(),
 589            selection_text: Default::default(),
 590            selection: Default::default(),
 591            cursor: RenderableCursor {
 592                shape: alacritty_terminal::vte::ansi::CursorShape::Block,
 593                point: AlacPoint::new(Line(0), Column(0)),
 594            },
 595            cursor_char: Default::default(),
 596            size: Default::default(),
 597            last_hovered_word: None,
 598        }
 599    }
 600}
 601
 602#[derive(PartialEq, Eq)]
 603pub enum SelectionPhase {
 604    Selecting,
 605    Ended,
 606}
 607
 608pub struct Terminal {
 609    pty_tx: Notifier,
 610    completion_tx: Sender<()>,
 611    term: Arc<FairMutex<Term<ZedListener>>>,
 612    term_config: Config,
 613    events: VecDeque<InternalEvent>,
 614    /// This is only used for mouse mode cell change detection
 615    last_mouse: Option<(AlacPoint, AlacDirection)>,
 616    /// This is only used for terminal hovered word checking
 617    last_mouse_position: Option<Point<Pixels>>,
 618    pub matches: Vec<RangeInclusive<AlacPoint>>,
 619    pub last_content: TerminalContent,
 620    pub selection_head: Option<AlacPoint>,
 621    pub breadcrumb_text: String,
 622    pub pty_info: PtyProcessInfo,
 623    title_override: Option<SharedString>,
 624    pub python_venv_directory: Option<PathBuf>,
 625    scroll_px: Pixels,
 626    next_link_id: usize,
 627    selection_phase: SelectionPhase,
 628    secondary_pressed: bool,
 629    hovered_word: bool,
 630    url_regex: RegexSearch,
 631    word_regex: RegexSearch,
 632    task: Option<TaskState>,
 633    vi_mode_enabled: bool,
 634    is_ssh_terminal: bool,
 635}
 636
 637pub struct TaskState {
 638    pub id: TaskId,
 639    pub full_label: String,
 640    pub label: String,
 641    pub command_label: String,
 642    pub status: TaskStatus,
 643    pub completion_rx: Receiver<()>,
 644    pub hide: HideStrategy,
 645    pub show_summary: bool,
 646    pub show_command: bool,
 647}
 648
 649/// A status of the current terminal tab's task.
 650#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 651pub enum TaskStatus {
 652    /// The task had been started, but got cancelled or somehow otherwise it did not
 653    /// report its exit code before the terminal event loop was shut down.
 654    Unknown,
 655    /// The task is started and running currently.
 656    Running,
 657    /// After the start, the task stopped running and reported its error code back.
 658    Completed { success: bool },
 659}
 660
 661impl TaskStatus {
 662    fn register_terminal_exit(&mut self) {
 663        if self == &Self::Running {
 664            *self = Self::Unknown;
 665        }
 666    }
 667
 668    fn register_task_exit(&mut self, error_code: i32) {
 669        *self = TaskStatus::Completed {
 670            success: error_code == 0,
 671        };
 672    }
 673}
 674
 675impl Terminal {
 676    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
 677        match event {
 678            AlacTermEvent::Title(title) => {
 679                self.breadcrumb_text = title.to_string();
 680                cx.emit(Event::BreadcrumbsChanged);
 681            }
 682            AlacTermEvent::ResetTitle => {
 683                self.breadcrumb_text = String::new();
 684                cx.emit(Event::BreadcrumbsChanged);
 685            }
 686            AlacTermEvent::ClipboardStore(_, data) => {
 687                cx.write_to_clipboard(ClipboardItem::new_string(data.to_string()))
 688            }
 689            AlacTermEvent::ClipboardLoad(_, format) => {
 690                self.write_to_pty(
 691                    match &cx.read_from_clipboard().and_then(|item| item.text()) {
 692                        // The terminal only supports pasting strings, not images.
 693                        Some(text) => format(text),
 694                        _ => format(""),
 695                    },
 696                )
 697            }
 698            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 699            AlacTermEvent::TextAreaSizeRequest(format) => {
 700                self.write_to_pty(format(self.last_content.size.into()))
 701            }
 702            AlacTermEvent::CursorBlinkingChange => {
 703                let terminal = self.term.lock();
 704                let blinking = terminal.cursor_style().blinking;
 705                cx.emit(Event::BlinkChanged(blinking));
 706            }
 707            AlacTermEvent::Bell => {
 708                cx.emit(Event::Bell);
 709            }
 710            AlacTermEvent::Exit => self.register_task_finished(None, cx),
 711            AlacTermEvent::MouseCursorDirty => {
 712                //NOOP, Handled in render
 713            }
 714            AlacTermEvent::Wakeup => {
 715                cx.emit(Event::Wakeup);
 716
 717                if self.pty_info.has_changed() {
 718                    cx.emit(Event::TitleChanged);
 719                }
 720            }
 721            AlacTermEvent::ColorRequest(index, format) => {
 722                // It's important that the color request is processed here to retain relative order
 723                // with other PTY writes. Otherwise applications might witness out-of-order
 724                // responses to requests. For example: An application sending `OSC 11 ; ? ST`
 725                // (color request) followed by `CSI c` (request device attributes) would receive
 726                // the response to `CSI c` first.
 727                // Instead of locking, we could store the colors in `self.last_content`. But then
 728                // we might respond with out of date value if a "set color" sequence is immediately
 729                // followed by a color request sequence.
 730                let color = self.term.lock().colors()[*index].unwrap_or_else(|| {
 731                    to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
 732                });
 733                self.write_to_pty(format(color));
 734            }
 735            AlacTermEvent::ChildExit(error_code) => {
 736                self.register_task_finished(Some(*error_code), cx);
 737            }
 738        }
 739    }
 740
 741    pub fn selection_started(&self) -> bool {
 742        self.selection_phase == SelectionPhase::Selecting
 743    }
 744
 745    ///Takes events from Alacritty and translates them to behavior on this view
 746    fn process_terminal_event(
 747        &mut self,
 748        event: &InternalEvent,
 749        term: &mut Term<ZedListener>,
 750        cx: &mut ModelContext<Self>,
 751    ) {
 752        match event {
 753            InternalEvent::Resize(mut new_size) => {
 754                new_size.size.height = cmp::max(new_size.line_height, new_size.height());
 755                new_size.size.width = cmp::max(new_size.cell_width, new_size.width());
 756
 757                self.last_content.size = new_size;
 758
 759                self.pty_tx.0.send(Msg::Resize(new_size.into())).ok();
 760
 761                term.resize(new_size);
 762            }
 763            InternalEvent::Clear => {
 764                // Clear back buffer
 765                term.clear_screen(ClearMode::Saved);
 766
 767                let cursor = term.grid().cursor.point;
 768
 769                // Clear the lines above
 770                term.grid_mut().reset_region(..cursor.line);
 771
 772                // Copy the current line up
 773                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 774                    .iter()
 775                    .cloned()
 776                    .enumerate()
 777                    .collect::<Vec<(usize, Cell)>>();
 778
 779                for (i, cell) in line {
 780                    term.grid_mut()[Line(0)][Column(i)] = cell;
 781                }
 782
 783                // Reset the cursor
 784                term.grid_mut().cursor.point =
 785                    AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
 786                let new_cursor = term.grid().cursor.point;
 787
 788                // Clear the lines below the new cursor
 789                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 790                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 791                }
 792
 793                cx.emit(Event::Wakeup);
 794            }
 795            InternalEvent::Scroll(scroll) => {
 796                term.scroll_display(*scroll);
 797                self.refresh_hovered_word();
 798
 799                if self.vi_mode_enabled {
 800                    match *scroll {
 801                        AlacScroll::Delta(delta) => {
 802                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
 803                        }
 804                        AlacScroll::PageUp => {
 805                            let lines = term.screen_lines() as i32;
 806                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
 807                        }
 808                        AlacScroll::PageDown => {
 809                            let lines = -(term.screen_lines() as i32);
 810                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
 811                        }
 812                        AlacScroll::Top => {
 813                            let point = AlacPoint::new(term.topmost_line(), Column(0));
 814                            term.vi_mode_cursor = ViModeCursor::new(point);
 815                        }
 816                        AlacScroll::Bottom => {
 817                            let point = AlacPoint::new(term.bottommost_line(), Column(0));
 818                            term.vi_mode_cursor = ViModeCursor::new(point);
 819                        }
 820                    }
 821                    if let Some(mut selection) = term.selection.take() {
 822                        let point = term.vi_mode_cursor.point;
 823                        selection.update(point, AlacDirection::Right);
 824                        term.selection = Some(selection);
 825
 826                        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 827                        if let Some(selection_text) = term.selection_to_string() {
 828                            cx.write_to_primary(ClipboardItem::new_string(selection_text));
 829                        }
 830
 831                        self.selection_head = Some(point);
 832                        cx.emit(Event::SelectionsChanged)
 833                    }
 834                }
 835            }
 836            InternalEvent::SetSelection(selection) => {
 837                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 838
 839                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 840                if let Some(selection_text) = term.selection_to_string() {
 841                    cx.write_to_primary(ClipboardItem::new_string(selection_text));
 842                }
 843
 844                if let Some((_, head)) = selection {
 845                    self.selection_head = Some(*head);
 846                }
 847                cx.emit(Event::SelectionsChanged)
 848            }
 849            InternalEvent::UpdateSelection(position) => {
 850                if let Some(mut selection) = term.selection.take() {
 851                    let (point, side) = grid_point_and_side(
 852                        *position,
 853                        self.last_content.size,
 854                        term.grid().display_offset(),
 855                    );
 856
 857                    selection.update(point, side);
 858                    term.selection = Some(selection);
 859
 860                    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 861                    if let Some(selection_text) = term.selection_to_string() {
 862                        cx.write_to_primary(ClipboardItem::new_string(selection_text));
 863                    }
 864
 865                    self.selection_head = Some(point);
 866                    cx.emit(Event::SelectionsChanged)
 867                }
 868            }
 869
 870            InternalEvent::Copy => {
 871                if let Some(txt) = term.selection_to_string() {
 872                    cx.write_to_clipboard(ClipboardItem::new_string(txt))
 873                }
 874            }
 875            InternalEvent::ScrollToAlacPoint(point) => {
 876                term.scroll_to_point(*point);
 877                self.refresh_hovered_word();
 878            }
 879            InternalEvent::ToggleViMode => {
 880                self.vi_mode_enabled = !self.vi_mode_enabled;
 881                term.toggle_vi_mode();
 882            }
 883            InternalEvent::ViMotion(motion) => {
 884                term.vi_motion(*motion);
 885            }
 886            InternalEvent::FindHyperlink(position, open) => {
 887                let prev_hovered_word = self.last_content.last_hovered_word.take();
 888
 889                let point = grid_point(
 890                    *position,
 891                    self.last_content.size,
 892                    term.grid().display_offset(),
 893                )
 894                .grid_clamp(term, Boundary::Grid);
 895
 896                let link = term.grid().index(point).hyperlink();
 897                let found_word = if link.is_some() {
 898                    let mut min_index = point;
 899                    loop {
 900                        let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
 901                        if new_min_index == min_index
 902                            || term.grid().index(new_min_index).hyperlink() != link
 903                        {
 904                            break;
 905                        } else {
 906                            min_index = new_min_index
 907                        }
 908                    }
 909
 910                    let mut max_index = point;
 911                    loop {
 912                        let new_max_index = max_index.add(term, Boundary::Cursor, 1);
 913                        if new_max_index == max_index
 914                            || term.grid().index(new_max_index).hyperlink() != link
 915                        {
 916                            break;
 917                        } else {
 918                            max_index = new_max_index
 919                        }
 920                    }
 921
 922                    let url = link.unwrap().uri().to_owned();
 923                    let url_match = min_index..=max_index;
 924
 925                    Some((url, true, url_match))
 926                } else if let Some(url_match) = regex_match_at(term, point, &mut self.url_regex) {
 927                    let url = term.bounds_to_string(*url_match.start(), *url_match.end());
 928                    Some((url, true, url_match))
 929                } else if let Some(word_match) = regex_match_at(term, point, &mut self.word_regex) {
 930                    let file_path = term.bounds_to_string(*word_match.start(), *word_match.end());
 931
 932                    let (sanitized_match, sanitized_word) = if file_path.starts_with('[')
 933                        && file_path.ends_with(']')
 934                        // this is to avoid sanitizing the match '[]' to an empty string,
 935                        // which would be considered a valid navigation target
 936                        && file_path.len() > 2
 937                    {
 938                        (
 939                            Match::new(
 940                                word_match.start().add(term, Boundary::Cursor, 1),
 941                                word_match.end().sub(term, Boundary::Cursor, 1),
 942                            ),
 943                            file_path[1..file_path.len() - 1].to_owned(),
 944                        )
 945                    } else {
 946                        (word_match, file_path)
 947                    };
 948
 949                    Some((sanitized_word, false, sanitized_match))
 950                } else {
 951                    None
 952                };
 953
 954                match found_word {
 955                    Some((maybe_url_or_path, is_url, url_match)) => {
 956                        if *open {
 957                            let target = if is_url {
 958                                MaybeNavigationTarget::Url(maybe_url_or_path)
 959                            } else {
 960                                MaybeNavigationTarget::PathLike(PathLikeTarget {
 961                                    maybe_path: maybe_url_or_path,
 962                                    terminal_dir: self.working_directory(),
 963                                })
 964                            };
 965                            cx.emit(Event::Open(target));
 966                        } else {
 967                            self.update_selected_word(
 968                                prev_hovered_word,
 969                                url_match,
 970                                maybe_url_or_path,
 971                                is_url,
 972                                cx,
 973                            );
 974                        }
 975                        self.hovered_word = true;
 976                    }
 977                    None => {
 978                        if self.hovered_word {
 979                            cx.emit(Event::NewNavigationTarget(None));
 980                        }
 981                        self.hovered_word = false;
 982                    }
 983                }
 984            }
 985        }
 986    }
 987
 988    fn update_selected_word(
 989        &mut self,
 990        prev_word: Option<HoveredWord>,
 991        word_match: RangeInclusive<AlacPoint>,
 992        word: String,
 993        is_url: bool,
 994        cx: &mut ModelContext<Self>,
 995    ) {
 996        if let Some(prev_word) = prev_word {
 997            if prev_word.word == word && prev_word.word_match == word_match {
 998                self.last_content.last_hovered_word = Some(HoveredWord {
 999                    word,
1000                    word_match,
1001                    id: prev_word.id,
1002                });
1003                return;
1004            }
1005        }
1006
1007        self.last_content.last_hovered_word = Some(HoveredWord {
1008            word: word.clone(),
1009            word_match,
1010            id: self.next_link_id(),
1011        });
1012        let navigation_target = if is_url {
1013            MaybeNavigationTarget::Url(word)
1014        } else {
1015            MaybeNavigationTarget::PathLike(PathLikeTarget {
1016                maybe_path: word,
1017                terminal_dir: self.working_directory(),
1018            })
1019        };
1020        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1021    }
1022
1023    fn next_link_id(&mut self) -> usize {
1024        let res = self.next_link_id;
1025        self.next_link_id = self.next_link_id.wrapping_add(1);
1026        res
1027    }
1028
1029    pub fn last_content(&self) -> &TerminalContent {
1030        &self.last_content
1031    }
1032
1033    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1034        self.term_config.default_cursor_style = cursor_shape.into();
1035        self.term.lock().set_options(self.term_config.clone());
1036    }
1037
1038    pub fn total_lines(&self) -> usize {
1039        let term = self.term.clone();
1040        let terminal = term.lock_unfair();
1041        terminal.total_lines()
1042    }
1043
1044    pub fn viewport_lines(&self) -> usize {
1045        let term = self.term.clone();
1046        let terminal = term.lock_unfair();
1047        terminal.screen_lines()
1048    }
1049
1050    //To test:
1051    //- Activate match on terminal (scrolling and selection)
1052    //- Editor search snapping behavior
1053
1054    pub fn activate_match(&mut self, index: usize) {
1055        if let Some(search_match) = self.matches.get(index).cloned() {
1056            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1057
1058            self.events
1059                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1060        }
1061    }
1062
1063    pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1064        let matches_to_select = self
1065            .matches
1066            .iter()
1067            .filter(|self_match| matches.contains(self_match))
1068            .cloned()
1069            .collect::<Vec<_>>();
1070        for match_to_select in matches_to_select {
1071            self.set_selection(Some((
1072                make_selection(&match_to_select),
1073                *match_to_select.end(),
1074            )));
1075        }
1076    }
1077
1078    pub fn select_all(&mut self) {
1079        let term = self.term.lock();
1080        let start = AlacPoint::new(term.topmost_line(), Column(0));
1081        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1082        drop(term);
1083        self.set_selection(Some((make_selection(&(start..=end)), end)));
1084    }
1085
1086    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1087        self.events
1088            .push_back(InternalEvent::SetSelection(selection));
1089    }
1090
1091    pub fn copy(&mut self) {
1092        self.events.push_back(InternalEvent::Copy);
1093    }
1094
1095    pub fn clear(&mut self) {
1096        self.events.push_back(InternalEvent::Clear)
1097    }
1098
1099    pub fn scroll_line_up(&mut self) {
1100        self.events
1101            .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1102    }
1103
1104    pub fn scroll_up_by(&mut self, lines: usize) {
1105        self.events
1106            .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1107    }
1108
1109    pub fn scroll_line_down(&mut self) {
1110        self.events
1111            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1112    }
1113
1114    pub fn scroll_down_by(&mut self, lines: usize) {
1115        self.events
1116            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1117    }
1118
1119    pub fn scroll_page_up(&mut self) {
1120        self.events
1121            .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1122    }
1123
1124    pub fn scroll_page_down(&mut self) {
1125        self.events
1126            .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1127    }
1128
1129    pub fn scroll_to_top(&mut self) {
1130        self.events
1131            .push_back(InternalEvent::Scroll(AlacScroll::Top));
1132    }
1133
1134    pub fn scroll_to_bottom(&mut self) {
1135        self.events
1136            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1137    }
1138
1139    ///Resize the terminal and the PTY.
1140    pub fn set_size(&mut self, new_size: TerminalSize) {
1141        if self.last_content.size != new_size {
1142            self.events.push_back(InternalEvent::Resize(new_size))
1143        }
1144    }
1145
1146    ///Write the Input payload to the tty.
1147    fn write_to_pty(&self, input: String) {
1148        self.pty_tx.notify(input.into_bytes());
1149    }
1150
1151    fn write_bytes_to_pty(&self, input: Vec<u8>) {
1152        self.pty_tx.notify(input);
1153    }
1154
1155    pub fn input(&mut self, input: String) {
1156        self.events
1157            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1158        self.events.push_back(InternalEvent::SetSelection(None));
1159
1160        self.write_to_pty(input);
1161    }
1162
1163    pub fn input_bytes(&mut self, input: Vec<u8>) {
1164        self.events
1165            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1166        self.events.push_back(InternalEvent::SetSelection(None));
1167
1168        self.write_bytes_to_pty(input);
1169    }
1170
1171    pub fn toggle_vi_mode(&mut self) {
1172        self.events.push_back(InternalEvent::ToggleViMode);
1173    }
1174
1175    pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1176        if !self.vi_mode_enabled {
1177            return;
1178        }
1179
1180        let mut key = keystroke.key.clone();
1181        if keystroke.modifiers.shift {
1182            key = key.to_uppercase();
1183        }
1184
1185        let motion: Option<ViMotion> = match key.as_str() {
1186            "h" => Some(ViMotion::Left),
1187            "j" => Some(ViMotion::Down),
1188            "k" => Some(ViMotion::Up),
1189            "l" => Some(ViMotion::Right),
1190            "w" => Some(ViMotion::WordRight),
1191            "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1192            "e" => Some(ViMotion::WordRightEnd),
1193            "%" => Some(ViMotion::Bracket),
1194            "$" => Some(ViMotion::Last),
1195            "0" => Some(ViMotion::First),
1196            "^" => Some(ViMotion::FirstOccupied),
1197            "H" => Some(ViMotion::High),
1198            "M" => Some(ViMotion::Middle),
1199            "L" => Some(ViMotion::Low),
1200            _ => None,
1201        };
1202
1203        if let Some(motion) = motion {
1204            let cursor = self.last_content.cursor.point;
1205            let cursor_pos = Point {
1206                x: cursor.column.0 as f32 * self.last_content.size.cell_width,
1207                y: cursor.line.0 as f32 * self.last_content.size.line_height,
1208            };
1209            self.events
1210                .push_back(InternalEvent::UpdateSelection(cursor_pos));
1211            self.events.push_back(InternalEvent::ViMotion(motion));
1212            return;
1213        }
1214
1215        let scroll_motion = match key.as_str() {
1216            "g" => Some(AlacScroll::Top),
1217            "G" => Some(AlacScroll::Bottom),
1218            "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1219            "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1220            "d" if keystroke.modifiers.control => {
1221                let amount = self.last_content.size.line_height().to_f64() as i32 / 2;
1222                Some(AlacScroll::Delta(-amount))
1223            }
1224            "u" if keystroke.modifiers.control => {
1225                let amount = self.last_content.size.line_height().to_f64() as i32 / 2;
1226                Some(AlacScroll::Delta(amount))
1227            }
1228            _ => None,
1229        };
1230
1231        if let Some(scroll_motion) = scroll_motion {
1232            self.events.push_back(InternalEvent::Scroll(scroll_motion));
1233            return;
1234        }
1235
1236        match key.as_str() {
1237            "v" => {
1238                let point = self.last_content.cursor.point;
1239                let selection_type = SelectionType::Simple;
1240                let side = AlacDirection::Right;
1241                let selection = Selection::new(selection_type, point, side);
1242                self.events
1243                    .push_back(InternalEvent::SetSelection(Some((selection, point))));
1244                return;
1245            }
1246
1247            "escape" => {
1248                self.events.push_back(InternalEvent::SetSelection(None));
1249                return;
1250            }
1251
1252            "y" => {
1253                self.events.push_back(InternalEvent::Copy);
1254                self.events.push_back(InternalEvent::SetSelection(None));
1255                return;
1256            }
1257
1258            "i" => {
1259                self.scroll_to_bottom();
1260                self.toggle_vi_mode();
1261                return;
1262            }
1263            _ => {}
1264        }
1265    }
1266
1267    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1268        if self.vi_mode_enabled {
1269            self.vi_motion(keystroke);
1270            return true;
1271        }
1272
1273        // Keep default terminal behavior
1274        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1275        if let Some(esc) = esc {
1276            self.input(esc);
1277            true
1278        } else {
1279            false
1280        }
1281    }
1282
1283    pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
1284        let changed = self.secondary_pressed != modifiers.secondary();
1285        if !self.secondary_pressed && modifiers.secondary() {
1286            self.refresh_hovered_word();
1287        }
1288        self.secondary_pressed = modifiers.secondary();
1289        changed
1290    }
1291
1292    ///Paste text into the terminal
1293    pub fn paste(&mut self, text: &str) {
1294        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1295            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1296        } else {
1297            text.replace("\r\n", "\r").replace('\n', "\r")
1298        };
1299
1300        self.input(paste_text);
1301    }
1302
1303    pub fn sync(&mut self, cx: &mut ModelContext<Self>) {
1304        let term = self.term.clone();
1305        let mut terminal = term.lock_unfair();
1306        //Note that the ordering of events matters for event processing
1307        while let Some(e) = self.events.pop_front() {
1308            self.process_terminal_event(&e, &mut terminal, cx)
1309        }
1310
1311        self.last_content = Self::make_content(&terminal, &self.last_content);
1312    }
1313
1314    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1315        let content = term.renderable_content();
1316        TerminalContent {
1317            cells: content
1318                .display_iter
1319                //TODO: Add this once there's a way to retain empty lines
1320                // .filter(|ic| {
1321                //     !ic.flags.contains(Flags::HIDDEN)
1322                //         && !(ic.bg == Named(NamedColor::Background)
1323                //             && ic.c == ' '
1324                //             && !ic.flags.contains(Flags::INVERSE))
1325                // })
1326                .map(|ic| IndexedCell {
1327                    point: ic.point,
1328                    cell: ic.cell.clone(),
1329                })
1330                .collect::<Vec<IndexedCell>>(),
1331            mode: content.mode,
1332            display_offset: content.display_offset,
1333            selection_text: term.selection_to_string(),
1334            selection: content.selection,
1335            cursor: content.cursor,
1336            cursor_char: term.grid()[content.cursor.point].c,
1337            size: last_content.size,
1338            last_hovered_word: last_content.last_hovered_word.clone(),
1339        }
1340    }
1341
1342    pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1343        let term = self.term.clone();
1344        let terminal = term.lock_unfair();
1345
1346        let mut lines = Vec::new();
1347        let mut current_line = terminal.bottommost_line();
1348        while lines.len() < n {
1349            let mut line_buffer = String::new();
1350            for cell in &terminal.grid()[current_line] {
1351                line_buffer.push(cell.c);
1352            }
1353            let line = line_buffer.trim_end();
1354            if !line.is_empty() {
1355                lines.push(line.to_string());
1356            }
1357
1358            if current_line == terminal.topmost_line() {
1359                break;
1360            }
1361            current_line = Line(current_line.0 - 1);
1362        }
1363        lines.reverse();
1364        lines
1365    }
1366
1367    pub fn focus_in(&self) {
1368        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1369            self.write_to_pty("\x1b[I".to_string());
1370        }
1371    }
1372
1373    pub fn focus_out(&mut self) {
1374        self.last_mouse_position = None;
1375        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1376            self.write_to_pty("\x1b[O".to_string());
1377        }
1378    }
1379
1380    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1381        match self.last_mouse {
1382            Some((old_point, old_side)) => {
1383                if old_point == point && old_side == side {
1384                    false
1385                } else {
1386                    self.last_mouse = Some((point, side));
1387                    true
1388                }
1389            }
1390            None => {
1391                self.last_mouse = Some((point, side));
1392                true
1393            }
1394        }
1395    }
1396
1397    pub fn mouse_mode(&self, shift: bool) -> bool {
1398        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1399    }
1400
1401    pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1402        let position = e.position - origin;
1403        self.last_mouse_position = Some(position);
1404        if self.mouse_mode(e.modifiers.shift) {
1405            let (point, side) = grid_point_and_side(
1406                position,
1407                self.last_content.size,
1408                self.last_content.display_offset,
1409            );
1410
1411            if self.mouse_changed(point, side) {
1412                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1413                    self.pty_tx.notify(bytes);
1414                }
1415            }
1416        } else if self.secondary_pressed {
1417            self.word_from_position(Some(position));
1418        }
1419    }
1420
1421    fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1422        if self.selection_phase == SelectionPhase::Selecting {
1423            self.last_content.last_hovered_word = None;
1424        } else if let Some(position) = position {
1425            self.events
1426                .push_back(InternalEvent::FindHyperlink(position, false));
1427        }
1428    }
1429
1430    pub fn mouse_drag(
1431        &mut self,
1432        e: &MouseMoveEvent,
1433        origin: Point<Pixels>,
1434        region: Bounds<Pixels>,
1435    ) {
1436        let position = e.position - origin;
1437        self.last_mouse_position = Some(position);
1438
1439        if !self.mouse_mode(e.modifiers.shift) {
1440            self.selection_phase = SelectionPhase::Selecting;
1441            // Alacritty has the same ordering, of first updating the selection
1442            // then scrolling 15ms later
1443            self.events
1444                .push_back(InternalEvent::UpdateSelection(position));
1445
1446            // Doesn't make sense to scroll the alt screen
1447            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1448                let scroll_delta = match self.drag_line_delta(e, region) {
1449                    Some(value) => value,
1450                    None => return,
1451                };
1452
1453                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1454
1455                self.events
1456                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1457            }
1458        }
1459    }
1460
1461    fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1462        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1463        let top = region.origin.y + (self.last_content.size.line_height * 2.);
1464        let bottom = region.bottom_left().y - (self.last_content.size.line_height * 2.);
1465        let scroll_delta = if e.position.y < top {
1466            (top - e.position.y).pow(1.1)
1467        } else if e.position.y > bottom {
1468            -((e.position.y - bottom).pow(1.1))
1469        } else {
1470            return None; //Nothing to do
1471        };
1472        Some(scroll_delta)
1473    }
1474
1475    pub fn mouse_down(
1476        &mut self,
1477        e: &MouseDownEvent,
1478        origin: Point<Pixels>,
1479        _cx: &mut ModelContext<Self>,
1480    ) {
1481        let position = e.position - origin;
1482        let point = grid_point(
1483            position,
1484            self.last_content.size,
1485            self.last_content.display_offset,
1486        );
1487
1488        if self.mouse_mode(e.modifiers.shift) {
1489            if let Some(bytes) =
1490                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1491            {
1492                self.pty_tx.notify(bytes);
1493            }
1494        } else {
1495            match e.button {
1496                MouseButton::Left => {
1497                    let position = e.position - origin;
1498                    let (point, side) = grid_point_and_side(
1499                        position,
1500                        self.last_content.size,
1501                        self.last_content.display_offset,
1502                    );
1503
1504                    let selection_type = match e.click_count {
1505                        0 => return, //This is a release
1506                        1 => Some(SelectionType::Simple),
1507                        2 => Some(SelectionType::Semantic),
1508                        3 => Some(SelectionType::Lines),
1509                        _ => None,
1510                    };
1511
1512                    let selection = selection_type
1513                        .map(|selection_type| Selection::new(selection_type, point, side));
1514
1515                    if let Some(sel) = selection {
1516                        self.events
1517                            .push_back(InternalEvent::SetSelection(Some((sel, point))));
1518                    }
1519                }
1520                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1521                MouseButton::Middle => {
1522                    if let Some(item) = _cx.read_from_primary() {
1523                        let text = item.text().unwrap_or_default().to_string();
1524                        self.input(text);
1525                    }
1526                }
1527                _ => {}
1528            }
1529        }
1530    }
1531
1532    pub fn mouse_up(&mut self, e: &MouseUpEvent, origin: Point<Pixels>, cx: &ModelContext<Self>) {
1533        let setting = TerminalSettings::get_global(cx);
1534
1535        let position = e.position - origin;
1536        if self.mouse_mode(e.modifiers.shift) {
1537            let point = grid_point(
1538                position,
1539                self.last_content.size,
1540                self.last_content.display_offset,
1541            );
1542
1543            if let Some(bytes) =
1544                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1545            {
1546                self.pty_tx.notify(bytes);
1547            }
1548        } else {
1549            if e.button == MouseButton::Left && setting.copy_on_select {
1550                self.copy();
1551            }
1552
1553            //Hyperlinks
1554            if self.selection_phase == SelectionPhase::Ended {
1555                let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1556                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1557                    cx.open_url(link.uri());
1558                } else if self.secondary_pressed {
1559                    self.events
1560                        .push_back(InternalEvent::FindHyperlink(position, true));
1561                }
1562            }
1563        }
1564
1565        self.selection_phase = SelectionPhase::Ended;
1566        self.last_mouse = None;
1567    }
1568
1569    ///Scroll the terminal
1570    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Point<Pixels>) {
1571        let mouse_mode = self.mouse_mode(e.shift);
1572
1573        if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1574            if mouse_mode {
1575                let point = grid_point(
1576                    e.position - origin,
1577                    self.last_content.size,
1578                    self.last_content.display_offset,
1579                );
1580
1581                if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1582                {
1583                    for scroll in scrolls {
1584                        self.pty_tx.notify(scroll);
1585                    }
1586                };
1587            } else if self
1588                .last_content
1589                .mode
1590                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1591                && !e.shift
1592            {
1593                self.pty_tx.notify(alt_scroll(scroll_lines))
1594            } else if scroll_lines != 0 {
1595                let scroll = AlacScroll::Delta(scroll_lines);
1596
1597                self.events.push_back(InternalEvent::Scroll(scroll));
1598            }
1599        }
1600    }
1601
1602    fn refresh_hovered_word(&mut self) {
1603        self.word_from_position(self.last_mouse_position);
1604    }
1605
1606    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1607        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1608        let line_height = self.last_content.size.line_height;
1609        match e.touch_phase {
1610            /* Reset scroll state on started */
1611            TouchPhase::Started => {
1612                self.scroll_px = px(0.);
1613                None
1614            }
1615            /* Calculate the appropriate scroll lines */
1616            TouchPhase::Moved => {
1617                let old_offset = (self.scroll_px / line_height) as i32;
1618
1619                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1620
1621                let new_offset = (self.scroll_px / line_height) as i32;
1622
1623                // Whenever we hit the edges, reset our stored scroll to 0
1624                // so we can respond to changes in direction quickly
1625                self.scroll_px %= self.last_content.size.height();
1626
1627                Some(new_offset - old_offset)
1628            }
1629            TouchPhase::Ended => None,
1630        }
1631    }
1632
1633    pub fn find_matches(
1634        &self,
1635        mut searcher: RegexSearch,
1636        cx: &ModelContext<Self>,
1637    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1638        let term = self.term.clone();
1639        cx.background_executor().spawn(async move {
1640            let term = term.lock();
1641
1642            all_search_matches(&term, &mut searcher).collect()
1643        })
1644    }
1645
1646    pub fn working_directory(&self) -> Option<PathBuf> {
1647        if self.is_ssh_terminal {
1648            // We can't yet reliably detect the working directory of a shell on the
1649            // SSH host. Until we can do that, it doesn't make sense to display
1650            // the working directory on the client and persist that.
1651            None
1652        } else {
1653            self.client_side_working_directory()
1654        }
1655    }
1656
1657    /// Returns the working directory of the process that's connected to the PTY.
1658    /// That means it returns the working directory of the local shell or program
1659    /// that's running inside the terminal.
1660    ///
1661    /// This does *not* return the working directory of the shell that runs on the
1662    /// remote host, in case Zed is connected to a remote host.
1663    fn client_side_working_directory(&self) -> Option<PathBuf> {
1664        self.pty_info
1665            .current
1666            .as_ref()
1667            .map(|process| process.cwd.clone())
1668    }
1669
1670    pub fn title(&self, truncate: bool) -> String {
1671        const MAX_CHARS: usize = 25;
1672        match &self.task {
1673            Some(task_state) => {
1674                if truncate {
1675                    truncate_and_trailoff(&task_state.label, MAX_CHARS)
1676                } else {
1677                    task_state.full_label.clone()
1678                }
1679            }
1680            None => self
1681                .title_override
1682                .as_ref()
1683                .map(|title_override| title_override.to_string())
1684                .unwrap_or_else(|| {
1685                    self.pty_info
1686                        .current
1687                        .as_ref()
1688                        .map(|fpi| {
1689                            let process_file = fpi
1690                                .cwd
1691                                .file_name()
1692                                .map(|name| name.to_string_lossy().to_string())
1693                                .unwrap_or_default();
1694
1695                            let argv = fpi.argv.clone();
1696                            let process_name = format!(
1697                                "{}{}",
1698                                fpi.name,
1699                                if !argv.is_empty() {
1700                                    format!(" {}", (argv[1..]).join(" "))
1701                                } else {
1702                                    "".to_string()
1703                                }
1704                            );
1705                            let (process_file, process_name) = if truncate {
1706                                (
1707                                    truncate_and_trailoff(&process_file, MAX_CHARS),
1708                                    truncate_and_trailoff(&process_name, MAX_CHARS),
1709                                )
1710                            } else {
1711                                (process_file, process_name)
1712                            };
1713                            format!("{process_file}{process_name}")
1714                        })
1715                        .unwrap_or_else(|| "Terminal".to_string())
1716                }),
1717        }
1718    }
1719
1720    pub fn can_navigate_to_selected_word(&self) -> bool {
1721        self.secondary_pressed && self.hovered_word
1722    }
1723
1724    pub fn task(&self) -> Option<&TaskState> {
1725        self.task.as_ref()
1726    }
1727
1728    pub fn wait_for_completed_task(&self, cx: &AppContext) -> Task<()> {
1729        if let Some(task) = self.task() {
1730            if task.status == TaskStatus::Running {
1731                let mut completion_receiver = task.completion_rx.clone();
1732                return cx.spawn(|_| async move {
1733                    completion_receiver.next().await;
1734                });
1735            }
1736        }
1737        Task::ready(())
1738    }
1739
1740    fn register_task_finished(
1741        &mut self,
1742        error_code: Option<i32>,
1743        cx: &mut ModelContext<'_, Terminal>,
1744    ) {
1745        self.completion_tx.try_send(()).ok();
1746        let task = match &mut self.task {
1747            Some(task) => task,
1748            None => {
1749                if error_code.is_none() {
1750                    cx.emit(Event::CloseTerminal);
1751                }
1752                return;
1753            }
1754        };
1755        if task.status != TaskStatus::Running {
1756            return;
1757        }
1758        match error_code {
1759            Some(error_code) => {
1760                task.status.register_task_exit(error_code);
1761            }
1762            None => {
1763                task.status.register_terminal_exit();
1764            }
1765        };
1766
1767        let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1768        let mut lines_to_show = Vec::new();
1769        if task.show_summary {
1770            lines_to_show.push(task_line.as_str());
1771        }
1772        if task.show_command {
1773            lines_to_show.push(command_line.as_str());
1774        }
1775
1776        if !lines_to_show.is_empty() {
1777            // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1778            // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1779            // when Zed task finishes and no more output is made.
1780            // After the task summary is output once, no more text is appended to the terminal.
1781            unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1782        }
1783
1784        match task.hide {
1785            HideStrategy::Never => {}
1786            HideStrategy::Always => {
1787                cx.emit(Event::CloseTerminal);
1788            }
1789            HideStrategy::OnSuccess => {
1790                if finished_successfully {
1791                    cx.emit(Event::CloseTerminal);
1792                }
1793            }
1794        }
1795    }
1796}
1797
1798const TASK_DELIMITER: &str = "";
1799fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1800    let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1801    let (success, task_line) = match error_code {
1802        Some(0) => {
1803            (true, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"))
1804        }
1805        Some(error_code) => {
1806            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"))
1807        }
1808        None => {
1809            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"))
1810        }
1811    };
1812    let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1813    let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1814    (success, task_line, command_line)
1815}
1816
1817/// Appends a stringified task summary to the terminal, after its output.
1818///
1819/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1820/// New text being added to the terminal here, uses "less public" APIs,
1821/// which are not maintaining the entire terminal state intact.
1822///
1823///
1824/// The library
1825///
1826/// * does not increment inner grid cursor's _lines_ on `input` calls
1827///   (but displaying the lines correctly and incrementing cursor's columns)
1828///
1829/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1830///
1831/// * does not alter grid state after `newline` call
1832///   so its `bottommost_line` is always the same additions, and
1833///   the cursor's `point` is not updated to the new line and column values
1834///
1835/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1836///   Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1837///
1838/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1839/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1840/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1841/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1842unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1843    term.newline();
1844    term.grid_mut().cursor.point.column = Column(0);
1845    for line in text_lines {
1846        for c in line.chars() {
1847            term.input(c);
1848        }
1849        term.newline();
1850        term.grid_mut().cursor.point.column = Column(0);
1851    }
1852}
1853
1854impl Drop for Terminal {
1855    fn drop(&mut self) {
1856        self.pty_tx.0.send(Msg::Shutdown).ok();
1857    }
1858}
1859
1860impl EventEmitter<Event> for Terminal {}
1861
1862/// Based on alacritty/src/display/hint.rs > regex_match_at
1863/// Retrieve the match, if the specified point is inside the content matching the regex.
1864fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1865    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1866}
1867
1868/// Copied from alacritty/src/display/hint.rs:
1869/// Iterate over all visible regex matches.
1870pub fn visible_regex_match_iter<'a, T>(
1871    term: &'a Term<T>,
1872    regex: &'a mut RegexSearch,
1873) -> impl Iterator<Item = Match> + 'a {
1874    let viewport_start = Line(-(term.grid().display_offset() as i32));
1875    let viewport_end = viewport_start + term.bottommost_line();
1876    let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1877    let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1878    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1879    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1880
1881    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1882        .skip_while(move |rm| rm.end().line < viewport_start)
1883        .take_while(move |rm| rm.start().line <= viewport_end)
1884}
1885
1886fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1887    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1888    selection.update(*range.end(), AlacDirection::Right);
1889    selection
1890}
1891
1892fn all_search_matches<'a, T>(
1893    term: &'a Term<T>,
1894    regex: &'a mut RegexSearch,
1895) -> impl Iterator<Item = Match> + 'a {
1896    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1897    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1898    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1899}
1900
1901fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1902    let col = (pos.x / size.cell_width()).round() as usize;
1903    let clamped_col = min(col, size.columns() - 1);
1904    let row = (pos.y / size.line_height()).round() as usize;
1905    let clamped_row = min(row, size.screen_lines() - 1);
1906    clamped_row * size.columns() + clamped_col
1907}
1908
1909/// Converts an 8 bit ANSI color to its GPUI equivalent.
1910/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1911/// Other than that use case, should only be called with values in the [0,255] range
1912pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1913    let colors = theme.colors();
1914
1915    match index {
1916        // 0-15 are the same as the named colors above
1917        0 => colors.terminal_ansi_black,
1918        1 => colors.terminal_ansi_red,
1919        2 => colors.terminal_ansi_green,
1920        3 => colors.terminal_ansi_yellow,
1921        4 => colors.terminal_ansi_blue,
1922        5 => colors.terminal_ansi_magenta,
1923        6 => colors.terminal_ansi_cyan,
1924        7 => colors.terminal_ansi_white,
1925        8 => colors.terminal_ansi_bright_black,
1926        9 => colors.terminal_ansi_bright_red,
1927        10 => colors.terminal_ansi_bright_green,
1928        11 => colors.terminal_ansi_bright_yellow,
1929        12 => colors.terminal_ansi_bright_blue,
1930        13 => colors.terminal_ansi_bright_magenta,
1931        14 => colors.terminal_ansi_bright_cyan,
1932        15 => colors.terminal_ansi_bright_white,
1933        // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1934        16..=231 => {
1935            let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1936            let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1937            rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1938        }
1939        // 232-255 are a 24 step grayscale from black to white
1940        232..=255 => {
1941            let i = index as u8 - 232; // Align index to 0..24
1942            let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1943            rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1944        }
1945        // For compatibility with the alacritty::Colors interface
1946        256 => colors.text,
1947        257 => colors.background,
1948        258 => theme.players().local().cursor,
1949        259 => colors.terminal_ansi_dim_black,
1950        260 => colors.terminal_ansi_dim_red,
1951        261 => colors.terminal_ansi_dim_green,
1952        262 => colors.terminal_ansi_dim_yellow,
1953        263 => colors.terminal_ansi_dim_blue,
1954        264 => colors.terminal_ansi_dim_magenta,
1955        265 => colors.terminal_ansi_dim_cyan,
1956        266 => colors.terminal_ansi_dim_white,
1957        267 => colors.terminal_bright_foreground,
1958        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1959
1960        _ => black(),
1961    }
1962}
1963
1964/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1965/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1966///
1967/// Wikipedia gives a formula for calculating the index for a given color:
1968///
1969/// ```
1970/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1971/// ```
1972///
1973/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1974fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1975    debug_assert!((16..=231).contains(&i));
1976    let i = i - 16;
1977    let r = (i - (i % 36)) / 36;
1978    let g = ((i % 36) - (i % 6)) / 6;
1979    let b = (i % 36) % 6;
1980    (r, g, b)
1981}
1982
1983pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1984    Rgba {
1985        r: (r as f32 / 255.),
1986        g: (g as f32 / 255.),
1987        b: (b as f32 / 255.),
1988        a: 1.,
1989    }
1990    .into()
1991}
1992
1993#[cfg(test)]
1994mod tests {
1995    use alacritty_terminal::{
1996        index::{Column, Line, Point as AlacPoint},
1997        term::cell::Cell,
1998    };
1999    use gpui::{point, size, Pixels};
2000    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
2001
2002    use crate::{
2003        content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
2004    };
2005
2006    #[test]
2007    fn test_rgb_for_index() {
2008        // Test every possible value in the color cube.
2009        for i in 16..=231 {
2010            let (r, g, b) = rgb_for_index(i);
2011            assert_eq!(i, 16 + 36 * r + 6 * g + b);
2012        }
2013    }
2014
2015    #[test]
2016    fn test_mouse_to_cell_test() {
2017        let mut rng = thread_rng();
2018        const ITERATIONS: usize = 10;
2019        const PRECISION: usize = 1000;
2020
2021        for _ in 0..ITERATIONS {
2022            let viewport_cells = rng.gen_range(15..20);
2023            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2024
2025            let size = crate::TerminalSize {
2026                cell_width: Pixels::from(cell_size),
2027                line_height: Pixels::from(cell_size),
2028                size: size(
2029                    Pixels::from(cell_size * (viewport_cells as f32)),
2030                    Pixels::from(cell_size * (viewport_cells as f32)),
2031                ),
2032            };
2033
2034            let cells = get_cells(size, &mut rng);
2035            let content = convert_cells_to_content(size, &cells);
2036
2037            for row in 0..(viewport_cells - 1) {
2038                let row = row as usize;
2039                for col in 0..(viewport_cells - 1) {
2040                    let col = col as usize;
2041
2042                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2043                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2044
2045                    let mouse_pos = point(
2046                        Pixels::from(col as f32 * cell_size + col_offset),
2047                        Pixels::from(row as f32 * cell_size + row_offset),
2048                    );
2049
2050                    let content_index = content_index_for_mouse(mouse_pos, &content.size);
2051                    let mouse_cell = content.cells[content_index].c;
2052                    let real_cell = cells[row][col];
2053
2054                    assert_eq!(mouse_cell, real_cell);
2055                }
2056            }
2057        }
2058    }
2059
2060    #[test]
2061    fn test_mouse_to_cell_clamp() {
2062        let mut rng = thread_rng();
2063
2064        let size = crate::TerminalSize {
2065            cell_width: Pixels::from(10.),
2066            line_height: Pixels::from(10.),
2067            size: size(Pixels::from(100.), Pixels::from(100.)),
2068        };
2069
2070        let cells = get_cells(size, &mut rng);
2071        let content = convert_cells_to_content(size, &cells);
2072
2073        assert_eq!(
2074            content.cells[content_index_for_mouse(
2075                point(Pixels::from(-10.), Pixels::from(-10.)),
2076                &content.size,
2077            )]
2078            .c,
2079            cells[0][0]
2080        );
2081        assert_eq!(
2082            content.cells[content_index_for_mouse(
2083                point(Pixels::from(1000.), Pixels::from(1000.)),
2084                &content.size,
2085            )]
2086            .c,
2087            cells[9][9]
2088        );
2089    }
2090
2091    fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2092        let mut cells = Vec::new();
2093
2094        for _ in 0..((size.height() / size.line_height()) as usize) {
2095            let mut row_vec = Vec::new();
2096            for _ in 0..((size.width() / size.cell_width()) as usize) {
2097                let cell_char = rng.sample(Alphanumeric) as char;
2098                row_vec.push(cell_char)
2099            }
2100            cells.push(row_vec)
2101        }
2102
2103        cells
2104    }
2105
2106    fn convert_cells_to_content(size: TerminalSize, cells: &[Vec<char>]) -> TerminalContent {
2107        let mut ic = Vec::new();
2108
2109        for (index, row) in cells.iter().enumerate() {
2110            for (cell_index, cell_char) in row.iter().enumerate() {
2111                ic.push(IndexedCell {
2112                    point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2113                    cell: Cell {
2114                        c: *cell_char,
2115                        ..Default::default()
2116                    },
2117                });
2118            }
2119        }
2120
2121        TerminalContent {
2122            cells: ic,
2123            size,
2124            ..Default::default()
2125        }
2126    }
2127
2128    fn re_test(re: &str, hay: &str, expected: Vec<&str>) {
2129        let results: Vec<_> = regex::Regex::new(re)
2130            .unwrap()
2131            .find_iter(hay)
2132            .map(|m| m.as_str())
2133            .collect();
2134        assert_eq!(results, expected);
2135    }
2136    #[test]
2137    fn test_url_regex() {
2138        re_test(
2139            crate::URL_REGEX,
2140            "test http://example.com test mailto:bob@example.com train",
2141            vec!["http://example.com", "mailto:bob@example.com"],
2142        );
2143    }
2144    #[test]
2145    fn test_word_regex() {
2146        re_test(
2147            crate::WORD_REGEX,
2148            "hello, world! \"What\" is this?",
2149            vec!["hello", "world", "What", "is", "this"],
2150        );
2151    }
2152    #[test]
2153    fn test_word_regex_with_linenum() {
2154        // filename(line) and filename(line,col) as used in MSBuild output
2155        // should be considered a single "word", even though comma is
2156        // usually a word separator
2157        re_test(
2158            crate::WORD_REGEX,
2159            "a Main.cs(20) b",
2160            vec!["a", "Main.cs(20)", "b"],
2161        );
2162        re_test(
2163            crate::WORD_REGEX,
2164            "Main.cs(20,5) Error desc",
2165            vec!["Main.cs(20,5)", "Error", "desc"],
2166        );
2167        // filename:line:col is a popular format for unix tools
2168        re_test(
2169            crate::WORD_REGEX,
2170            "a Main.cs:20:5 b",
2171            vec!["a", "Main.cs:20:5", "b"],
2172        );
2173        // Some tools output "filename:line:col:message", which currently isn't
2174        // handled correctly, but might be in the future
2175        re_test(
2176            crate::WORD_REGEX,
2177            "Main.cs:20:5:Error desc",
2178            vec!["Main.cs:20:5:Error", "desc"],
2179        );
2180    }
2181}