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