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