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