terminal.rs

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