terminal.rs

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