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,
  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    #[allow(clippy::too_many_arguments)]
 329    pub fn new(
 330        working_directory: Option<PathBuf>,
 331        python_venv_directory: Option<PathBuf>,
 332        task: Option<TaskState>,
 333        shell: Shell,
 334        mut env: HashMap<String, String>,
 335        cursor_shape: CursorShape,
 336        alternate_scroll: AlternateScroll,
 337        max_scroll_history_lines: Option<usize>,
 338        is_ssh_terminal: bool,
 339        window: AnyWindowHandle,
 340        completion_tx: Sender<()>,
 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            is_ssh_terminal,
 478            python_venv_directory,
 479        };
 480
 481        Ok(TerminalBuilder {
 482            terminal,
 483            events_rx,
 484        })
 485    }
 486
 487    pub fn subscribe(mut self, cx: &Context<Terminal>) -> Terminal {
 488        //Event loop
 489        cx.spawn(|terminal, mut cx| async move {
 490            while let Some(event) = self.events_rx.next().await {
 491                terminal.update(&mut cx, |terminal, cx| {
 492                    //Process the first event immediately for lowered latency
 493                    terminal.process_event(&event, cx);
 494                })?;
 495
 496                'outer: loop {
 497                    let mut events = Vec::new();
 498                    let mut timer = cx
 499                        .background_executor()
 500                        .timer(Duration::from_millis(4))
 501                        .fuse();
 502                    let mut wakeup = false;
 503                    loop {
 504                        futures::select_biased! {
 505                            _ = timer => break,
 506                            event = self.events_rx.next() => {
 507                                if let Some(event) = event {
 508                                    if matches!(event, AlacTermEvent::Wakeup) {
 509                                        wakeup = true;
 510                                    } else {
 511                                        events.push(event);
 512                                    }
 513
 514                                    if events.len() > 100 {
 515                                        break;
 516                                    }
 517                                } else {
 518                                    break;
 519                                }
 520                            },
 521                        }
 522                    }
 523
 524                    if events.is_empty() && !wakeup {
 525                        smol::future::yield_now().await;
 526                        break 'outer;
 527                    }
 528
 529                    terminal.update(&mut cx, |this, cx| {
 530                        if wakeup {
 531                            this.process_event(&AlacTermEvent::Wakeup, cx);
 532                        }
 533
 534                        for event in events {
 535                            this.process_event(&event, cx);
 536                        }
 537                    })?;
 538                    smol::future::yield_now().await;
 539                }
 540            }
 541
 542            anyhow::Ok(())
 543        })
 544        .detach();
 545
 546        self.terminal
 547    }
 548}
 549
 550#[derive(Debug, Clone, Deserialize, Serialize)]
 551pub struct IndexedCell {
 552    pub point: AlacPoint,
 553    pub cell: Cell,
 554}
 555
 556impl Deref for IndexedCell {
 557    type Target = Cell;
 558
 559    #[inline]
 560    fn deref(&self) -> &Cell {
 561        &self.cell
 562    }
 563}
 564
 565// TODO: Un-pub
 566#[derive(Clone)]
 567pub struct TerminalContent {
 568    pub cells: Vec<IndexedCell>,
 569    pub mode: TermMode,
 570    pub display_offset: usize,
 571    pub selection_text: Option<String>,
 572    pub selection: Option<SelectionRange>,
 573    pub cursor: RenderableCursor,
 574    pub cursor_char: char,
 575    pub terminal_bounds: TerminalBounds,
 576    pub last_hovered_word: Option<HoveredWord>,
 577}
 578
 579#[derive(Clone)]
 580pub struct HoveredWord {
 581    pub word: String,
 582    pub word_match: RangeInclusive<AlacPoint>,
 583    pub id: usize,
 584}
 585
 586impl Default for TerminalContent {
 587    fn default() -> Self {
 588        TerminalContent {
 589            cells: Default::default(),
 590            mode: Default::default(),
 591            display_offset: Default::default(),
 592            selection_text: Default::default(),
 593            selection: Default::default(),
 594            cursor: RenderableCursor {
 595                shape: alacritty_terminal::vte::ansi::CursorShape::Block,
 596                point: AlacPoint::new(Line(0), Column(0)),
 597            },
 598            cursor_char: Default::default(),
 599            terminal_bounds: Default::default(),
 600            last_hovered_word: None,
 601        }
 602    }
 603}
 604
 605#[derive(PartialEq, Eq)]
 606pub enum SelectionPhase {
 607    Selecting,
 608    Ended,
 609}
 610
 611pub struct Terminal {
 612    pty_tx: Notifier,
 613    completion_tx: Sender<()>,
 614    term: Arc<FairMutex<Term<ZedListener>>>,
 615    term_config: Config,
 616    events: VecDeque<InternalEvent>,
 617    /// This is only used for mouse mode cell change detection
 618    last_mouse: Option<(AlacPoint, AlacDirection)>,
 619    pub matches: Vec<RangeInclusive<AlacPoint>>,
 620    pub last_content: TerminalContent,
 621    pub selection_head: Option<AlacPoint>,
 622    pub breadcrumb_text: String,
 623    pub pty_info: PtyProcessInfo,
 624    title_override: Option<SharedString>,
 625    pub python_venv_directory: Option<PathBuf>,
 626    scroll_px: Pixels,
 627    next_link_id: usize,
 628    selection_phase: SelectionPhase,
 629    url_regex: RegexSearch,
 630    word_regex: RegexSearch,
 631    task: Option<TaskState>,
 632    vi_mode_enabled: bool,
 633    is_ssh_terminal: bool,
 634}
 635
 636pub struct TaskState {
 637    pub id: TaskId,
 638    pub full_label: String,
 639    pub label: String,
 640    pub command_label: String,
 641    pub status: TaskStatus,
 642    pub completion_rx: Receiver<()>,
 643    pub hide: HideStrategy,
 644    pub show_summary: bool,
 645    pub show_command: bool,
 646}
 647
 648/// A status of the current terminal tab's task.
 649#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 650pub enum TaskStatus {
 651    /// The task had been started, but got cancelled or somehow otherwise it did not
 652    /// report its exit code before the terminal event loop was shut down.
 653    Unknown,
 654    /// The task is started and running currently.
 655    Running,
 656    /// After the start, the task stopped running and reported its error code back.
 657    Completed { success: bool },
 658}
 659
 660impl TaskStatus {
 661    fn register_terminal_exit(&mut self) {
 662        if self == &Self::Running {
 663            *self = Self::Unknown;
 664        }
 665    }
 666
 667    fn register_task_exit(&mut self, error_code: i32) {
 668        *self = TaskStatus::Completed {
 669            success: error_code == 0,
 670        };
 671    }
 672}
 673
 674impl Terminal {
 675    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut Context<Self>) {
 676        match event {
 677            AlacTermEvent::Title(title) => {
 678                self.breadcrumb_text = title.to_string();
 679                cx.emit(Event::BreadcrumbsChanged);
 680            }
 681            AlacTermEvent::ResetTitle => {
 682                self.breadcrumb_text = String::new();
 683                cx.emit(Event::BreadcrumbsChanged);
 684            }
 685            AlacTermEvent::ClipboardStore(_, data) => {
 686                cx.write_to_clipboard(ClipboardItem::new_string(data.to_string()))
 687            }
 688            AlacTermEvent::ClipboardLoad(_, format) => {
 689                self.write_to_pty(
 690                    match &cx.read_from_clipboard().and_then(|item| item.text()) {
 691                        // The terminal only supports pasting strings, not images.
 692                        Some(text) => format(text),
 693                        _ => format(""),
 694                    },
 695                )
 696            }
 697            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 698            AlacTermEvent::TextAreaSizeRequest(format) => {
 699                self.write_to_pty(format(self.last_content.terminal_bounds.into()))
 700            }
 701            AlacTermEvent::CursorBlinkingChange => {
 702                let terminal = self.term.lock();
 703                let blinking = terminal.cursor_style().blinking;
 704                cx.emit(Event::BlinkChanged(blinking));
 705            }
 706            AlacTermEvent::Bell => {
 707                cx.emit(Event::Bell);
 708            }
 709            AlacTermEvent::Exit => self.register_task_finished(None, cx),
 710            AlacTermEvent::MouseCursorDirty => {
 711                //NOOP, Handled in render
 712            }
 713            AlacTermEvent::Wakeup => {
 714                cx.emit(Event::Wakeup);
 715
 716                if self.pty_info.has_changed() {
 717                    cx.emit(Event::TitleChanged);
 718                }
 719            }
 720            AlacTermEvent::ColorRequest(index, format) => {
 721                // It's important that the color request is processed here to retain relative order
 722                // with other PTY writes. Otherwise applications might witness out-of-order
 723                // responses to requests. For example: An application sending `OSC 11 ; ? ST`
 724                // (color request) followed by `CSI c` (request device attributes) would receive
 725                // the response to `CSI c` first.
 726                // Instead of locking, we could store the colors in `self.last_content`. But then
 727                // we might respond with out of date value if a "set color" sequence is immediately
 728                // followed by a color request sequence.
 729                let color = self.term.lock().colors()[*index].unwrap_or_else(|| {
 730                    to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
 731                });
 732                self.write_to_pty(format(color));
 733            }
 734            AlacTermEvent::ChildExit(error_code) => {
 735                self.register_task_finished(Some(*error_code), cx);
 736            }
 737        }
 738    }
 739
 740    pub fn selection_started(&self) -> bool {
 741        self.selection_phase == SelectionPhase::Selecting
 742    }
 743
 744    fn process_terminal_event(
 745        &mut self,
 746        event: &InternalEvent,
 747        term: &mut Term<ZedListener>,
 748        window: &mut Window,
 749        cx: &mut Context<Self>,
 750    ) {
 751        match event {
 752            InternalEvent::Resize(mut new_bounds) => {
 753                new_bounds.bounds.size.height =
 754                    cmp::max(new_bounds.line_height, new_bounds.height());
 755                new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
 756
 757                self.last_content.terminal_bounds = new_bounds;
 758
 759                self.pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
 760
 761                term.resize(new_bounds);
 762            }
 763            InternalEvent::Clear => {
 764                // Clear back buffer
 765                term.clear_screen(ClearMode::Saved);
 766
 767                let cursor = term.grid().cursor.point;
 768
 769                // Clear the lines above
 770                term.grid_mut().reset_region(..cursor.line);
 771
 772                // Copy the current line up
 773                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 774                    .iter()
 775                    .cloned()
 776                    .enumerate()
 777                    .collect::<Vec<(usize, Cell)>>();
 778
 779                for (i, cell) in line {
 780                    term.grid_mut()[Line(0)][Column(i)] = cell;
 781                }
 782
 783                // Reset the cursor
 784                term.grid_mut().cursor.point =
 785                    AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
 786                let new_cursor = term.grid().cursor.point;
 787
 788                // Clear the lines below the new cursor
 789                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 790                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 791                }
 792
 793                cx.emit(Event::Wakeup);
 794            }
 795            InternalEvent::Scroll(scroll) => {
 796                term.scroll_display(*scroll);
 797                self.refresh_hovered_word(window);
 798
 799                if self.vi_mode_enabled {
 800                    match *scroll {
 801                        AlacScroll::Delta(delta) => {
 802                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
 803                        }
 804                        AlacScroll::PageUp => {
 805                            let lines = term.screen_lines() as i32;
 806                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
 807                        }
 808                        AlacScroll::PageDown => {
 809                            let lines = -(term.screen_lines() as i32);
 810                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
 811                        }
 812                        AlacScroll::Top => {
 813                            let point = AlacPoint::new(term.topmost_line(), Column(0));
 814                            term.vi_mode_cursor = ViModeCursor::new(point);
 815                        }
 816                        AlacScroll::Bottom => {
 817                            let point = AlacPoint::new(term.bottommost_line(), Column(0));
 818                            term.vi_mode_cursor = ViModeCursor::new(point);
 819                        }
 820                    }
 821                    if let Some(mut selection) = term.selection.take() {
 822                        let point = term.vi_mode_cursor.point;
 823                        selection.update(point, AlacDirection::Right);
 824                        term.selection = Some(selection);
 825
 826                        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 827                        if let Some(selection_text) = term.selection_to_string() {
 828                            cx.write_to_primary(ClipboardItem::new_string(selection_text));
 829                        }
 830
 831                        self.selection_head = Some(point);
 832                        cx.emit(Event::SelectionsChanged)
 833                    }
 834                }
 835            }
 836            InternalEvent::SetSelection(selection) => {
 837                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 838
 839                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 840                if let Some(selection_text) = term.selection_to_string() {
 841                    cx.write_to_primary(ClipboardItem::new_string(selection_text));
 842                }
 843
 844                if let Some((_, head)) = selection {
 845                    self.selection_head = Some(*head);
 846                }
 847                cx.emit(Event::SelectionsChanged)
 848            }
 849            InternalEvent::UpdateSelection(position) => {
 850                if let Some(mut selection) = term.selection.take() {
 851                    let (point, side) = grid_point_and_side(
 852                        *position,
 853                        self.last_content.terminal_bounds,
 854                        term.grid().display_offset(),
 855                    );
 856
 857                    selection.update(point, side);
 858                    term.selection = Some(selection);
 859
 860                    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 861                    if let Some(selection_text) = term.selection_to_string() {
 862                        cx.write_to_primary(ClipboardItem::new_string(selection_text));
 863                    }
 864
 865                    self.selection_head = Some(point);
 866                    cx.emit(Event::SelectionsChanged)
 867                }
 868            }
 869
 870            InternalEvent::Copy => {
 871                if let Some(txt) = term.selection_to_string() {
 872                    cx.write_to_clipboard(ClipboardItem::new_string(txt))
 873                }
 874            }
 875            InternalEvent::ScrollToAlacPoint(point) => {
 876                term.scroll_to_point(*point);
 877                self.refresh_hovered_word(window);
 878            }
 879            InternalEvent::ToggleViMode => {
 880                self.vi_mode_enabled = !self.vi_mode_enabled;
 881                term.toggle_vi_mode();
 882            }
 883            InternalEvent::ViMotion(motion) => {
 884                term.vi_motion(*motion);
 885            }
 886            InternalEvent::FindHyperlink(position, open) => {
 887                let prev_hovered_word = self.last_content.last_hovered_word.take();
 888
 889                let point = grid_point(
 890                    *position,
 891                    self.last_content.terminal_bounds,
 892                    term.grid().display_offset(),
 893                )
 894                .grid_clamp(term, Boundary::Grid);
 895
 896                let link = term.grid().index(point).hyperlink();
 897                let found_word = if link.is_some() {
 898                    let mut min_index = point;
 899                    loop {
 900                        let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
 901                        if new_min_index == min_index
 902                            || term.grid().index(new_min_index).hyperlink() != link
 903                        {
 904                            break;
 905                        } else {
 906                            min_index = new_min_index
 907                        }
 908                    }
 909
 910                    let mut max_index = point;
 911                    loop {
 912                        let new_max_index = max_index.add(term, Boundary::Cursor, 1);
 913                        if new_max_index == max_index
 914                            || term.grid().index(new_max_index).hyperlink() != link
 915                        {
 916                            break;
 917                        } else {
 918                            max_index = new_max_index
 919                        }
 920                    }
 921
 922                    let url = link.unwrap().uri().to_owned();
 923                    let url_match = min_index..=max_index;
 924
 925                    Some((url, true, url_match))
 926                } else if let Some(url_match) = regex_match_at(term, point, &mut self.url_regex) {
 927                    let url = term.bounds_to_string(*url_match.start(), *url_match.end());
 928                    Some((url, true, url_match))
 929                } else if let Some(word_match) = regex_match_at(term, point, &mut self.word_regex) {
 930                    let file_path = term.bounds_to_string(*word_match.start(), *word_match.end());
 931
 932                    let (sanitized_match, sanitized_word) =
 933                        if is_path_surrounded_by_common_symbols(&file_path) {
 934                            (
 935                                Match::new(
 936                                    word_match.start().add(term, Boundary::Cursor, 1),
 937                                    word_match.end().sub(term, Boundary::Cursor, 1),
 938                                ),
 939                                file_path[1..file_path.len() - 1].to_owned(),
 940                            )
 941                        } else {
 942                            (word_match, file_path)
 943                        };
 944
 945                    Some((sanitized_word, false, sanitized_match))
 946                } else {
 947                    None
 948                };
 949
 950                match found_word {
 951                    Some((maybe_url_or_path, is_url, url_match)) => {
 952                        let target = if is_url {
 953                            // Treat "file://" URLs like file paths to ensure
 954                            // that line numbers at the end of the path are
 955                            // handled correctly
 956                            if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
 957                                MaybeNavigationTarget::PathLike(PathLikeTarget {
 958                                    maybe_path: path.to_string(),
 959                                    terminal_dir: self.working_directory(),
 960                                })
 961                            } else {
 962                                MaybeNavigationTarget::Url(maybe_url_or_path.clone())
 963                            }
 964                        } else {
 965                            MaybeNavigationTarget::PathLike(PathLikeTarget {
 966                                maybe_path: maybe_url_or_path.clone(),
 967                                terminal_dir: self.working_directory(),
 968                            })
 969                        };
 970                        if *open {
 971                            cx.emit(Event::Open(target));
 972                        } else {
 973                            self.update_selected_word(
 974                                prev_hovered_word,
 975                                url_match,
 976                                maybe_url_or_path,
 977                                target,
 978                                cx,
 979                            );
 980                        }
 981                    }
 982                    None => {
 983                        cx.emit(Event::NewNavigationTarget(None));
 984                    }
 985                }
 986            }
 987        }
 988    }
 989
 990    fn update_selected_word(
 991        &mut self,
 992        prev_word: Option<HoveredWord>,
 993        word_match: RangeInclusive<AlacPoint>,
 994        word: String,
 995        navigation_target: MaybeNavigationTarget,
 996        cx: &mut Context<Self>,
 997    ) {
 998        if let Some(prev_word) = prev_word {
 999            if prev_word.word == word && prev_word.word_match == word_match {
1000                self.last_content.last_hovered_word = Some(HoveredWord {
1001                    word,
1002                    word_match,
1003                    id: prev_word.id,
1004                });
1005                return;
1006            }
1007        }
1008
1009        self.last_content.last_hovered_word = Some(HoveredWord {
1010            word: word.clone(),
1011            word_match,
1012            id: self.next_link_id(),
1013        });
1014        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
1015        cx.notify()
1016    }
1017
1018    fn next_link_id(&mut self) -> usize {
1019        let res = self.next_link_id;
1020        self.next_link_id = self.next_link_id.wrapping_add(1);
1021        res
1022    }
1023
1024    pub fn last_content(&self) -> &TerminalContent {
1025        &self.last_content
1026    }
1027
1028    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
1029        self.term_config.default_cursor_style = cursor_shape.into();
1030        self.term.lock().set_options(self.term_config.clone());
1031    }
1032
1033    pub fn total_lines(&self) -> usize {
1034        let term = self.term.clone();
1035        let terminal = term.lock_unfair();
1036        terminal.total_lines()
1037    }
1038
1039    pub fn viewport_lines(&self) -> usize {
1040        let term = self.term.clone();
1041        let terminal = term.lock_unfair();
1042        terminal.screen_lines()
1043    }
1044
1045    //To test:
1046    //- Activate match on terminal (scrolling and selection)
1047    //- Editor search snapping behavior
1048
1049    pub fn activate_match(&mut self, index: usize) {
1050        if let Some(search_match) = self.matches.get(index).cloned() {
1051            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1052
1053            self.events
1054                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1055        }
1056    }
1057
1058    pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1059        let matches_to_select = self
1060            .matches
1061            .iter()
1062            .filter(|self_match| matches.contains(self_match))
1063            .cloned()
1064            .collect::<Vec<_>>();
1065        for match_to_select in matches_to_select {
1066            self.set_selection(Some((
1067                make_selection(&match_to_select),
1068                *match_to_select.end(),
1069            )));
1070        }
1071    }
1072
1073    pub fn select_all(&mut self) {
1074        let term = self.term.lock();
1075        let start = AlacPoint::new(term.topmost_line(), Column(0));
1076        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1077        drop(term);
1078        self.set_selection(Some((make_selection(&(start..=end)), end)));
1079    }
1080
1081    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1082        self.events
1083            .push_back(InternalEvent::SetSelection(selection));
1084    }
1085
1086    pub fn copy(&mut self) {
1087        self.events.push_back(InternalEvent::Copy);
1088    }
1089
1090    pub fn clear(&mut self) {
1091        self.events.push_back(InternalEvent::Clear)
1092    }
1093
1094    pub fn scroll_line_up(&mut self) {
1095        self.events
1096            .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1097    }
1098
1099    pub fn scroll_up_by(&mut self, lines: usize) {
1100        self.events
1101            .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1102    }
1103
1104    pub fn scroll_line_down(&mut self) {
1105        self.events
1106            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1107    }
1108
1109    pub fn scroll_down_by(&mut self, lines: usize) {
1110        self.events
1111            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1112    }
1113
1114    pub fn scroll_page_up(&mut self) {
1115        self.events
1116            .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1117    }
1118
1119    pub fn scroll_page_down(&mut self) {
1120        self.events
1121            .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1122    }
1123
1124    pub fn scroll_to_top(&mut self) {
1125        self.events
1126            .push_back(InternalEvent::Scroll(AlacScroll::Top));
1127    }
1128
1129    pub fn scroll_to_bottom(&mut self) {
1130        self.events
1131            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1132    }
1133
1134    ///Resize the terminal and the PTY.
1135    pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1136        if self.last_content.terminal_bounds != new_bounds {
1137            self.events.push_back(InternalEvent::Resize(new_bounds))
1138        }
1139    }
1140
1141    ///Write the Input payload to the tty.
1142    fn write_to_pty(&self, input: String) {
1143        self.pty_tx.notify(input.into_bytes());
1144    }
1145
1146    fn write_bytes_to_pty(&self, input: Vec<u8>) {
1147        self.pty_tx.notify(input);
1148    }
1149
1150    pub fn input(&mut self, input: String) {
1151        self.events
1152            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1153        self.events.push_back(InternalEvent::SetSelection(None));
1154
1155        self.write_to_pty(input);
1156    }
1157
1158    pub fn input_bytes(&mut self, input: Vec<u8>) {
1159        self.events
1160            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1161        self.events.push_back(InternalEvent::SetSelection(None));
1162
1163        self.write_bytes_to_pty(input);
1164    }
1165
1166    pub fn toggle_vi_mode(&mut self) {
1167        self.events.push_back(InternalEvent::ToggleViMode);
1168    }
1169
1170    pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1171        if !self.vi_mode_enabled {
1172            return;
1173        }
1174
1175        let mut key = keystroke.key.clone();
1176        if keystroke.modifiers.shift {
1177            key = key.to_uppercase();
1178        }
1179
1180        let motion: Option<ViMotion> = match key.as_str() {
1181            "h" | "left" => Some(ViMotion::Left),
1182            "j" | "down" => Some(ViMotion::Down),
1183            "k" | "up" => Some(ViMotion::Up),
1184            "l" | "right" => Some(ViMotion::Right),
1185            "w" => Some(ViMotion::WordRight),
1186            "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1187            "e" => Some(ViMotion::WordRightEnd),
1188            "%" => Some(ViMotion::Bracket),
1189            "$" => Some(ViMotion::Last),
1190            "0" => Some(ViMotion::First),
1191            "^" => Some(ViMotion::FirstOccupied),
1192            "H" => Some(ViMotion::High),
1193            "M" => Some(ViMotion::Middle),
1194            "L" => Some(ViMotion::Low),
1195            _ => None,
1196        };
1197
1198        if let Some(motion) = motion {
1199            let cursor = self.last_content.cursor.point;
1200            let cursor_pos = Point {
1201                x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1202                y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1203            };
1204            self.events
1205                .push_back(InternalEvent::UpdateSelection(cursor_pos));
1206            self.events.push_back(InternalEvent::ViMotion(motion));
1207            return;
1208        }
1209
1210        let scroll_motion = match key.as_str() {
1211            "g" => Some(AlacScroll::Top),
1212            "G" => Some(AlacScroll::Bottom),
1213            "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1214            "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1215            "d" if keystroke.modifiers.control => {
1216                let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1217                Some(AlacScroll::Delta(-amount))
1218            }
1219            "u" if keystroke.modifiers.control => {
1220                let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1221                Some(AlacScroll::Delta(amount))
1222            }
1223            _ => None,
1224        };
1225
1226        if let Some(scroll_motion) = scroll_motion {
1227            self.events.push_back(InternalEvent::Scroll(scroll_motion));
1228            return;
1229        }
1230
1231        match key.as_str() {
1232            "v" => {
1233                let point = self.last_content.cursor.point;
1234                let selection_type = SelectionType::Simple;
1235                let side = AlacDirection::Right;
1236                let selection = Selection::new(selection_type, point, side);
1237                self.events
1238                    .push_back(InternalEvent::SetSelection(Some((selection, point))));
1239                return;
1240            }
1241
1242            "escape" => {
1243                self.events.push_back(InternalEvent::SetSelection(None));
1244                return;
1245            }
1246
1247            "y" => {
1248                self.events.push_back(InternalEvent::Copy);
1249                self.events.push_back(InternalEvent::SetSelection(None));
1250                return;
1251            }
1252
1253            "i" => {
1254                self.scroll_to_bottom();
1255                self.toggle_vi_mode();
1256                return;
1257            }
1258            _ => {}
1259        }
1260    }
1261
1262    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1263        if self.vi_mode_enabled {
1264            self.vi_motion(keystroke);
1265            return true;
1266        }
1267
1268        // Keep default terminal behavior
1269        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1270        if let Some(esc) = esc {
1271            self.input(esc);
1272            true
1273        } else {
1274            false
1275        }
1276    }
1277
1278    pub fn try_modifiers_change(
1279        &mut self,
1280        modifiers: &Modifiers,
1281        window: &Window,
1282        cx: &mut Context<Self>,
1283    ) {
1284        if self
1285            .last_content
1286            .terminal_bounds
1287            .bounds
1288            .contains(&window.mouse_position())
1289            && modifiers.secondary()
1290        {
1291            self.refresh_hovered_word(window);
1292        }
1293        cx.notify();
1294    }
1295
1296    ///Paste text into the terminal
1297    pub fn paste(&mut self, text: &str) {
1298        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1299            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1300        } else {
1301            text.replace("\r\n", "\r").replace('\n', "\r")
1302        };
1303
1304        self.input(paste_text);
1305    }
1306
1307    pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1308        let term = self.term.clone();
1309        let mut terminal = term.lock_unfair();
1310        //Note that the ordering of events matters for event processing
1311        while let Some(e) = self.events.pop_front() {
1312            self.process_terminal_event(&e, &mut terminal, window, cx)
1313        }
1314
1315        self.last_content = Self::make_content(&terminal, &self.last_content);
1316    }
1317
1318    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1319        let content = term.renderable_content();
1320        TerminalContent {
1321            cells: content
1322                .display_iter
1323                //TODO: Add this once there's a way to retain empty lines
1324                // .filter(|ic| {
1325                //     !ic.flags.contains(Flags::HIDDEN)
1326                //         && !(ic.bg == Named(NamedColor::Background)
1327                //             && ic.c == ' '
1328                //             && !ic.flags.contains(Flags::INVERSE))
1329                // })
1330                .map(|ic| IndexedCell {
1331                    point: ic.point,
1332                    cell: ic.cell.clone(),
1333                })
1334                .collect::<Vec<IndexedCell>>(),
1335            mode: content.mode,
1336            display_offset: content.display_offset,
1337            selection_text: term.selection_to_string(),
1338            selection: content.selection,
1339            cursor: content.cursor,
1340            cursor_char: term.grid()[content.cursor.point].c,
1341            terminal_bounds: last_content.terminal_bounds,
1342            last_hovered_word: last_content.last_hovered_word.clone(),
1343        }
1344    }
1345
1346    pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1347        let term = self.term.clone();
1348        let terminal = term.lock_unfair();
1349
1350        let mut lines = Vec::new();
1351        let mut current_line = terminal.bottommost_line();
1352        while lines.len() < n {
1353            let mut line_buffer = String::new();
1354            for cell in &terminal.grid()[current_line] {
1355                line_buffer.push(cell.c);
1356            }
1357            let line = line_buffer.trim_end();
1358            if !line.is_empty() {
1359                lines.push(line.to_string());
1360            }
1361
1362            if current_line == terminal.topmost_line() {
1363                break;
1364            }
1365            current_line = Line(current_line.0 - 1);
1366        }
1367        lines.reverse();
1368        lines
1369    }
1370
1371    pub fn focus_in(&self) {
1372        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1373            self.write_to_pty("\x1b[I".to_string());
1374        }
1375    }
1376
1377    pub fn focus_out(&mut self) {
1378        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1379            self.write_to_pty("\x1b[O".to_string());
1380        }
1381    }
1382
1383    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1384        match self.last_mouse {
1385            Some((old_point, old_side)) => {
1386                if old_point == point && old_side == side {
1387                    false
1388                } else {
1389                    self.last_mouse = Some((point, side));
1390                    true
1391                }
1392            }
1393            None => {
1394                self.last_mouse = Some((point, side));
1395                true
1396            }
1397        }
1398    }
1399
1400    pub fn mouse_mode(&self, shift: bool) -> bool {
1401        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1402    }
1403
1404    pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1405        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1406        if self.mouse_mode(e.modifiers.shift) {
1407            let (point, side) = grid_point_and_side(
1408                position,
1409                self.last_content.terminal_bounds,
1410                self.last_content.display_offset,
1411            );
1412
1413            if self.mouse_changed(point, side) {
1414                if let Some(bytes) =
1415                    mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1416                {
1417                    self.pty_tx.notify(bytes);
1418                }
1419            }
1420        } else if e.modifiers.secondary() {
1421            self.word_from_position(e.position);
1422        }
1423        cx.notify();
1424    }
1425
1426    fn word_from_position(&mut self, position: Point<Pixels>) {
1427        if self.selection_phase == SelectionPhase::Selecting {
1428            self.last_content.last_hovered_word = None;
1429        } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1430            self.events.push_back(InternalEvent::FindHyperlink(
1431                position - self.last_content.terminal_bounds.bounds.origin,
1432                false,
1433            ));
1434        } else {
1435            self.last_content.last_hovered_word = None;
1436        }
1437    }
1438
1439    pub fn mouse_drag(
1440        &mut self,
1441        e: &MouseMoveEvent,
1442        region: Bounds<Pixels>,
1443        cx: &mut Context<Self>,
1444    ) {
1445        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1446        if !self.mouse_mode(e.modifiers.shift) {
1447            self.selection_phase = SelectionPhase::Selecting;
1448            // Alacritty has the same ordering, of first updating the selection
1449            // then scrolling 15ms later
1450            self.events
1451                .push_back(InternalEvent::UpdateSelection(position));
1452
1453            // Doesn't make sense to scroll the alt screen
1454            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1455                let scroll_delta = match self.drag_line_delta(e, region) {
1456                    Some(value) => value,
1457                    None => return,
1458                };
1459
1460                let scroll_lines =
1461                    (scroll_delta / self.last_content.terminal_bounds.line_height) as i32;
1462
1463                self.events
1464                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1465            }
1466
1467            cx.notify();
1468        }
1469    }
1470
1471    fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1472        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1473        let top = region.origin.y + (self.last_content.terminal_bounds.line_height * 2.);
1474        let bottom = region.bottom_left().y - (self.last_content.terminal_bounds.line_height * 2.);
1475        let scroll_delta = if e.position.y < top {
1476            (top - e.position.y).pow(1.1)
1477        } else if e.position.y > bottom {
1478            -((e.position.y - bottom).pow(1.1))
1479        } else {
1480            return None; //Nothing to do
1481        };
1482        Some(scroll_delta)
1483    }
1484
1485    pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1486        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1487        let point = grid_point(
1488            position,
1489            self.last_content.terminal_bounds,
1490            self.last_content.display_offset,
1491        );
1492
1493        if self.mouse_mode(e.modifiers.shift) {
1494            if let Some(bytes) =
1495                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1496            {
1497                self.pty_tx.notify(bytes);
1498            }
1499        } else {
1500            match e.button {
1501                MouseButton::Left => {
1502                    let (point, side) = grid_point_and_side(
1503                        position,
1504                        self.last_content.terminal_bounds,
1505                        self.last_content.display_offset,
1506                    );
1507
1508                    let selection_type = match e.click_count {
1509                        0 => return, //This is a release
1510                        1 => Some(SelectionType::Simple),
1511                        2 => Some(SelectionType::Semantic),
1512                        3 => Some(SelectionType::Lines),
1513                        _ => None,
1514                    };
1515
1516                    if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1517                        self.events
1518                            .push_back(InternalEvent::UpdateSelection(position));
1519                        return;
1520                    }
1521
1522                    let selection = selection_type
1523                        .map(|selection_type| Selection::new(selection_type, point, side));
1524
1525                    if let Some(sel) = selection {
1526                        self.events
1527                            .push_back(InternalEvent::SetSelection(Some((sel, point))));
1528                    }
1529                }
1530                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1531                MouseButton::Middle => {
1532                    if let Some(item) = _cx.read_from_primary() {
1533                        let text = item.text().unwrap_or_default().to_string();
1534                        self.input(text);
1535                    }
1536                }
1537                _ => {}
1538            }
1539        }
1540    }
1541
1542    pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1543        let setting = TerminalSettings::get_global(cx);
1544
1545        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1546        if self.mouse_mode(e.modifiers.shift) {
1547            let point = grid_point(
1548                position,
1549                self.last_content.terminal_bounds,
1550                self.last_content.display_offset,
1551            );
1552
1553            if let Some(bytes) =
1554                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1555            {
1556                self.pty_tx.notify(bytes);
1557            }
1558        } else {
1559            if e.button == MouseButton::Left && setting.copy_on_select {
1560                self.copy();
1561            }
1562
1563            //Hyperlinks
1564            if self.selection_phase == SelectionPhase::Ended {
1565                let mouse_cell_index =
1566                    content_index_for_mouse(position, &self.last_content.terminal_bounds);
1567                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1568                    cx.open_url(link.uri());
1569                } else if e.modifiers.secondary() {
1570                    self.events
1571                        .push_back(InternalEvent::FindHyperlink(position, true));
1572                }
1573            }
1574        }
1575
1576        self.selection_phase = SelectionPhase::Ended;
1577        self.last_mouse = None;
1578    }
1579
1580    ///Scroll the terminal
1581    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1582        let mouse_mode = self.mouse_mode(e.shift);
1583
1584        if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1585            if mouse_mode {
1586                let point = grid_point(
1587                    e.position - self.last_content.terminal_bounds.bounds.origin,
1588                    self.last_content.terminal_bounds,
1589                    self.last_content.display_offset,
1590                );
1591
1592                if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1593                {
1594                    for scroll in scrolls {
1595                        self.pty_tx.notify(scroll);
1596                    }
1597                };
1598            } else if self
1599                .last_content
1600                .mode
1601                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1602                && !e.shift
1603            {
1604                self.pty_tx.notify(alt_scroll(scroll_lines))
1605            } else if scroll_lines != 0 {
1606                let scroll = AlacScroll::Delta(scroll_lines);
1607
1608                self.events.push_back(InternalEvent::Scroll(scroll));
1609            }
1610        }
1611    }
1612
1613    fn refresh_hovered_word(&mut self, window: &Window) {
1614        self.word_from_position(window.mouse_position());
1615    }
1616
1617    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1618        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1619        let line_height = self.last_content.terminal_bounds.line_height;
1620        match e.touch_phase {
1621            /* Reset scroll state on started */
1622            TouchPhase::Started => {
1623                self.scroll_px = px(0.);
1624                None
1625            }
1626            /* Calculate the appropriate scroll lines */
1627            TouchPhase::Moved => {
1628                let old_offset = (self.scroll_px / line_height) as i32;
1629
1630                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1631
1632                let new_offset = (self.scroll_px / line_height) as i32;
1633
1634                // Whenever we hit the edges, reset our stored scroll to 0
1635                // so we can respond to changes in direction quickly
1636                self.scroll_px %= self.last_content.terminal_bounds.height();
1637
1638                Some(new_offset - old_offset)
1639            }
1640            TouchPhase::Ended => None,
1641        }
1642    }
1643
1644    pub fn find_matches(
1645        &self,
1646        mut searcher: RegexSearch,
1647        cx: &Context<Self>,
1648    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1649        let term = self.term.clone();
1650        cx.background_spawn(async move {
1651            let term = term.lock();
1652
1653            all_search_matches(&term, &mut searcher).collect()
1654        })
1655    }
1656
1657    pub fn working_directory(&self) -> Option<PathBuf> {
1658        if self.is_ssh_terminal {
1659            // We can't yet reliably detect the working directory of a shell on the
1660            // SSH host. Until we can do that, it doesn't make sense to display
1661            // the working directory on the client and persist that.
1662            None
1663        } else {
1664            self.client_side_working_directory()
1665        }
1666    }
1667
1668    /// Returns the working directory of the process that's connected to the PTY.
1669    /// That means it returns the working directory of the local shell or program
1670    /// that's running inside the terminal.
1671    ///
1672    /// This does *not* return the working directory of the shell that runs on the
1673    /// remote host, in case Zed is connected to a remote host.
1674    fn client_side_working_directory(&self) -> Option<PathBuf> {
1675        self.pty_info
1676            .current
1677            .as_ref()
1678            .map(|process| process.cwd.clone())
1679    }
1680
1681    pub fn title(&self, truncate: bool) -> String {
1682        const MAX_CHARS: usize = 25;
1683        match &self.task {
1684            Some(task_state) => {
1685                if truncate {
1686                    truncate_and_trailoff(&task_state.label, MAX_CHARS)
1687                } else {
1688                    task_state.full_label.clone()
1689                }
1690            }
1691            None => self
1692                .title_override
1693                .as_ref()
1694                .map(|title_override| title_override.to_string())
1695                .unwrap_or_else(|| {
1696                    self.pty_info
1697                        .current
1698                        .as_ref()
1699                        .map(|fpi| {
1700                            let process_file = fpi
1701                                .cwd
1702                                .file_name()
1703                                .map(|name| name.to_string_lossy().to_string())
1704                                .unwrap_or_default();
1705
1706                            let argv = fpi.argv.clone();
1707                            let process_name = format!(
1708                                "{}{}",
1709                                fpi.name,
1710                                if !argv.is_empty() {
1711                                    format!(" {}", (argv[1..]).join(" "))
1712                                } else {
1713                                    "".to_string()
1714                                }
1715                            );
1716                            let (process_file, process_name) = if truncate {
1717                                (
1718                                    truncate_and_trailoff(&process_file, MAX_CHARS),
1719                                    truncate_and_trailoff(&process_name, MAX_CHARS),
1720                                )
1721                            } else {
1722                                (process_file, process_name)
1723                            };
1724                            format!("{process_file}{process_name}")
1725                        })
1726                        .unwrap_or_else(|| "Terminal".to_string())
1727                }),
1728        }
1729    }
1730
1731    pub fn task(&self) -> Option<&TaskState> {
1732        self.task.as_ref()
1733    }
1734
1735    pub fn wait_for_completed_task(&self, cx: &App) -> Task<()> {
1736        if let Some(task) = self.task() {
1737            if task.status == TaskStatus::Running {
1738                let completion_receiver = task.completion_rx.clone();
1739                return cx.spawn(|_| async move {
1740                    let _ = completion_receiver.recv().await;
1741                });
1742            }
1743        }
1744        Task::ready(())
1745    }
1746
1747    fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<'_, Terminal>) {
1748        self.completion_tx.try_send(()).ok();
1749        let task = match &mut self.task {
1750            Some(task) => task,
1751            None => {
1752                if error_code.is_none() {
1753                    cx.emit(Event::CloseTerminal);
1754                }
1755                return;
1756            }
1757        };
1758        if task.status != TaskStatus::Running {
1759            return;
1760        }
1761        match error_code {
1762            Some(error_code) => {
1763                task.status.register_task_exit(error_code);
1764            }
1765            None => {
1766                task.status.register_terminal_exit();
1767            }
1768        };
1769
1770        let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1771        let mut lines_to_show = Vec::new();
1772        if task.show_summary {
1773            lines_to_show.push(task_line.as_str());
1774        }
1775        if task.show_command {
1776            lines_to_show.push(command_line.as_str());
1777        }
1778
1779        if !lines_to_show.is_empty() {
1780            // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1781            // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1782            // when Zed task finishes and no more output is made.
1783            // After the task summary is output once, no more text is appended to the terminal.
1784            unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1785        }
1786
1787        match task.hide {
1788            HideStrategy::Never => {}
1789            HideStrategy::Always => {
1790                cx.emit(Event::CloseTerminal);
1791            }
1792            HideStrategy::OnSuccess => {
1793                if finished_successfully {
1794                    cx.emit(Event::CloseTerminal);
1795                }
1796            }
1797        }
1798    }
1799}
1800
1801fn is_path_surrounded_by_common_symbols(path: &str) -> bool {
1802    // Avoid detecting `[]` or `()` strings as paths, surrounded by common symbols
1803    path.len() > 2
1804        // The rest of the brackets and various quotes cannot be matched by the [`WORD_REGEX`] hence not checked for.
1805        && (path.starts_with('[') && path.ends_with(']')
1806            || path.starts_with('(') && path.ends_with(')'))
1807}
1808
1809const TASK_DELIMITER: &str = "";
1810fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1811    let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1812    let (success, task_line) = match error_code {
1813        Some(0) => {
1814            (true, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"))
1815        }
1816        Some(error_code) => {
1817            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"))
1818        }
1819        None => {
1820            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"))
1821        }
1822    };
1823    let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1824    let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1825    (success, task_line, command_line)
1826}
1827
1828/// Appends a stringified task summary to the terminal, after its output.
1829///
1830/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1831/// New text being added to the terminal here, uses "less public" APIs,
1832/// which are not maintaining the entire terminal state intact.
1833///
1834///
1835/// The library
1836///
1837/// * does not increment inner grid cursor's _lines_ on `input` calls
1838///   (but displaying the lines correctly and incrementing cursor's columns)
1839///
1840/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1841///
1842/// * does not alter grid state after `newline` call
1843///   so its `bottommost_line` is always the same additions, and
1844///   the cursor's `point` is not updated to the new line and column values
1845///
1846/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1847///   Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1848///
1849/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1850/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1851/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1852/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1853unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1854    term.newline();
1855    term.grid_mut().cursor.point.column = Column(0);
1856    for line in text_lines {
1857        for c in line.chars() {
1858            term.input(c);
1859        }
1860        term.newline();
1861        term.grid_mut().cursor.point.column = Column(0);
1862    }
1863}
1864
1865impl Drop for Terminal {
1866    fn drop(&mut self) {
1867        self.pty_tx.0.send(Msg::Shutdown).ok();
1868    }
1869}
1870
1871impl EventEmitter<Event> for Terminal {}
1872
1873/// Based on alacritty/src/display/hint.rs > regex_match_at
1874/// Retrieve the match, if the specified point is inside the content matching the regex.
1875fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1876    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1877}
1878
1879/// Copied from alacritty/src/display/hint.rs:
1880/// Iterate over all visible regex matches.
1881pub fn visible_regex_match_iter<'a, T>(
1882    term: &'a Term<T>,
1883    regex: &'a mut RegexSearch,
1884) -> impl Iterator<Item = Match> + 'a {
1885    let viewport_start = Line(-(term.grid().display_offset() as i32));
1886    let viewport_end = viewport_start + term.bottommost_line();
1887    let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1888    let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1889    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1890    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1891
1892    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1893        .skip_while(move |rm| rm.end().line < viewport_start)
1894        .take_while(move |rm| rm.start().line <= viewport_end)
1895}
1896
1897fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1898    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1899    selection.update(*range.end(), AlacDirection::Right);
1900    selection
1901}
1902
1903fn all_search_matches<'a, T>(
1904    term: &'a Term<T>,
1905    regex: &'a mut RegexSearch,
1906) -> impl Iterator<Item = Match> + 'a {
1907    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1908    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1909    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1910}
1911
1912fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
1913    let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
1914    let clamped_col = min(col, terminal_bounds.columns() - 1);
1915    let row = (pos.y / terminal_bounds.line_height()).round() as usize;
1916    let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
1917    clamped_row * terminal_bounds.columns() + clamped_col
1918}
1919
1920/// Converts an 8 bit ANSI color to its GPUI equivalent.
1921/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1922/// Other than that use case, should only be called with values in the `[0,255]` range
1923pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1924    let colors = theme.colors();
1925
1926    match index {
1927        // 0-15 are the same as the named colors above
1928        0 => colors.terminal_ansi_black,
1929        1 => colors.terminal_ansi_red,
1930        2 => colors.terminal_ansi_green,
1931        3 => colors.terminal_ansi_yellow,
1932        4 => colors.terminal_ansi_blue,
1933        5 => colors.terminal_ansi_magenta,
1934        6 => colors.terminal_ansi_cyan,
1935        7 => colors.terminal_ansi_white,
1936        8 => colors.terminal_ansi_bright_black,
1937        9 => colors.terminal_ansi_bright_red,
1938        10 => colors.terminal_ansi_bright_green,
1939        11 => colors.terminal_ansi_bright_yellow,
1940        12 => colors.terminal_ansi_bright_blue,
1941        13 => colors.terminal_ansi_bright_magenta,
1942        14 => colors.terminal_ansi_bright_cyan,
1943        15 => colors.terminal_ansi_bright_white,
1944        // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1945        16..=231 => {
1946            let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1947            let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1948            rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1949        }
1950        // 232-255 are a 24 step grayscale from black to white
1951        232..=255 => {
1952            let i = index as u8 - 232; // Align index to 0..24
1953            let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1954            rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1955        }
1956        // For compatibility with the alacritty::Colors interface
1957        256 => colors.text,
1958        257 => colors.background,
1959        258 => theme.players().local().cursor,
1960        259 => colors.terminal_ansi_dim_black,
1961        260 => colors.terminal_ansi_dim_red,
1962        261 => colors.terminal_ansi_dim_green,
1963        262 => colors.terminal_ansi_dim_yellow,
1964        263 => colors.terminal_ansi_dim_blue,
1965        264 => colors.terminal_ansi_dim_magenta,
1966        265 => colors.terminal_ansi_dim_cyan,
1967        266 => colors.terminal_ansi_dim_white,
1968        267 => colors.terminal_bright_foreground,
1969        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1970
1971        _ => black(),
1972    }
1973}
1974
1975/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1976/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1977///
1978/// Wikipedia gives a formula for calculating the index for a given color:
1979///
1980/// ```
1981/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1982/// ```
1983///
1984/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1985fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1986    debug_assert!((16..=231).contains(&i));
1987    let i = i - 16;
1988    let r = (i - (i % 36)) / 36;
1989    let g = ((i % 36) - (i % 6)) / 6;
1990    let b = (i % 36) % 6;
1991    (r, g, b)
1992}
1993
1994pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1995    Rgba {
1996        r: (r as f32 / 255.),
1997        g: (g as f32 / 255.),
1998        b: (b as f32 / 255.),
1999        a: 1.,
2000    }
2001    .into()
2002}
2003
2004#[cfg(test)]
2005mod tests {
2006    use alacritty_terminal::{
2007        index::{Column, Line, Point as AlacPoint},
2008        term::cell::Cell,
2009    };
2010    use gpui::{bounds, point, size, Pixels, Point};
2011    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
2012
2013    use crate::{
2014        content_index_for_mouse, rgb_for_index, IndexedCell, TerminalBounds, TerminalContent,
2015    };
2016
2017    #[test]
2018    fn test_rgb_for_index() {
2019        // Test every possible value in the color cube.
2020        for i in 16..=231 {
2021            let (r, g, b) = rgb_for_index(i);
2022            assert_eq!(i, 16 + 36 * r + 6 * g + b);
2023        }
2024    }
2025
2026    #[test]
2027    fn test_mouse_to_cell_test() {
2028        let mut rng = thread_rng();
2029        const ITERATIONS: usize = 10;
2030        const PRECISION: usize = 1000;
2031
2032        for _ in 0..ITERATIONS {
2033            let viewport_cells = rng.gen_range(15..20);
2034            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2035
2036            let size = crate::TerminalBounds {
2037                cell_width: Pixels::from(cell_size),
2038                line_height: Pixels::from(cell_size),
2039                bounds: bounds(
2040                    Point::default(),
2041                    size(
2042                        Pixels::from(cell_size * (viewport_cells as f32)),
2043                        Pixels::from(cell_size * (viewport_cells as f32)),
2044                    ),
2045                ),
2046            };
2047
2048            let cells = get_cells(size, &mut rng);
2049            let content = convert_cells_to_content(size, &cells);
2050
2051            for row in 0..(viewport_cells - 1) {
2052                let row = row as usize;
2053                for col in 0..(viewport_cells - 1) {
2054                    let col = col as usize;
2055
2056                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2057                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2058
2059                    let mouse_pos = point(
2060                        Pixels::from(col as f32 * cell_size + col_offset),
2061                        Pixels::from(row as f32 * cell_size + row_offset),
2062                    );
2063
2064                    let content_index =
2065                        content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2066                    let mouse_cell = content.cells[content_index].c;
2067                    let real_cell = cells[row][col];
2068
2069                    assert_eq!(mouse_cell, real_cell);
2070                }
2071            }
2072        }
2073    }
2074
2075    #[test]
2076    fn test_mouse_to_cell_clamp() {
2077        let mut rng = thread_rng();
2078
2079        let size = crate::TerminalBounds {
2080            cell_width: Pixels::from(10.),
2081            line_height: Pixels::from(10.),
2082            bounds: bounds(
2083                Point::default(),
2084                size(Pixels::from(100.), Pixels::from(100.)),
2085            ),
2086        };
2087
2088        let cells = get_cells(size, &mut rng);
2089        let content = convert_cells_to_content(size, &cells);
2090
2091        assert_eq!(
2092            content.cells[content_index_for_mouse(
2093                point(Pixels::from(-10.), Pixels::from(-10.)),
2094                &content.terminal_bounds,
2095            )]
2096            .c,
2097            cells[0][0]
2098        );
2099        assert_eq!(
2100            content.cells[content_index_for_mouse(
2101                point(Pixels::from(1000.), Pixels::from(1000.)),
2102                &content.terminal_bounds,
2103            )]
2104            .c,
2105            cells[9][9]
2106        );
2107    }
2108
2109    fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2110        let mut cells = Vec::new();
2111
2112        for _ in 0..((size.height() / size.line_height()) as usize) {
2113            let mut row_vec = Vec::new();
2114            for _ in 0..((size.width() / size.cell_width()) as usize) {
2115                let cell_char = rng.sample(Alphanumeric) as char;
2116                row_vec.push(cell_char)
2117            }
2118            cells.push(row_vec)
2119        }
2120
2121        cells
2122    }
2123
2124    fn convert_cells_to_content(
2125        terminal_bounds: TerminalBounds,
2126        cells: &[Vec<char>],
2127    ) -> TerminalContent {
2128        let mut ic = Vec::new();
2129
2130        for (index, row) in cells.iter().enumerate() {
2131            for (cell_index, cell_char) in row.iter().enumerate() {
2132                ic.push(IndexedCell {
2133                    point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2134                    cell: Cell {
2135                        c: *cell_char,
2136                        ..Default::default()
2137                    },
2138                });
2139            }
2140        }
2141
2142        TerminalContent {
2143            cells: ic,
2144            terminal_bounds,
2145            ..Default::default()
2146        }
2147    }
2148
2149    fn re_test(re: &str, hay: &str, expected: Vec<&str>) {
2150        let results: Vec<_> = regex::Regex::new(re)
2151            .unwrap()
2152            .find_iter(hay)
2153            .map(|m| m.as_str())
2154            .collect();
2155        assert_eq!(results, expected);
2156    }
2157    #[test]
2158    fn test_url_regex() {
2159        re_test(
2160            crate::URL_REGEX,
2161            "test http://example.com test mailto:bob@example.com train",
2162            vec!["http://example.com", "mailto:bob@example.com"],
2163        );
2164    }
2165    #[test]
2166    fn test_word_regex() {
2167        re_test(
2168            crate::WORD_REGEX,
2169            "hello, world! \"What\" is this?",
2170            vec!["hello", "world", "What", "is", "this"],
2171        );
2172    }
2173    #[test]
2174    fn test_word_regex_with_linenum() {
2175        // filename(line) and filename(line,col) as used in MSBuild output
2176        // should be considered a single "word", even though comma is
2177        // usually a word separator
2178        re_test(
2179            crate::WORD_REGEX,
2180            "a Main.cs(20) b",
2181            vec!["a", "Main.cs(20)", "b"],
2182        );
2183        re_test(
2184            crate::WORD_REGEX,
2185            "Main.cs(20,5) Error desc",
2186            vec!["Main.cs(20,5)", "Error", "desc"],
2187        );
2188        // filename:line:col is a popular format for unix tools
2189        re_test(
2190            crate::WORD_REGEX,
2191            "a Main.cs:20:5 b",
2192            vec!["a", "Main.cs:20:5", "b"],
2193        );
2194        // Some tools output "filename:line:col:message", which currently isn't
2195        // handled correctly, but might be in the future
2196        re_test(
2197            crate::WORD_REGEX,
2198            "Main.cs:20:5:Error desc",
2199            vec!["Main.cs:20:5:Error", "desc"],
2200        );
2201    }
2202}