terminal.rs

   1pub mod mappings;
   2
   3pub use alacritty_terminal;
   4
   5mod pty_info;
   6pub mod terminal_settings;
   7
   8use alacritty_terminal::{
   9    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
  10    event_loop::{EventLoop, Msg, Notifier},
  11    grid::{Dimensions, Scroll as AlacScroll},
  12    index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
  13    selection::{Selection, SelectionRange, SelectionType},
  14    sync::FairMutex,
  15    term::{
  16        cell::Cell,
  17        search::{Match, RegexIter, RegexSearch},
  18        Config, RenderableCursor, TermMode,
  19    },
  20    tty::{self},
  21    vte::ansi::{
  22        ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
  23    },
  24    Term,
  25};
  26use anyhow::{bail, Result};
  27
  28use futures::{
  29    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
  30    FutureExt,
  31};
  32
  33use mappings::mouse::{
  34    alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
  35    scroll_report,
  36};
  37
  38use collections::{HashMap, VecDeque};
  39use futures::StreamExt;
  40use pty_info::PtyProcessInfo;
  41use serde::{Deserialize, Serialize};
  42use settings::Settings;
  43use smol::channel::{Receiver, Sender};
  44use task::{HideStrategy, Shell, TaskId};
  45use terminal_settings::{AlternateScroll, CursorShape, TerminalBlink, TerminalSettings};
  46use theme::{ActiveTheme, Theme};
  47use util::truncate_and_trailoff;
  48
  49use std::{
  50    cmp::{self, min},
  51    fmt::Display,
  52    ops::{Deref, Index, RangeInclusive},
  53    path::PathBuf,
  54    sync::Arc,
  55    time::Duration,
  56};
  57use thiserror::Error;
  58
  59use gpui::{
  60    actions, black, px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla,
  61    Keystroke, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
  62    Pixels, Point, Rgba, ScrollWheelEvent, Size, Task, TouchPhase,
  63};
  64
  65use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
  66
  67actions!(
  68    terminal,
  69    [
  70        Clear,
  71        Copy,
  72        Paste,
  73        ShowCharacterPalette,
  74        SearchTest,
  75        ScrollLineUp,
  76        ScrollLineDown,
  77        ScrollPageUp,
  78        ScrollPageDown,
  79        ScrollToTop,
  80        ScrollToBottom,
  81    ]
  82);
  83
  84///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  85///Scroll multiplier that is set to 3 by default. This will be removed when I
  86///Implement scroll bars.
  87#[cfg(target_os = "macos")]
  88const SCROLL_MULTIPLIER: f32 = 4.;
  89#[cfg(not(target_os = "macos"))]
  90const SCROLL_MULTIPLIER: f32 = 1.;
  91const MAX_SEARCH_LINES: usize = 100;
  92const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
  93const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
  94const DEBUG_CELL_WIDTH: Pixels = px(5.);
  95const DEBUG_LINE_HEIGHT: Pixels = px(5.);
  96
  97///Upward flowing events, for changing the title and such
  98#[derive(Clone, Debug)]
  99pub enum Event {
 100    TitleChanged,
 101    BreadcrumbsChanged,
 102    CloseTerminal,
 103    Bell,
 104    Wakeup,
 105    BlinkChanged,
 106    SelectionsChanged,
 107    NewNavigationTarget(Option<MaybeNavigationTarget>),
 108    Open(MaybeNavigationTarget),
 109}
 110
 111#[derive(Clone, Debug)]
 112pub struct PathLikeTarget {
 113    /// File system path, absolute or relative, existing or not.
 114    /// Might have line and column number(s) attached as `file.rs:1:23`
 115    pub maybe_path: String,
 116    /// Current working directory of the terminal
 117    pub terminal_dir: Option<PathBuf>,
 118}
 119
 120/// A string inside terminal, potentially useful as a URI that can be opened.
 121#[derive(Clone, Debug)]
 122pub enum MaybeNavigationTarget {
 123    /// HTTP, git, etc. string determined by the [`URL_REGEX`] regex.
 124    Url(String),
 125    /// File system path, absolute or relative, existing or not.
 126    /// Might have line and column number(s) attached as `file.rs:1:23`
 127    PathLike(PathLikeTarget),
 128}
 129
 130#[derive(Clone)]
 131enum InternalEvent {
 132    Resize(TerminalSize),
 133    Clear,
 134    // FocusNextMatch,
 135    Scroll(AlacScroll),
 136    ScrollToAlacPoint(AlacPoint),
 137    SetSelection(Option<(Selection, AlacPoint)>),
 138    UpdateSelection(Point<Pixels>),
 139    // Adjusted mouse position, should open
 140    FindHyperlink(Point<Pixels>, bool),
 141    Copy,
 142}
 143
 144///A translation struct for Alacritty to communicate with us from their event loop
 145#[derive(Clone)]
 146pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
 147
 148impl EventListener for ZedListener {
 149    fn send_event(&self, event: AlacTermEvent) {
 150        self.0.unbounded_send(event).ok();
 151    }
 152}
 153
 154pub fn init(cx: &mut AppContext) {
 155    TerminalSettings::register(cx);
 156}
 157
 158#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
 159pub struct TerminalSize {
 160    pub cell_width: Pixels,
 161    pub line_height: Pixels,
 162    pub size: Size<Pixels>,
 163}
 164
 165impl TerminalSize {
 166    pub fn new(line_height: Pixels, cell_width: Pixels, size: Size<Pixels>) -> Self {
 167        TerminalSize {
 168            cell_width,
 169            line_height,
 170            size,
 171        }
 172    }
 173
 174    pub fn num_lines(&self) -> usize {
 175        (self.size.height / self.line_height).floor() as usize
 176    }
 177
 178    pub fn num_columns(&self) -> usize {
 179        (self.size.width / self.cell_width).floor() as usize
 180    }
 181
 182    pub fn height(&self) -> Pixels {
 183        self.size.height
 184    }
 185
 186    pub fn width(&self) -> Pixels {
 187        self.size.width
 188    }
 189
 190    pub fn cell_width(&self) -> Pixels {
 191        self.cell_width
 192    }
 193
 194    pub fn line_height(&self) -> Pixels {
 195        self.line_height
 196    }
 197}
 198
 199impl Default for TerminalSize {
 200    fn default() -> Self {
 201        TerminalSize::new(
 202            DEBUG_LINE_HEIGHT,
 203            DEBUG_CELL_WIDTH,
 204            Size {
 205                width: DEBUG_TERMINAL_WIDTH,
 206                height: DEBUG_TERMINAL_HEIGHT,
 207            },
 208        )
 209    }
 210}
 211
 212impl From<TerminalSize> for WindowSize {
 213    fn from(val: TerminalSize) -> Self {
 214        WindowSize {
 215            num_lines: val.num_lines() as u16,
 216            num_cols: val.num_columns() as u16,
 217            cell_width: f32::from(val.cell_width()) as u16,
 218            cell_height: f32::from(val.line_height()) as u16,
 219        }
 220    }
 221}
 222
 223impl Dimensions for TerminalSize {
 224    /// Note: this is supposed to be for the back buffer's length,
 225    /// but we exclusively use it to resize the terminal, which does not
 226    /// use this method. We still have to implement it for the trait though,
 227    /// hence, this comment.
 228    fn total_lines(&self) -> usize {
 229        self.screen_lines()
 230    }
 231
 232    fn screen_lines(&self) -> usize {
 233        self.num_lines()
 234    }
 235
 236    fn columns(&self) -> usize {
 237        self.num_columns()
 238    }
 239}
 240
 241#[derive(Error, Debug)]
 242pub struct TerminalError {
 243    pub directory: Option<PathBuf>,
 244    pub shell: Shell,
 245    pub source: std::io::Error,
 246}
 247
 248impl TerminalError {
 249    pub fn fmt_directory(&self) -> String {
 250        self.directory
 251            .clone()
 252            .map(|path| {
 253                match path
 254                    .into_os_string()
 255                    .into_string()
 256                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 257                {
 258                    Ok(s) => s,
 259                    Err(s) => s,
 260                }
 261            })
 262            .unwrap_or_else(|| {
 263                let default_dir =
 264                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
 265                match default_dir {
 266                    Some(dir) => format!("<none specified, using home directory> {}", dir),
 267                    None => "<none specified, could not find home directory>".to_string(),
 268                }
 269            })
 270    }
 271
 272    pub fn shell_to_string(&self) -> String {
 273        match &self.shell {
 274            Shell::System => "<system shell>".to_string(),
 275            Shell::Program(p) => p.to_string(),
 276            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 277        }
 278    }
 279
 280    pub fn fmt_shell(&self) -> String {
 281        match &self.shell {
 282            Shell::System => "<system defined shell>".to_string(),
 283            Shell::Program(s) => s.to_string(),
 284            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 285        }
 286    }
 287}
 288
 289impl Display for TerminalError {
 290    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 291        let dir_string: String = self.fmt_directory();
 292        let shell = self.fmt_shell();
 293
 294        write!(
 295            f,
 296            "Working directory: {} Shell command: `{}`, IOError: {}",
 297            dir_string, shell, self.source
 298        )
 299    }
 300}
 301
 302// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
 303const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
 304const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
 305
 306pub struct TerminalBuilder {
 307    terminal: Terminal,
 308    events_rx: UnboundedReceiver<AlacTermEvent>,
 309}
 310
 311impl TerminalBuilder {
 312    #[allow(clippy::too_many_arguments)]
 313    pub fn new(
 314        working_directory: Option<PathBuf>,
 315        task: Option<TaskState>,
 316        shell: Shell,
 317        mut env: HashMap<String, String>,
 318        blink_settings: Option<TerminalBlink>,
 319        cursor_shape: CursorShape,
 320        alternate_scroll: AlternateScroll,
 321        max_scroll_history_lines: Option<usize>,
 322        window: AnyWindowHandle,
 323        completion_tx: Sender<()>,
 324        cx: &mut AppContext,
 325    ) -> Result<TerminalBuilder> {
 326        // TODO: Properly set the current locale,
 327        env.entry("LC_ALL".to_string())
 328            .or_insert_with(|| "en_US.UTF-8".to_string());
 329
 330        env.insert("ZED_TERM".to_string(), "true".to_string());
 331        env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
 332        env.insert(
 333            "TERM_PROGRAM_VERSION".to_string(),
 334            release_channel::AppVersion::global(cx).to_string(),
 335        );
 336
 337        let pty_options = {
 338            let alac_shell = match shell.clone() {
 339                Shell::System => None,
 340                Shell::Program(program) => {
 341                    Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
 342                }
 343                Shell::WithArguments { program, args } => {
 344                    Some(alacritty_terminal::tty::Shell::new(program, args))
 345                }
 346            };
 347
 348            alacritty_terminal::tty::Options {
 349                shell: alac_shell,
 350                working_directory: working_directory.clone(),
 351                hold: false,
 352                env: env.into_iter().collect(),
 353            }
 354        };
 355
 356        // Setup Alacritty's env, which modifies the current process's environment
 357        alacritty_terminal::tty::setup_env();
 358
 359        let default_cursor_style = AlacCursorStyle::from(cursor_shape);
 360        let scrolling_history = if task.is_some() {
 361            // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
 362            // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
 363            // cause excessive memory usage over time.
 364            MAX_SCROLL_HISTORY_LINES
 365        } else {
 366            max_scroll_history_lines
 367                .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
 368                .min(MAX_SCROLL_HISTORY_LINES)
 369        };
 370        let config = Config {
 371            scrolling_history,
 372            default_cursor_style,
 373            ..Config::default()
 374        };
 375
 376        //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
 377        //TODO: Remove with a bounded sender which can be dispatched on &self
 378        let (events_tx, events_rx) = unbounded();
 379        //Set up the terminal...
 380        let mut term = Term::new(
 381            config,
 382            &TerminalSize::default(),
 383            ZedListener(events_tx.clone()),
 384        );
 385
 386        //Start off blinking if we need to
 387        if let Some(TerminalBlink::On) = blink_settings {
 388            term.set_private_mode(PrivateMode::Named(NamedPrivateMode::BlinkingCursor));
 389        }
 390
 391        //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
 392        if let AlternateScroll::Off = alternate_scroll {
 393            term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
 394        }
 395
 396        let term = Arc::new(FairMutex::new(term));
 397
 398        //Setup the pty...
 399        let pty = match tty::new(
 400            &pty_options,
 401            TerminalSize::default().into(),
 402            window.window_id().as_u64(),
 403        ) {
 404            Ok(pty) => pty,
 405            Err(error) => {
 406                bail!(TerminalError {
 407                    directory: working_directory,
 408                    shell,
 409                    source: error,
 410                });
 411            }
 412        };
 413
 414        let pty_info = PtyProcessInfo::new(&pty);
 415
 416        //And connect them together
 417        let event_loop = EventLoop::new(
 418            term.clone(),
 419            ZedListener(events_tx.clone()),
 420            pty,
 421            pty_options.hold,
 422            false,
 423        )?;
 424
 425        //Kick things off
 426        let pty_tx = event_loop.channel();
 427        let _io_thread = event_loop.spawn(); // DANGER
 428
 429        let url_regex = RegexSearch::new(r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`]+"#).unwrap();
 430        // Optional suffix matches MSBuild diagnostic suffixes for path parsing in PathLikeWithPosition
 431        // https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks
 432        let word_regex =
 433            RegexSearch::new(r#"[\$\+\w.\[\]:/\\@\-~()]+(?:\((?:\d+|\d+,\d+)\))?"#).unwrap();
 434
 435        let terminal = Terminal {
 436            task,
 437            pty_tx: Notifier(pty_tx),
 438            completion_tx,
 439            term,
 440            events: VecDeque::with_capacity(10), //Should never get this high.
 441            last_content: Default::default(),
 442            last_mouse: None,
 443            matches: Vec::new(),
 444            selection_head: None,
 445            pty_info,
 446            breadcrumb_text: String::new(),
 447            scroll_px: px(0.),
 448            last_mouse_position: None,
 449            next_link_id: 0,
 450            selection_phase: SelectionPhase::Ended,
 451            secondary_pressed: false,
 452            hovered_word: false,
 453            url_regex,
 454            word_regex,
 455        };
 456
 457        Ok(TerminalBuilder {
 458            terminal,
 459            events_rx,
 460        })
 461    }
 462
 463    pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
 464        //Event loop
 465        cx.spawn(|terminal, mut cx| async move {
 466            while let Some(event) = self.events_rx.next().await {
 467                terminal.update(&mut cx, |terminal, cx| {
 468                    //Process the first event immediately for lowered latency
 469                    terminal.process_event(&event, cx);
 470                })?;
 471
 472                'outer: loop {
 473                    let mut events = Vec::new();
 474                    let mut timer = cx
 475                        .background_executor()
 476                        .timer(Duration::from_millis(4))
 477                        .fuse();
 478                    let mut wakeup = false;
 479                    loop {
 480                        futures::select_biased! {
 481                            _ = timer => break,
 482                            event = self.events_rx.next() => {
 483                                if let Some(event) = event {
 484                                    if matches!(event, AlacTermEvent::Wakeup) {
 485                                        wakeup = true;
 486                                    } else {
 487                                        events.push(event);
 488                                    }
 489
 490                                    if events.len() > 100 {
 491                                        break;
 492                                    }
 493                                } else {
 494                                    break;
 495                                }
 496                            },
 497                        }
 498                    }
 499
 500                    if events.is_empty() && !wakeup {
 501                        smol::future::yield_now().await;
 502                        break 'outer;
 503                    }
 504
 505                    terminal.update(&mut cx, |this, cx| {
 506                        if wakeup {
 507                            this.process_event(&AlacTermEvent::Wakeup, cx);
 508                        }
 509
 510                        for event in events {
 511                            this.process_event(&event, cx);
 512                        }
 513                    })?;
 514                    smol::future::yield_now().await;
 515                }
 516            }
 517
 518            anyhow::Ok(())
 519        })
 520        .detach();
 521
 522        self.terminal
 523    }
 524}
 525
 526#[derive(Debug, Clone, Deserialize, Serialize)]
 527pub struct IndexedCell {
 528    pub point: AlacPoint,
 529    pub cell: Cell,
 530}
 531
 532impl Deref for IndexedCell {
 533    type Target = Cell;
 534
 535    #[inline]
 536    fn deref(&self) -> &Cell {
 537        &self.cell
 538    }
 539}
 540
 541// TODO: Un-pub
 542#[derive(Clone)]
 543pub struct TerminalContent {
 544    pub cells: Vec<IndexedCell>,
 545    pub mode: TermMode,
 546    pub display_offset: usize,
 547    pub selection_text: Option<String>,
 548    pub selection: Option<SelectionRange>,
 549    pub cursor: RenderableCursor,
 550    pub cursor_char: char,
 551    pub size: TerminalSize,
 552    pub last_hovered_word: Option<HoveredWord>,
 553}
 554
 555#[derive(Clone)]
 556pub struct HoveredWord {
 557    pub word: String,
 558    pub word_match: RangeInclusive<AlacPoint>,
 559    pub id: usize,
 560}
 561
 562impl Default for TerminalContent {
 563    fn default() -> Self {
 564        TerminalContent {
 565            cells: Default::default(),
 566            mode: Default::default(),
 567            display_offset: Default::default(),
 568            selection_text: Default::default(),
 569            selection: Default::default(),
 570            cursor: RenderableCursor {
 571                shape: alacritty_terminal::vte::ansi::CursorShape::Block,
 572                point: AlacPoint::new(Line(0), Column(0)),
 573            },
 574            cursor_char: Default::default(),
 575            size: Default::default(),
 576            last_hovered_word: None,
 577        }
 578    }
 579}
 580
 581#[derive(PartialEq, Eq)]
 582pub enum SelectionPhase {
 583    Selecting,
 584    Ended,
 585}
 586
 587pub struct Terminal {
 588    pty_tx: Notifier,
 589    completion_tx: Sender<()>,
 590    term: Arc<FairMutex<Term<ZedListener>>>,
 591    events: VecDeque<InternalEvent>,
 592    /// This is only used for mouse mode cell change detection
 593    last_mouse: Option<(AlacPoint, AlacDirection)>,
 594    /// This is only used for terminal hovered word checking
 595    last_mouse_position: Option<Point<Pixels>>,
 596    pub matches: Vec<RangeInclusive<AlacPoint>>,
 597    pub last_content: TerminalContent,
 598    pub selection_head: Option<AlacPoint>,
 599    pub breadcrumb_text: String,
 600    pub pty_info: PtyProcessInfo,
 601    scroll_px: Pixels,
 602    next_link_id: usize,
 603    selection_phase: SelectionPhase,
 604    secondary_pressed: bool,
 605    hovered_word: bool,
 606    url_regex: RegexSearch,
 607    word_regex: RegexSearch,
 608    task: Option<TaskState>,
 609}
 610
 611pub struct TaskState {
 612    pub id: TaskId,
 613    pub full_label: String,
 614    pub label: String,
 615    pub command_label: String,
 616    pub status: TaskStatus,
 617    pub completion_rx: Receiver<()>,
 618    pub hide: HideStrategy,
 619}
 620
 621/// A status of the current terminal tab's task.
 622#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 623pub enum TaskStatus {
 624    /// The task had been started, but got cancelled or somehow otherwise it did not
 625    /// report its exit code before the terminal event loop was shut down.
 626    Unknown,
 627    /// The task is started and running currently.
 628    Running,
 629    /// After the start, the task stopped running and reported its error code back.
 630    Completed { success: bool },
 631}
 632
 633impl TaskStatus {
 634    fn register_terminal_exit(&mut self) {
 635        if self == &Self::Running {
 636            *self = Self::Unknown;
 637        }
 638    }
 639
 640    fn register_task_exit(&mut self, error_code: i32) {
 641        *self = TaskStatus::Completed {
 642            success: error_code == 0,
 643        };
 644    }
 645}
 646
 647impl Terminal {
 648    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
 649        match event {
 650            AlacTermEvent::Title(title) => {
 651                self.breadcrumb_text = title.to_string();
 652                cx.emit(Event::BreadcrumbsChanged);
 653            }
 654            AlacTermEvent::ResetTitle => {
 655                self.breadcrumb_text = String::new();
 656                cx.emit(Event::BreadcrumbsChanged);
 657            }
 658            AlacTermEvent::ClipboardStore(_, data) => {
 659                cx.write_to_clipboard(ClipboardItem::new_string(data.to_string()))
 660            }
 661            AlacTermEvent::ClipboardLoad(_, format) => {
 662                self.write_to_pty(
 663                    match &cx.read_from_clipboard().and_then(|item| item.text()) {
 664                        // The terminal only supports pasting strings, not images.
 665                        Some(text) => format(text),
 666                        _ => format(""),
 667                    },
 668                )
 669            }
 670            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 671            AlacTermEvent::TextAreaSizeRequest(format) => {
 672                self.write_to_pty(format(self.last_content.size.into()))
 673            }
 674            AlacTermEvent::CursorBlinkingChange => {
 675                cx.emit(Event::BlinkChanged);
 676            }
 677            AlacTermEvent::Bell => {
 678                cx.emit(Event::Bell);
 679            }
 680            AlacTermEvent::Exit => self.register_task_finished(None, cx),
 681            AlacTermEvent::MouseCursorDirty => {
 682                //NOOP, Handled in render
 683            }
 684            AlacTermEvent::Wakeup => {
 685                cx.emit(Event::Wakeup);
 686
 687                if self.pty_info.has_changed() {
 688                    cx.emit(Event::TitleChanged);
 689                }
 690            }
 691            AlacTermEvent::ColorRequest(index, format) => {
 692                // It's important that the color request is processed here to retain relative order
 693                // with other PTY writes. Otherwise applications might witness out-of-order
 694                // responses to requests. For example: An application sending `OSC 11 ; ? ST`
 695                // (color request) followed by `CSI c` (request device attributes) would receive
 696                // the response to `CSI c` first.
 697                // Instead of locking, we could store the colors in `self.last_content`. But then
 698                // we might respond with out of date value if a "set color" sequence is immediately
 699                // followed by a color request sequence.
 700                let color = self.term.lock().colors()[*index].unwrap_or_else(|| {
 701                    to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
 702                });
 703                self.write_to_pty(format(color));
 704            }
 705            AlacTermEvent::ChildExit(error_code) => {
 706                self.register_task_finished(Some(*error_code), cx);
 707            }
 708        }
 709    }
 710
 711    pub fn selection_started(&self) -> bool {
 712        self.selection_phase == SelectionPhase::Selecting
 713    }
 714
 715    pub fn get_cwd(&self) -> Option<PathBuf> {
 716        self.pty_info.current.as_ref().map(|info| info.cwd.clone())
 717    }
 718
 719    ///Takes events from Alacritty and translates them to behavior on this view
 720    fn process_terminal_event(
 721        &mut self,
 722        event: &InternalEvent,
 723        term: &mut Term<ZedListener>,
 724        cx: &mut ModelContext<Self>,
 725    ) {
 726        match event {
 727            InternalEvent::Resize(mut new_size) => {
 728                new_size.size.height = cmp::max(new_size.line_height, new_size.height());
 729                new_size.size.width = cmp::max(new_size.cell_width, new_size.width());
 730
 731                self.last_content.size = new_size;
 732
 733                self.pty_tx.0.send(Msg::Resize(new_size.into())).ok();
 734
 735                term.resize(new_size);
 736            }
 737            InternalEvent::Clear => {
 738                // Clear back buffer
 739                term.clear_screen(ClearMode::Saved);
 740
 741                let cursor = term.grid().cursor.point;
 742
 743                // Clear the lines above
 744                term.grid_mut().reset_region(..cursor.line);
 745
 746                // Copy the current line up
 747                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 748                    .iter()
 749                    .cloned()
 750                    .enumerate()
 751                    .collect::<Vec<(usize, Cell)>>();
 752
 753                for (i, cell) in line {
 754                    term.grid_mut()[Line(0)][Column(i)] = cell;
 755                }
 756
 757                // Reset the cursor
 758                term.grid_mut().cursor.point =
 759                    AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
 760                let new_cursor = term.grid().cursor.point;
 761
 762                // Clear the lines below the new cursor
 763                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 764                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 765                }
 766
 767                cx.emit(Event::Wakeup);
 768            }
 769            InternalEvent::Scroll(scroll) => {
 770                term.scroll_display(*scroll);
 771                self.refresh_hovered_word();
 772            }
 773            InternalEvent::SetSelection(selection) => {
 774                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 775
 776                #[cfg(target_os = "linux")]
 777                if let Some(selection_text) = term.selection_to_string() {
 778                    cx.write_to_primary(ClipboardItem::new_string(selection_text));
 779                }
 780
 781                if let Some((_, head)) = selection {
 782                    self.selection_head = Some(*head);
 783                }
 784                cx.emit(Event::SelectionsChanged)
 785            }
 786            InternalEvent::UpdateSelection(position) => {
 787                if let Some(mut selection) = term.selection.take() {
 788                    let (point, side) = grid_point_and_side(
 789                        *position,
 790                        self.last_content.size,
 791                        term.grid().display_offset(),
 792                    );
 793
 794                    selection.update(point, side);
 795                    term.selection = Some(selection);
 796
 797                    #[cfg(target_os = "linux")]
 798                    if let Some(selection_text) = term.selection_to_string() {
 799                        cx.write_to_primary(ClipboardItem::new_string(selection_text));
 800                    }
 801
 802                    self.selection_head = Some(point);
 803                    cx.emit(Event::SelectionsChanged)
 804                }
 805            }
 806
 807            InternalEvent::Copy => {
 808                if let Some(txt) = term.selection_to_string() {
 809                    cx.write_to_clipboard(ClipboardItem::new_string(txt))
 810                }
 811            }
 812            InternalEvent::ScrollToAlacPoint(point) => {
 813                term.scroll_to_point(*point);
 814                self.refresh_hovered_word();
 815            }
 816            InternalEvent::FindHyperlink(position, open) => {
 817                let prev_hovered_word = self.last_content.last_hovered_word.take();
 818
 819                let point = grid_point(
 820                    *position,
 821                    self.last_content.size,
 822                    term.grid().display_offset(),
 823                )
 824                .grid_clamp(term, Boundary::Grid);
 825
 826                let link = term.grid().index(point).hyperlink();
 827                let found_word = if link.is_some() {
 828                    let mut min_index = point;
 829                    loop {
 830                        let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
 831                        if new_min_index == min_index
 832                            || term.grid().index(new_min_index).hyperlink() != link
 833                        {
 834                            break;
 835                        } else {
 836                            min_index = new_min_index
 837                        }
 838                    }
 839
 840                    let mut max_index = point;
 841                    loop {
 842                        let new_max_index = max_index.add(term, Boundary::Cursor, 1);
 843                        if new_max_index == max_index
 844                            || term.grid().index(new_max_index).hyperlink() != link
 845                        {
 846                            break;
 847                        } else {
 848                            max_index = new_max_index
 849                        }
 850                    }
 851
 852                    let url = link.unwrap().uri().to_owned();
 853                    let url_match = min_index..=max_index;
 854
 855                    Some((url, true, url_match))
 856                } else if let Some(url_match) = regex_match_at(term, point, &mut self.url_regex) {
 857                    let url = term.bounds_to_string(*url_match.start(), *url_match.end());
 858                    Some((url, true, url_match))
 859                } else if let Some(word_match) = regex_match_at(term, point, &mut self.word_regex) {
 860                    let file_path = term.bounds_to_string(*word_match.start(), *word_match.end());
 861
 862                    let (sanitized_match, sanitized_word) =
 863                        if file_path.starts_with('[') && file_path.ends_with(']') {
 864                            (
 865                                Match::new(
 866                                    word_match.start().add(term, Boundary::Cursor, 1),
 867                                    word_match.end().sub(term, Boundary::Cursor, 1),
 868                                ),
 869                                file_path[1..file_path.len() - 1].to_owned(),
 870                            )
 871                        } else {
 872                            (word_match, file_path)
 873                        };
 874
 875                    Some((sanitized_word, false, sanitized_match))
 876                } else {
 877                    None
 878                };
 879
 880                match found_word {
 881                    Some((maybe_url_or_path, is_url, url_match)) => {
 882                        if *open {
 883                            let target = if is_url {
 884                                MaybeNavigationTarget::Url(maybe_url_or_path)
 885                            } else {
 886                                MaybeNavigationTarget::PathLike(PathLikeTarget {
 887                                    maybe_path: maybe_url_or_path,
 888                                    terminal_dir: self.get_cwd(),
 889                                })
 890                            };
 891                            cx.emit(Event::Open(target));
 892                        } else {
 893                            self.update_selected_word(
 894                                prev_hovered_word,
 895                                url_match,
 896                                maybe_url_or_path,
 897                                is_url,
 898                                cx,
 899                            );
 900                        }
 901                        self.hovered_word = true;
 902                    }
 903                    None => {
 904                        if self.hovered_word {
 905                            cx.emit(Event::NewNavigationTarget(None));
 906                        }
 907                        self.hovered_word = false;
 908                    }
 909                }
 910            }
 911        }
 912    }
 913
 914    fn update_selected_word(
 915        &mut self,
 916        prev_word: Option<HoveredWord>,
 917        word_match: RangeInclusive<AlacPoint>,
 918        word: String,
 919        is_url: bool,
 920        cx: &mut ModelContext<Self>,
 921    ) {
 922        if let Some(prev_word) = prev_word {
 923            if prev_word.word == word && prev_word.word_match == word_match {
 924                self.last_content.last_hovered_word = Some(HoveredWord {
 925                    word,
 926                    word_match,
 927                    id: prev_word.id,
 928                });
 929                return;
 930            }
 931        }
 932
 933        self.last_content.last_hovered_word = Some(HoveredWord {
 934            word: word.clone(),
 935            word_match,
 936            id: self.next_link_id(),
 937        });
 938        let navigation_target = if is_url {
 939            MaybeNavigationTarget::Url(word)
 940        } else {
 941            MaybeNavigationTarget::PathLike(PathLikeTarget {
 942                maybe_path: word,
 943                terminal_dir: self.get_cwd(),
 944            })
 945        };
 946        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
 947    }
 948
 949    fn next_link_id(&mut self) -> usize {
 950        let res = self.next_link_id;
 951        self.next_link_id = self.next_link_id.wrapping_add(1);
 952        res
 953    }
 954
 955    pub fn last_content(&self) -> &TerminalContent {
 956        &self.last_content
 957    }
 958
 959    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
 960        self.term.lock().set_cursor_style(Some(cursor_shape.into()));
 961    }
 962
 963    pub fn total_lines(&self) -> usize {
 964        let term = self.term.clone();
 965        let terminal = term.lock_unfair();
 966        terminal.total_lines()
 967    }
 968
 969    pub fn viewport_lines(&self) -> usize {
 970        let term = self.term.clone();
 971        let terminal = term.lock_unfair();
 972        terminal.screen_lines()
 973    }
 974
 975    //To test:
 976    //- Activate match on terminal (scrolling and selection)
 977    //- Editor search snapping behavior
 978
 979    pub fn activate_match(&mut self, index: usize) {
 980        if let Some(search_match) = self.matches.get(index).cloned() {
 981            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 982
 983            self.events
 984                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
 985        }
 986    }
 987
 988    pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
 989        let matches_to_select = self
 990            .matches
 991            .iter()
 992            .filter(|self_match| matches.contains(self_match))
 993            .cloned()
 994            .collect::<Vec<_>>();
 995        for match_to_select in matches_to_select {
 996            self.set_selection(Some((
 997                make_selection(&match_to_select),
 998                *match_to_select.end(),
 999            )));
1000        }
1001    }
1002
1003    pub fn select_all(&mut self) {
1004        let term = self.term.lock();
1005        let start = AlacPoint::new(term.topmost_line(), Column(0));
1006        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1007        drop(term);
1008        self.set_selection(Some((make_selection(&(start..=end)), end)));
1009    }
1010
1011    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1012        self.events
1013            .push_back(InternalEvent::SetSelection(selection));
1014    }
1015
1016    pub fn copy(&mut self) {
1017        self.events.push_back(InternalEvent::Copy);
1018    }
1019
1020    pub fn clear(&mut self) {
1021        self.events.push_back(InternalEvent::Clear)
1022    }
1023
1024    pub fn scroll_line_up(&mut self) {
1025        self.events
1026            .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1027    }
1028
1029    pub fn scroll_up_by(&mut self, lines: usize) {
1030        self.events
1031            .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1032    }
1033
1034    pub fn scroll_line_down(&mut self) {
1035        self.events
1036            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1037    }
1038
1039    pub fn scroll_down_by(&mut self, lines: usize) {
1040        self.events
1041            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1042    }
1043
1044    pub fn scroll_page_up(&mut self) {
1045        self.events
1046            .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1047    }
1048
1049    pub fn scroll_page_down(&mut self) {
1050        self.events
1051            .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1052    }
1053
1054    pub fn scroll_to_top(&mut self) {
1055        self.events
1056            .push_back(InternalEvent::Scroll(AlacScroll::Top));
1057    }
1058
1059    pub fn scroll_to_bottom(&mut self) {
1060        self.events
1061            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1062    }
1063
1064    ///Resize the terminal and the PTY.
1065    pub fn set_size(&mut self, new_size: TerminalSize) {
1066        if self.last_content.size != new_size {
1067            self.events.push_back(InternalEvent::Resize(new_size))
1068        }
1069    }
1070
1071    ///Write the Input payload to the tty.
1072    fn write_to_pty(&self, input: String) {
1073        self.pty_tx.notify(input.into_bytes());
1074    }
1075
1076    fn write_bytes_to_pty(&self, input: Vec<u8>) {
1077        self.pty_tx.notify(input);
1078    }
1079
1080    pub fn input(&mut self, input: String) {
1081        self.events
1082            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1083        self.events.push_back(InternalEvent::SetSelection(None));
1084
1085        self.write_to_pty(input);
1086    }
1087
1088    pub fn input_bytes(&mut self, input: Vec<u8>) {
1089        self.events
1090            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1091        self.events.push_back(InternalEvent::SetSelection(None));
1092
1093        self.write_bytes_to_pty(input);
1094    }
1095
1096    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1097        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1098        if let Some(esc) = esc {
1099            self.input(esc);
1100            true
1101        } else {
1102            false
1103        }
1104    }
1105
1106    pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
1107        let changed = self.secondary_pressed != modifiers.secondary();
1108        if !self.secondary_pressed && modifiers.secondary() {
1109            self.refresh_hovered_word();
1110        }
1111        self.secondary_pressed = modifiers.secondary();
1112        changed
1113    }
1114
1115    ///Paste text into the terminal
1116    pub fn paste(&mut self, text: &str) {
1117        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1118            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1119        } else {
1120            text.replace("\r\n", "\r").replace('\n', "\r")
1121        };
1122
1123        self.input(paste_text);
1124    }
1125
1126    pub fn sync(&mut self, cx: &mut ModelContext<Self>) {
1127        let term = self.term.clone();
1128        let mut terminal = term.lock_unfair();
1129        //Note that the ordering of events matters for event processing
1130        while let Some(e) = self.events.pop_front() {
1131            self.process_terminal_event(&e, &mut terminal, cx)
1132        }
1133
1134        self.last_content = Self::make_content(&terminal, &self.last_content);
1135    }
1136
1137    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1138        let content = term.renderable_content();
1139        TerminalContent {
1140            cells: content
1141                .display_iter
1142                //TODO: Add this once there's a way to retain empty lines
1143                // .filter(|ic| {
1144                //     !ic.flags.contains(Flags::HIDDEN)
1145                //         && !(ic.bg == Named(NamedColor::Background)
1146                //             && ic.c == ' '
1147                //             && !ic.flags.contains(Flags::INVERSE))
1148                // })
1149                .map(|ic| IndexedCell {
1150                    point: ic.point,
1151                    cell: ic.cell.clone(),
1152                })
1153                .collect::<Vec<IndexedCell>>(),
1154            mode: content.mode,
1155            display_offset: content.display_offset,
1156            selection_text: term.selection_to_string(),
1157            selection: content.selection,
1158            cursor: content.cursor,
1159            cursor_char: term.grid()[content.cursor.point].c,
1160            size: last_content.size,
1161            last_hovered_word: last_content.last_hovered_word.clone(),
1162        }
1163    }
1164
1165    pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1166        let term = self.term.clone();
1167        let terminal = term.lock_unfair();
1168
1169        let mut lines = Vec::new();
1170        let mut current_line = terminal.bottommost_line();
1171        while lines.len() < n {
1172            let mut line_buffer = String::new();
1173            for cell in &terminal.grid()[current_line] {
1174                line_buffer.push(cell.c);
1175            }
1176            let line = line_buffer.trim_end();
1177            if !line.is_empty() {
1178                lines.push(line.to_string());
1179            }
1180
1181            if current_line == terminal.topmost_line() {
1182                break;
1183            }
1184            current_line = Line(current_line.0 - 1);
1185        }
1186        lines.reverse();
1187        lines
1188    }
1189
1190    pub fn focus_in(&self) {
1191        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1192            self.write_to_pty("\x1b[I".to_string());
1193        }
1194    }
1195
1196    pub fn focus_out(&mut self) {
1197        self.last_mouse_position = None;
1198        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1199            self.write_to_pty("\x1b[O".to_string());
1200        }
1201    }
1202
1203    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1204        match self.last_mouse {
1205            Some((old_point, old_side)) => {
1206                if old_point == point && old_side == side {
1207                    false
1208                } else {
1209                    self.last_mouse = Some((point, side));
1210                    true
1211                }
1212            }
1213            None => {
1214                self.last_mouse = Some((point, side));
1215                true
1216            }
1217        }
1218    }
1219
1220    pub fn mouse_mode(&self, shift: bool) -> bool {
1221        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1222    }
1223
1224    pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1225        let position = e.position - origin;
1226        self.last_mouse_position = Some(position);
1227        if self.mouse_mode(e.modifiers.shift) {
1228            let (point, side) = grid_point_and_side(
1229                position,
1230                self.last_content.size,
1231                self.last_content.display_offset,
1232            );
1233
1234            if self.mouse_changed(point, side) {
1235                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1236                    self.pty_tx.notify(bytes);
1237                }
1238            }
1239        } else if self.secondary_pressed {
1240            self.word_from_position(Some(position));
1241        }
1242    }
1243
1244    fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1245        if self.selection_phase == SelectionPhase::Selecting {
1246            self.last_content.last_hovered_word = None;
1247        } else if let Some(position) = position {
1248            self.events
1249                .push_back(InternalEvent::FindHyperlink(position, false));
1250        }
1251    }
1252
1253    pub fn mouse_drag(
1254        &mut self,
1255        e: &MouseMoveEvent,
1256        origin: Point<Pixels>,
1257        region: Bounds<Pixels>,
1258    ) {
1259        let position = e.position - origin;
1260        self.last_mouse_position = Some(position);
1261
1262        if !self.mouse_mode(e.modifiers.shift) {
1263            self.selection_phase = SelectionPhase::Selecting;
1264            // Alacritty has the same ordering, of first updating the selection
1265            // then scrolling 15ms later
1266            self.events
1267                .push_back(InternalEvent::UpdateSelection(position));
1268
1269            // Doesn't make sense to scroll the alt screen
1270            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1271                let scroll_delta = match self.drag_line_delta(e, region) {
1272                    Some(value) => value,
1273                    None => return,
1274                };
1275
1276                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1277
1278                self.events
1279                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1280            }
1281        }
1282    }
1283
1284    fn drag_line_delta(&mut self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1285        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1286        let top = region.origin.y + (self.last_content.size.line_height * 2.);
1287        let bottom = region.lower_left().y - (self.last_content.size.line_height * 2.);
1288        let scroll_delta = if e.position.y < top {
1289            (top - e.position.y).pow(1.1)
1290        } else if e.position.y > bottom {
1291            -((e.position.y - bottom).pow(1.1))
1292        } else {
1293            return None; //Nothing to do
1294        };
1295        Some(scroll_delta)
1296    }
1297
1298    pub fn mouse_down(
1299        &mut self,
1300        e: &MouseDownEvent,
1301        origin: Point<Pixels>,
1302        _cx: &mut ModelContext<Self>,
1303    ) {
1304        let position = e.position - origin;
1305        let point = grid_point(
1306            position,
1307            self.last_content.size,
1308            self.last_content.display_offset,
1309        );
1310
1311        if self.mouse_mode(e.modifiers.shift) {
1312            if let Some(bytes) =
1313                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1314            {
1315                self.pty_tx.notify(bytes);
1316            }
1317        } else {
1318            match e.button {
1319                MouseButton::Left => {
1320                    let position = e.position - origin;
1321                    let (point, side) = grid_point_and_side(
1322                        position,
1323                        self.last_content.size,
1324                        self.last_content.display_offset,
1325                    );
1326
1327                    let selection_type = match e.click_count {
1328                        0 => return, //This is a release
1329                        1 => Some(SelectionType::Simple),
1330                        2 => Some(SelectionType::Semantic),
1331                        3 => Some(SelectionType::Lines),
1332                        _ => None,
1333                    };
1334
1335                    let selection = selection_type
1336                        .map(|selection_type| Selection::new(selection_type, point, side));
1337
1338                    if let Some(sel) = selection {
1339                        self.events
1340                            .push_back(InternalEvent::SetSelection(Some((sel, point))));
1341                    }
1342                }
1343                #[cfg(target_os = "linux")]
1344                MouseButton::Middle => {
1345                    if let Some(item) = _cx.read_from_primary() {
1346                        let text = item.text().unwrap_or_default().to_string();
1347                        self.input(text);
1348                    }
1349                }
1350                _ => {}
1351            }
1352        }
1353    }
1354
1355    pub fn mouse_up(
1356        &mut self,
1357        e: &MouseUpEvent,
1358        origin: Point<Pixels>,
1359        cx: &mut ModelContext<Self>,
1360    ) {
1361        let setting = TerminalSettings::get_global(cx);
1362
1363        let position = e.position - origin;
1364        if self.mouse_mode(e.modifiers.shift) {
1365            let point = grid_point(
1366                position,
1367                self.last_content.size,
1368                self.last_content.display_offset,
1369            );
1370
1371            if let Some(bytes) =
1372                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1373            {
1374                self.pty_tx.notify(bytes);
1375            }
1376        } else {
1377            if e.button == MouseButton::Left && setting.copy_on_select {
1378                self.copy();
1379            }
1380
1381            //Hyperlinks
1382            if self.selection_phase == SelectionPhase::Ended {
1383                let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1384                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1385                    cx.open_url(link.uri());
1386                } else if self.secondary_pressed {
1387                    self.events
1388                        .push_back(InternalEvent::FindHyperlink(position, true));
1389                }
1390            }
1391        }
1392
1393        self.selection_phase = SelectionPhase::Ended;
1394        self.last_mouse = None;
1395    }
1396
1397    ///Scroll the terminal
1398    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Point<Pixels>) {
1399        let mouse_mode = self.mouse_mode(e.shift);
1400
1401        if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1402            if mouse_mode {
1403                let point = grid_point(
1404                    e.position - origin,
1405                    self.last_content.size,
1406                    self.last_content.display_offset,
1407                );
1408
1409                if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1410                {
1411                    for scroll in scrolls {
1412                        self.pty_tx.notify(scroll);
1413                    }
1414                };
1415            } else if self
1416                .last_content
1417                .mode
1418                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1419                && !e.shift
1420            {
1421                self.pty_tx.notify(alt_scroll(scroll_lines))
1422            } else if scroll_lines != 0 {
1423                let scroll = AlacScroll::Delta(scroll_lines);
1424
1425                self.events.push_back(InternalEvent::Scroll(scroll));
1426            }
1427        }
1428    }
1429
1430    fn refresh_hovered_word(&mut self) {
1431        self.word_from_position(self.last_mouse_position);
1432    }
1433
1434    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1435        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1436        let line_height = self.last_content.size.line_height;
1437        match e.touch_phase {
1438            /* Reset scroll state on started */
1439            TouchPhase::Started => {
1440                self.scroll_px = px(0.);
1441                None
1442            }
1443            /* Calculate the appropriate scroll lines */
1444            TouchPhase::Moved => {
1445                let old_offset = (self.scroll_px / line_height) as i32;
1446
1447                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1448
1449                let new_offset = (self.scroll_px / line_height) as i32;
1450
1451                // Whenever we hit the edges, reset our stored scroll to 0
1452                // so we can respond to changes in direction quickly
1453                self.scroll_px %= self.last_content.size.height();
1454
1455                Some(new_offset - old_offset)
1456            }
1457            TouchPhase::Ended => None,
1458        }
1459    }
1460
1461    pub fn find_matches(
1462        &mut self,
1463        mut searcher: RegexSearch,
1464        cx: &mut ModelContext<Self>,
1465    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1466        let term = self.term.clone();
1467        cx.background_executor().spawn(async move {
1468            let term = term.lock();
1469
1470            all_search_matches(&term, &mut searcher).collect()
1471        })
1472    }
1473
1474    pub fn working_directory(&self) -> Option<PathBuf> {
1475        self.pty_info
1476            .current
1477            .as_ref()
1478            .map(|process| process.cwd.clone())
1479    }
1480
1481    pub fn title(&self, truncate: bool) -> String {
1482        const MAX_CHARS: usize = 25;
1483        match &self.task {
1484            Some(task_state) => {
1485                if truncate {
1486                    truncate_and_trailoff(&task_state.label, MAX_CHARS)
1487                } else {
1488                    task_state.full_label.clone()
1489                }
1490            }
1491            None => self
1492                .pty_info
1493                .current
1494                .as_ref()
1495                .map(|fpi| {
1496                    let process_file = fpi
1497                        .cwd
1498                        .file_name()
1499                        .map(|name| name.to_string_lossy().to_string())
1500                        .unwrap_or_default();
1501
1502                    let argv = fpi.argv.clone();
1503                    let process_name = format!(
1504                        "{}{}",
1505                        fpi.name,
1506                        if !argv.is_empty() {
1507                            format!(" {}", (argv[1..]).join(" "))
1508                        } else {
1509                            "".to_string()
1510                        }
1511                    );
1512                    let (process_file, process_name) = if truncate {
1513                        (
1514                            truncate_and_trailoff(&process_file, MAX_CHARS),
1515                            truncate_and_trailoff(&process_name, MAX_CHARS),
1516                        )
1517                    } else {
1518                        (process_file, process_name)
1519                    };
1520                    format!("{process_file}{process_name}")
1521                })
1522                .unwrap_or_else(|| "Terminal".to_string()),
1523        }
1524    }
1525
1526    pub fn can_navigate_to_selected_word(&self) -> bool {
1527        self.secondary_pressed && self.hovered_word
1528    }
1529
1530    pub fn task(&self) -> Option<&TaskState> {
1531        self.task.as_ref()
1532    }
1533
1534    pub fn wait_for_completed_task(&self, cx: &mut AppContext) -> Task<()> {
1535        if let Some(task) = self.task() {
1536            if task.status == TaskStatus::Running {
1537                let mut completion_receiver = task.completion_rx.clone();
1538                return cx.spawn(|_| async move {
1539                    completion_receiver.next().await;
1540                });
1541            }
1542        }
1543        Task::ready(())
1544    }
1545
1546    fn register_task_finished(
1547        &mut self,
1548        error_code: Option<i32>,
1549        cx: &mut ModelContext<'_, Terminal>,
1550    ) {
1551        self.completion_tx.try_send(()).ok();
1552        let task = match &mut self.task {
1553            Some(task) => task,
1554            None => {
1555                if error_code.is_none() {
1556                    cx.emit(Event::CloseTerminal);
1557                }
1558                return;
1559            }
1560        };
1561        if task.status != TaskStatus::Running {
1562            return;
1563        }
1564        match error_code {
1565            Some(error_code) => {
1566                task.status.register_task_exit(error_code);
1567            }
1568            None => {
1569                task.status.register_terminal_exit();
1570            }
1571        };
1572
1573        let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1574        // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1575        // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1576        // when Zed task finishes and no more output is made.
1577        // After the task summary is output once, no more text is appended to the terminal.
1578        unsafe { append_text_to_term(&mut self.term.lock(), &[&task_line, &command_line]) };
1579        match task.hide {
1580            HideStrategy::Never => {}
1581            HideStrategy::Always => {
1582                cx.emit(Event::CloseTerminal);
1583            }
1584            HideStrategy::OnSuccess => {
1585                if finished_successfully {
1586                    cx.emit(Event::CloseTerminal);
1587                }
1588            }
1589        }
1590    }
1591}
1592
1593const TASK_DELIMITER: &str = "";
1594fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1595    let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1596    let (success, task_line) = match error_code {
1597        Some(0) => {
1598            (true, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"))
1599        }
1600        Some(error_code) => {
1601            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"))
1602        }
1603        None => {
1604            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"))
1605        }
1606    };
1607    let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1608    let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1609    (success, task_line, command_line)
1610}
1611
1612/// Appends a stringified task summary to the terminal, after its output.
1613///
1614/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1615/// New text being added to the terminal here, uses "less public" APIs,
1616/// which are not maintaining the entire terminal state intact.
1617///
1618///
1619/// The library
1620///
1621/// * does not increment inner grid cursor's _lines_ on `input` calls
1622///   (but displaying the lines correctly and incrementing cursor's columns)
1623///
1624/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1625///
1626/// * does not alter grid state after `newline` call
1627///   so its `bottommost_line` is always the same additions, and
1628///   the cursor's `point` is not updated to the new line and column values
1629///
1630/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1631///   Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1632///
1633/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1634/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1635/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1636/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1637unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1638    term.newline();
1639    term.grid_mut().cursor.point.column = Column(0);
1640    for line in text_lines {
1641        for c in line.chars() {
1642            term.input(c);
1643        }
1644        term.newline();
1645        term.grid_mut().cursor.point.column = Column(0);
1646    }
1647}
1648
1649impl Drop for Terminal {
1650    fn drop(&mut self) {
1651        self.pty_tx.0.send(Msg::Shutdown).ok();
1652    }
1653}
1654
1655impl EventEmitter<Event> for Terminal {}
1656
1657/// Based on alacritty/src/display/hint.rs > regex_match_at
1658/// Retrieve the match, if the specified point is inside the content matching the regex.
1659fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1660    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1661}
1662
1663/// Copied from alacritty/src/display/hint.rs:
1664/// Iterate over all visible regex matches.
1665pub fn visible_regex_match_iter<'a, T>(
1666    term: &'a Term<T>,
1667    regex: &'a mut RegexSearch,
1668) -> impl Iterator<Item = Match> + 'a {
1669    let viewport_start = Line(-(term.grid().display_offset() as i32));
1670    let viewport_end = viewport_start + term.bottommost_line();
1671    let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1672    let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1673    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1674    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1675
1676    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1677        .skip_while(move |rm| rm.end().line < viewport_start)
1678        .take_while(move |rm| rm.start().line <= viewport_end)
1679}
1680
1681fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1682    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1683    selection.update(*range.end(), AlacDirection::Right);
1684    selection
1685}
1686
1687fn all_search_matches<'a, T>(
1688    term: &'a Term<T>,
1689    regex: &'a mut RegexSearch,
1690) -> impl Iterator<Item = Match> + 'a {
1691    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1692    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1693    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1694}
1695
1696fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1697    let col = (pos.x / size.cell_width()).round() as usize;
1698    let clamped_col = min(col, size.columns() - 1);
1699    let row = (pos.y / size.line_height()).round() as usize;
1700    let clamped_row = min(row, size.screen_lines() - 1);
1701    clamped_row * size.columns() + clamped_col
1702}
1703
1704/// Converts an 8 bit ANSI color to its GPUI equivalent.
1705/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1706/// Other than that use case, should only be called with values in the [0,255] range
1707pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1708    let colors = theme.colors();
1709
1710    match index {
1711        // 0-15 are the same as the named colors above
1712        0 => colors.terminal_ansi_black,
1713        1 => colors.terminal_ansi_red,
1714        2 => colors.terminal_ansi_green,
1715        3 => colors.terminal_ansi_yellow,
1716        4 => colors.terminal_ansi_blue,
1717        5 => colors.terminal_ansi_magenta,
1718        6 => colors.terminal_ansi_cyan,
1719        7 => colors.terminal_ansi_white,
1720        8 => colors.terminal_ansi_bright_black,
1721        9 => colors.terminal_ansi_bright_red,
1722        10 => colors.terminal_ansi_bright_green,
1723        11 => colors.terminal_ansi_bright_yellow,
1724        12 => colors.terminal_ansi_bright_blue,
1725        13 => colors.terminal_ansi_bright_magenta,
1726        14 => colors.terminal_ansi_bright_cyan,
1727        15 => colors.terminal_ansi_bright_white,
1728        // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1729        16..=231 => {
1730            let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1731            let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1732            rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1733        }
1734        // 232-255 are a 24 step grayscale from black to white
1735        232..=255 => {
1736            let i = index as u8 - 232; // Align index to 0..24
1737            let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1738            rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1739        }
1740        // For compatibility with the alacritty::Colors interface
1741        256 => colors.text,
1742        257 => colors.background,
1743        258 => theme.players().local().cursor,
1744        259 => colors.terminal_ansi_dim_black,
1745        260 => colors.terminal_ansi_dim_red,
1746        261 => colors.terminal_ansi_dim_green,
1747        262 => colors.terminal_ansi_dim_yellow,
1748        263 => colors.terminal_ansi_dim_blue,
1749        264 => colors.terminal_ansi_dim_magenta,
1750        265 => colors.terminal_ansi_dim_cyan,
1751        266 => colors.terminal_ansi_dim_white,
1752        267 => colors.terminal_bright_foreground,
1753        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1754
1755        _ => black(),
1756    }
1757}
1758
1759/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1760/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1761///
1762/// Wikipedia gives a formula for calculating the index for a given color:
1763///
1764/// ```
1765/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1766/// ```
1767///
1768/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1769fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1770    debug_assert!((16..=231).contains(&i));
1771    let i = i - 16;
1772    let r = (i - (i % 36)) / 36;
1773    let g = ((i % 36) - (i % 6)) / 6;
1774    let b = (i % 36) % 6;
1775    (r, g, b)
1776}
1777
1778pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1779    Rgba {
1780        r: (r as f32 / 255.),
1781        g: (g as f32 / 255.),
1782        b: (b as f32 / 255.),
1783        a: 1.,
1784    }
1785    .into()
1786}
1787
1788#[cfg(test)]
1789mod tests {
1790    use alacritty_terminal::{
1791        index::{Column, Line, Point as AlacPoint},
1792        term::cell::Cell,
1793    };
1794    use gpui::{point, size, Pixels};
1795    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1796
1797    use crate::{
1798        content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
1799    };
1800
1801    #[test]
1802    fn test_rgb_for_index() {
1803        // Test every possible value in the color cube.
1804        for i in 16..=231 {
1805            let (r, g, b) = rgb_for_index(i);
1806            assert_eq!(i, 16 + 36 * r + 6 * g + b);
1807        }
1808    }
1809
1810    #[test]
1811    fn test_mouse_to_cell_test() {
1812        let mut rng = thread_rng();
1813        const ITERATIONS: usize = 10;
1814        const PRECISION: usize = 1000;
1815
1816        for _ in 0..ITERATIONS {
1817            let viewport_cells = rng.gen_range(15..20);
1818            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1819
1820            let size = crate::TerminalSize {
1821                cell_width: Pixels::from(cell_size),
1822                line_height: Pixels::from(cell_size),
1823                size: size(
1824                    Pixels::from(cell_size * (viewport_cells as f32)),
1825                    Pixels::from(cell_size * (viewport_cells as f32)),
1826                ),
1827            };
1828
1829            let cells = get_cells(size, &mut rng);
1830            let content = convert_cells_to_content(size, &cells);
1831
1832            for row in 0..(viewport_cells - 1) {
1833                let row = row as usize;
1834                for col in 0..(viewport_cells - 1) {
1835                    let col = col as usize;
1836
1837                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1838                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1839
1840                    let mouse_pos = point(
1841                        Pixels::from(col as f32 * cell_size + col_offset),
1842                        Pixels::from(row as f32 * cell_size + row_offset),
1843                    );
1844
1845                    let content_index = content_index_for_mouse(mouse_pos, &content.size);
1846                    let mouse_cell = content.cells[content_index].c;
1847                    let real_cell = cells[row][col];
1848
1849                    assert_eq!(mouse_cell, real_cell);
1850                }
1851            }
1852        }
1853    }
1854
1855    #[test]
1856    fn test_mouse_to_cell_clamp() {
1857        let mut rng = thread_rng();
1858
1859        let size = crate::TerminalSize {
1860            cell_width: Pixels::from(10.),
1861            line_height: Pixels::from(10.),
1862            size: size(Pixels::from(100.), Pixels::from(100.)),
1863        };
1864
1865        let cells = get_cells(size, &mut rng);
1866        let content = convert_cells_to_content(size, &cells);
1867
1868        assert_eq!(
1869            content.cells[content_index_for_mouse(
1870                point(Pixels::from(-10.), Pixels::from(-10.)),
1871                &content.size,
1872            )]
1873            .c,
1874            cells[0][0]
1875        );
1876        assert_eq!(
1877            content.cells[content_index_for_mouse(
1878                point(Pixels::from(1000.), Pixels::from(1000.)),
1879                &content.size,
1880            )]
1881            .c,
1882            cells[9][9]
1883        );
1884    }
1885
1886    fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1887        let mut cells = Vec::new();
1888
1889        for _ in 0..((size.height() / size.line_height()) as usize) {
1890            let mut row_vec = Vec::new();
1891            for _ in 0..((size.width() / size.cell_width()) as usize) {
1892                let cell_char = rng.sample(Alphanumeric) as char;
1893                row_vec.push(cell_char)
1894            }
1895            cells.push(row_vec)
1896        }
1897
1898        cells
1899    }
1900
1901    fn convert_cells_to_content(size: TerminalSize, cells: &[Vec<char>]) -> TerminalContent {
1902        let mut ic = Vec::new();
1903
1904        for (index, row) in cells.iter().enumerate() {
1905            for (cell_index, cell_char) in row.iter().enumerate() {
1906                ic.push(IndexedCell {
1907                    point: AlacPoint::new(Line(index as i32), Column(cell_index)),
1908                    cell: Cell {
1909                        c: *cell_char,
1910                        ..Default::default()
1911                    },
1912                });
1913            }
1914        }
1915
1916        TerminalContent {
1917            cells: ic,
1918            size,
1919            ..Default::default()
1920        }
1921    }
1922}