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