terminal.rs

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