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