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