terminal.rs

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