terminal.rs

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