terminal.rs

   1pub mod mappings;
   2
   3pub use alacritty_terminal;
   4
   5mod pty_info;
   6pub mod terminal_settings;
   7
   8use alacritty_terminal::{
   9    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
  10    event_loop::{EventLoop, Msg, Notifier},
  11    grid::{Dimensions, Grid, Row, Scroll as AlacScroll},
  12    index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
  13    selection::{Selection, SelectionRange, SelectionType},
  14    sync::FairMutex,
  15    term::{
  16        cell::{Cell, Flags},
  17        search::{Match, RegexIter, RegexSearch},
  18        Config, RenderableCursor, TermMode,
  19    },
  20    tty::{self},
  21    vi_mode::{ViModeCursor, ViMotion},
  22    vte::ansi::{
  23        ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
  24    },
  25    Term,
  26};
  27use anyhow::{bail, Result};
  28
  29use futures::{
  30    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
  31    FutureExt,
  32};
  33
  34use mappings::mouse::{
  35    alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
  36    scroll_report,
  37};
  38
  39use collections::{HashMap, VecDeque};
  40use futures::StreamExt;
  41use pty_info::PtyProcessInfo;
  42use serde::{Deserialize, Serialize};
  43use settings::Settings;
  44use smol::channel::{Receiver, Sender};
  45use task::{HideStrategy, Shell, TaskId};
  46use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
  47use theme::{ActiveTheme, Theme};
  48use util::{paths::home_dir, truncate_and_trailoff};
  49
  50use std::{
  51    cmp::{self, min},
  52    fmt::Display,
  53    ops::{Deref, Index, RangeInclusive},
  54    path::PathBuf,
  55    sync::Arc,
  56    time::Duration,
  57};
  58use thiserror::Error;
  59
  60use gpui::{
  61    actions, black, px, AnyWindowHandle, App, AppContext as _, Bounds, ClipboardItem, Context,
  62    EventEmitter, Hsla, Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent,
  63    MouseUpEvent, Pixels, Point, Rgba, ScrollWheelEvent, SharedString, Size, Task, TouchPhase,
  64    Window,
  65};
  66
  67use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
  68
  69actions!(
  70    terminal,
  71    [
  72        Clear,
  73        Copy,
  74        Paste,
  75        ShowCharacterPalette,
  76        SearchTest,
  77        ScrollLineUp,
  78        ScrollLineDown,
  79        ScrollPageUp,
  80        ScrollPageDown,
  81        ScrollToTop,
  82        ScrollToBottom,
  83        ToggleViMode,
  84    ]
  85);
  86
  87///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  88///Scroll multiplier that is set to 3 by default. This will be removed when I
  89///Implement scroll bars.
  90#[cfg(target_os = "macos")]
  91const SCROLL_MULTIPLIER: f32 = 4.;
  92#[cfg(not(target_os = "macos"))]
  93const SCROLL_MULTIPLIER: f32 = 1.;
  94const MAX_SEARCH_LINES: usize = 100;
  95const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
  96const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
  97const DEBUG_CELL_WIDTH: Pixels = px(5.);
  98const DEBUG_LINE_HEIGHT: Pixels = px(5.);
  99
 100///Upward flowing events, for changing the title and such
 101#[derive(Clone, Debug)]
 102pub enum Event {
 103    TitleChanged,
 104    BreadcrumbsChanged,
 105    CloseTerminal,
 106    Bell,
 107    Wakeup,
 108    BlinkChanged(bool),
 109    SelectionsChanged,
 110    NewNavigationTarget(Option<MaybeNavigationTarget>),
 111    Open(MaybeNavigationTarget),
 112}
 113
 114#[derive(Clone, Debug)]
 115pub struct PathLikeTarget {
 116    /// File system path, absolute or relative, existing or not.
 117    /// Might have line and column number(s) attached as `file.rs:1:23`
 118    pub maybe_path: String,
 119    /// Current working directory of the terminal
 120    pub terminal_dir: Option<PathBuf>,
 121}
 122
 123/// A string inside terminal, potentially useful as a URI that can be opened.
 124#[derive(Clone, Debug)]
 125pub enum MaybeNavigationTarget {
 126    /// HTTP, git, etc. string determined by the `URL_REGEX` regex.
 127    Url(String),
 128    /// File system path, absolute or relative, existing or not.
 129    /// Might have line and column number(s) attached as `file.rs:1:23`
 130    PathLike(PathLikeTarget),
 131}
 132
 133#[derive(Clone)]
 134enum InternalEvent {
 135    Resize(TerminalBounds),
 136    Clear,
 137    // FocusNextMatch,
 138    Scroll(AlacScroll),
 139    ScrollToAlacPoint(AlacPoint),
 140    SetSelection(Option<(Selection, AlacPoint)>),
 141    UpdateSelection(Point<Pixels>),
 142    // Adjusted mouse position, should open
 143    FindHyperlink(Point<Pixels>, bool),
 144    Copy,
 145    // Vi mode events
 146    ToggleViMode,
 147    ViMotion(ViMotion),
 148}
 149
 150///A translation struct for Alacritty to communicate with us from their event loop
 151#[derive(Clone)]
 152pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
 153
 154impl EventListener for ZedListener {
 155    fn send_event(&self, event: AlacTermEvent) {
 156        self.0.unbounded_send(event).ok();
 157    }
 158}
 159
 160pub fn init(cx: &mut App) {
 161    TerminalSettings::register(cx);
 162}
 163
 164#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
 165pub struct TerminalBounds {
 166    pub cell_width: Pixels,
 167    pub line_height: Pixels,
 168    pub bounds: Bounds<Pixels>,
 169}
 170
 171impl TerminalBounds {
 172    pub fn new(line_height: Pixels, cell_width: Pixels, bounds: Bounds<Pixels>) -> Self {
 173        TerminalBounds {
 174            cell_width,
 175            line_height,
 176            bounds,
 177        }
 178    }
 179
 180    pub fn num_lines(&self) -> usize {
 181        (self.bounds.size.height / self.line_height).floor() as usize
 182    }
 183
 184    pub fn num_columns(&self) -> usize {
 185        (self.bounds.size.width / self.cell_width).floor() as usize
 186    }
 187
 188    pub fn height(&self) -> Pixels {
 189        self.bounds.size.height
 190    }
 191
 192    pub fn width(&self) -> Pixels {
 193        self.bounds.size.width
 194    }
 195
 196    pub fn cell_width(&self) -> Pixels {
 197        self.cell_width
 198    }
 199
 200    pub fn line_height(&self) -> Pixels {
 201        self.line_height
 202    }
 203}
 204
 205impl Default for TerminalBounds {
 206    fn default() -> Self {
 207        TerminalBounds::new(
 208            DEBUG_LINE_HEIGHT,
 209            DEBUG_CELL_WIDTH,
 210            Bounds {
 211                origin: Point::default(),
 212                size: Size {
 213                    width: DEBUG_TERMINAL_WIDTH,
 214                    height: DEBUG_TERMINAL_HEIGHT,
 215                },
 216            },
 217        )
 218    }
 219}
 220
 221impl From<TerminalBounds> for WindowSize {
 222    fn from(val: TerminalBounds) -> Self {
 223        WindowSize {
 224            num_lines: val.num_lines() as u16,
 225            num_cols: val.num_columns() as u16,
 226            cell_width: f32::from(val.cell_width()) as u16,
 227            cell_height: f32::from(val.line_height()) as u16,
 228        }
 229    }
 230}
 231
 232impl Dimensions for TerminalBounds {
 233    /// Note: this is supposed to be for the back buffer's length,
 234    /// but we exclusively use it to resize the terminal, which does not
 235    /// use this method. We still have to implement it for the trait though,
 236    /// hence, this comment.
 237    fn total_lines(&self) -> usize {
 238        self.screen_lines()
 239    }
 240
 241    fn screen_lines(&self) -> usize {
 242        self.num_lines()
 243    }
 244
 245    fn columns(&self) -> usize {
 246        self.num_columns()
 247    }
 248}
 249
 250#[derive(Error, Debug)]
 251pub struct TerminalError {
 252    pub directory: Option<PathBuf>,
 253    pub shell: Shell,
 254    pub source: std::io::Error,
 255}
 256
 257impl TerminalError {
 258    pub fn fmt_directory(&self) -> String {
 259        self.directory
 260            .clone()
 261            .map(|path| {
 262                match path
 263                    .into_os_string()
 264                    .into_string()
 265                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 266                {
 267                    Ok(s) => s,
 268                    Err(s) => s,
 269                }
 270            })
 271            .unwrap_or_else(|| {
 272                let default_dir =
 273                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
 274                match default_dir {
 275                    Some(dir) => format!("<none specified, using home directory> {}", dir),
 276                    None => "<none specified, could not find home directory>".to_string(),
 277                }
 278            })
 279    }
 280
 281    pub fn fmt_shell(&self) -> String {
 282        match &self.shell {
 283            Shell::System => "<system defined shell>".to_string(),
 284            Shell::Program(s) => s.to_string(),
 285            Shell::WithArguments {
 286                program,
 287                args,
 288                title_override,
 289            } => {
 290                if let Some(title_override) = title_override {
 291                    format!("{} {} ({})", program, args.join(" "), title_override)
 292                } else {
 293                    format!("{} {}", program, args.join(" "))
 294                }
 295            }
 296        }
 297    }
 298}
 299
 300impl Display for TerminalError {
 301    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 302        let dir_string: String = self.fmt_directory();
 303        let shell = self.fmt_shell();
 304
 305        write!(
 306            f,
 307            "Working directory: {} Shell command: `{}`, IOError: {}",
 308            dir_string, shell, self.source
 309        )
 310    }
 311}
 312
 313// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
 314const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
 315const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
 316const URL_REGEX: &str = r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`]+"#;
 317// Optional suffix matches MSBuild diagnostic suffixes for path parsing in PathLikeWithPosition
 318// https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks
 319const WORD_REGEX: &str =
 320    r#"[\$\+\w.\[\]:/\\@\-~()]+(?:\((?:\d+|\d+,\d+)\))|[\$\+\w.\[\]:/\\@\-~()]+"#;
 321
 322pub struct TerminalBuilder {
 323    terminal: Terminal,
 324    events_rx: UnboundedReceiver<AlacTermEvent>,
 325}
 326
 327impl TerminalBuilder {
 328    pub fn new(
 329        working_directory: Option<PathBuf>,
 330        python_venv_directory: Option<PathBuf>,
 331        task: Option<TaskState>,
 332        shell: Shell,
 333        mut env: HashMap<String, String>,
 334        cursor_shape: CursorShape,
 335        alternate_scroll: AlternateScroll,
 336        max_scroll_history_lines: Option<usize>,
 337        is_ssh_terminal: bool,
 338        window: AnyWindowHandle,
 339        completion_tx: Sender<()>,
 340        debug_terminal: bool,
 341        cx: &App,
 342    ) -> Result<TerminalBuilder> {
 343        // If the parent environment doesn't have a locale set
 344        // (As is the case when launched from a .app on MacOS),
 345        // and the Project doesn't have a locale set, then
 346        // set a fallback for our child environment to use.
 347        if std::env::var("LANG").is_err() {
 348            env.entry("LANG".to_string())
 349                .or_insert_with(|| "en_US.UTF-8".to_string());
 350        }
 351
 352        env.insert("ZED_TERM".to_string(), "true".to_string());
 353        env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
 354        env.insert("TERM".to_string(), "xterm-256color".to_string());
 355        env.insert(
 356            "TERM_PROGRAM_VERSION".to_string(),
 357            release_channel::AppVersion::global(cx).to_string(),
 358        );
 359
 360        let mut terminal_title_override = None;
 361
 362        let pty_options = {
 363            let alac_shell = match shell.clone() {
 364                Shell::System => None,
 365                Shell::Program(program) => {
 366                    Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
 367                }
 368                Shell::WithArguments {
 369                    program,
 370                    args,
 371                    title_override,
 372                } => {
 373                    terminal_title_override = title_override;
 374                    Some(alacritty_terminal::tty::Shell::new(program, args))
 375                }
 376            };
 377
 378            alacritty_terminal::tty::Options {
 379                shell: alac_shell,
 380                working_directory: working_directory
 381                    .clone()
 382                    .or_else(|| Some(home_dir().to_path_buf())),
 383                drain_on_exit: true,
 384                env: env.into_iter().collect(),
 385            }
 386        };
 387
 388        // Setup Alacritty's env, which modifies the current process's environment
 389        alacritty_terminal::tty::setup_env();
 390
 391        let default_cursor_style = AlacCursorStyle::from(cursor_shape);
 392        let scrolling_history = if task.is_some() {
 393            // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
 394            // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
 395            // cause excessive memory usage over time.
 396            MAX_SCROLL_HISTORY_LINES
 397        } else {
 398            max_scroll_history_lines
 399                .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
 400                .min(MAX_SCROLL_HISTORY_LINES)
 401        };
 402        let config = Config {
 403            scrolling_history,
 404            default_cursor_style,
 405            ..Config::default()
 406        };
 407
 408        //Spawn a task so the Alacritty EventLoop can communicate with us
 409        //TODO: Remove with a bounded sender which can be dispatched on &self
 410        let (events_tx, events_rx) = unbounded();
 411        //Set up the terminal...
 412        let mut term = Term::new(
 413            config.clone(),
 414            &TerminalBounds::default(),
 415            ZedListener(events_tx.clone()),
 416        );
 417
 418        //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
 419        if let AlternateScroll::Off = alternate_scroll {
 420            term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
 421        }
 422
 423        let term = Arc::new(FairMutex::new(term));
 424
 425        //Setup the pty...
 426        let pty = match tty::new(
 427            &pty_options,
 428            TerminalBounds::default().into(),
 429            window.window_id().as_u64(),
 430        ) {
 431            Ok(pty) => pty,
 432            Err(error) => {
 433                bail!(TerminalError {
 434                    directory: working_directory,
 435                    shell,
 436                    source: error,
 437                });
 438            }
 439        };
 440
 441        let pty_info = PtyProcessInfo::new(&pty);
 442
 443        //And connect them together
 444        let event_loop = EventLoop::new(
 445            term.clone(),
 446            ZedListener(events_tx.clone()),
 447            pty,
 448            pty_options.drain_on_exit,
 449            false,
 450        )?;
 451
 452        //Kick things off
 453        let pty_tx = event_loop.channel();
 454        let _io_thread = event_loop.spawn(); // DANGER
 455
 456        let terminal = Terminal {
 457            task,
 458            pty_tx: Notifier(pty_tx),
 459            completion_tx,
 460            term,
 461            term_config: config,
 462            title_override: terminal_title_override,
 463            events: VecDeque::with_capacity(10), //Should never get this high.
 464            last_content: Default::default(),
 465            last_mouse: None,
 466            matches: Vec::new(),
 467            selection_head: None,
 468            pty_info,
 469            breadcrumb_text: String::new(),
 470            scroll_px: px(0.),
 471            next_link_id: 0,
 472            selection_phase: SelectionPhase::Ended,
 473            // hovered_word: false,
 474            url_regex: RegexSearch::new(URL_REGEX).unwrap(),
 475            word_regex: RegexSearch::new(WORD_REGEX).unwrap(),
 476            vi_mode_enabled: false,
 477            debug_terminal,
 478            is_ssh_terminal,
 479            python_venv_directory,
 480        };
 481
 482        Ok(TerminalBuilder {
 483            terminal,
 484            events_rx,
 485        })
 486    }
 487
 488    pub fn subscribe(mut self, cx: &Context<Terminal>) -> Terminal {
 489        //Event loop
 490        cx.spawn(|terminal, mut cx| async move {
 491            while let Some(event) = self.events_rx.next().await {
 492                terminal.update(&mut cx, |terminal, cx| {
 493                    //Process the first event immediately for lowered latency
 494                    terminal.process_event(&event, cx);
 495                })?;
 496
 497                'outer: loop {
 498                    let mut events = Vec::new();
 499                    let mut timer = cx
 500                        .background_executor()
 501                        .timer(Duration::from_millis(4))
 502                        .fuse();
 503                    let mut wakeup = false;
 504                    loop {
 505                        futures::select_biased! {
 506                            _ = timer => break,
 507                            event = self.events_rx.next() => {
 508                                if let Some(event) = event {
 509                                    if matches!(event, AlacTermEvent::Wakeup) {
 510                                        wakeup = true;
 511                                    } else {
 512                                        events.push(event);
 513                                    }
 514
 515                                    if events.len() > 100 {
 516                                        break;
 517                                    }
 518                                } else {
 519                                    break;
 520                                }
 521                            },
 522                        }
 523                    }
 524
 525                    if events.is_empty() && !wakeup {
 526                        smol::future::yield_now().await;
 527                        break 'outer;
 528                    }
 529
 530                    terminal.update(&mut cx, |this, cx| {
 531                        if wakeup {
 532                            this.process_event(&AlacTermEvent::Wakeup, cx);
 533                        }
 534
 535                        for event in events {
 536                            this.process_event(&event, cx);
 537                        }
 538                    })?;
 539                    smol::future::yield_now().await;
 540                }
 541            }
 542
 543            anyhow::Ok(())
 544        })
 545        .detach();
 546
 547        self.terminal
 548    }
 549}
 550
 551#[derive(Debug, Clone, Deserialize, Serialize)]
 552pub struct IndexedCell {
 553    pub point: AlacPoint,
 554    pub cell: Cell,
 555}
 556
 557impl Deref for IndexedCell {
 558    type Target = Cell;
 559
 560    #[inline]
 561    fn deref(&self) -> &Cell {
 562        &self.cell
 563    }
 564}
 565
 566// TODO: Un-pub
 567#[derive(Clone)]
 568pub struct TerminalContent {
 569    pub cells: Vec<IndexedCell>,
 570    pub mode: TermMode,
 571    pub display_offset: usize,
 572    pub selection_text: Option<String>,
 573    pub selection: Option<SelectionRange>,
 574    pub cursor: RenderableCursor,
 575    pub cursor_char: char,
 576    pub terminal_bounds: TerminalBounds,
 577    pub last_hovered_word: Option<HoveredWord>,
 578}
 579
 580#[derive(Clone)]
 581pub struct HoveredWord {
 582    pub word: String,
 583    pub word_match: RangeInclusive<AlacPoint>,
 584    pub id: usize,
 585}
 586
 587impl Default for TerminalContent {
 588    fn default() -> Self {
 589        TerminalContent {
 590            cells: Default::default(),
 591            mode: Default::default(),
 592            display_offset: Default::default(),
 593            selection_text: Default::default(),
 594            selection: Default::default(),
 595            cursor: RenderableCursor {
 596                shape: alacritty_terminal::vte::ansi::CursorShape::Block,
 597                point: AlacPoint::new(Line(0), Column(0)),
 598            },
 599            cursor_char: Default::default(),
 600            terminal_bounds: Default::default(),
 601            last_hovered_word: None,
 602        }
 603    }
 604}
 605
 606#[derive(PartialEq, Eq)]
 607pub enum SelectionPhase {
 608    Selecting,
 609    Ended,
 610}
 611
 612pub struct Terminal {
 613    pty_tx: Notifier,
 614    completion_tx: Sender<()>,
 615    term: Arc<FairMutex<Term<ZedListener>>>,
 616    term_config: Config,
 617    events: VecDeque<InternalEvent>,
 618    /// This is only used for mouse mode cell change detection
 619    last_mouse: Option<(AlacPoint, AlacDirection)>,
 620    pub matches: Vec<RangeInclusive<AlacPoint>>,
 621    pub last_content: TerminalContent,
 622    pub selection_head: Option<AlacPoint>,
 623    pub breadcrumb_text: String,
 624    pub pty_info: PtyProcessInfo,
 625    title_override: Option<SharedString>,
 626    pub python_venv_directory: Option<PathBuf>,
 627    scroll_px: Pixels,
 628    next_link_id: usize,
 629    selection_phase: SelectionPhase,
 630    url_regex: RegexSearch,
 631    word_regex: RegexSearch,
 632    task: Option<TaskState>,
 633    vi_mode_enabled: bool,
 634    debug_terminal: bool,
 635    is_ssh_terminal: bool,
 636}
 637
 638pub struct TaskState {
 639    pub id: TaskId,
 640    pub full_label: String,
 641    pub label: String,
 642    pub command_label: String,
 643    pub status: TaskStatus,
 644    pub completion_rx: Receiver<()>,
 645    pub hide: HideStrategy,
 646    pub show_summary: bool,
 647    pub show_command: bool,
 648    pub show_rerun: bool,
 649}
 650
 651/// A status of the current terminal tab's task.
 652#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 653pub enum TaskStatus {
 654    /// The task had been started, but got cancelled or somehow otherwise it did not
 655    /// report its exit code before the terminal event loop was shut down.
 656    Unknown,
 657    /// The task is started and running currently.
 658    Running,
 659    /// After the start, the task stopped running and reported its error code back.
 660    Completed { success: bool },
 661}
 662
 663impl TaskStatus {
 664    fn register_terminal_exit(&mut self) {
 665        if self == &Self::Running {
 666            *self = Self::Unknown;
 667        }
 668    }
 669
 670    fn register_task_exit(&mut self, error_code: i32) {
 671        *self = TaskStatus::Completed {
 672            success: error_code == 0,
 673        };
 674    }
 675}
 676
 677impl Terminal {
 678    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut Context<Self>) {
 679        match event {
 680            AlacTermEvent::Title(title) => {
 681                self.breadcrumb_text = title.to_string();
 682                cx.emit(Event::BreadcrumbsChanged);
 683            }
 684            AlacTermEvent::ResetTitle => {
 685                self.breadcrumb_text = String::new();
 686                cx.emit(Event::BreadcrumbsChanged);
 687            }
 688            AlacTermEvent::ClipboardStore(_, data) => {
 689                cx.write_to_clipboard(ClipboardItem::new_string(data.to_string()))
 690            }
 691            AlacTermEvent::ClipboardLoad(_, format) => {
 692                self.write_to_pty(
 693                    match &cx.read_from_clipboard().and_then(|item| item.text()) {
 694                        // The terminal only supports pasting strings, not images.
 695                        Some(text) => format(text),
 696                        _ => format(""),
 697                    },
 698                )
 699            }
 700            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 701            AlacTermEvent::TextAreaSizeRequest(format) => {
 702                self.write_to_pty(format(self.last_content.terminal_bounds.into()))
 703            }
 704            AlacTermEvent::CursorBlinkingChange => {
 705                let terminal = self.term.lock();
 706                let blinking = terminal.cursor_style().blinking;
 707                cx.emit(Event::BlinkChanged(blinking));
 708            }
 709            AlacTermEvent::Bell => {
 710                cx.emit(Event::Bell);
 711            }
 712            AlacTermEvent::Exit => self.register_task_finished(None, cx),
 713            AlacTermEvent::MouseCursorDirty => {
 714                //NOOP, Handled in render
 715            }
 716            AlacTermEvent::Wakeup => {
 717                cx.emit(Event::Wakeup);
 718
 719                if self.pty_info.has_changed() {
 720                    cx.emit(Event::TitleChanged);
 721                }
 722            }
 723            AlacTermEvent::ColorRequest(index, format) => {
 724                // It's important that the color request is processed here to retain relative order
 725                // with other PTY writes. Otherwise applications might witness out-of-order
 726                // responses to requests. For example: An application sending `OSC 11 ; ? ST`
 727                // (color request) followed by `CSI c` (request device attributes) would receive
 728                // the response to `CSI c` first.
 729                // Instead of locking, we could store the colors in `self.last_content`. But then
 730                // we might respond with out of date value if a "set color" sequence is immediately
 731                // followed by a color request sequence.
 732                let color = self.term.lock().colors()[*index].unwrap_or_else(|| {
 733                    to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
 734                });
 735                self.write_to_pty(format(color));
 736            }
 737            AlacTermEvent::ChildExit(error_code) => {
 738                self.register_task_finished(Some(*error_code), cx);
 739            }
 740        }
 741    }
 742
 743    pub fn selection_started(&self) -> bool {
 744        self.selection_phase == SelectionPhase::Selecting
 745    }
 746
 747    fn process_terminal_event(
 748        &mut self,
 749        event: &InternalEvent,
 750        term: &mut Term<ZedListener>,
 751        window: &mut Window,
 752        cx: &mut Context<Self>,
 753    ) {
 754        match event {
 755            InternalEvent::Resize(mut new_bounds) => {
 756                new_bounds.bounds.size.height =
 757                    cmp::max(new_bounds.line_height, new_bounds.height());
 758                new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
 759
 760                self.last_content.terminal_bounds = new_bounds;
 761
 762                self.pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
 763
 764                term.resize(new_bounds);
 765            }
 766            InternalEvent::Clear => {
 767                // Clear back buffer
 768                term.clear_screen(ClearMode::Saved);
 769
 770                let cursor = term.grid().cursor.point;
 771
 772                // Clear the lines above
 773                term.grid_mut().reset_region(..cursor.line);
 774
 775                // Copy the current line up
 776                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 777                    .iter()
 778                    .cloned()
 779                    .enumerate()
 780                    .collect::<Vec<(usize, Cell)>>();
 781
 782                for (i, cell) in line {
 783                    term.grid_mut()[Line(0)][Column(i)] = cell;
 784                }
 785
 786                // Reset the cursor
 787                term.grid_mut().cursor.point =
 788                    AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
 789                let new_cursor = term.grid().cursor.point;
 790
 791                // Clear the lines below the new cursor
 792                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 793                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 794                }
 795
 796                cx.emit(Event::Wakeup);
 797            }
 798            InternalEvent::Scroll(scroll) => {
 799                term.scroll_display(*scroll);
 800                self.refresh_hovered_word(window);
 801
 802                if self.vi_mode_enabled {
 803                    match *scroll {
 804                        AlacScroll::Delta(delta) => {
 805                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
 806                        }
 807                        AlacScroll::PageUp => {
 808                            let lines = term.screen_lines() as i32;
 809                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
 810                        }
 811                        AlacScroll::PageDown => {
 812                            let lines = -(term.screen_lines() as i32);
 813                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
 814                        }
 815                        AlacScroll::Top => {
 816                            let point = AlacPoint::new(term.topmost_line(), Column(0));
 817                            term.vi_mode_cursor = ViModeCursor::new(point);
 818                        }
 819                        AlacScroll::Bottom => {
 820                            let point = AlacPoint::new(term.bottommost_line(), Column(0));
 821                            term.vi_mode_cursor = ViModeCursor::new(point);
 822                        }
 823                    }
 824                    if let Some(mut selection) = term.selection.take() {
 825                        let point = term.vi_mode_cursor.point;
 826                        selection.update(point, AlacDirection::Right);
 827                        term.selection = Some(selection);
 828
 829                        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 830                        if let Some(selection_text) = term.selection_to_string() {
 831                            cx.write_to_primary(ClipboardItem::new_string(selection_text));
 832                        }
 833
 834                        self.selection_head = Some(point);
 835                        cx.emit(Event::SelectionsChanged)
 836                    }
 837                }
 838            }
 839            InternalEvent::SetSelection(selection) => {
 840                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 841
 842                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 843                if let Some(selection_text) = term.selection_to_string() {
 844                    cx.write_to_primary(ClipboardItem::new_string(selection_text));
 845                }
 846
 847                if let Some((_, head)) = selection {
 848                    self.selection_head = Some(*head);
 849                }
 850                cx.emit(Event::SelectionsChanged)
 851            }
 852            InternalEvent::UpdateSelection(position) => {
 853                if let Some(mut selection) = term.selection.take() {
 854                    let (point, side) = grid_point_and_side(
 855                        *position,
 856                        self.last_content.terminal_bounds,
 857                        term.grid().display_offset(),
 858                    );
 859
 860                    selection.update(point, side);
 861                    term.selection = Some(selection);
 862
 863                    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 864                    if let Some(selection_text) = term.selection_to_string() {
 865                        cx.write_to_primary(ClipboardItem::new_string(selection_text));
 866                    }
 867
 868                    self.selection_head = Some(point);
 869                    cx.emit(Event::SelectionsChanged)
 870                }
 871            }
 872
 873            InternalEvent::Copy => {
 874                if let Some(txt) = term.selection_to_string() {
 875                    cx.write_to_clipboard(ClipboardItem::new_string(txt))
 876                }
 877            }
 878            InternalEvent::ScrollToAlacPoint(point) => {
 879                term.scroll_to_point(*point);
 880                self.refresh_hovered_word(window);
 881            }
 882            InternalEvent::ToggleViMode => {
 883                self.vi_mode_enabled = !self.vi_mode_enabled;
 884                term.toggle_vi_mode();
 885            }
 886            InternalEvent::ViMotion(motion) => {
 887                term.vi_motion(*motion);
 888            }
 889            InternalEvent::FindHyperlink(position, open) => {
 890                let prev_hovered_word = self.last_content.last_hovered_word.take();
 891
 892                let point = grid_point(
 893                    *position,
 894                    self.last_content.terminal_bounds,
 895                    term.grid().display_offset(),
 896                )
 897                .grid_clamp(term, Boundary::Grid);
 898
 899                let link = term.grid().index(point).hyperlink();
 900                let found_word = if link.is_some() {
 901                    let mut min_index = point;
 902                    loop {
 903                        let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
 904                        if new_min_index == min_index
 905                            || term.grid().index(new_min_index).hyperlink() != link
 906                        {
 907                            break;
 908                        } else {
 909                            min_index = new_min_index
 910                        }
 911                    }
 912
 913                    let mut max_index = point;
 914                    loop {
 915                        let new_max_index = max_index.add(term, Boundary::Cursor, 1);
 916                        if new_max_index == max_index
 917                            || term.grid().index(new_max_index).hyperlink() != link
 918                        {
 919                            break;
 920                        } else {
 921                            max_index = new_max_index
 922                        }
 923                    }
 924
 925                    let url = link.unwrap().uri().to_owned();
 926                    let url_match = min_index..=max_index;
 927
 928                    Some((url, true, url_match))
 929                } else if let Some(url_match) = regex_match_at(term, point, &mut self.url_regex) {
 930                    let url = term.bounds_to_string(*url_match.start(), *url_match.end());
 931                    Some((url, true, url_match))
 932                } else if let Some(word_match) = regex_match_at(term, point, &mut self.word_regex) {
 933                    let file_path = term.bounds_to_string(*word_match.start(), *word_match.end());
 934
 935                    let (sanitized_match, sanitized_word) = 'sanitize: {
 936                        let mut word_match = word_match;
 937                        let mut file_path = file_path;
 938
 939                        if is_path_surrounded_by_common_symbols(&file_path) {
 940                            word_match = Match::new(
 941                                word_match.start().add(term, Boundary::Grid, 1),
 942                                word_match.end().sub(term, Boundary::Grid, 1),
 943                            );
 944                            file_path = file_path[1..file_path.len() - 1].to_owned();
 945                        }
 946
 947                        while file_path.ends_with(':') {
 948                            file_path.pop();
 949                            word_match = Match::new(
 950                                *word_match.start(),
 951                                word_match.end().sub(term, Boundary::Grid, 1),
 952                            );
 953                        }
 954                        let mut colon_count = 0;
 955                        for c in file_path.chars() {
 956                            if c == ':' {
 957                                colon_count += 1;
 958                            }
 959                        }
 960                        // strip trailing comment after colon in case of
 961                        // file/at/path.rs:row:column:description or error message
 962                        // so that the file path is `file/at/path.rs:row:column`
 963                        if colon_count > 2 {
 964                            let last_index = file_path.rfind(':').unwrap();
 965                            let prev_is_digit = last_index > 0
 966                                && file_path
 967                                    .chars()
 968                                    .nth(last_index - 1)
 969                                    .map_or(false, |c| c.is_ascii_digit());
 970                            let next_is_digit = last_index < file_path.len() - 1
 971                                && file_path
 972                                    .chars()
 973                                    .nth(last_index + 1)
 974                                    .map_or(true, |c| c.is_ascii_digit());
 975                            if prev_is_digit && !next_is_digit {
 976                                let stripped_len = file_path.len() - last_index;
 977                                word_match = Match::new(
 978                                    *word_match.start(),
 979                                    word_match.end().sub(term, Boundary::Grid, stripped_len),
 980                                );
 981                                file_path = file_path[0..last_index].to_owned();
 982                            }
 983                        }
 984
 985                        break 'sanitize (word_match, file_path);
 986                    };
 987
 988                    Some((sanitized_word, false, sanitized_match))
 989                } else {
 990                    None
 991                };
 992
 993                match found_word {
 994                    Some((maybe_url_or_path, is_url, url_match)) => {
 995                        let target = if is_url {
 996                            // Treat "file://" URLs like file paths to ensure
 997                            // that line numbers at the end of the path are
 998                            // handled correctly
 999                            if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
1000                                MaybeNavigationTarget::PathLike(PathLikeTarget {
1001                                    maybe_path: path.to_string(),
1002                                    terminal_dir: self.working_directory(),
1003                                })
1004                            } else {
1005                                MaybeNavigationTarget::Url(maybe_url_or_path.clone())
1006                            }
1007                        } else {
1008                            MaybeNavigationTarget::PathLike(PathLikeTarget {
1009                                maybe_path: maybe_url_or_path.clone(),
1010                                terminal_dir: self.working_directory(),
1011                            })
1012                        };
1013                        if *open {
1014                            cx.emit(Event::Open(target));
1015                        } else {
1016                            self.update_selected_word(
1017                                prev_hovered_word,
1018                                url_match,
1019                                maybe_url_or_path,
1020                                target,
1021                                cx,
1022                            );
1023                        }
1024                    }
1025                    None => {
1026                        cx.emit(Event::NewNavigationTarget(None));
1027                    }
1028                }
1029            }
1030        }
1031    }
1032
1033    fn update_selected_word(
1034        &mut self,
1035        prev_word: Option<HoveredWord>,
1036        word_match: RangeInclusive<AlacPoint>,
1037        word: String,
1038        navigation_target: MaybeNavigationTarget,
1039        cx: &mut Context<Self>,
1040    ) {
1041        if let Some(prev_word) = prev_word {
1042            if prev_word.word == word && prev_word.word_match == word_match {
1043                self.last_content.last_hovered_word = Some(HoveredWord {
1044                    word,
1045                    word_match,
1046                    id: prev_word.id,
1047                });
1048                return;
1049            }
1050        }
1051
1052        self.last_content.last_hovered_word = Some(HoveredWord {
1053            word: word.clone(),
1054            word_match,
1055            id: self.next_link_id(),
1056        });
1057        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1058        cx.notify()
1059    }
1060
1061    fn next_link_id(&mut self) -> usize {
1062        let res = self.next_link_id;
1063        self.next_link_id = self.next_link_id.wrapping_add(1);
1064        res
1065    }
1066
1067    pub fn last_content(&self) -> &TerminalContent {
1068        &self.last_content
1069    }
1070
1071    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1072        self.term_config.default_cursor_style = cursor_shape.into();
1073        self.term.lock().set_options(self.term_config.clone());
1074    }
1075
1076    pub fn total_lines(&self) -> usize {
1077        let term = self.term.clone();
1078        let terminal = term.lock_unfair();
1079        terminal.total_lines()
1080    }
1081
1082    pub fn viewport_lines(&self) -> usize {
1083        let term = self.term.clone();
1084        let terminal = term.lock_unfair();
1085        terminal.screen_lines()
1086    }
1087
1088    //To test:
1089    //- Activate match on terminal (scrolling and selection)
1090    //- Editor search snapping behavior
1091
1092    pub fn activate_match(&mut self, index: usize) {
1093        if let Some(search_match) = self.matches.get(index).cloned() {
1094            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1095
1096            self.events
1097                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1098        }
1099    }
1100
1101    pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1102        let matches_to_select = self
1103            .matches
1104            .iter()
1105            .filter(|self_match| matches.contains(self_match))
1106            .cloned()
1107            .collect::<Vec<_>>();
1108        for match_to_select in matches_to_select {
1109            self.set_selection(Some((
1110                make_selection(&match_to_select),
1111                *match_to_select.end(),
1112            )));
1113        }
1114    }
1115
1116    pub fn select_all(&mut self) {
1117        let term = self.term.lock();
1118        let start = AlacPoint::new(term.topmost_line(), Column(0));
1119        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1120        drop(term);
1121        self.set_selection(Some((make_selection(&(start..=end)), end)));
1122    }
1123
1124    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1125        self.events
1126            .push_back(InternalEvent::SetSelection(selection));
1127    }
1128
1129    pub fn copy(&mut self) {
1130        self.events.push_back(InternalEvent::Copy);
1131    }
1132
1133    pub fn clear(&mut self) {
1134        self.events.push_back(InternalEvent::Clear)
1135    }
1136
1137    pub fn scroll_line_up(&mut self) {
1138        self.events
1139            .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1140    }
1141
1142    pub fn scroll_up_by(&mut self, lines: usize) {
1143        self.events
1144            .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1145    }
1146
1147    pub fn scroll_line_down(&mut self) {
1148        self.events
1149            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1150    }
1151
1152    pub fn scroll_down_by(&mut self, lines: usize) {
1153        self.events
1154            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1155    }
1156
1157    pub fn scroll_page_up(&mut self) {
1158        self.events
1159            .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1160    }
1161
1162    pub fn scroll_page_down(&mut self) {
1163        self.events
1164            .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1165    }
1166
1167    pub fn scroll_to_top(&mut self) {
1168        self.events
1169            .push_back(InternalEvent::Scroll(AlacScroll::Top));
1170    }
1171
1172    pub fn scroll_to_bottom(&mut self) {
1173        self.events
1174            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1175    }
1176
1177    ///Resize the terminal and the PTY.
1178    pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1179        if self.last_content.terminal_bounds != new_bounds {
1180            self.events.push_back(InternalEvent::Resize(new_bounds))
1181        }
1182    }
1183
1184    ///Write the Input payload to the tty.
1185    fn write_to_pty(&self, input: String) {
1186        self.pty_tx.notify(input.into_bytes());
1187    }
1188
1189    fn write_bytes_to_pty(&self, input: Vec<u8>) {
1190        self.pty_tx.notify(input);
1191    }
1192
1193    pub fn input(&mut self, input: String) {
1194        self.events
1195            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1196        self.events.push_back(InternalEvent::SetSelection(None));
1197
1198        self.write_to_pty(input);
1199    }
1200
1201    pub fn input_bytes(&mut self, input: Vec<u8>) {
1202        self.events
1203            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1204        self.events.push_back(InternalEvent::SetSelection(None));
1205
1206        self.write_bytes_to_pty(input);
1207    }
1208
1209    pub fn toggle_vi_mode(&mut self) {
1210        self.events.push_back(InternalEvent::ToggleViMode);
1211    }
1212
1213    pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1214        if !self.vi_mode_enabled {
1215            return;
1216        }
1217
1218        let mut key = keystroke.key.clone();
1219        if keystroke.modifiers.shift {
1220            key = key.to_uppercase();
1221        }
1222
1223        let motion: Option<ViMotion> = match key.as_str() {
1224            "h" | "left" => Some(ViMotion::Left),
1225            "j" | "down" => Some(ViMotion::Down),
1226            "k" | "up" => Some(ViMotion::Up),
1227            "l" | "right" => Some(ViMotion::Right),
1228            "w" => Some(ViMotion::WordRight),
1229            "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1230            "e" => Some(ViMotion::WordRightEnd),
1231            "%" => Some(ViMotion::Bracket),
1232            "$" => Some(ViMotion::Last),
1233            "0" => Some(ViMotion::First),
1234            "^" => Some(ViMotion::FirstOccupied),
1235            "H" => Some(ViMotion::High),
1236            "M" => Some(ViMotion::Middle),
1237            "L" => Some(ViMotion::Low),
1238            _ => None,
1239        };
1240
1241        if let Some(motion) = motion {
1242            let cursor = self.last_content.cursor.point;
1243            let cursor_pos = Point {
1244                x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1245                y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1246            };
1247            self.events
1248                .push_back(InternalEvent::UpdateSelection(cursor_pos));
1249            self.events.push_back(InternalEvent::ViMotion(motion));
1250            return;
1251        }
1252
1253        let scroll_motion = match key.as_str() {
1254            "g" => Some(AlacScroll::Top),
1255            "G" => Some(AlacScroll::Bottom),
1256            "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1257            "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1258            "d" if keystroke.modifiers.control => {
1259                let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1260                Some(AlacScroll::Delta(-amount))
1261            }
1262            "u" if keystroke.modifiers.control => {
1263                let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1264                Some(AlacScroll::Delta(amount))
1265            }
1266            _ => None,
1267        };
1268
1269        if let Some(scroll_motion) = scroll_motion {
1270            self.events.push_back(InternalEvent::Scroll(scroll_motion));
1271            return;
1272        }
1273
1274        match key.as_str() {
1275            "v" => {
1276                let point = self.last_content.cursor.point;
1277                let selection_type = SelectionType::Simple;
1278                let side = AlacDirection::Right;
1279                let selection = Selection::new(selection_type, point, side);
1280                self.events
1281                    .push_back(InternalEvent::SetSelection(Some((selection, point))));
1282                return;
1283            }
1284
1285            "escape" => {
1286                self.events.push_back(InternalEvent::SetSelection(None));
1287                return;
1288            }
1289
1290            "y" => {
1291                self.events.push_back(InternalEvent::Copy);
1292                self.events.push_back(InternalEvent::SetSelection(None));
1293                return;
1294            }
1295
1296            "i" => {
1297                self.scroll_to_bottom();
1298                self.toggle_vi_mode();
1299                return;
1300            }
1301            _ => {}
1302        }
1303    }
1304
1305    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1306        if self.vi_mode_enabled {
1307            self.vi_motion(keystroke);
1308            return true;
1309        }
1310
1311        // Keep default terminal behavior
1312        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1313        if let Some(esc) = esc {
1314            self.input(esc);
1315            true
1316        } else {
1317            false
1318        }
1319    }
1320
1321    pub fn try_modifiers_change(
1322        &mut self,
1323        modifiers: &Modifiers,
1324        window: &Window,
1325        cx: &mut Context<Self>,
1326    ) {
1327        if self
1328            .last_content
1329            .terminal_bounds
1330            .bounds
1331            .contains(&window.mouse_position())
1332            && modifiers.secondary()
1333        {
1334            self.refresh_hovered_word(window);
1335        }
1336        cx.notify();
1337    }
1338
1339    ///Paste text into the terminal
1340    pub fn paste(&mut self, text: &str) {
1341        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1342            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1343        } else {
1344            text.replace("\r\n", "\r").replace('\n', "\r")
1345        };
1346
1347        self.input(paste_text);
1348    }
1349
1350    pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1351        let term = self.term.clone();
1352        let mut terminal = term.lock_unfair();
1353        //Note that the ordering of events matters for event processing
1354        while let Some(e) = self.events.pop_front() {
1355            self.process_terminal_event(&e, &mut terminal, window, cx)
1356        }
1357
1358        self.last_content = Self::make_content(&terminal, &self.last_content);
1359    }
1360
1361    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1362        let content = term.renderable_content();
1363        TerminalContent {
1364            cells: content
1365                .display_iter
1366                //TODO: Add this once there's a way to retain empty lines
1367                // .filter(|ic| {
1368                //     !ic.flags.contains(Flags::HIDDEN)
1369                //         && !(ic.bg == Named(NamedColor::Background)
1370                //             && ic.c == ' '
1371                //             && !ic.flags.contains(Flags::INVERSE))
1372                // })
1373                .map(|ic| IndexedCell {
1374                    point: ic.point,
1375                    cell: ic.cell.clone(),
1376                })
1377                .collect::<Vec<IndexedCell>>(),
1378            mode: content.mode,
1379            display_offset: content.display_offset,
1380            selection_text: term.selection_to_string(),
1381            selection: content.selection,
1382            cursor: content.cursor,
1383            cursor_char: term.grid()[content.cursor.point].c,
1384            terminal_bounds: last_content.terminal_bounds,
1385            last_hovered_word: last_content.last_hovered_word.clone(),
1386        }
1387    }
1388
1389    pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1390        let term = self.term.clone();
1391        let terminal = term.lock_unfair();
1392        let grid = terminal.grid();
1393        let mut lines = Vec::new();
1394
1395        let mut current_line = grid.bottommost_line().0;
1396        let topmost_line = grid.topmost_line().0;
1397
1398        while current_line >= topmost_line && lines.len() < n {
1399            let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1400            let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1401
1402            if let Some(line) = self.process_line(logical_line) {
1403                lines.push(line);
1404            }
1405
1406            // Move to the line above the start of the current logical line
1407            current_line = logical_line_start - 1;
1408        }
1409
1410        lines.reverse();
1411        lines
1412    }
1413
1414    fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1415        let mut line_start = current;
1416        while line_start > topmost {
1417            let prev_line = Line(line_start - 1);
1418            let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1419            if !last_cell.flags.contains(Flags::WRAPLINE) {
1420                break;
1421            }
1422            line_start -= 1;
1423        }
1424        line_start
1425    }
1426
1427    fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1428        let mut logical_line = String::new();
1429        for row in start..=end {
1430            let grid_row = &grid[Line(row)];
1431            logical_line.push_str(&row_to_string(grid_row));
1432        }
1433        logical_line
1434    }
1435
1436    fn process_line(&self, line: String) -> Option<String> {
1437        let trimmed = line.trim_end().to_string();
1438        if !trimmed.is_empty() {
1439            Some(trimmed)
1440        } else {
1441            None
1442        }
1443    }
1444
1445    pub fn focus_in(&self) {
1446        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1447            self.write_to_pty("\x1b[I".to_string());
1448        }
1449    }
1450
1451    pub fn focus_out(&mut self) {
1452        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1453            self.write_to_pty("\x1b[O".to_string());
1454        }
1455    }
1456
1457    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1458        match self.last_mouse {
1459            Some((old_point, old_side)) => {
1460                if old_point == point && old_side == side {
1461                    false
1462                } else {
1463                    self.last_mouse = Some((point, side));
1464                    true
1465                }
1466            }
1467            None => {
1468                self.last_mouse = Some((point, side));
1469                true
1470            }
1471        }
1472    }
1473
1474    pub fn mouse_mode(&self, shift: bool) -> bool {
1475        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1476    }
1477
1478    pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1479        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1480        if self.mouse_mode(e.modifiers.shift) {
1481            let (point, side) = grid_point_and_side(
1482                position,
1483                self.last_content.terminal_bounds,
1484                self.last_content.display_offset,
1485            );
1486
1487            if self.mouse_changed(point, side) {
1488                if let Some(bytes) =
1489                    mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1490                {
1491                    self.pty_tx.notify(bytes);
1492                }
1493            }
1494        } else if e.modifiers.secondary() {
1495            self.word_from_position(e.position);
1496        }
1497        cx.notify();
1498    }
1499
1500    fn word_from_position(&mut self, position: Point<Pixels>) {
1501        if self.selection_phase == SelectionPhase::Selecting {
1502            self.last_content.last_hovered_word = None;
1503        } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1504            self.events.push_back(InternalEvent::FindHyperlink(
1505                position - self.last_content.terminal_bounds.bounds.origin,
1506                false,
1507            ));
1508        } else {
1509            self.last_content.last_hovered_word = None;
1510        }
1511    }
1512
1513    pub fn mouse_drag(
1514        &mut self,
1515        e: &MouseMoveEvent,
1516        region: Bounds<Pixels>,
1517        cx: &mut Context<Self>,
1518    ) {
1519        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1520        if !self.mouse_mode(e.modifiers.shift) {
1521            self.selection_phase = SelectionPhase::Selecting;
1522            // Alacritty has the same ordering, of first updating the selection
1523            // then scrolling 15ms later
1524            self.events
1525                .push_back(InternalEvent::UpdateSelection(position));
1526
1527            // Doesn't make sense to scroll the alt screen
1528            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1529                let scroll_lines = match self.drag_line_delta(e, region) {
1530                    Some(value) => value,
1531                    None => return,
1532                };
1533
1534                self.events
1535                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1536            }
1537
1538            cx.notify();
1539        }
1540    }
1541
1542    fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1543        let top = region.origin.y;
1544        let bottom = region.bottom_left().y;
1545
1546        let scroll_lines = if e.position.y < top {
1547            let scroll_delta = (top - e.position.y).pow(1.1);
1548            (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1549        } else if e.position.y > bottom {
1550            let scroll_delta = -((e.position.y - bottom).pow(1.1));
1551            (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1552        } else {
1553            return None;
1554        };
1555
1556        Some(scroll_lines)
1557    }
1558
1559    pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1560        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1561        let point = grid_point(
1562            position,
1563            self.last_content.terminal_bounds,
1564            self.last_content.display_offset,
1565        );
1566
1567        if self.mouse_mode(e.modifiers.shift) {
1568            if let Some(bytes) =
1569                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1570            {
1571                self.pty_tx.notify(bytes);
1572            }
1573        } else {
1574            match e.button {
1575                MouseButton::Left => {
1576                    let (point, side) = grid_point_and_side(
1577                        position,
1578                        self.last_content.terminal_bounds,
1579                        self.last_content.display_offset,
1580                    );
1581
1582                    let selection_type = match e.click_count {
1583                        0 => return, //This is a release
1584                        1 => Some(SelectionType::Simple),
1585                        2 => Some(SelectionType::Semantic),
1586                        3 => Some(SelectionType::Lines),
1587                        _ => None,
1588                    };
1589
1590                    if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1591                        self.events
1592                            .push_back(InternalEvent::UpdateSelection(position));
1593                        return;
1594                    }
1595
1596                    let selection = selection_type
1597                        .map(|selection_type| Selection::new(selection_type, point, side));
1598
1599                    if let Some(sel) = selection {
1600                        self.events
1601                            .push_back(InternalEvent::SetSelection(Some((sel, point))));
1602                    }
1603                }
1604                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1605                MouseButton::Middle => {
1606                    if let Some(item) = _cx.read_from_primary() {
1607                        let text = item.text().unwrap_or_default().to_string();
1608                        self.input(text);
1609                    }
1610                }
1611                _ => {}
1612            }
1613        }
1614    }
1615
1616    pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1617        let setting = TerminalSettings::get_global(cx);
1618
1619        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1620        if self.mouse_mode(e.modifiers.shift) {
1621            let point = grid_point(
1622                position,
1623                self.last_content.terminal_bounds,
1624                self.last_content.display_offset,
1625            );
1626
1627            if let Some(bytes) =
1628                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1629            {
1630                self.pty_tx.notify(bytes);
1631            }
1632        } else {
1633            if e.button == MouseButton::Left && setting.copy_on_select {
1634                self.copy();
1635            }
1636
1637            //Hyperlinks
1638            if self.selection_phase == SelectionPhase::Ended {
1639                let mouse_cell_index =
1640                    content_index_for_mouse(position, &self.last_content.terminal_bounds);
1641                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1642                    cx.open_url(link.uri());
1643                } else if e.modifiers.secondary() {
1644                    self.events
1645                        .push_back(InternalEvent::FindHyperlink(position, true));
1646                }
1647            }
1648        }
1649
1650        self.selection_phase = SelectionPhase::Ended;
1651        self.last_mouse = None;
1652    }
1653
1654    ///Scroll the terminal
1655    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1656        let mouse_mode = self.mouse_mode(e.shift);
1657
1658        if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1659            if mouse_mode {
1660                let point = grid_point(
1661                    e.position - self.last_content.terminal_bounds.bounds.origin,
1662                    self.last_content.terminal_bounds,
1663                    self.last_content.display_offset,
1664                );
1665
1666                if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1667                {
1668                    for scroll in scrolls {
1669                        self.pty_tx.notify(scroll);
1670                    }
1671                };
1672            } else if self
1673                .last_content
1674                .mode
1675                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1676                && !e.shift
1677            {
1678                self.pty_tx.notify(alt_scroll(scroll_lines))
1679            } else if scroll_lines != 0 {
1680                let scroll = AlacScroll::Delta(scroll_lines);
1681
1682                self.events.push_back(InternalEvent::Scroll(scroll));
1683            }
1684        }
1685    }
1686
1687    fn refresh_hovered_word(&mut self, window: &Window) {
1688        self.word_from_position(window.mouse_position());
1689    }
1690
1691    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1692        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1693        let line_height = self.last_content.terminal_bounds.line_height;
1694        match e.touch_phase {
1695            /* Reset scroll state on started */
1696            TouchPhase::Started => {
1697                self.scroll_px = px(0.);
1698                None
1699            }
1700            /* Calculate the appropriate scroll lines */
1701            TouchPhase::Moved => {
1702                let old_offset = (self.scroll_px / line_height) as i32;
1703
1704                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1705
1706                let new_offset = (self.scroll_px / line_height) as i32;
1707
1708                // Whenever we hit the edges, reset our stored scroll to 0
1709                // so we can respond to changes in direction quickly
1710                self.scroll_px %= self.last_content.terminal_bounds.height();
1711
1712                Some(new_offset - old_offset)
1713            }
1714            TouchPhase::Ended => None,
1715        }
1716    }
1717
1718    pub fn find_matches(
1719        &self,
1720        mut searcher: RegexSearch,
1721        cx: &Context<Self>,
1722    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1723        let term = self.term.clone();
1724        cx.background_spawn(async move {
1725            let term = term.lock();
1726
1727            all_search_matches(&term, &mut searcher).collect()
1728        })
1729    }
1730
1731    pub fn working_directory(&self) -> Option<PathBuf> {
1732        if self.is_ssh_terminal {
1733            // We can't yet reliably detect the working directory of a shell on the
1734            // SSH host. Until we can do that, it doesn't make sense to display
1735            // the working directory on the client and persist that.
1736            None
1737        } else {
1738            self.client_side_working_directory()
1739        }
1740    }
1741
1742    /// Returns the working directory of the process that's connected to the PTY.
1743    /// That means it returns the working directory of the local shell or program
1744    /// that's running inside the terminal.
1745    ///
1746    /// This does *not* return the working directory of the shell that runs on the
1747    /// remote host, in case Zed is connected to a remote host.
1748    fn client_side_working_directory(&self) -> Option<PathBuf> {
1749        self.pty_info
1750            .current
1751            .as_ref()
1752            .map(|process| process.cwd.clone())
1753    }
1754
1755    pub fn title(&self, truncate: bool) -> String {
1756        const MAX_CHARS: usize = 25;
1757        match &self.task {
1758            Some(task_state) => {
1759                if truncate {
1760                    truncate_and_trailoff(&task_state.label, MAX_CHARS)
1761                } else {
1762                    task_state.full_label.clone()
1763                }
1764            }
1765            None => self
1766                .title_override
1767                .as_ref()
1768                .map(|title_override| title_override.to_string())
1769                .unwrap_or_else(|| {
1770                    self.pty_info
1771                        .current
1772                        .as_ref()
1773                        .map(|fpi| {
1774                            let process_file = fpi
1775                                .cwd
1776                                .file_name()
1777                                .map(|name| name.to_string_lossy().to_string())
1778                                .unwrap_or_default();
1779
1780                            let argv = fpi.argv.clone();
1781                            let process_name = format!(
1782                                "{}{}",
1783                                fpi.name,
1784                                if !argv.is_empty() {
1785                                    format!(" {}", (argv[1..]).join(" "))
1786                                } else {
1787                                    "".to_string()
1788                                }
1789                            );
1790                            let (process_file, process_name) = if truncate {
1791                                (
1792                                    truncate_and_trailoff(&process_file, MAX_CHARS),
1793                                    truncate_and_trailoff(&process_name, MAX_CHARS),
1794                                )
1795                            } else {
1796                                (process_file, process_name)
1797                            };
1798                            format!("{process_file}{process_name}")
1799                        })
1800                        .unwrap_or_else(|| "Terminal".to_string())
1801                }),
1802        }
1803    }
1804
1805    pub fn task(&self) -> Option<&TaskState> {
1806        self.task.as_ref()
1807    }
1808
1809    pub fn debug_terminal(&self) -> bool {
1810        self.debug_terminal
1811    }
1812
1813    pub fn wait_for_completed_task(&self, cx: &App) -> Task<()> {
1814        if let Some(task) = self.task() {
1815            if task.status == TaskStatus::Running {
1816                let completion_receiver = task.completion_rx.clone();
1817                return cx.spawn(|_| async move {
1818                    let _ = completion_receiver.recv().await;
1819                });
1820            }
1821        }
1822        Task::ready(())
1823    }
1824
1825    fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<'_, Terminal>) {
1826        self.completion_tx.try_send(()).ok();
1827        let task = match &mut self.task {
1828            Some(task) => task,
1829            None => {
1830                if error_code.is_none() {
1831                    cx.emit(Event::CloseTerminal);
1832                }
1833                return;
1834            }
1835        };
1836        if task.status != TaskStatus::Running {
1837            return;
1838        }
1839        match error_code {
1840            Some(error_code) => {
1841                task.status.register_task_exit(error_code);
1842            }
1843            None => {
1844                task.status.register_terminal_exit();
1845            }
1846        };
1847
1848        let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1849        let mut lines_to_show = Vec::new();
1850        if task.show_summary {
1851            lines_to_show.push(task_line.as_str());
1852        }
1853        if task.show_command {
1854            lines_to_show.push(command_line.as_str());
1855        }
1856
1857        if !lines_to_show.is_empty() {
1858            // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1859            // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1860            // when Zed task finishes and no more output is made.
1861            // After the task summary is output once, no more text is appended to the terminal.
1862            unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1863        }
1864
1865        match task.hide {
1866            HideStrategy::Never => {}
1867            HideStrategy::Always => {
1868                cx.emit(Event::CloseTerminal);
1869            }
1870            HideStrategy::OnSuccess => {
1871                if finished_successfully {
1872                    cx.emit(Event::CloseTerminal);
1873                }
1874            }
1875        }
1876    }
1877}
1878
1879// Helper function to convert a grid row to a string
1880pub fn row_to_string(row: &Row<Cell>) -> String {
1881    row[..Column(row.len())]
1882        .iter()
1883        .map(|cell| cell.c)
1884        .collect::<String>()
1885}
1886
1887fn is_path_surrounded_by_common_symbols(path: &str) -> bool {
1888    // Avoid detecting `[]` or `()` strings as paths, surrounded by common symbols
1889    path.len() > 2
1890        // The rest of the brackets and various quotes cannot be matched by the [`WORD_REGEX`] hence not checked for.
1891        && (path.starts_with('[') && path.ends_with(']')
1892            || path.starts_with('(') && path.ends_with(')'))
1893}
1894
1895const TASK_DELIMITER: &str = "";
1896fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1897    let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1898    let (success, task_line) = match error_code {
1899        Some(0) => {
1900            (true, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"))
1901        }
1902        Some(error_code) => {
1903            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"))
1904        }
1905        None => {
1906            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"))
1907        }
1908    };
1909    let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1910    let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1911    (success, task_line, command_line)
1912}
1913
1914/// Appends a stringified task summary to the terminal, after its output.
1915///
1916/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1917/// New text being added to the terminal here, uses "less public" APIs,
1918/// which are not maintaining the entire terminal state intact.
1919///
1920///
1921/// The library
1922///
1923/// * does not increment inner grid cursor's _lines_ on `input` calls
1924///   (but displaying the lines correctly and incrementing cursor's columns)
1925///
1926/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1927///
1928/// * does not alter grid state after `newline` call
1929///   so its `bottommost_line` is always the same additions, and
1930///   the cursor's `point` is not updated to the new line and column values
1931///
1932/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1933///   Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1934///
1935/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1936/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1937/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1938/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1939unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1940    term.newline();
1941    term.grid_mut().cursor.point.column = Column(0);
1942    for line in text_lines {
1943        for c in line.chars() {
1944            term.input(c);
1945        }
1946        term.newline();
1947        term.grid_mut().cursor.point.column = Column(0);
1948    }
1949}
1950
1951impl Drop for Terminal {
1952    fn drop(&mut self) {
1953        self.pty_tx.0.send(Msg::Shutdown).ok();
1954    }
1955}
1956
1957impl EventEmitter<Event> for Terminal {}
1958
1959/// Based on alacritty/src/display/hint.rs > regex_match_at
1960/// Retrieve the match, if the specified point is inside the content matching the regex.
1961fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1962    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1963}
1964
1965/// Copied from alacritty/src/display/hint.rs:
1966/// Iterate over all visible regex matches.
1967pub fn visible_regex_match_iter<'a, T>(
1968    term: &'a Term<T>,
1969    regex: &'a mut RegexSearch,
1970) -> impl Iterator<Item = Match> + 'a {
1971    let viewport_start = Line(-(term.grid().display_offset() as i32));
1972    let viewport_end = viewport_start + term.bottommost_line();
1973    let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1974    let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1975    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1976    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1977
1978    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1979        .skip_while(move |rm| rm.end().line < viewport_start)
1980        .take_while(move |rm| rm.start().line <= viewport_end)
1981}
1982
1983fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1984    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1985    selection.update(*range.end(), AlacDirection::Right);
1986    selection
1987}
1988
1989fn all_search_matches<'a, T>(
1990    term: &'a Term<T>,
1991    regex: &'a mut RegexSearch,
1992) -> impl Iterator<Item = Match> + 'a {
1993    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1994    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1995    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1996}
1997
1998fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
1999    let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
2000    let clamped_col = min(col, terminal_bounds.columns() - 1);
2001    let row = (pos.y / terminal_bounds.line_height()).round() as usize;
2002    let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
2003    clamped_row * terminal_bounds.columns() + clamped_col
2004}
2005
2006/// Converts an 8 bit ANSI color to its GPUI equivalent.
2007/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
2008/// Other than that use case, should only be called with values in the `[0,255]` range
2009pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
2010    let colors = theme.colors();
2011
2012    match index {
2013        // 0-15 are the same as the named colors above
2014        0 => colors.terminal_ansi_black,
2015        1 => colors.terminal_ansi_red,
2016        2 => colors.terminal_ansi_green,
2017        3 => colors.terminal_ansi_yellow,
2018        4 => colors.terminal_ansi_blue,
2019        5 => colors.terminal_ansi_magenta,
2020        6 => colors.terminal_ansi_cyan,
2021        7 => colors.terminal_ansi_white,
2022        8 => colors.terminal_ansi_bright_black,
2023        9 => colors.terminal_ansi_bright_red,
2024        10 => colors.terminal_ansi_bright_green,
2025        11 => colors.terminal_ansi_bright_yellow,
2026        12 => colors.terminal_ansi_bright_blue,
2027        13 => colors.terminal_ansi_bright_magenta,
2028        14 => colors.terminal_ansi_bright_cyan,
2029        15 => colors.terminal_ansi_bright_white,
2030        // 16-231 are mapped to their RGB colors on a 0-5 range per channel
2031        16..=231 => {
2032            let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
2033            let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
2034            rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
2035        }
2036        // 232-255 are a 24 step grayscale from black to white
2037        232..=255 => {
2038            let i = index as u8 - 232; // Align index to 0..24
2039            let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
2040            rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
2041        }
2042        // For compatibility with the alacritty::Colors interface
2043        256 => colors.text,
2044        257 => colors.background,
2045        258 => theme.players().local().cursor,
2046        259 => colors.terminal_ansi_dim_black,
2047        260 => colors.terminal_ansi_dim_red,
2048        261 => colors.terminal_ansi_dim_green,
2049        262 => colors.terminal_ansi_dim_yellow,
2050        263 => colors.terminal_ansi_dim_blue,
2051        264 => colors.terminal_ansi_dim_magenta,
2052        265 => colors.terminal_ansi_dim_cyan,
2053        266 => colors.terminal_ansi_dim_white,
2054        267 => colors.terminal_bright_foreground,
2055        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
2056
2057        _ => black(),
2058    }
2059}
2060
2061/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
2062/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
2063///
2064/// Wikipedia gives a formula for calculating the index for a given color:
2065///
2066/// ```
2067/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2068/// ```
2069///
2070/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2071fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2072    debug_assert!((16..=231).contains(&i));
2073    let i = i - 16;
2074    let r = (i - (i % 36)) / 36;
2075    let g = ((i % 36) - (i % 6)) / 6;
2076    let b = (i % 36) % 6;
2077    (r, g, b)
2078}
2079
2080pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2081    Rgba {
2082        r: (r as f32 / 255.),
2083        g: (g as f32 / 255.),
2084        b: (b as f32 / 255.),
2085        a: 1.,
2086    }
2087    .into()
2088}
2089
2090#[cfg(test)]
2091mod tests {
2092    use alacritty_terminal::{
2093        index::{Column, Line, Point as AlacPoint},
2094        term::cell::Cell,
2095    };
2096    use gpui::{bounds, point, size, Pixels, Point};
2097    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
2098
2099    use crate::{
2100        content_index_for_mouse, rgb_for_index, IndexedCell, TerminalBounds, TerminalContent,
2101    };
2102
2103    #[test]
2104    fn test_rgb_for_index() {
2105        // Test every possible value in the color cube.
2106        for i in 16..=231 {
2107            let (r, g, b) = rgb_for_index(i);
2108            assert_eq!(i, 16 + 36 * r + 6 * g + b);
2109        }
2110    }
2111
2112    #[test]
2113    fn test_mouse_to_cell_test() {
2114        let mut rng = thread_rng();
2115        const ITERATIONS: usize = 10;
2116        const PRECISION: usize = 1000;
2117
2118        for _ in 0..ITERATIONS {
2119            let viewport_cells = rng.gen_range(15..20);
2120            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2121
2122            let size = crate::TerminalBounds {
2123                cell_width: Pixels::from(cell_size),
2124                line_height: Pixels::from(cell_size),
2125                bounds: bounds(
2126                    Point::default(),
2127                    size(
2128                        Pixels::from(cell_size * (viewport_cells as f32)),
2129                        Pixels::from(cell_size * (viewport_cells as f32)),
2130                    ),
2131                ),
2132            };
2133
2134            let cells = get_cells(size, &mut rng);
2135            let content = convert_cells_to_content(size, &cells);
2136
2137            for row in 0..(viewport_cells - 1) {
2138                let row = row as usize;
2139                for col in 0..(viewport_cells - 1) {
2140                    let col = col as usize;
2141
2142                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2143                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2144
2145                    let mouse_pos = point(
2146                        Pixels::from(col as f32 * cell_size + col_offset),
2147                        Pixels::from(row as f32 * cell_size + row_offset),
2148                    );
2149
2150                    let content_index =
2151                        content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2152                    let mouse_cell = content.cells[content_index].c;
2153                    let real_cell = cells[row][col];
2154
2155                    assert_eq!(mouse_cell, real_cell);
2156                }
2157            }
2158        }
2159    }
2160
2161    #[test]
2162    fn test_mouse_to_cell_clamp() {
2163        let mut rng = thread_rng();
2164
2165        let size = crate::TerminalBounds {
2166            cell_width: Pixels::from(10.),
2167            line_height: Pixels::from(10.),
2168            bounds: bounds(
2169                Point::default(),
2170                size(Pixels::from(100.), Pixels::from(100.)),
2171            ),
2172        };
2173
2174        let cells = get_cells(size, &mut rng);
2175        let content = convert_cells_to_content(size, &cells);
2176
2177        assert_eq!(
2178            content.cells[content_index_for_mouse(
2179                point(Pixels::from(-10.), Pixels::from(-10.)),
2180                &content.terminal_bounds,
2181            )]
2182            .c,
2183            cells[0][0]
2184        );
2185        assert_eq!(
2186            content.cells[content_index_for_mouse(
2187                point(Pixels::from(1000.), Pixels::from(1000.)),
2188                &content.terminal_bounds,
2189            )]
2190            .c,
2191            cells[9][9]
2192        );
2193    }
2194
2195    fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2196        let mut cells = Vec::new();
2197
2198        for _ in 0..((size.height() / size.line_height()) as usize) {
2199            let mut row_vec = Vec::new();
2200            for _ in 0..((size.width() / size.cell_width()) as usize) {
2201                let cell_char = rng.sample(Alphanumeric) as char;
2202                row_vec.push(cell_char)
2203            }
2204            cells.push(row_vec)
2205        }
2206
2207        cells
2208    }
2209
2210    fn convert_cells_to_content(
2211        terminal_bounds: TerminalBounds,
2212        cells: &[Vec<char>],
2213    ) -> TerminalContent {
2214        let mut ic = Vec::new();
2215
2216        for (index, row) in cells.iter().enumerate() {
2217            for (cell_index, cell_char) in row.iter().enumerate() {
2218                ic.push(IndexedCell {
2219                    point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2220                    cell: Cell {
2221                        c: *cell_char,
2222                        ..Default::default()
2223                    },
2224                });
2225            }
2226        }
2227
2228        TerminalContent {
2229            cells: ic,
2230            terminal_bounds,
2231            ..Default::default()
2232        }
2233    }
2234
2235    fn re_test(re: &str, hay: &str, expected: Vec<&str>) {
2236        let results: Vec<_> = regex::Regex::new(re)
2237            .unwrap()
2238            .find_iter(hay)
2239            .map(|m| m.as_str())
2240            .collect();
2241        assert_eq!(results, expected);
2242    }
2243    #[test]
2244    fn test_url_regex() {
2245        re_test(
2246            crate::URL_REGEX,
2247            "test http://example.com test mailto:bob@example.com train",
2248            vec!["http://example.com", "mailto:bob@example.com"],
2249        );
2250    }
2251    #[test]
2252    fn test_word_regex() {
2253        re_test(
2254            crate::WORD_REGEX,
2255            "hello, world! \"What\" is this?",
2256            vec!["hello", "world", "What", "is", "this"],
2257        );
2258    }
2259    #[test]
2260    fn test_word_regex_with_linenum() {
2261        // filename(line) and filename(line,col) as used in MSBuild output
2262        // should be considered a single "word", even though comma is
2263        // usually a word separator
2264        re_test(
2265            crate::WORD_REGEX,
2266            "a Main.cs(20) b",
2267            vec!["a", "Main.cs(20)", "b"],
2268        );
2269        re_test(
2270            crate::WORD_REGEX,
2271            "Main.cs(20,5) Error desc",
2272            vec!["Main.cs(20,5)", "Error", "desc"],
2273        );
2274        // filename:line:col is a popular format for unix tools
2275        re_test(
2276            crate::WORD_REGEX,
2277            "a Main.cs:20:5 b",
2278            vec!["a", "Main.cs:20:5", "b"],
2279        );
2280        // Some tools output "filename:line:col:message", which currently isn't
2281        // handled correctly, but might be in the future
2282        re_test(
2283            crate::WORD_REGEX,
2284            "Main.cs:20:5:Error desc",
2285            vec!["Main.cs:20:5:Error", "desc"],
2286        );
2287    }
2288}