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