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