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