terminal.rs

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