terminal.rs

   1pub mod mappings;
   2pub use alacritty_terminal;
   3
   4use alacritty_terminal::{
   5    ansi::{ClearMode, Handler},
   6    config::{Config, Program, PtyConfig, Scrolling},
   7    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
   8    event_loop::{EventLoop, Msg, Notifier},
   9    grid::{Dimensions, Scroll as AlacScroll},
  10    index::{Column, Direction as AlacDirection, Line, Point},
  11    selection::{Selection, SelectionRange, SelectionType},
  12    sync::FairMutex,
  13    term::{
  14        cell::Cell,
  15        color::Rgb,
  16        search::{Match, RegexIter, RegexSearch},
  17        RenderableCursor, TermMode,
  18    },
  19    tty::{self, setup_env},
  20    Term,
  21};
  22use anyhow::{bail, Result};
  23
  24use futures::{
  25    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
  26    FutureExt,
  27};
  28
  29use mappings::mouse::{
  30    alt_scroll, grid_point, mouse_button_report, mouse_moved_report, mouse_side, scroll_report,
  31};
  32
  33use procinfo::LocalProcessInfo;
  34use serde::{Deserialize, Serialize};
  35use settings::{AlternateScroll, Settings, Shell, TerminalBlink};
  36use util::truncate_and_trailoff;
  37
  38use std::{
  39    cmp::min,
  40    collections::{HashMap, VecDeque},
  41    fmt::Display,
  42    ops::{Deref, Index, RangeInclusive, Sub},
  43    os::unix::prelude::AsRawFd,
  44    path::PathBuf,
  45    sync::Arc,
  46    time::{Duration, Instant},
  47};
  48use thiserror::Error;
  49
  50use gpui::{
  51    geometry::vector::{vec2f, Vector2F},
  52    keymap_matcher::Keystroke,
  53    platform::{MouseButton, MouseMovedEvent, TouchPhase},
  54    scene::{MouseDown, MouseDrag, MouseScrollWheel, MouseUp},
  55    ClipboardItem, Entity, ModelContext, Task,
  56};
  57
  58use crate::mappings::{
  59    colors::{get_color_at_index, to_alac_rgb},
  60    keys::to_esc_str,
  61};
  62use lazy_static::lazy_static;
  63
  64///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  65///Scroll multiplier that is set to 3 by default. This will be removed when I
  66///Implement scroll bars.
  67const SCROLL_MULTIPLIER: f32 = 4.;
  68const MAX_SEARCH_LINES: usize = 100;
  69const DEBUG_TERMINAL_WIDTH: f32 = 500.;
  70const DEBUG_TERMINAL_HEIGHT: f32 = 30.;
  71const DEBUG_CELL_WIDTH: f32 = 5.;
  72const DEBUG_LINE_HEIGHT: f32 = 5.;
  73
  74// Regex Copied from alacritty's ui_config.rs
  75
  76lazy_static! {
  77    static ref URL_REGEX: RegexSearch = RegexSearch::new("(ipfs:|ipns:|magnet:|mailto:|gemini:|gopher:|https:|http:|news:|file:|git:|ssh:|ftp:)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>\"\\s{-}\\^⟨⟩`]+").unwrap();
  78}
  79
  80///Upward flowing events, for changing the title and such
  81#[derive(Clone, Copy, Debug)]
  82pub enum Event {
  83    TitleChanged,
  84    BreadcrumbsChanged,
  85    CloseTerminal,
  86    Bell,
  87    Wakeup,
  88    BlinkChanged,
  89    SelectionsChanged,
  90}
  91
  92#[derive(Clone)]
  93enum InternalEvent {
  94    ColorRequest(usize, Arc<dyn Fn(Rgb) -> String + Sync + Send + 'static>),
  95    Resize(TerminalSize),
  96    Clear,
  97    // FocusNextMatch,
  98    Scroll(AlacScroll),
  99    ScrollToPoint(Point),
 100    SetSelection(Option<(Selection, Point)>),
 101    UpdateSelection(Vector2F),
 102    // Adjusted mouse position, should open
 103    FindHyperlink(Vector2F, bool),
 104    Copy,
 105}
 106
 107///A translation struct for Alacritty to communicate with us from their event loop
 108#[derive(Clone)]
 109pub struct ZedListener(UnboundedSender<AlacTermEvent>);
 110
 111impl EventListener for ZedListener {
 112    fn send_event(&self, event: AlacTermEvent) {
 113        self.0.unbounded_send(event).ok();
 114    }
 115}
 116
 117#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
 118pub struct TerminalSize {
 119    pub cell_width: f32,
 120    pub line_height: f32,
 121    pub height: f32,
 122    pub width: f32,
 123}
 124
 125impl TerminalSize {
 126    pub fn new(line_height: f32, cell_width: f32, size: Vector2F) -> Self {
 127        TerminalSize {
 128            cell_width,
 129            line_height,
 130            width: size.x(),
 131            height: size.y(),
 132        }
 133    }
 134
 135    pub fn num_lines(&self) -> usize {
 136        (self.height / self.line_height).floor() as usize
 137    }
 138
 139    pub fn num_columns(&self) -> usize {
 140        (self.width / self.cell_width).floor() as usize
 141    }
 142
 143    pub fn height(&self) -> f32 {
 144        self.height
 145    }
 146
 147    pub fn width(&self) -> f32 {
 148        self.width
 149    }
 150
 151    pub fn cell_width(&self) -> f32 {
 152        self.cell_width
 153    }
 154
 155    pub fn line_height(&self) -> f32 {
 156        self.line_height
 157    }
 158}
 159impl Default for TerminalSize {
 160    fn default() -> Self {
 161        TerminalSize::new(
 162            DEBUG_LINE_HEIGHT,
 163            DEBUG_CELL_WIDTH,
 164            vec2f(DEBUG_TERMINAL_WIDTH, DEBUG_TERMINAL_HEIGHT),
 165        )
 166    }
 167}
 168
 169impl From<TerminalSize> for WindowSize {
 170    fn from(val: TerminalSize) -> Self {
 171        WindowSize {
 172            num_lines: val.num_lines() as u16,
 173            num_cols: val.num_columns() as u16,
 174            cell_width: val.cell_width() as u16,
 175            cell_height: val.line_height() as u16,
 176        }
 177    }
 178}
 179
 180impl Dimensions for TerminalSize {
 181    /// Note: this is supposed to be for the back buffer's length,
 182    /// but we exclusively use it to resize the terminal, which does not
 183    /// use this method. We still have to implement it for the trait though,
 184    /// hence, this comment.
 185    fn total_lines(&self) -> usize {
 186        self.screen_lines()
 187    }
 188
 189    fn screen_lines(&self) -> usize {
 190        self.num_lines()
 191    }
 192
 193    fn columns(&self) -> usize {
 194        self.num_columns()
 195    }
 196}
 197
 198#[derive(Error, Debug)]
 199pub struct TerminalError {
 200    pub directory: Option<PathBuf>,
 201    pub shell: Shell,
 202    pub source: std::io::Error,
 203}
 204
 205impl TerminalError {
 206    pub fn fmt_directory(&self) -> String {
 207        self.directory
 208            .clone()
 209            .map(|path| {
 210                match path
 211                    .into_os_string()
 212                    .into_string()
 213                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 214                {
 215                    Ok(s) => s,
 216                    Err(s) => s,
 217                }
 218            })
 219            .unwrap_or_else(|| {
 220                let default_dir =
 221                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
 222                match default_dir {
 223                    Some(dir) => format!("<none specified, using home directory> {}", dir),
 224                    None => "<none specified, could not find home directory>".to_string(),
 225                }
 226            })
 227    }
 228
 229    pub fn shell_to_string(&self) -> String {
 230        match &self.shell {
 231            Shell::System => "<system shell>".to_string(),
 232            Shell::Program(p) => p.to_string(),
 233            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 234        }
 235    }
 236
 237    pub fn fmt_shell(&self) -> String {
 238        match &self.shell {
 239            Shell::System => "<system defined shell>".to_string(),
 240            Shell::Program(s) => s.to_string(),
 241            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 242        }
 243    }
 244}
 245
 246impl Display for TerminalError {
 247    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 248        let dir_string: String = self.fmt_directory();
 249        let shell = self.fmt_shell();
 250
 251        write!(
 252            f,
 253            "Working directory: {} Shell command: `{}`, IOError: {}",
 254            dir_string, shell, self.source
 255        )
 256    }
 257}
 258
 259pub struct TerminalBuilder {
 260    terminal: Terminal,
 261    events_rx: UnboundedReceiver<AlacTermEvent>,
 262}
 263
 264impl TerminalBuilder {
 265    pub fn new(
 266        working_directory: Option<PathBuf>,
 267        shell: Shell,
 268        mut env: HashMap<String, String>,
 269        blink_settings: Option<TerminalBlink>,
 270        alternate_scroll: AlternateScroll,
 271        window_id: usize,
 272    ) -> Result<TerminalBuilder> {
 273        let pty_config = {
 274            let alac_shell = match shell.clone() {
 275                Shell::System => None,
 276                Shell::Program(program) => Some(Program::Just(program)),
 277                Shell::WithArguments { program, args } => Some(Program::WithArgs { program, args }),
 278            };
 279
 280            PtyConfig {
 281                shell: alac_shell,
 282                working_directory: working_directory.clone(),
 283                hold: false,
 284            }
 285        };
 286
 287        //TODO: Properly set the current locale,
 288        env.insert("LC_ALL".to_string(), "en_US.UTF-8".to_string());
 289        env.insert("ZED_TERM".to_string(), true.to_string());
 290
 291        let alac_scrolling = Scrolling::default();
 292        // alac_scrolling.set_history((BACK_BUFFER_SIZE * 2) as u32);
 293
 294        let config = Config {
 295            pty_config: pty_config.clone(),
 296            env,
 297            scrolling: alac_scrolling,
 298            ..Default::default()
 299        };
 300
 301        setup_env(&config);
 302
 303        //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
 304        //TODO: Remove with a bounded sender which can be dispatched on &self
 305        let (events_tx, events_rx) = unbounded();
 306        //Set up the terminal...
 307        let mut term = Term::new(
 308            &config,
 309            &TerminalSize::default(),
 310            ZedListener(events_tx.clone()),
 311        );
 312
 313        //Start off blinking if we need to
 314        if let Some(TerminalBlink::On) = blink_settings {
 315            term.set_mode(alacritty_terminal::ansi::Mode::BlinkingCursor)
 316        }
 317
 318        //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
 319        if let AlternateScroll::Off = alternate_scroll {
 320            term.unset_mode(alacritty_terminal::ansi::Mode::AlternateScroll)
 321        }
 322
 323        let term = Arc::new(FairMutex::new(term));
 324
 325        //Setup the pty...
 326        let pty = match tty::new(
 327            &pty_config,
 328            TerminalSize::default().into(),
 329            window_id as u64,
 330        ) {
 331            Ok(pty) => pty,
 332            Err(error) => {
 333                bail!(TerminalError {
 334                    directory: working_directory,
 335                    shell,
 336                    source: error,
 337                });
 338            }
 339        };
 340
 341        let fd = pty.file().as_raw_fd();
 342        let shell_pid = pty.child().id();
 343
 344        //And connect them together
 345        let event_loop = EventLoop::new(
 346            term.clone(),
 347            ZedListener(events_tx.clone()),
 348            pty,
 349            pty_config.hold,
 350            false,
 351        );
 352
 353        //Kick things off
 354        let pty_tx = event_loop.channel();
 355        let _io_thread = event_loop.spawn();
 356
 357        let terminal = Terminal {
 358            pty_tx: Notifier(pty_tx),
 359            term,
 360            events: VecDeque::with_capacity(10), //Should never get this high.
 361            last_content: Default::default(),
 362            last_mouse: None,
 363            matches: Vec::new(),
 364            last_synced: Instant::now(),
 365            sync_task: None,
 366            selection_head: None,
 367            shell_fd: fd as u32,
 368            shell_pid,
 369            foreground_process_info: None,
 370            breadcrumb_text: String::new(),
 371            scroll_px: 0.,
 372            last_mouse_position: None,
 373            next_link_id: 0,
 374            selection_phase: SelectionPhase::Ended,
 375        };
 376
 377        Ok(TerminalBuilder {
 378            terminal,
 379            events_rx,
 380        })
 381    }
 382
 383    pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
 384        //Event loop
 385        cx.spawn_weak(|this, mut cx| async move {
 386            use futures::StreamExt;
 387
 388            while let Some(event) = self.events_rx.next().await {
 389                this.upgrade(&cx)?.update(&mut cx, |this, cx| {
 390                    //Process the first event immediately for lowered latency
 391                    this.process_event(&event, cx);
 392                });
 393
 394                'outer: loop {
 395                    let mut events = vec![];
 396                    let mut timer = cx.background().timer(Duration::from_millis(4)).fuse();
 397                    let mut wakeup = false;
 398                    loop {
 399                        futures::select_biased! {
 400                            _ = timer => break,
 401                            event = self.events_rx.next() => {
 402                                if let Some(event) = event {
 403                                    if matches!(event, AlacTermEvent::Wakeup) {
 404                                        wakeup = true;
 405                                    } else {
 406                                        events.push(event);
 407                                    }
 408
 409                                    if events.len() > 100 {
 410                                        break;
 411                                    }
 412                                } else {
 413                                    break;
 414                                }
 415                            },
 416                        }
 417                    }
 418
 419                    if events.is_empty() && wakeup == false {
 420                        smol::future::yield_now().await;
 421                        break 'outer;
 422                    } else {
 423                        this.upgrade(&cx)?.update(&mut cx, |this, cx| {
 424                            if wakeup {
 425                                this.process_event(&AlacTermEvent::Wakeup, cx);
 426                            }
 427
 428                            for event in events {
 429                                this.process_event(&event, cx);
 430                            }
 431                        });
 432                        smol::future::yield_now().await;
 433                    }
 434                }
 435            }
 436
 437            Some(())
 438        })
 439        .detach();
 440
 441        self.terminal
 442    }
 443}
 444
 445#[derive(Debug, Clone, Deserialize, Serialize)]
 446pub struct IndexedCell {
 447    pub point: Point,
 448    pub cell: Cell,
 449}
 450
 451impl Deref for IndexedCell {
 452    type Target = Cell;
 453
 454    #[inline]
 455    fn deref(&self) -> &Cell {
 456        &self.cell
 457    }
 458}
 459
 460// TODO: Un-pub
 461#[derive(Clone)]
 462pub struct TerminalContent {
 463    pub cells: Vec<IndexedCell>,
 464    pub mode: TermMode,
 465    pub display_offset: usize,
 466    pub selection_text: Option<String>,
 467    pub selection: Option<SelectionRange>,
 468    pub cursor: RenderableCursor,
 469    pub cursor_char: char,
 470    pub size: TerminalSize,
 471    pub last_hovered_hyperlink: Option<(String, RangeInclusive<Point>, usize)>,
 472}
 473
 474impl Default for TerminalContent {
 475    fn default() -> Self {
 476        TerminalContent {
 477            cells: Default::default(),
 478            mode: Default::default(),
 479            display_offset: Default::default(),
 480            selection_text: Default::default(),
 481            selection: Default::default(),
 482            cursor: RenderableCursor {
 483                shape: alacritty_terminal::ansi::CursorShape::Block,
 484                point: Point::new(Line(0), Column(0)),
 485            },
 486            cursor_char: Default::default(),
 487            size: Default::default(),
 488            last_hovered_hyperlink: None,
 489        }
 490    }
 491}
 492
 493#[derive(PartialEq, Eq)]
 494pub enum SelectionPhase {
 495    Selecting,
 496    Ended,
 497}
 498
 499pub struct Terminal {
 500    pty_tx: Notifier,
 501    term: Arc<FairMutex<Term<ZedListener>>>,
 502    events: VecDeque<InternalEvent>,
 503    /// This is only used for mouse mode cell change detection
 504    last_mouse: Option<(Point, AlacDirection)>,
 505    /// This is only used for terminal hyperlink checking
 506    last_mouse_position: Option<Vector2F>,
 507    pub matches: Vec<RangeInclusive<Point>>,
 508    pub last_content: TerminalContent,
 509    last_synced: Instant,
 510    sync_task: Option<Task<()>>,
 511    pub selection_head: Option<Point>,
 512    pub breadcrumb_text: String,
 513    shell_pid: u32,
 514    shell_fd: u32,
 515    pub foreground_process_info: Option<LocalProcessInfo>,
 516    scroll_px: f32,
 517    next_link_id: usize,
 518    selection_phase: SelectionPhase,
 519}
 520
 521impl Terminal {
 522    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
 523        match event {
 524            AlacTermEvent::Title(title) => {
 525                self.breadcrumb_text = title.to_string();
 526                cx.emit(Event::BreadcrumbsChanged);
 527            }
 528            AlacTermEvent::ResetTitle => {
 529                self.breadcrumb_text = String::new();
 530                cx.emit(Event::BreadcrumbsChanged);
 531            }
 532            AlacTermEvent::ClipboardStore(_, data) => {
 533                cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
 534            }
 535            AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
 536                &cx.read_from_clipboard()
 537                    .map(|ci| ci.text().to_string())
 538                    .unwrap_or_else(|| "".to_string()),
 539            )),
 540            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 541            AlacTermEvent::TextAreaSizeRequest(format) => {
 542                self.write_to_pty(format(self.last_content.size.into()))
 543            }
 544            AlacTermEvent::CursorBlinkingChange => {
 545                cx.emit(Event::BlinkChanged);
 546            }
 547            AlacTermEvent::Bell => {
 548                cx.emit(Event::Bell);
 549            }
 550            AlacTermEvent::Exit => cx.emit(Event::CloseTerminal),
 551            AlacTermEvent::MouseCursorDirty => {
 552                //NOOP, Handled in render
 553            }
 554            AlacTermEvent::Wakeup => {
 555                cx.emit(Event::Wakeup);
 556
 557                if self.update_process_info() {
 558                    cx.emit(Event::TitleChanged);
 559                }
 560            }
 561            AlacTermEvent::ColorRequest(idx, fun_ptr) => {
 562                self.events
 563                    .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
 564            }
 565        }
 566    }
 567
 568    /// Update the cached process info, returns whether the Zed-relevant info has changed
 569    fn update_process_info(&mut self) -> bool {
 570        let mut pid = unsafe { libc::tcgetpgrp(self.shell_fd as i32) };
 571        if pid < 0 {
 572            pid = self.shell_pid as i32;
 573        }
 574
 575        if let Some(process_info) = LocalProcessInfo::with_root_pid(pid as u32) {
 576            let res = self
 577                .foreground_process_info
 578                .as_ref()
 579                .map(|old_info| {
 580                    process_info.cwd != old_info.cwd || process_info.name != old_info.name
 581                })
 582                .unwrap_or(true);
 583
 584            self.foreground_process_info = Some(process_info.clone());
 585
 586            res
 587        } else {
 588            false
 589        }
 590    }
 591
 592    ///Takes events from Alacritty and translates them to behavior on this view
 593    fn process_terminal_event(
 594        &mut self,
 595        event: &InternalEvent,
 596        term: &mut Term<ZedListener>,
 597        cx: &mut ModelContext<Self>,
 598    ) {
 599        match event {
 600            InternalEvent::ColorRequest(index, format) => {
 601                let color = term.colors()[*index].unwrap_or_else(|| {
 602                    let term_style = &cx.global::<Settings>().theme.terminal;
 603                    to_alac_rgb(get_color_at_index(index, &term_style))
 604                });
 605                self.write_to_pty(format(color))
 606            }
 607            InternalEvent::Resize(mut new_size) => {
 608                new_size.height = f32::max(new_size.line_height, new_size.height);
 609                new_size.width = f32::max(new_size.cell_width, new_size.width);
 610
 611                self.last_content.size = new_size.clone();
 612
 613                self.pty_tx.0.send(Msg::Resize((new_size).into())).ok();
 614
 615                term.resize(new_size);
 616            }
 617            InternalEvent::Clear => {
 618                // Clear back buffer
 619                term.clear_screen(ClearMode::Saved);
 620
 621                let cursor = term.grid().cursor.point;
 622
 623                // Clear the lines above
 624                term.grid_mut().reset_region(..cursor.line);
 625
 626                // Copy the current line up
 627                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 628                    .iter()
 629                    .cloned()
 630                    .enumerate()
 631                    .collect::<Vec<(usize, Cell)>>();
 632
 633                for (i, cell) in line {
 634                    term.grid_mut()[Line(0)][Column(i)] = cell;
 635                }
 636
 637                // Reset the cursor
 638                term.grid_mut().cursor.point =
 639                    Point::new(Line(0), term.grid_mut().cursor.point.column);
 640                let new_cursor = term.grid().cursor.point;
 641
 642                // Clear the lines below the new cursor
 643                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 644                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 645                }
 646
 647                cx.emit(Event::Wakeup);
 648            }
 649            InternalEvent::Scroll(scroll) => {
 650                term.scroll_display(*scroll);
 651                self.refresh_hyperlink();
 652            }
 653            InternalEvent::SetSelection(selection) => {
 654                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 655
 656                if let Some((_, head)) = selection {
 657                    self.selection_head = Some(*head);
 658                }
 659                cx.emit(Event::SelectionsChanged)
 660            }
 661            InternalEvent::UpdateSelection(position) => {
 662                if let Some(mut selection) = term.selection.take() {
 663                    let point = grid_point(
 664                        *position,
 665                        self.last_content.size,
 666                        term.grid().display_offset(),
 667                    );
 668
 669                    let side = mouse_side(*position, self.last_content.size);
 670
 671                    selection.update(point, side);
 672                    term.selection = Some(selection);
 673
 674                    self.selection_head = Some(point);
 675                    cx.emit(Event::SelectionsChanged)
 676                }
 677            }
 678
 679            InternalEvent::Copy => {
 680                if let Some(txt) = term.selection_to_string() {
 681                    cx.write_to_clipboard(ClipboardItem::new(txt))
 682                }
 683            }
 684            InternalEvent::ScrollToPoint(point) => {
 685                term.scroll_to_point(*point);
 686                self.refresh_hyperlink();
 687            }
 688            InternalEvent::FindHyperlink(position, open) => {
 689                let prev_hyperlink = self.last_content.last_hovered_hyperlink.take();
 690
 691                let point = grid_point(
 692                    *position,
 693                    self.last_content.size,
 694                    term.grid().display_offset(),
 695                )
 696                .grid_clamp(term, alacritty_terminal::index::Boundary::Cursor);
 697
 698                let link = term.grid().index(point).hyperlink();
 699                let found_url = if link.is_some() {
 700                    let mut min_index = point;
 701                    loop {
 702                        let new_min_index =
 703                            min_index.sub(term, alacritty_terminal::index::Boundary::Cursor, 1);
 704                        if new_min_index == min_index {
 705                            break;
 706                        } else if term.grid().index(new_min_index).hyperlink() != link {
 707                            break;
 708                        } else {
 709                            min_index = new_min_index
 710                        }
 711                    }
 712
 713                    let mut max_index = point;
 714                    loop {
 715                        let new_max_index =
 716                            max_index.add(term, alacritty_terminal::index::Boundary::Cursor, 1);
 717                        if new_max_index == max_index {
 718                            break;
 719                        } else if term.grid().index(new_max_index).hyperlink() != link {
 720                            break;
 721                        } else {
 722                            max_index = new_max_index
 723                        }
 724                    }
 725
 726                    let url = link.unwrap().uri().to_owned();
 727                    let url_match = min_index..=max_index;
 728
 729                    Some((url, url_match))
 730                } else if let Some(url_match) = regex_match_at(term, point, &URL_REGEX) {
 731                    let url = term.bounds_to_string(*url_match.start(), *url_match.end());
 732
 733                    Some((url, url_match))
 734                } else {
 735                    None
 736                };
 737
 738                if let Some((url, url_match)) = found_url {
 739                    if *open {
 740                        cx.platform().open_url(url.as_str());
 741                    } else {
 742                        self.update_hyperlink(prev_hyperlink, url, url_match);
 743                    }
 744                }
 745            }
 746        }
 747    }
 748
 749    fn update_hyperlink(
 750        &mut self,
 751        prev_hyperlink: Option<(String, RangeInclusive<Point>, usize)>,
 752        url: String,
 753        url_match: RangeInclusive<Point>,
 754    ) {
 755        if let Some(prev_hyperlink) = prev_hyperlink {
 756            if prev_hyperlink.0 == url && prev_hyperlink.1 == url_match {
 757                self.last_content.last_hovered_hyperlink = Some((url, url_match, prev_hyperlink.2));
 758            } else {
 759                self.last_content.last_hovered_hyperlink =
 760                    Some((url, url_match, self.next_link_id()));
 761            }
 762        } else {
 763            self.last_content.last_hovered_hyperlink = Some((url, url_match, self.next_link_id()));
 764        }
 765    }
 766
 767    fn next_link_id(&mut self) -> usize {
 768        let res = self.next_link_id;
 769        self.next_link_id = self.next_link_id.wrapping_add(1);
 770        res
 771    }
 772
 773    pub fn last_content(&self) -> &TerminalContent {
 774        &self.last_content
 775    }
 776
 777    //To test:
 778    //- Activate match on terminal (scrolling and selection)
 779    //- Editor search snapping behavior
 780
 781    pub fn activate_match(&mut self, index: usize) {
 782        if let Some(search_match) = self.matches.get(index).cloned() {
 783            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 784
 785            self.events
 786                .push_back(InternalEvent::ScrollToPoint(*search_match.start()));
 787        }
 788    }
 789
 790    fn set_selection(&mut self, selection: Option<(Selection, Point)>) {
 791        self.events
 792            .push_back(InternalEvent::SetSelection(selection));
 793    }
 794
 795    pub fn copy(&mut self) {
 796        self.events.push_back(InternalEvent::Copy);
 797    }
 798
 799    pub fn clear(&mut self) {
 800        self.events.push_back(InternalEvent::Clear)
 801    }
 802
 803    ///Resize the terminal and the PTY.
 804    pub fn set_size(&mut self, new_size: TerminalSize) {
 805        self.events.push_back(InternalEvent::Resize(new_size))
 806    }
 807
 808    ///Write the Input payload to the tty.
 809    fn write_to_pty(&self, input: String) {
 810        self.pty_tx.notify(input.into_bytes());
 811    }
 812
 813    pub fn input(&mut self, input: String) {
 814        self.events
 815            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
 816        self.events.push_back(InternalEvent::SetSelection(None));
 817
 818        self.write_to_pty(input);
 819    }
 820
 821    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
 822        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
 823        if let Some(esc) = esc {
 824            self.input(esc);
 825            true
 826        } else {
 827            false
 828        }
 829    }
 830
 831    ///Paste text into the terminal
 832    pub fn paste(&mut self, text: &str) {
 833        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
 834            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
 835        } else {
 836            text.replace("\r\n", "\r").replace('\n', "\r")
 837        };
 838
 839        self.input(paste_text);
 840    }
 841
 842    pub fn try_sync(&mut self, cx: &mut ModelContext<Self>) {
 843        let term = self.term.clone();
 844
 845        let mut terminal = if let Some(term) = term.try_lock_unfair() {
 846            term
 847        } else if self.last_synced.elapsed().as_secs_f32() > 0.25 {
 848            term.lock_unfair() //It's been too long, force block
 849        } else if let None = self.sync_task {
 850            //Skip this frame
 851            let delay = cx.background().timer(Duration::from_millis(16));
 852            self.sync_task = Some(cx.spawn_weak(|weak_handle, mut cx| async move {
 853                delay.await;
 854                cx.update(|cx| {
 855                    if let Some(handle) = weak_handle.upgrade(cx) {
 856                        handle.update(cx, |terminal, cx| {
 857                            terminal.sync_task.take();
 858                            cx.notify();
 859                        });
 860                    }
 861                });
 862            }));
 863            return;
 864        } else {
 865            //No lock and delayed rendering already scheduled, nothing to do
 866            return;
 867        };
 868
 869        //Note that the ordering of events matters for event processing
 870        while let Some(e) = self.events.pop_front() {
 871            self.process_terminal_event(&e, &mut terminal, cx)
 872        }
 873
 874        self.last_content = Self::make_content(&terminal, &self.last_content);
 875        self.last_synced = Instant::now();
 876    }
 877
 878    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
 879        let content = term.renderable_content();
 880        TerminalContent {
 881            cells: content
 882                .display_iter
 883                //TODO: Add this once there's a way to retain empty lines
 884                // .filter(|ic| {
 885                //     !ic.flags.contains(Flags::HIDDEN)
 886                //         && !(ic.bg == Named(NamedColor::Background)
 887                //             && ic.c == ' '
 888                //             && !ic.flags.contains(Flags::INVERSE))
 889                // })
 890                .map(|ic| IndexedCell {
 891                    point: ic.point,
 892                    cell: ic.cell.clone(),
 893                })
 894                .collect::<Vec<IndexedCell>>(),
 895            mode: content.mode,
 896            display_offset: content.display_offset,
 897            selection_text: term.selection_to_string(),
 898            selection: content.selection,
 899            cursor: content.cursor,
 900            cursor_char: term.grid()[content.cursor.point].c,
 901            size: last_content.size,
 902            last_hovered_hyperlink: last_content.last_hovered_hyperlink.clone(),
 903        }
 904    }
 905
 906    pub fn focus_in(&self) {
 907        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
 908            self.write_to_pty("\x1b[I".to_string());
 909        }
 910    }
 911
 912    pub fn focus_out(&mut self) {
 913        self.last_mouse_position = None;
 914        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
 915            self.write_to_pty("\x1b[O".to_string());
 916        }
 917    }
 918
 919    pub fn mouse_changed(&mut self, point: Point, side: AlacDirection) -> bool {
 920        match self.last_mouse {
 921            Some((old_point, old_side)) => {
 922                if old_point == point && old_side == side {
 923                    false
 924                } else {
 925                    self.last_mouse = Some((point, side));
 926                    true
 927                }
 928            }
 929            None => {
 930                self.last_mouse = Some((point, side));
 931                true
 932            }
 933        }
 934    }
 935
 936    pub fn mouse_mode(&self, shift: bool) -> bool {
 937        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
 938    }
 939
 940    pub fn mouse_move(&mut self, e: &MouseMovedEvent, origin: Vector2F) {
 941        let position = e.position.sub(origin);
 942        self.last_mouse_position = Some(position);
 943        if self.mouse_mode(e.shift) {
 944            let point = grid_point(
 945                position,
 946                self.last_content.size,
 947                self.last_content.display_offset,
 948            );
 949            let side = mouse_side(position, self.last_content.size);
 950
 951            if self.mouse_changed(point, side) {
 952                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
 953                    self.pty_tx.notify(bytes);
 954                }
 955            }
 956        } else {
 957            self.hyperlink_from_position(Some(position));
 958        }
 959    }
 960
 961    fn hyperlink_from_position(&mut self, position: Option<Vector2F>) {
 962        if self.selection_phase == SelectionPhase::Selecting {
 963            self.last_content.last_hovered_hyperlink = None;
 964        } else if let Some(position) = position {
 965            self.events
 966                .push_back(InternalEvent::FindHyperlink(position, false));
 967        }
 968    }
 969
 970    pub fn mouse_drag(&mut self, e: MouseDrag, origin: Vector2F) {
 971        let position = e.position.sub(origin);
 972        self.last_mouse_position = Some(position);
 973
 974        if !self.mouse_mode(e.shift) {
 975            self.selection_phase = SelectionPhase::Selecting;
 976            // Alacritty has the same ordering, of first updating the selection
 977            // then scrolling 15ms later
 978            self.events
 979                .push_back(InternalEvent::UpdateSelection(position));
 980
 981            // Doesn't make sense to scroll the alt screen
 982            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
 983                let scroll_delta = match self.drag_line_delta(e) {
 984                    Some(value) => value,
 985                    None => return,
 986                };
 987
 988                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
 989
 990                self.events
 991                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
 992            }
 993        }
 994    }
 995
 996    fn drag_line_delta(&mut self, e: MouseDrag) -> Option<f32> {
 997        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
 998        let top = e.region.origin_y() + (self.last_content.size.line_height * 2.);
 999        let bottom = e.region.lower_left().y() - (self.last_content.size.line_height * 2.);
1000        let scroll_delta = if e.position.y() < top {
1001            (top - e.position.y()).powf(1.1)
1002        } else if e.position.y() > bottom {
1003            -((e.position.y() - bottom).powf(1.1))
1004        } else {
1005            return None; //Nothing to do
1006        };
1007        Some(scroll_delta)
1008    }
1009
1010    pub fn mouse_down(&mut self, e: &MouseDown, origin: Vector2F) {
1011        let position = e.position.sub(origin);
1012        let point = grid_point(
1013            position,
1014            self.last_content.size,
1015            self.last_content.display_offset,
1016        );
1017
1018        if self.mouse_mode(e.shift) {
1019            if let Some(bytes) = mouse_button_report(point, e, true, self.last_content.mode) {
1020                self.pty_tx.notify(bytes);
1021            }
1022        } else if e.button == MouseButton::Left {
1023            let position = e.position.sub(origin);
1024            let point = grid_point(
1025                position,
1026                self.last_content.size,
1027                self.last_content.display_offset,
1028            );
1029
1030            // Use .opposite so that selection is inclusive of the cell clicked.
1031            let side = mouse_side(position, self.last_content.size);
1032
1033            let selection_type = match e.click_count {
1034                0 => return, //This is a release
1035                1 => Some(SelectionType::Simple),
1036                2 => Some(SelectionType::Semantic),
1037                3 => Some(SelectionType::Lines),
1038                _ => None,
1039            };
1040
1041            let selection =
1042                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1043
1044            if let Some(sel) = selection {
1045                self.events
1046                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
1047            }
1048        }
1049    }
1050
1051    pub fn mouse_up(&mut self, e: &MouseUp, origin: Vector2F, cx: &mut ModelContext<Self>) {
1052        let settings = cx.global::<Settings>();
1053        let copy_on_select = settings
1054            .terminal_overrides
1055            .copy_on_select
1056            .unwrap_or_else(|| {
1057                settings
1058                    .terminal_defaults
1059                    .copy_on_select
1060                    .expect("Should be set in defaults")
1061            });
1062
1063        let position = e.position.sub(origin);
1064        if self.mouse_mode(e.shift) {
1065            let point = grid_point(
1066                position,
1067                self.last_content.size,
1068                self.last_content.display_offset,
1069            );
1070
1071            if let Some(bytes) = mouse_button_report(point, e, false, self.last_content.mode) {
1072                self.pty_tx.notify(bytes);
1073            }
1074        } else {
1075            if e.button == MouseButton::Left && copy_on_select {
1076                self.copy();
1077            }
1078
1079            //Hyperlinks
1080            if self.selection_phase == SelectionPhase::Ended {
1081                let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1082                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1083                    cx.platform().open_url(link.uri());
1084                } else {
1085                    self.events
1086                        .push_back(InternalEvent::FindHyperlink(position, true));
1087                }
1088            }
1089        }
1090
1091        self.selection_phase = SelectionPhase::Ended;
1092        self.last_mouse = None;
1093    }
1094
1095    ///Scroll the terminal
1096    pub fn scroll_wheel(&mut self, e: MouseScrollWheel, origin: Vector2F) {
1097        let mouse_mode = self.mouse_mode(e.shift);
1098
1099        if let Some(scroll_lines) = self.determine_scroll_lines(&e, mouse_mode) {
1100            if mouse_mode {
1101                let point = grid_point(
1102                    e.position.sub(origin),
1103                    self.last_content.size,
1104                    self.last_content.display_offset,
1105                );
1106
1107                if let Some(scrolls) =
1108                    scroll_report(point, scroll_lines as i32, &e, self.last_content.mode)
1109                {
1110                    for scroll in scrolls {
1111                        self.pty_tx.notify(scroll);
1112                    }
1113                };
1114            } else if self
1115                .last_content
1116                .mode
1117                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1118                && !e.shift
1119            {
1120                self.pty_tx.notify(alt_scroll(scroll_lines))
1121            } else {
1122                if scroll_lines != 0 {
1123                    let scroll = AlacScroll::Delta(scroll_lines);
1124
1125                    self.events.push_back(InternalEvent::Scroll(scroll));
1126                }
1127            }
1128        }
1129    }
1130
1131    pub fn refresh_hyperlink(&mut self) {
1132        self.hyperlink_from_position(self.last_mouse_position);
1133    }
1134
1135    fn determine_scroll_lines(&mut self, e: &MouseScrollWheel, mouse_mode: bool) -> Option<i32> {
1136        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1137        let line_height = self.last_content.size.line_height;
1138        match e.phase {
1139            /* Reset scroll state on started */
1140            Some(TouchPhase::Started) => {
1141                self.scroll_px = 0.;
1142                None
1143            }
1144            /* Calculate the appropriate scroll lines */
1145            Some(gpui::platform::TouchPhase::Moved) => {
1146                let old_offset = (self.scroll_px / line_height) as i32;
1147
1148                self.scroll_px += e.delta.pixel_delta(line_height).y() * scroll_multiplier;
1149
1150                let new_offset = (self.scroll_px / line_height) as i32;
1151
1152                // Whenever we hit the edges, reset our stored scroll to 0
1153                // so we can respond to changes in direction quickly
1154                self.scroll_px %= self.last_content.size.height;
1155
1156                Some(new_offset - old_offset)
1157            }
1158            /* Fall back to delta / line_height */
1159            None => Some(
1160                ((e.delta.pixel_delta(line_height).y() * scroll_multiplier) / line_height) as i32,
1161            ),
1162            _ => None,
1163        }
1164    }
1165
1166    pub fn find_matches(
1167        &mut self,
1168        searcher: RegexSearch,
1169        cx: &mut ModelContext<Self>,
1170    ) -> Task<Vec<RangeInclusive<Point>>> {
1171        let term = self.term.clone();
1172        cx.background().spawn(async move {
1173            let term = term.lock();
1174
1175            all_search_matches(&term, &searcher).collect()
1176        })
1177    }
1178
1179    pub fn title(&self) -> String {
1180        self.foreground_process_info
1181            .as_ref()
1182            .map(|fpi| {
1183                format!(
1184                    "{}{}",
1185                    truncate_and_trailoff(
1186                        &fpi.cwd
1187                            .file_name()
1188                            .map(|name| name.to_string_lossy().to_string())
1189                            .unwrap_or_default(),
1190                        25
1191                    ),
1192                    truncate_and_trailoff(
1193                        &{
1194                            format!(
1195                                "{}{}",
1196                                fpi.name,
1197                                if fpi.argv.len() >= 1 {
1198                                    format!(" {}", (&fpi.argv[1..]).join(" "))
1199                                } else {
1200                                    "".to_string()
1201                                }
1202                            )
1203                        },
1204                        25
1205                    )
1206                )
1207            })
1208            .unwrap_or_else(|| "Terminal".to_string())
1209    }
1210}
1211
1212impl Drop for Terminal {
1213    fn drop(&mut self) {
1214        self.pty_tx.0.send(Msg::Shutdown).ok();
1215    }
1216}
1217
1218impl Entity for Terminal {
1219    type Event = Event;
1220}
1221
1222/// Based on alacritty/src/display/hint.rs > regex_match_at
1223/// Retrieve the match, if the specified point is inside the content matching the regex.
1224fn regex_match_at<T>(term: &Term<T>, point: Point, regex: &RegexSearch) -> Option<Match> {
1225    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1226}
1227
1228/// Copied from alacritty/src/display/hint.rs:
1229/// Iterate over all visible regex matches.
1230pub fn visible_regex_match_iter<'a, T>(
1231    term: &'a Term<T>,
1232    regex: &'a RegexSearch,
1233) -> impl Iterator<Item = Match> + 'a {
1234    let viewport_start = Line(-(term.grid().display_offset() as i32));
1235    let viewport_end = viewport_start + term.bottommost_line();
1236    let mut start = term.line_search_left(Point::new(viewport_start, Column(0)));
1237    let mut end = term.line_search_right(Point::new(viewport_end, Column(0)));
1238    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1239    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1240
1241    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1242        .skip_while(move |rm| rm.end().line < viewport_start)
1243        .take_while(move |rm| rm.start().line <= viewport_end)
1244}
1245
1246fn make_selection(range: &RangeInclusive<Point>) -> Selection {
1247    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1248    selection.update(*range.end(), AlacDirection::Right);
1249    selection
1250}
1251
1252fn all_search_matches<'a, T>(
1253    term: &'a Term<T>,
1254    regex: &'a RegexSearch,
1255) -> impl Iterator<Item = Match> + 'a {
1256    let start = Point::new(term.grid().topmost_line(), Column(0));
1257    let end = Point::new(term.grid().bottommost_line(), term.grid().last_column());
1258    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1259}
1260
1261fn content_index_for_mouse(pos: Vector2F, size: &TerminalSize) -> usize {
1262    let col = (pos.x() / size.cell_width()).round() as usize;
1263
1264    let clamped_col = min(col, size.columns() - 1);
1265
1266    let row = (pos.y() / size.line_height()).round() as usize;
1267
1268    let clamped_row = min(row, size.screen_lines() - 1);
1269
1270    clamped_row * size.columns() + clamped_col
1271}
1272
1273#[cfg(test)]
1274mod tests {
1275    use alacritty_terminal::{
1276        index::{Column, Line, Point},
1277        term::cell::Cell,
1278    };
1279    use gpui::geometry::vector::vec2f;
1280    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1281
1282    use crate::{content_index_for_mouse, IndexedCell, TerminalContent, TerminalSize};
1283
1284    #[test]
1285    fn test_mouse_to_cell_test() {
1286        let mut rng = thread_rng();
1287        const ITERATIONS: usize = 10;
1288        const PRECISION: usize = 1000;
1289
1290        for _ in 0..ITERATIONS {
1291            let viewport_cells = rng.gen_range(15..20);
1292            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1293
1294            let size = crate::TerminalSize {
1295                cell_width: cell_size,
1296                line_height: cell_size,
1297                height: cell_size * (viewport_cells as f32),
1298                width: cell_size * (viewport_cells as f32),
1299            };
1300
1301            let cells = get_cells(size, &mut rng);
1302            let content = convert_cells_to_content(size, &cells);
1303
1304            for row in 0..(viewport_cells - 1) {
1305                let row = row as usize;
1306                for col in 0..(viewport_cells - 1) {
1307                    let col = col as usize;
1308
1309                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1310                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1311
1312                    let mouse_pos = vec2f(
1313                        col as f32 * cell_size + col_offset,
1314                        row as f32 * cell_size + row_offset,
1315                    );
1316
1317                    let content_index = content_index_for_mouse(mouse_pos, &content.size);
1318                    let mouse_cell = content.cells[content_index].c;
1319                    let real_cell = cells[row][col];
1320
1321                    assert_eq!(mouse_cell, real_cell);
1322                }
1323            }
1324        }
1325    }
1326
1327    #[test]
1328    fn test_mouse_to_cell_clamp() {
1329        let mut rng = thread_rng();
1330
1331        let size = crate::TerminalSize {
1332            cell_width: 10.,
1333            line_height: 10.,
1334            height: 100.,
1335            width: 100.,
1336        };
1337
1338        let cells = get_cells(size, &mut rng);
1339        let content = convert_cells_to_content(size, &cells);
1340
1341        assert_eq!(
1342            content.cells[content_index_for_mouse(vec2f(-10., -10.), &content.size)].c,
1343            cells[0][0]
1344        );
1345        assert_eq!(
1346            content.cells[content_index_for_mouse(vec2f(1000., 1000.), &content.size)].c,
1347            cells[9][9]
1348        );
1349    }
1350
1351    fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1352        let mut cells = Vec::new();
1353
1354        for _ in 0..((size.height() / size.line_height()) as usize) {
1355            let mut row_vec = Vec::new();
1356            for _ in 0..((size.width() / size.cell_width()) as usize) {
1357                let cell_char = rng.sample(Alphanumeric) as char;
1358                row_vec.push(cell_char)
1359            }
1360            cells.push(row_vec)
1361        }
1362
1363        cells
1364    }
1365
1366    fn convert_cells_to_content(size: TerminalSize, cells: &Vec<Vec<char>>) -> TerminalContent {
1367        let mut ic = Vec::new();
1368
1369        for row in 0..cells.len() {
1370            for col in 0..cells[row].len() {
1371                let cell_char = cells[row][col];
1372                ic.push(IndexedCell {
1373                    point: Point::new(Line(row as i32), Column(col)),
1374                    cell: Cell {
1375                        c: cell_char,
1376                        ..Default::default()
1377                    },
1378                });
1379            }
1380        }
1381
1382        TerminalContent {
1383            cells: ic,
1384            size,
1385            ..Default::default()
1386        }
1387    }
1388}