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