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