terminal.rs

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