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