terminal.rs

   1pub mod mappings;
   2pub use alacritty_terminal;
   3pub mod terminal_settings;
   4
   5use alacritty_terminal::{
   6    ansi::{ClearMode, Handler},
   7    config::{Config, Program, PtyConfig, Scrolling},
   8    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
   9    event_loop::{EventLoop, Msg, Notifier},
  10    grid::{Dimensions, Scroll as AlacScroll},
  11    index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
  12    selection::{Selection, SelectionRange, SelectionType},
  13    sync::FairMutex,
  14    term::{
  15        cell::Cell,
  16        color::Rgb,
  17        search::{Match, RegexIter, RegexSearch},
  18        RenderableCursor, TermMode,
  19    },
  20    tty::{self, setup_env},
  21    Term,
  22};
  23use anyhow::{bail, Result};
  24
  25use futures::{
  26    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
  27    FutureExt,
  28};
  29
  30use mappings::mouse::{
  31    alt_scroll, grid_point, mouse_button_report, mouse_moved_report, mouse_side, scroll_report,
  32};
  33
  34use procinfo::LocalProcessInfo;
  35use serde::{Deserialize, Serialize};
  36use settings::Settings;
  37use terminal_settings::{AlternateScroll, Shell, TerminalBlink, TerminalSettings};
  38use theme::{ActiveTheme, Theme};
  39use util::truncate_and_trailoff;
  40
  41use std::{
  42    cmp::{self, min},
  43    collections::{HashMap, VecDeque},
  44    fmt::Display,
  45    ops::{Deref, Index, RangeInclusive},
  46    os::unix::prelude::AsRawFd,
  47    path::PathBuf,
  48    sync::Arc,
  49    time::{Duration, Instant},
  50};
  51use thiserror::Error;
  52
  53use gpui::{
  54    actions, black, px, red, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter,
  55    Hsla, Keystroke, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent,
  56    MouseUpEvent, Pixels, Point, Rgba, ScrollWheelEvent, Size, Task, TouchPhase,
  57};
  58
  59use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
  60use lazy_static::lazy_static;
  61
  62actions!(
  63    terminal,
  64    [
  65        Clear,
  66        Copy,
  67        Paste,
  68        ShowCharacterPalette,
  69        SearchTest,
  70        SendText,
  71        SendKeystroke,
  72    ]
  73);
  74
  75///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  76///Scroll multiplier that is set to 3 by default. This will be removed when I
  77///Implement scroll bars.
  78const SCROLL_MULTIPLIER: f32 = 4.;
  79const MAX_SEARCH_LINES: usize = 100;
  80const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
  81const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
  82const DEBUG_CELL_WIDTH: Pixels = px(5.);
  83const DEBUG_LINE_HEIGHT: Pixels = px(5.);
  84
  85lazy_static! {
  86    // Regex Copied from alacritty's ui_config.rs and modified its declaration slightly:
  87    // * avoid Rust-specific escaping.
  88    // * use more strict regex for `file://` protocol matching: original regex has `file:` inside, but we want to avoid matching `some::file::module` strings.
  89    static ref URL_REGEX: RegexSearch = RegexSearch::new(r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`]+"#).unwrap();
  90
  91    static ref WORD_REGEX: RegexSearch = RegexSearch::new(r#"[\w.\[\]:/@\-~]+"#).unwrap();
  92}
  93
  94///Upward flowing events, for changing the title and such
  95#[derive(Clone, Debug)]
  96pub enum Event {
  97    TitleChanged,
  98    BreadcrumbsChanged,
  99    CloseTerminal,
 100    Bell,
 101    Wakeup,
 102    BlinkChanged,
 103    SelectionsChanged,
 104    NewNavigationTarget(Option<MaybeNavigationTarget>),
 105    Open(MaybeNavigationTarget),
 106}
 107
 108/// A string inside terminal, potentially useful as a URI that can be opened.
 109#[derive(Clone, Debug)]
 110pub enum MaybeNavigationTarget {
 111    /// HTTP, git, etc. string determined by the [`URL_REGEX`] regex.
 112    Url(String),
 113    /// File system path, absolute or relative, existing or not.
 114    /// Might have line and column number(s) attached as `file.rs:1:23`
 115    PathLike(String),
 116}
 117
 118#[derive(Clone)]
 119enum InternalEvent {
 120    ColorRequest(usize, Arc<dyn Fn(Rgb) -> String + Sync + Send + 'static>),
 121    Resize(TerminalSize),
 122    Clear,
 123    // FocusNextMatch,
 124    Scroll(AlacScroll),
 125    ScrollToAlacPoint(AlacPoint),
 126    SetSelection(Option<(Selection, AlacPoint)>),
 127    UpdateSelection(Point<Pixels>),
 128    // Adjusted mouse position, should open
 129    FindHyperlink(Point<Pixels>, bool),
 130    Copy,
 131}
 132
 133///A translation struct for Alacritty to communicate with us from their event loop
 134#[derive(Clone)]
 135pub struct ZedListener(UnboundedSender<AlacTermEvent>);
 136
 137impl EventListener for ZedListener {
 138    fn send_event(&self, event: AlacTermEvent) {
 139        self.0.unbounded_send(event).ok();
 140    }
 141}
 142
 143pub fn init(cx: &mut AppContext) {
 144    TerminalSettings::register(cx);
 145}
 146
 147#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
 148pub struct TerminalSize {
 149    pub cell_width: Pixels,
 150    pub line_height: Pixels,
 151    pub size: Size<Pixels>,
 152}
 153
 154impl TerminalSize {
 155    pub fn new(line_height: Pixels, cell_width: Pixels, size: Size<Pixels>) -> Self {
 156        TerminalSize {
 157            cell_width,
 158            line_height,
 159            size,
 160        }
 161    }
 162
 163    pub fn num_lines(&self) -> usize {
 164        f32::from((self.size.height / self.line_height).floor()) as usize
 165    }
 166
 167    pub fn num_columns(&self) -> usize {
 168        f32::from((self.size.width / self.cell_width).floor()) as usize
 169    }
 170
 171    pub fn height(&self) -> Pixels {
 172        self.size.height
 173    }
 174
 175    pub fn width(&self) -> Pixels {
 176        self.size.width
 177    }
 178
 179    pub fn cell_width(&self) -> Pixels {
 180        self.cell_width
 181    }
 182
 183    pub fn line_height(&self) -> Pixels {
 184        self.line_height
 185    }
 186}
 187impl Default for TerminalSize {
 188    fn default() -> Self {
 189        TerminalSize::new(
 190            DEBUG_LINE_HEIGHT,
 191            DEBUG_CELL_WIDTH,
 192            Size {
 193                width: DEBUG_TERMINAL_WIDTH,
 194                height: DEBUG_TERMINAL_HEIGHT,
 195            },
 196        )
 197    }
 198}
 199
 200impl From<TerminalSize> for WindowSize {
 201    fn from(val: TerminalSize) -> Self {
 202        WindowSize {
 203            num_lines: val.num_lines() as u16,
 204            num_cols: val.num_columns() as u16,
 205            cell_width: f32::from(val.cell_width()) as u16,
 206            cell_height: f32::from(val.line_height()) as u16,
 207        }
 208    }
 209}
 210
 211impl Dimensions for TerminalSize {
 212    /// Note: this is supposed to be for the back buffer's length,
 213    /// but we exclusively use it to resize the terminal, which does not
 214    /// use this method. We still have to implement it for the trait though,
 215    /// hence, this comment.
 216    fn total_lines(&self) -> usize {
 217        self.screen_lines()
 218    }
 219
 220    fn screen_lines(&self) -> usize {
 221        self.num_lines()
 222    }
 223
 224    fn columns(&self) -> usize {
 225        self.num_columns()
 226    }
 227}
 228
 229#[derive(Error, Debug)]
 230pub struct TerminalError {
 231    pub directory: Option<PathBuf>,
 232    pub shell: Shell,
 233    pub source: std::io::Error,
 234}
 235
 236impl TerminalError {
 237    pub fn fmt_directory(&self) -> String {
 238        self.directory
 239            .clone()
 240            .map(|path| {
 241                match path
 242                    .into_os_string()
 243                    .into_string()
 244                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 245                {
 246                    Ok(s) => s,
 247                    Err(s) => s,
 248                }
 249            })
 250            .unwrap_or_else(|| {
 251                let default_dir =
 252                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
 253                match default_dir {
 254                    Some(dir) => format!("<none specified, using home directory> {}", dir),
 255                    None => "<none specified, could not find home directory>".to_string(),
 256                }
 257            })
 258    }
 259
 260    pub fn shell_to_string(&self) -> String {
 261        match &self.shell {
 262            Shell::System => "<system shell>".to_string(),
 263            Shell::Program(p) => p.to_string(),
 264            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 265        }
 266    }
 267
 268    pub fn fmt_shell(&self) -> String {
 269        match &self.shell {
 270            Shell::System => "<system defined shell>".to_string(),
 271            Shell::Program(s) => s.to_string(),
 272            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 273        }
 274    }
 275}
 276
 277impl Display for TerminalError {
 278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 279        let dir_string: String = self.fmt_directory();
 280        let shell = self.fmt_shell();
 281
 282        write!(
 283            f,
 284            "Working directory: {} Shell command: `{}`, IOError: {}",
 285            dir_string, shell, self.source
 286        )
 287    }
 288}
 289
 290pub struct TerminalBuilder {
 291    terminal: Terminal,
 292    events_rx: UnboundedReceiver<AlacTermEvent>,
 293}
 294
 295impl TerminalBuilder {
 296    pub fn new(
 297        working_directory: Option<PathBuf>,
 298        shell: Shell,
 299        mut env: HashMap<String, String>,
 300        blink_settings: Option<TerminalBlink>,
 301        alternate_scroll: AlternateScroll,
 302        window: AnyWindowHandle,
 303    ) -> Result<TerminalBuilder> {
 304        let pty_config = {
 305            let alac_shell = match shell.clone() {
 306                Shell::System => None,
 307                Shell::Program(program) => Some(Program::Just(program)),
 308                Shell::WithArguments { program, args } => Some(Program::WithArgs { program, args }),
 309            };
 310
 311            PtyConfig {
 312                shell: alac_shell,
 313                working_directory: working_directory.clone(),
 314                hold: false,
 315            }
 316        };
 317
 318        //TODO: Properly set the current locale,
 319        env.insert("LC_ALL".to_string(), "en_US.UTF-8".to_string());
 320        env.insert("ZED_TERM".to_string(), true.to_string());
 321
 322        let alac_scrolling = Scrolling::default();
 323        // alac_scrolling.set_history((BACK_BUFFER_SIZE * 2) as u32);
 324
 325        let config = Config {
 326            pty_config: pty_config.clone(),
 327            env,
 328            scrolling: alac_scrolling,
 329            ..Default::default()
 330        };
 331
 332        setup_env(&config);
 333
 334        //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
 335        //TODO: Remove with a bounded sender which can be dispatched on &self
 336        let (events_tx, events_rx) = unbounded();
 337        //Set up the terminal...
 338        let mut term = Term::new(
 339            &config,
 340            &TerminalSize::default(),
 341            ZedListener(events_tx.clone()),
 342        );
 343
 344        //Start off blinking if we need to
 345        if let Some(TerminalBlink::On) = blink_settings {
 346            term.set_mode(alacritty_terminal::ansi::Mode::BlinkingCursor)
 347        }
 348
 349        //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
 350        if let AlternateScroll::Off = alternate_scroll {
 351            term.unset_mode(alacritty_terminal::ansi::Mode::AlternateScroll)
 352        }
 353
 354        let term = Arc::new(FairMutex::new(term));
 355
 356        //Setup the pty...
 357        let pty = match tty::new(
 358            &pty_config,
 359            TerminalSize::default().into(),
 360            window.window_id().as_u64(),
 361        ) {
 362            Ok(pty) => pty,
 363            Err(error) => {
 364                bail!(TerminalError {
 365                    directory: working_directory,
 366                    shell,
 367                    source: error,
 368                });
 369            }
 370        };
 371
 372        let fd = pty.file().as_raw_fd();
 373        let shell_pid = pty.child().id();
 374
 375        //And connect them together
 376        let event_loop = EventLoop::new(
 377            term.clone(),
 378            ZedListener(events_tx.clone()),
 379            pty,
 380            pty_config.hold,
 381            false,
 382        );
 383
 384        //Kick things off
 385        let pty_tx = event_loop.channel();
 386        let _io_thread = event_loop.spawn();
 387
 388        let terminal = Terminal {
 389            pty_tx: Notifier(pty_tx),
 390            term,
 391            events: VecDeque::with_capacity(10), //Should never get this high.
 392            last_content: Default::default(),
 393            last_mouse: None,
 394            matches: Vec::new(),
 395            last_synced: Instant::now(),
 396            sync_task: None,
 397            selection_head: None,
 398            shell_fd: fd as u32,
 399            shell_pid,
 400            foreground_process_info: None,
 401            breadcrumb_text: String::new(),
 402            scroll_px: px(0.),
 403            last_mouse_position: None,
 404            next_link_id: 0,
 405            selection_phase: SelectionPhase::Ended,
 406            cmd_pressed: false,
 407            hovered_word: false,
 408        };
 409
 410        Ok(TerminalBuilder {
 411            terminal,
 412            events_rx,
 413        })
 414    }
 415
 416    pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
 417        //Event loop
 418        cx.spawn(|this, mut cx| async move {
 419            use futures::StreamExt;
 420
 421            while let Some(event) = self.events_rx.next().await {
 422                this.update(&mut cx, |this, cx| {
 423                    //Process the first event immediately for lowered latency
 424                    this.process_event(&event, cx);
 425                })?;
 426
 427                'outer: loop {
 428                    let mut events = vec![];
 429                    let mut timer = cx
 430                        .background_executor()
 431                        .timer(Duration::from_millis(4))
 432                        .fuse();
 433                    let mut wakeup = false;
 434                    loop {
 435                        futures::select_biased! {
 436                            _ = timer => break,
 437                            event = self.events_rx.next() => {
 438                                if let Some(event) = event {
 439                                    if matches!(event, AlacTermEvent::Wakeup) {
 440                                        wakeup = true;
 441                                    } else {
 442                                        events.push(event);
 443                                    }
 444
 445                                    if events.len() > 100 {
 446                                        break;
 447                                    }
 448                                } else {
 449                                    break;
 450                                }
 451                            },
 452                        }
 453                    }
 454
 455                    if events.is_empty() && wakeup == false {
 456                        smol::future::yield_now().await;
 457                        break 'outer;
 458                    } else {
 459                        this.update(&mut cx, |this, cx| {
 460                            if wakeup {
 461                                this.process_event(&AlacTermEvent::Wakeup, cx);
 462                            }
 463
 464                            for event in events {
 465                                this.process_event(&event, cx);
 466                            }
 467                        })?;
 468                        smol::future::yield_now().await;
 469                    }
 470                }
 471            }
 472
 473            anyhow::Ok(())
 474        })
 475        .detach();
 476
 477        self.terminal
 478    }
 479}
 480
 481#[derive(Debug, Clone, Deserialize, Serialize)]
 482pub struct IndexedCell {
 483    pub point: AlacPoint,
 484    pub cell: Cell,
 485}
 486
 487impl Deref for IndexedCell {
 488    type Target = Cell;
 489
 490    #[inline]
 491    fn deref(&self) -> &Cell {
 492        &self.cell
 493    }
 494}
 495
 496// TODO: Un-pub
 497#[derive(Clone)]
 498pub struct TerminalContent {
 499    pub cells: Vec<IndexedCell>,
 500    pub mode: TermMode,
 501    pub display_offset: usize,
 502    pub selection_text: Option<String>,
 503    pub selection: Option<SelectionRange>,
 504    pub cursor: RenderableCursor,
 505    pub cursor_char: char,
 506    pub size: TerminalSize,
 507    pub last_hovered_word: Option<HoveredWord>,
 508}
 509
 510#[derive(Clone)]
 511pub struct HoveredWord {
 512    pub word: String,
 513    pub word_match: RangeInclusive<AlacPoint>,
 514    pub id: usize,
 515}
 516
 517impl Default for TerminalContent {
 518    fn default() -> Self {
 519        TerminalContent {
 520            cells: Default::default(),
 521            mode: Default::default(),
 522            display_offset: Default::default(),
 523            selection_text: Default::default(),
 524            selection: Default::default(),
 525            cursor: RenderableCursor {
 526                shape: alacritty_terminal::ansi::CursorShape::Block,
 527                point: AlacPoint::new(Line(0), Column(0)),
 528            },
 529            cursor_char: Default::default(),
 530            size: Default::default(),
 531            last_hovered_word: None,
 532        }
 533    }
 534}
 535
 536#[derive(PartialEq, Eq)]
 537pub enum SelectionPhase {
 538    Selecting,
 539    Ended,
 540}
 541
 542pub struct Terminal {
 543    pty_tx: Notifier,
 544    term: Arc<FairMutex<Term<ZedListener>>>,
 545    events: VecDeque<InternalEvent>,
 546    /// This is only used for mouse mode cell change detection
 547    last_mouse: Option<(AlacPoint, AlacDirection)>,
 548    /// This is only used for terminal hovered word checking
 549    last_mouse_position: Option<Point<Pixels>>,
 550    pub matches: Vec<RangeInclusive<AlacPoint>>,
 551    pub last_content: TerminalContent,
 552    last_synced: Instant,
 553    sync_task: Option<Task<()>>,
 554    pub selection_head: Option<AlacPoint>,
 555    pub breadcrumb_text: String,
 556    shell_pid: u32,
 557    shell_fd: u32,
 558    pub foreground_process_info: Option<LocalProcessInfo>,
 559    scroll_px: Pixels,
 560    next_link_id: usize,
 561    selection_phase: SelectionPhase,
 562    cmd_pressed: bool,
 563    hovered_word: bool,
 564}
 565
 566impl Terminal {
 567    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
 568        match event {
 569            AlacTermEvent::Title(title) => {
 570                self.breadcrumb_text = title.to_string();
 571                cx.emit(Event::BreadcrumbsChanged);
 572            }
 573            AlacTermEvent::ResetTitle => {
 574                self.breadcrumb_text = String::new();
 575                cx.emit(Event::BreadcrumbsChanged);
 576            }
 577            AlacTermEvent::ClipboardStore(_, data) => {
 578                cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
 579            }
 580            AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
 581                &cx.read_from_clipboard()
 582                    .map(|ci| ci.text().to_string())
 583                    .unwrap_or_else(|| "".to_string()),
 584            )),
 585            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 586            AlacTermEvent::TextAreaSizeRequest(format) => {
 587                self.write_to_pty(format(self.last_content.size.into()))
 588            }
 589            AlacTermEvent::CursorBlinkingChange => {
 590                cx.emit(Event::BlinkChanged);
 591            }
 592            AlacTermEvent::Bell => {
 593                cx.emit(Event::Bell);
 594            }
 595            AlacTermEvent::Exit => cx.emit(Event::CloseTerminal),
 596            AlacTermEvent::MouseCursorDirty => {
 597                //NOOP, Handled in render
 598            }
 599            AlacTermEvent::Wakeup => {
 600                cx.emit(Event::Wakeup);
 601
 602                if self.update_process_info() {
 603                    cx.emit(Event::TitleChanged);
 604                }
 605            }
 606            AlacTermEvent::ColorRequest(idx, fun_ptr) => {
 607                self.events
 608                    .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
 609            }
 610        }
 611    }
 612
 613    /// Update the cached process info, returns whether the Zed-relevant info has changed
 614    fn update_process_info(&mut self) -> bool {
 615        let mut pid = unsafe { libc::tcgetpgrp(self.shell_fd as i32) };
 616        if pid < 0 {
 617            pid = self.shell_pid as i32;
 618        }
 619
 620        if let Some(process_info) = LocalProcessInfo::with_root_pid(pid as u32) {
 621            let res = self
 622                .foreground_process_info
 623                .as_ref()
 624                .map(|old_info| {
 625                    process_info.cwd != old_info.cwd || process_info.name != old_info.name
 626                })
 627                .unwrap_or(true);
 628
 629            self.foreground_process_info = Some(process_info.clone());
 630
 631            res
 632        } else {
 633            false
 634        }
 635    }
 636
 637    ///Takes events from Alacritty and translates them to behavior on this view
 638    fn process_terminal_event(
 639        &mut self,
 640        event: &InternalEvent,
 641        term: &mut Term<ZedListener>,
 642        cx: &mut ModelContext<Self>,
 643    ) {
 644        match event {
 645            InternalEvent::ColorRequest(index, format) => {
 646                let color = term.colors()[*index].unwrap_or_else(|| {
 647                    to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
 648                });
 649                self.write_to_pty(format(color))
 650            }
 651            InternalEvent::Resize(mut new_size) => {
 652                new_size.size.height = cmp::max(new_size.line_height, new_size.height());
 653                new_size.size.width = cmp::max(new_size.cell_width, new_size.width());
 654
 655                self.last_content.size = new_size.clone();
 656
 657                self.pty_tx.0.send(Msg::Resize(new_size.into())).ok();
 658
 659                term.resize(new_size);
 660            }
 661            InternalEvent::Clear => {
 662                // Clear back buffer
 663                term.clear_screen(ClearMode::Saved);
 664
 665                let cursor = term.grid().cursor.point;
 666
 667                // Clear the lines above
 668                term.grid_mut().reset_region(..cursor.line);
 669
 670                // Copy the current line up
 671                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 672                    .iter()
 673                    .cloned()
 674                    .enumerate()
 675                    .collect::<Vec<(usize, Cell)>>();
 676
 677                for (i, cell) in line {
 678                    term.grid_mut()[Line(0)][Column(i)] = cell;
 679                }
 680
 681                // Reset the cursor
 682                term.grid_mut().cursor.point =
 683                    AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
 684                let new_cursor = term.grid().cursor.point;
 685
 686                // Clear the lines below the new cursor
 687                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 688                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 689                }
 690
 691                cx.emit(Event::Wakeup);
 692            }
 693            InternalEvent::Scroll(scroll) => {
 694                term.scroll_display(*scroll);
 695                self.refresh_hovered_word();
 696            }
 697            InternalEvent::SetSelection(selection) => {
 698                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 699
 700                if let Some((_, head)) = selection {
 701                    self.selection_head = Some(*head);
 702                }
 703                cx.emit(Event::SelectionsChanged)
 704            }
 705            InternalEvent::UpdateSelection(position) => {
 706                if let Some(mut selection) = term.selection.take() {
 707                    let point = grid_point(
 708                        *position,
 709                        self.last_content.size,
 710                        term.grid().display_offset(),
 711                    );
 712
 713                    let side = mouse_side(*position, self.last_content.size);
 714
 715                    selection.update(point, side);
 716                    term.selection = Some(selection);
 717
 718                    self.selection_head = Some(point);
 719                    cx.emit(Event::SelectionsChanged)
 720                }
 721            }
 722
 723            InternalEvent::Copy => {
 724                if let Some(txt) = term.selection_to_string() {
 725                    cx.write_to_clipboard(ClipboardItem::new(txt))
 726                }
 727            }
 728            InternalEvent::ScrollToAlacPoint(point) => {
 729                term.scroll_to_point(*point);
 730                self.refresh_hovered_word();
 731            }
 732            InternalEvent::FindHyperlink(position, open) => {
 733                let prev_hovered_word = self.last_content.last_hovered_word.take();
 734
 735                let point = grid_point(
 736                    *position,
 737                    self.last_content.size,
 738                    term.grid().display_offset(),
 739                )
 740                .grid_clamp(term, Boundary::Grid);
 741
 742                let link = term.grid().index(point).hyperlink();
 743                let found_word = if link.is_some() {
 744                    let mut min_index = point;
 745                    loop {
 746                        let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
 747                        if new_min_index == min_index {
 748                            break;
 749                        } else if term.grid().index(new_min_index).hyperlink() != link {
 750                            break;
 751                        } else {
 752                            min_index = new_min_index
 753                        }
 754                    }
 755
 756                    let mut max_index = point;
 757                    loop {
 758                        let new_max_index = max_index.add(term, Boundary::Cursor, 1);
 759                        if new_max_index == max_index {
 760                            break;
 761                        } else if term.grid().index(new_max_index).hyperlink() != link {
 762                            break;
 763                        } else {
 764                            max_index = new_max_index
 765                        }
 766                    }
 767
 768                    let url = link.unwrap().uri().to_owned();
 769                    let url_match = min_index..=max_index;
 770
 771                    Some((url, true, url_match))
 772                } else if let Some(word_match) = regex_match_at(term, point, &WORD_REGEX) {
 773                    let maybe_url_or_path =
 774                        term.bounds_to_string(*word_match.start(), *word_match.end());
 775                    let original_match = word_match.clone();
 776                    let (sanitized_match, sanitized_word) =
 777                        if maybe_url_or_path.starts_with('[') && maybe_url_or_path.ends_with(']') {
 778                            (
 779                                Match::new(
 780                                    word_match.start().add(term, Boundary::Cursor, 1),
 781                                    word_match.end().sub(term, Boundary::Cursor, 1),
 782                                ),
 783                                maybe_url_or_path[1..maybe_url_or_path.len() - 1].to_owned(),
 784                            )
 785                        } else {
 786                            (word_match, maybe_url_or_path)
 787                        };
 788
 789                    let is_url = match regex_match_at(term, point, &URL_REGEX) {
 790                        Some(url_match) => {
 791                            // `]` is a valid symbol in the `file://` URL, so the regex match will include it
 792                            // consider that when ensuring that the URL match is the same as the original word
 793                            if sanitized_match != original_match {
 794                                url_match.start() == sanitized_match.start()
 795                                    && url_match.end() == original_match.end()
 796                            } else {
 797                                url_match == sanitized_match
 798                            }
 799                        }
 800                        None => false,
 801                    };
 802                    Some((sanitized_word, is_url, sanitized_match))
 803                } else {
 804                    None
 805                };
 806
 807                match found_word {
 808                    Some((maybe_url_or_path, is_url, url_match)) => {
 809                        if *open {
 810                            let target = if is_url {
 811                                MaybeNavigationTarget::Url(maybe_url_or_path)
 812                            } else {
 813                                MaybeNavigationTarget::PathLike(maybe_url_or_path)
 814                            };
 815                            cx.emit(Event::Open(target));
 816                        } else {
 817                            self.update_selected_word(
 818                                prev_hovered_word,
 819                                url_match,
 820                                maybe_url_or_path,
 821                                is_url,
 822                                cx,
 823                            );
 824                        }
 825                        self.hovered_word = true;
 826                    }
 827                    None => {
 828                        if self.hovered_word {
 829                            cx.emit(Event::NewNavigationTarget(None));
 830                        }
 831                        self.hovered_word = false;
 832                    }
 833                }
 834            }
 835        }
 836    }
 837
 838    fn update_selected_word(
 839        &mut self,
 840        prev_word: Option<HoveredWord>,
 841        word_match: RangeInclusive<AlacPoint>,
 842        word: String,
 843        is_url: bool,
 844        cx: &mut ModelContext<Self>,
 845    ) {
 846        if let Some(prev_word) = prev_word {
 847            if prev_word.word == word && prev_word.word_match == word_match {
 848                self.last_content.last_hovered_word = Some(HoveredWord {
 849                    word,
 850                    word_match,
 851                    id: prev_word.id,
 852                });
 853                return;
 854            }
 855        }
 856
 857        self.last_content.last_hovered_word = Some(HoveredWord {
 858            word: word.clone(),
 859            word_match,
 860            id: self.next_link_id(),
 861        });
 862        let navigation_target = if is_url {
 863            MaybeNavigationTarget::Url(word)
 864        } else {
 865            MaybeNavigationTarget::PathLike(word)
 866        };
 867        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
 868    }
 869
 870    fn next_link_id(&mut self) -> usize {
 871        let res = self.next_link_id;
 872        self.next_link_id = self.next_link_id.wrapping_add(1);
 873        res
 874    }
 875
 876    pub fn last_content(&self) -> &TerminalContent {
 877        &self.last_content
 878    }
 879
 880    //To test:
 881    //- Activate match on terminal (scrolling and selection)
 882    //- Editor search snapping behavior
 883
 884    pub fn activate_match(&mut self, index: usize) {
 885        if let Some(search_match) = self.matches.get(index).cloned() {
 886            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 887
 888            self.events
 889                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
 890        }
 891    }
 892
 893    pub fn select_matches(&mut self, matches: Vec<RangeInclusive<AlacPoint>>) {
 894        let matches_to_select = self
 895            .matches
 896            .iter()
 897            .filter(|self_match| matches.contains(self_match))
 898            .cloned()
 899            .collect::<Vec<_>>();
 900        for match_to_select in matches_to_select {
 901            self.set_selection(Some((
 902                make_selection(&match_to_select),
 903                *match_to_select.end(),
 904            )));
 905        }
 906    }
 907
 908    pub fn select_all(&mut self) {
 909        let term = self.term.lock();
 910        let start = AlacPoint::new(term.topmost_line(), Column(0));
 911        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
 912        drop(term);
 913        self.set_selection(Some((make_selection(&(start..=end)), end)));
 914    }
 915
 916    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
 917        self.events
 918            .push_back(InternalEvent::SetSelection(selection));
 919    }
 920
 921    pub fn copy(&mut self) {
 922        self.events.push_back(InternalEvent::Copy);
 923    }
 924
 925    pub fn clear(&mut self) {
 926        self.events.push_back(InternalEvent::Clear)
 927    }
 928
 929    ///Resize the terminal and the PTY.
 930    pub fn set_size(&mut self, new_size: TerminalSize) {
 931        self.events.push_back(InternalEvent::Resize(new_size))
 932    }
 933
 934    ///Write the Input payload to the tty.
 935    fn write_to_pty(&self, input: String) {
 936        self.pty_tx.notify(input.into_bytes());
 937    }
 938
 939    fn write_bytes_to_pty(&self, input: Vec<u8>) {
 940        self.pty_tx.notify(input);
 941    }
 942
 943    pub fn input(&mut self, input: String) {
 944        self.events
 945            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
 946        self.events.push_back(InternalEvent::SetSelection(None));
 947
 948        self.write_to_pty(input);
 949    }
 950
 951    pub fn input_bytes(&mut self, input: Vec<u8>) {
 952        self.events
 953            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
 954        self.events.push_back(InternalEvent::SetSelection(None));
 955
 956        self.write_bytes_to_pty(input);
 957    }
 958
 959    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
 960        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
 961        if let Some(esc) = esc {
 962            self.input(esc);
 963            true
 964        } else {
 965            false
 966        }
 967    }
 968
 969    pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
 970        let changed = self.cmd_pressed != modifiers.command;
 971        if !self.cmd_pressed && modifiers.command {
 972            self.refresh_hovered_word();
 973        }
 974        self.cmd_pressed = modifiers.command;
 975        changed
 976    }
 977
 978    ///Paste text into the terminal
 979    pub fn paste(&mut self, text: &str) {
 980        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
 981            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
 982        } else {
 983            text.replace("\r\n", "\r").replace('\n', "\r")
 984        };
 985
 986        self.input(paste_text);
 987    }
 988
 989    pub fn try_sync(&mut self, cx: &mut ModelContext<Self>) {
 990        let term = self.term.clone();
 991
 992        let mut terminal = if let Some(term) = term.try_lock_unfair() {
 993            term
 994        } else if self.last_synced.elapsed().as_secs_f32() > 0.25 {
 995            term.lock_unfair() //It's been too long, force block
 996        } else if let None = self.sync_task {
 997            //Skip this frame
 998            let delay = cx.background_executor().timer(Duration::from_millis(16));
 999            self.sync_task = Some(cx.spawn(|weak_handle, mut cx| async move {
1000                delay.await;
1001                if let Some(handle) = weak_handle.upgrade() {
1002                    handle
1003                        .update(&mut cx, |terminal, cx| {
1004                            terminal.sync_task.take();
1005                            cx.notify();
1006                        })
1007                        .ok();
1008                }
1009            }));
1010            return;
1011        } else {
1012            //No lock and delayed rendering already scheduled, nothing to do
1013            return;
1014        };
1015
1016        //Note that the ordering of events matters for event processing
1017        while let Some(e) = self.events.pop_front() {
1018            self.process_terminal_event(&e, &mut terminal, cx)
1019        }
1020
1021        self.last_content = Self::make_content(&terminal, &self.last_content);
1022        self.last_synced = Instant::now();
1023    }
1024
1025    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1026        let content = term.renderable_content();
1027        TerminalContent {
1028            cells: content
1029                .display_iter
1030                //TODO: Add this once there's a way to retain empty lines
1031                // .filter(|ic| {
1032                //     !ic.flags.contains(Flags::HIDDEN)
1033                //         && !(ic.bg == Named(NamedColor::Background)
1034                //             && ic.c == ' '
1035                //             && !ic.flags.contains(Flags::INVERSE))
1036                // })
1037                .map(|ic| IndexedCell {
1038                    point: ic.point,
1039                    cell: ic.cell.clone(),
1040                })
1041                .collect::<Vec<IndexedCell>>(),
1042            mode: content.mode,
1043            display_offset: content.display_offset,
1044            selection_text: term.selection_to_string(),
1045            selection: content.selection,
1046            cursor: content.cursor,
1047            cursor_char: term.grid()[content.cursor.point].c,
1048            size: last_content.size,
1049            last_hovered_word: last_content.last_hovered_word.clone(),
1050        }
1051    }
1052
1053    pub fn focus_in(&self) {
1054        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1055            self.write_to_pty("\x1b[I".to_string());
1056        }
1057    }
1058
1059    pub fn focus_out(&mut self) {
1060        self.last_mouse_position = None;
1061        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1062            self.write_to_pty("\x1b[O".to_string());
1063        }
1064    }
1065
1066    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1067        match self.last_mouse {
1068            Some((old_point, old_side)) => {
1069                if old_point == point && old_side == side {
1070                    false
1071                } else {
1072                    self.last_mouse = Some((point, side));
1073                    true
1074                }
1075            }
1076            None => {
1077                self.last_mouse = Some((point, side));
1078                true
1079            }
1080        }
1081    }
1082
1083    pub fn mouse_mode(&self, shift: bool) -> bool {
1084        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1085    }
1086
1087    pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1088        let position = e.position - origin;
1089        self.last_mouse_position = Some(position);
1090        if self.mouse_mode(e.modifiers.shift) {
1091            let point = grid_point(
1092                position,
1093                self.last_content.size,
1094                self.last_content.display_offset,
1095            );
1096            let side = mouse_side(position, self.last_content.size);
1097
1098            if self.mouse_changed(point, side) {
1099                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1100                    self.pty_tx.notify(bytes);
1101                }
1102            }
1103        } else if self.cmd_pressed {
1104            self.word_from_position(Some(position));
1105        }
1106    }
1107
1108    fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1109        if self.selection_phase == SelectionPhase::Selecting {
1110            self.last_content.last_hovered_word = None;
1111        } else if let Some(position) = position {
1112            self.events
1113                .push_back(InternalEvent::FindHyperlink(position, false));
1114        }
1115    }
1116
1117    pub fn mouse_drag(
1118        &mut self,
1119        e: &MouseMoveEvent,
1120        origin: Point<Pixels>,
1121        region: Bounds<Pixels>,
1122    ) {
1123        let position = e.position - origin;
1124        self.last_mouse_position = Some(position);
1125
1126        if !self.mouse_mode(e.modifiers.shift) {
1127            self.selection_phase = SelectionPhase::Selecting;
1128            // Alacritty has the same ordering, of first updating the selection
1129            // then scrolling 15ms later
1130            self.events
1131                .push_back(InternalEvent::UpdateSelection(position));
1132
1133            // Doesn't make sense to scroll the alt screen
1134            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1135                let scroll_delta = match self.drag_line_delta(e, region) {
1136                    Some(value) => value,
1137                    None => return,
1138                };
1139
1140                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1141
1142                self.events
1143                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1144            }
1145        }
1146    }
1147
1148    fn drag_line_delta(&mut self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1149        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1150        let top = region.origin.y + (self.last_content.size.line_height * 2.);
1151        let bottom = region.lower_left().y - (self.last_content.size.line_height * 2.);
1152        let scroll_delta = if e.position.y < top {
1153            (top - e.position.y).pow(1.1)
1154        } else if e.position.y > bottom {
1155            -((e.position.y - bottom).pow(1.1))
1156        } else {
1157            return None; //Nothing to do
1158        };
1159        Some(scroll_delta)
1160    }
1161
1162    pub fn mouse_down(&mut self, e: &MouseDownEvent, origin: Point<Pixels>) {
1163        let position = e.position - origin;
1164        let point = grid_point(
1165            position,
1166            self.last_content.size,
1167            self.last_content.display_offset,
1168        );
1169
1170        if self.mouse_mode(e.modifiers.shift) {
1171            if let Some(bytes) =
1172                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1173            {
1174                self.pty_tx.notify(bytes);
1175            }
1176        } else if e.button == MouseButton::Left {
1177            let position = e.position - origin;
1178            let point = grid_point(
1179                position,
1180                self.last_content.size,
1181                self.last_content.display_offset,
1182            );
1183
1184            // Use .opposite so that selection is inclusive of the cell clicked.
1185            let side = mouse_side(position, self.last_content.size);
1186
1187            let selection_type = match e.click_count {
1188                0 => return, //This is a release
1189                1 => Some(SelectionType::Simple),
1190                2 => Some(SelectionType::Semantic),
1191                3 => Some(SelectionType::Lines),
1192                _ => None,
1193            };
1194
1195            let selection =
1196                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1197
1198            if let Some(sel) = selection {
1199                self.events
1200                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
1201            }
1202        }
1203    }
1204
1205    pub fn mouse_up(
1206        &mut self,
1207        e: &MouseUpEvent,
1208        origin: Point<Pixels>,
1209        cx: &mut ModelContext<Self>,
1210    ) {
1211        let setting = TerminalSettings::get_global(cx);
1212
1213        let position = e.position - origin;
1214        if self.mouse_mode(e.modifiers.shift) {
1215            let point = grid_point(
1216                position,
1217                self.last_content.size,
1218                self.last_content.display_offset,
1219            );
1220
1221            if let Some(bytes) =
1222                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1223            {
1224                self.pty_tx.notify(bytes);
1225            }
1226        } else {
1227            if e.button == MouseButton::Left && setting.copy_on_select {
1228                self.copy();
1229            }
1230
1231            //Hyperlinks
1232            if self.selection_phase == SelectionPhase::Ended {
1233                let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1234                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1235                    cx.open_url(link.uri());
1236                } else if self.cmd_pressed {
1237                    self.events
1238                        .push_back(InternalEvent::FindHyperlink(position, true));
1239                }
1240            }
1241        }
1242
1243        self.selection_phase = SelectionPhase::Ended;
1244        self.last_mouse = None;
1245    }
1246
1247    ///Scroll the terminal
1248    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Point<Pixels>) {
1249        let mouse_mode = self.mouse_mode(e.shift);
1250
1251        if let Some(scroll_lines) = self.determine_scroll_lines(&e, mouse_mode) {
1252            if mouse_mode {
1253                let point = grid_point(
1254                    e.position - origin,
1255                    self.last_content.size,
1256                    self.last_content.display_offset,
1257                );
1258
1259                if let Some(scrolls) =
1260                    scroll_report(point, scroll_lines as i32, &e, self.last_content.mode)
1261                {
1262                    for scroll in scrolls {
1263                        self.pty_tx.notify(scroll);
1264                    }
1265                };
1266            } else if self
1267                .last_content
1268                .mode
1269                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1270                && !e.shift
1271            {
1272                self.pty_tx.notify(alt_scroll(scroll_lines))
1273            } else {
1274                if scroll_lines != 0 {
1275                    let scroll = AlacScroll::Delta(scroll_lines);
1276
1277                    self.events.push_back(InternalEvent::Scroll(scroll));
1278                }
1279            }
1280        }
1281    }
1282
1283    fn refresh_hovered_word(&mut self) {
1284        self.word_from_position(self.last_mouse_position);
1285    }
1286
1287    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1288        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1289        let line_height = self.last_content.size.line_height;
1290        match e.touch_phase {
1291            /* Reset scroll state on started */
1292            TouchPhase::Started => {
1293                self.scroll_px = px(0.);
1294                None
1295            }
1296            /* Calculate the appropriate scroll lines */
1297            TouchPhase::Moved => {
1298                let old_offset = (self.scroll_px / line_height) as i32;
1299
1300                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1301
1302                let new_offset = (self.scroll_px / line_height) as i32;
1303
1304                // Whenever we hit the edges, reset our stored scroll to 0
1305                // so we can respond to changes in direction quickly
1306                self.scroll_px %= self.last_content.size.height();
1307
1308                Some(new_offset - old_offset)
1309            }
1310            TouchPhase::Ended => None,
1311        }
1312    }
1313
1314    pub fn find_matches(
1315        &mut self,
1316        searcher: RegexSearch,
1317        cx: &mut ModelContext<Self>,
1318    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1319        let term = self.term.clone();
1320        cx.background_executor().spawn(async move {
1321            let term = term.lock();
1322
1323            all_search_matches(&term, &searcher).collect()
1324        })
1325    }
1326
1327    pub fn title(&self) -> String {
1328        self.foreground_process_info
1329            .as_ref()
1330            .map(|fpi| {
1331                format!(
1332                    "{}{}",
1333                    truncate_and_trailoff(
1334                        &fpi.cwd
1335                            .file_name()
1336                            .map(|name| name.to_string_lossy().to_string())
1337                            .unwrap_or_default(),
1338                        25
1339                    ),
1340                    truncate_and_trailoff(
1341                        &{
1342                            format!(
1343                                "{}{}",
1344                                fpi.name,
1345                                if fpi.argv.len() >= 1 {
1346                                    format!(" {}", (&fpi.argv[1..]).join(" "))
1347                                } else {
1348                                    "".to_string()
1349                                }
1350                            )
1351                        },
1352                        25
1353                    )
1354                )
1355            })
1356            .unwrap_or_else(|| "Terminal".to_string())
1357    }
1358
1359    pub fn can_navigate_to_selected_word(&self) -> bool {
1360        self.cmd_pressed && self.hovered_word
1361    }
1362}
1363
1364impl Drop for Terminal {
1365    fn drop(&mut self) {
1366        self.pty_tx.0.send(Msg::Shutdown).ok();
1367    }
1368}
1369
1370impl EventEmitter<Event> for Terminal {}
1371
1372/// Based on alacritty/src/display/hint.rs > regex_match_at
1373/// Retrieve the match, if the specified point is inside the content matching the regex.
1374fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &RegexSearch) -> Option<Match> {
1375    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1376}
1377
1378/// Copied from alacritty/src/display/hint.rs:
1379/// Iterate over all visible regex matches.
1380pub fn visible_regex_match_iter<'a, T>(
1381    term: &'a Term<T>,
1382    regex: &'a RegexSearch,
1383) -> impl Iterator<Item = Match> + 'a {
1384    let viewport_start = Line(-(term.grid().display_offset() as i32));
1385    let viewport_end = viewport_start + term.bottommost_line();
1386    let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1387    let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1388    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1389    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1390
1391    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1392        .skip_while(move |rm| rm.end().line < viewport_start)
1393        .take_while(move |rm| rm.start().line <= viewport_end)
1394}
1395
1396fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1397    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1398    selection.update(*range.end(), AlacDirection::Right);
1399    selection
1400}
1401
1402fn all_search_matches<'a, T>(
1403    term: &'a Term<T>,
1404    regex: &'a RegexSearch,
1405) -> impl Iterator<Item = Match> + 'a {
1406    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1407    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1408    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1409}
1410
1411fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1412    let col = (pos.x / size.cell_width()).round() as usize;
1413    let clamped_col = min(col, size.columns() - 1);
1414    let row = (pos.y / size.line_height()).round() as usize;
1415    let clamped_row = min(row, size.screen_lines() - 1);
1416    clamped_row * size.columns() + clamped_col
1417}
1418
1419///Converts an 8 bit ANSI color to it's GPUI equivalent.
1420///Accepts usize for compatibility with the alacritty::Colors interface,
1421///Other than that use case, should only be called with values in the [0,255] range
1422pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1423    let colors = theme.colors();
1424
1425    match index {
1426        //0-15 are the same as the named colors above
1427        0 => colors.terminal_ansi_black,
1428        1 => colors.terminal_ansi_red,
1429        2 => colors.terminal_ansi_green,
1430        3 => colors.terminal_ansi_yellow,
1431        4 => colors.terminal_ansi_blue,
1432        5 => colors.terminal_ansi_magenta,
1433        6 => colors.terminal_ansi_cyan,
1434        7 => colors.terminal_ansi_white,
1435        8 => colors.terminal_ansi_bright_black,
1436        9 => colors.terminal_ansi_bright_red,
1437        10 => colors.terminal_ansi_bright_green,
1438        11 => colors.terminal_ansi_bright_yellow,
1439        12 => colors.terminal_ansi_bright_blue,
1440        13 => colors.terminal_ansi_bright_magenta,
1441        14 => colors.terminal_ansi_bright_cyan,
1442        15 => colors.terminal_ansi_bright_white,
1443        //16-231 are mapped to their RGB colors on a 0-5 range per channel
1444        16..=231 => {
1445            let (r, g, b) = rgb_for_index(&(index as u8)); //Split the index into it's ANSI-RGB components
1446            let step = (u8::MAX as f32 / 5.).floor() as u8; //Split the RGB range into 5 chunks, with floor so no overflow
1447            rgba_color(r * step, g * step, b * step) //Map the ANSI-RGB components to an RGB color
1448        }
1449        //232-255 are a 24 step grayscale from black to white
1450        232..=255 => {
1451            let i = index as u8 - 232; //Align index to 0..24
1452            let step = (u8::MAX as f32 / 24.).floor() as u8; //Split the RGB grayscale values into 24 chunks
1453            rgba_color(i * step, i * step, i * step) //Map the ANSI-grayscale components to the RGB-grayscale
1454        }
1455        //For compatibility with the alacritty::Colors interface
1456        256 => colors.text,
1457        257 => colors.background,
1458        258 => theme.players().local().cursor,
1459
1460        // todo!(more colors)
1461        259 => red(),                      //style.dim_black,
1462        260 => red(),                      //style.dim_red,
1463        261 => red(),                      //style.dim_green,
1464        262 => red(),                      //style.dim_yellow,
1465        263 => red(),                      //style.dim_blue,
1466        264 => red(),                      //style.dim_magenta,
1467        265 => red(),                      //style.dim_cyan,
1468        266 => red(),                      //style.dim_white,
1469        267 => red(),                      //style.bright_foreground,
1470        268 => colors.terminal_ansi_black, //'Dim Background', non-standard color
1471
1472        _ => black(),
1473    }
1474}
1475
1476///Generates the rgb channels in [0, 5] for a given index into the 6x6x6 ANSI color cube
1477///See: [8 bit ansi color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1478///
1479///Wikipedia gives a formula for calculating the index for a given color:
1480///
1481///index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1482///
1483///This function does the reverse, calculating the r, g, and b components from a given index.
1484fn rgb_for_index(i: &u8) -> (u8, u8, u8) {
1485    debug_assert!((&16..=&231).contains(&i));
1486    let i = i - 16;
1487    let r = (i - (i % 36)) / 36;
1488    let g = ((i % 36) - (i % 6)) / 6;
1489    let b = (i % 36) % 6;
1490    (r, g, b)
1491}
1492
1493pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1494    Rgba {
1495        r: (r as f32 / 255.) as f32,
1496        g: (g as f32 / 255.) as f32,
1497        b: (b as f32 / 255.) as f32,
1498        a: 1.,
1499    }
1500    .into()
1501}
1502
1503#[cfg(test)]
1504mod tests {
1505    use alacritty_terminal::{
1506        index::{Column, Line, Point as AlacPoint},
1507        term::cell::Cell,
1508    };
1509    use gpui::{point, size, Pixels};
1510    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1511
1512    use crate::{
1513        content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
1514    };
1515
1516    #[test]
1517    fn test_rgb_for_index() {
1518        //Test every possible value in the color cube
1519        for i in 16..=231 {
1520            let (r, g, b) = rgb_for_index(&(i as u8));
1521            assert_eq!(i, 16 + 36 * r + 6 * g + b);
1522        }
1523    }
1524
1525    #[test]
1526    fn test_mouse_to_cell_test() {
1527        let mut rng = thread_rng();
1528        const ITERATIONS: usize = 10;
1529        const PRECISION: usize = 1000;
1530
1531        for _ in 0..ITERATIONS {
1532            let viewport_cells = rng.gen_range(15..20);
1533            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1534
1535            let size = crate::TerminalSize {
1536                cell_width: Pixels::from(cell_size),
1537                line_height: Pixels::from(cell_size),
1538                size: size(
1539                    Pixels::from(cell_size * (viewport_cells as f32)),
1540                    Pixels::from(cell_size * (viewport_cells as f32)),
1541                ),
1542            };
1543
1544            let cells = get_cells(size, &mut rng);
1545            let content = convert_cells_to_content(size, &cells);
1546
1547            for row in 0..(viewport_cells - 1) {
1548                let row = row as usize;
1549                for col in 0..(viewport_cells - 1) {
1550                    let col = col as usize;
1551
1552                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1553                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1554
1555                    let mouse_pos = point(
1556                        Pixels::from(col as f32 * cell_size + col_offset),
1557                        Pixels::from(row as f32 * cell_size + row_offset),
1558                    );
1559
1560                    let content_index = content_index_for_mouse(mouse_pos, &content.size);
1561                    let mouse_cell = content.cells[content_index].c;
1562                    let real_cell = cells[row][col];
1563
1564                    assert_eq!(mouse_cell, real_cell);
1565                }
1566            }
1567        }
1568    }
1569
1570    #[test]
1571    fn test_mouse_to_cell_clamp() {
1572        let mut rng = thread_rng();
1573
1574        let size = crate::TerminalSize {
1575            cell_width: Pixels::from(10.),
1576            line_height: Pixels::from(10.),
1577            size: size(Pixels::from(100.), Pixels::from(100.)),
1578        };
1579
1580        let cells = get_cells(size, &mut rng);
1581        let content = convert_cells_to_content(size, &cells);
1582
1583        assert_eq!(
1584            content.cells[content_index_for_mouse(
1585                point(Pixels::from(-10.), Pixels::from(-10.)),
1586                &content.size
1587            )]
1588            .c,
1589            cells[0][0]
1590        );
1591        assert_eq!(
1592            content.cells[content_index_for_mouse(
1593                point(Pixels::from(1000.), Pixels::from(1000.)),
1594                &content.size
1595            )]
1596            .c,
1597            cells[9][9]
1598        );
1599    }
1600
1601    fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1602        let mut cells = Vec::new();
1603
1604        for _ in 0..(f32::from(size.height() / size.line_height()) as usize) {
1605            let mut row_vec = Vec::new();
1606            for _ in 0..(f32::from(size.width() / size.cell_width()) as usize) {
1607                let cell_char = rng.sample(Alphanumeric) as char;
1608                row_vec.push(cell_char)
1609            }
1610            cells.push(row_vec)
1611        }
1612
1613        cells
1614    }
1615
1616    fn convert_cells_to_content(size: TerminalSize, cells: &Vec<Vec<char>>) -> TerminalContent {
1617        let mut ic = Vec::new();
1618
1619        for row in 0..cells.len() {
1620            for col in 0..cells[row].len() {
1621                let cell_char = cells[row][col];
1622                ic.push(IndexedCell {
1623                    point: AlacPoint::new(Line(row as i32), Column(col)),
1624                    cell: Cell {
1625                        c: cell_char,
1626                        ..Default::default()
1627                    },
1628                });
1629            }
1630        }
1631
1632        TerminalContent {
1633            cells: ic,
1634            size,
1635            ..Default::default()
1636        }
1637    }
1638}