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