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