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