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