terminal.rs

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