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