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 settings::{AlternateScroll, Settings, Shell, TerminalBlink};
  35use util::ResultExt;
  36
  37use std::{
  38    cmp::min,
  39    collections::{HashMap, VecDeque},
  40    fmt::Display,
  41    io,
  42    ops::{Deref, Index, RangeInclusive, Sub},
  43    os::unix::{prelude::AsRawFd, process::CommandExt},
  44    path::PathBuf,
  45    process::Command,
  46    sync::Arc,
  47    time::{Duration, Instant},
  48};
  49use thiserror::Error;
  50
  51use gpui::{
  52    geometry::vector::{vec2f, Vector2F},
  53    keymap_matcher::Keystroke,
  54    scene::{MouseDown, MouseDrag, MouseScrollWheel, MouseUp},
  55    ClipboardItem, Entity, ModelContext, MouseButton, MouseMovedEvent, 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)]
 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)]
 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                    let side = mouse_side(*position, self.last_content.size);
 669
 670                    selection.update(point, side);
 671                    term.selection = Some(selection);
 672
 673                    self.selection_head = Some(point);
 674                    cx.emit(Event::SelectionsChanged)
 675                }
 676            }
 677
 678            InternalEvent::Copy => {
 679                if let Some(txt) = term.selection_to_string() {
 680                    cx.write_to_clipboard(ClipboardItem::new(txt))
 681                }
 682            }
 683            InternalEvent::ScrollToPoint(point) => {
 684                term.scroll_to_point(*point);
 685                self.refresh_hyperlink();
 686            }
 687            InternalEvent::FindHyperlink(position, open) => {
 688                let prev_hyperlink = self.last_content.last_hovered_hyperlink.take();
 689
 690                let point = grid_point(
 691                    *position,
 692                    self.last_content.size,
 693                    term.grid().display_offset(),
 694                )
 695                .grid_clamp(term, alacritty_terminal::index::Boundary::Cursor);
 696
 697                let link = term.grid().index(point).hyperlink();
 698                let found_url = if link.is_some() {
 699                    let mut min_index = point;
 700                    loop {
 701                        let new_min_index =
 702                            min_index.sub(term, alacritty_terminal::index::Boundary::Cursor, 1);
 703                        if new_min_index == min_index {
 704                            break;
 705                        } else if term.grid().index(new_min_index).hyperlink() != link {
 706                            break;
 707                        } else {
 708                            min_index = new_min_index
 709                        }
 710                    }
 711
 712                    let mut max_index = point;
 713                    loop {
 714                        let new_max_index =
 715                            max_index.add(term, alacritty_terminal::index::Boundary::Cursor, 1);
 716                        if new_max_index == max_index {
 717                            break;
 718                        } else if term.grid().index(new_max_index).hyperlink() != link {
 719                            break;
 720                        } else {
 721                            max_index = new_max_index
 722                        }
 723                    }
 724
 725                    let url = link.unwrap().uri().to_owned();
 726                    let url_match = min_index..=max_index;
 727
 728                    Some((url, url_match))
 729                } else if let Some(url_match) = regex_match_at(term, point, &URL_REGEX) {
 730                    let url = term.bounds_to_string(*url_match.start(), *url_match.end());
 731
 732                    Some((url, url_match))
 733                } else {
 734                    None
 735                };
 736
 737                if let Some((url, url_match)) = found_url {
 738                    if *open {
 739                        open_uri(&url).log_err();
 740                    } else {
 741                        self.update_hyperlink(prev_hyperlink, url, url_match);
 742                    }
 743                }
 744            }
 745        }
 746    }
 747
 748    fn update_hyperlink(
 749        &mut self,
 750        prev_hyperlink: Option<(String, RangeInclusive<Point>, usize)>,
 751        url: String,
 752        url_match: RangeInclusive<Point>,
 753    ) {
 754        if let Some(prev_hyperlink) = prev_hyperlink {
 755            if prev_hyperlink.0 == url && prev_hyperlink.1 == url_match {
 756                self.last_content.last_hovered_hyperlink = Some((url, url_match, prev_hyperlink.2));
 757            } else {
 758                self.last_content.last_hovered_hyperlink =
 759                    Some((url, url_match, self.next_link_id()));
 760            }
 761        } else {
 762            self.last_content.last_hovered_hyperlink = Some((url, url_match, self.next_link_id()));
 763        }
 764    }
 765
 766    fn next_link_id(&mut self) -> usize {
 767        let res = self.next_link_id;
 768        self.next_link_id = self.next_link_id.wrapping_add(1);
 769        res
 770    }
 771
 772    pub fn last_content(&self) -> &TerminalContent {
 773        &self.last_content
 774    }
 775
 776    //To test:
 777    //- Activate match on terminal (scrolling and selection)
 778    //- Editor search snapping behavior
 779
 780    pub fn activate_match(&mut self, index: usize) {
 781        if let Some(search_match) = self.matches.get(index).cloned() {
 782            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 783
 784            self.events
 785                .push_back(InternalEvent::ScrollToPoint(*search_match.start()));
 786        }
 787    }
 788
 789    fn set_selection(&mut self, selection: Option<(Selection, Point)>) {
 790        self.events
 791            .push_back(InternalEvent::SetSelection(selection));
 792    }
 793
 794    pub fn copy(&mut self) {
 795        self.events.push_back(InternalEvent::Copy);
 796    }
 797
 798    pub fn clear(&mut self) {
 799        self.events.push_back(InternalEvent::Clear)
 800    }
 801
 802    ///Resize the terminal and the PTY.
 803    pub fn set_size(&mut self, new_size: TerminalSize) {
 804        self.events.push_back(InternalEvent::Resize(new_size))
 805    }
 806
 807    ///Write the Input payload to the tty.
 808    fn write_to_pty(&self, input: String) {
 809        self.pty_tx.notify(input.into_bytes());
 810    }
 811
 812    pub fn input(&mut self, input: String) {
 813        self.events
 814            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
 815        self.events.push_back(InternalEvent::SetSelection(None));
 816
 817        self.write_to_pty(input);
 818    }
 819
 820    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
 821        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
 822        if let Some(esc) = esc {
 823            self.input(esc);
 824            true
 825        } else {
 826            false
 827        }
 828    }
 829
 830    ///Paste text into the terminal
 831    pub fn paste(&mut self, text: &str) {
 832        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
 833            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
 834        } else {
 835            text.replace("\r\n", "\r").replace('\n', "\r")
 836        };
 837
 838        self.input(paste_text);
 839    }
 840
 841    pub fn try_sync(&mut self, cx: &mut ModelContext<Self>) {
 842        let term = self.term.clone();
 843
 844        let mut terminal = if let Some(term) = term.try_lock_unfair() {
 845            term
 846        } else if self.last_synced.elapsed().as_secs_f32() > 0.25 {
 847            term.lock_unfair() //It's been too long, force block
 848        } else if let None = self.sync_task {
 849            //Skip this frame
 850            let delay = cx.background().timer(Duration::from_millis(16));
 851            self.sync_task = Some(cx.spawn_weak(|weak_handle, mut cx| async move {
 852                delay.await;
 853                cx.update(|cx| {
 854                    if let Some(handle) = weak_handle.upgrade(cx) {
 855                        handle.update(cx, |terminal, cx| {
 856                            terminal.sync_task.take();
 857                            cx.notify();
 858                        });
 859                    }
 860                });
 861            }));
 862            return;
 863        } else {
 864            //No lock and delayed rendering already scheduled, nothing to do
 865            return;
 866        };
 867
 868        //Note that the ordering of events matters for event processing
 869        while let Some(e) = self.events.pop_front() {
 870            self.process_terminal_event(&e, &mut terminal, cx)
 871        }
 872
 873        self.last_content = Self::make_content(&terminal, &self.last_content);
 874        self.last_synced = Instant::now();
 875    }
 876
 877    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
 878        let content = term.renderable_content();
 879        TerminalContent {
 880            cells: content
 881                .display_iter
 882                //TODO: Add this once there's a way to retain empty lines
 883                // .filter(|ic| {
 884                //     !ic.flags.contains(Flags::HIDDEN)
 885                //         && !(ic.bg == Named(NamedColor::Background)
 886                //             && ic.c == ' '
 887                //             && !ic.flags.contains(Flags::INVERSE))
 888                // })
 889                .map(|ic| IndexedCell {
 890                    point: ic.point,
 891                    cell: ic.cell.clone(),
 892                })
 893                .collect::<Vec<IndexedCell>>(),
 894            mode: content.mode,
 895            display_offset: content.display_offset,
 896            selection_text: term.selection_to_string(),
 897            selection: content.selection,
 898            cursor: content.cursor,
 899            cursor_char: term.grid()[content.cursor.point].c,
 900            size: last_content.size,
 901            last_hovered_hyperlink: last_content.last_hovered_hyperlink.clone(),
 902        }
 903    }
 904
 905    pub fn focus_in(&self) {
 906        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
 907            self.write_to_pty("\x1b[I".to_string());
 908        }
 909    }
 910
 911    pub fn focus_out(&mut self) {
 912        self.last_mouse_position = None;
 913        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
 914            self.write_to_pty("\x1b[O".to_string());
 915        }
 916    }
 917
 918    pub fn mouse_changed(&mut self, point: Point, side: AlacDirection) -> bool {
 919        match self.last_mouse {
 920            Some((old_point, old_side)) => {
 921                if old_point == point && old_side == side {
 922                    false
 923                } else {
 924                    self.last_mouse = Some((point, side));
 925                    true
 926                }
 927            }
 928            None => {
 929                self.last_mouse = Some((point, side));
 930                true
 931            }
 932        }
 933    }
 934
 935    pub fn mouse_mode(&self, shift: bool) -> bool {
 936        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
 937    }
 938
 939    pub fn mouse_move(&mut self, e: &MouseMovedEvent, origin: Vector2F) {
 940        let position = e.position.sub(origin);
 941        self.last_mouse_position = Some(position);
 942        if self.mouse_mode(e.shift) {
 943            let point = grid_point(
 944                position,
 945                self.last_content.size,
 946                self.last_content.display_offset,
 947            );
 948            let side = mouse_side(position, self.last_content.size);
 949
 950            if self.mouse_changed(point, side) {
 951                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
 952                    self.pty_tx.notify(bytes);
 953                }
 954            }
 955        } else {
 956            self.hyperlink_from_position(Some(position));
 957        }
 958    }
 959
 960    fn hyperlink_from_position(&mut self, position: Option<Vector2F>) {
 961        if self.selection_phase == SelectionPhase::Selecting {
 962            self.last_content.last_hovered_hyperlink = None;
 963        } else if let Some(position) = position {
 964            self.events
 965                .push_back(InternalEvent::FindHyperlink(position, false));
 966        }
 967    }
 968
 969    pub fn mouse_drag(&mut self, e: MouseDrag, origin: Vector2F) {
 970        let position = e.position.sub(origin);
 971        self.last_mouse_position = Some(position);
 972
 973        if !self.mouse_mode(e.shift) {
 974            self.selection_phase = SelectionPhase::Selecting;
 975            // Alacritty has the same ordering, of first updating the selection
 976            // then scrolling 15ms later
 977            self.events
 978                .push_back(InternalEvent::UpdateSelection(position));
 979
 980            // Doesn't make sense to scroll the alt screen
 981            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
 982                let scroll_delta = match self.drag_line_delta(e) {
 983                    Some(value) => value,
 984                    None => return,
 985                };
 986
 987                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
 988
 989                self.events
 990                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
 991            }
 992        }
 993    }
 994
 995    fn drag_line_delta(&mut self, e: MouseDrag) -> Option<f32> {
 996        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
 997        let top = e.region.origin_y() + (self.last_content.size.line_height * 2.);
 998        let bottom = e.region.lower_left().y() - (self.last_content.size.line_height * 2.);
 999        let scroll_delta = if e.position.y() < top {
1000            (top - e.position.y()).powf(1.1)
1001        } else if e.position.y() > bottom {
1002            -((e.position.y() - bottom).powf(1.1))
1003        } else {
1004            return None; //Nothing to do
1005        };
1006        Some(scroll_delta)
1007    }
1008
1009    pub fn mouse_down(&mut self, e: &MouseDown, origin: Vector2F) {
1010        let position = e.position.sub(origin);
1011        let point = grid_point(
1012            position,
1013            self.last_content.size,
1014            self.last_content.display_offset,
1015        );
1016
1017        if self.mouse_mode(e.shift) {
1018            if let Some(bytes) = mouse_button_report(point, e, true, self.last_content.mode) {
1019                self.pty_tx.notify(bytes);
1020            }
1021        } else if e.button == MouseButton::Left {
1022            let position = e.position.sub(origin);
1023            let point = grid_point(
1024                position,
1025                self.last_content.size,
1026                self.last_content.display_offset,
1027            );
1028            let side = mouse_side(position, self.last_content.size);
1029
1030            let selection_type = match e.click_count {
1031                0 => return, //This is a release
1032                1 => Some(SelectionType::Simple),
1033                2 => Some(SelectionType::Semantic),
1034                3 => Some(SelectionType::Lines),
1035                _ => None,
1036            };
1037
1038            let selection =
1039                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1040
1041            if let Some(sel) = selection {
1042                self.events
1043                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
1044            }
1045        }
1046    }
1047
1048    pub fn mouse_up(&mut self, e: &MouseUp, origin: Vector2F, cx: &mut ModelContext<Self>) {
1049        let settings = cx.global::<Settings>();
1050        let copy_on_select = settings
1051            .terminal_overrides
1052            .copy_on_select
1053            .unwrap_or_else(|| {
1054                settings
1055                    .terminal_defaults
1056                    .copy_on_select
1057                    .expect("Should be set in defaults")
1058            });
1059
1060        let position = e.position.sub(origin);
1061        if self.mouse_mode(e.shift) {
1062            let point = grid_point(
1063                position,
1064                self.last_content.size,
1065                self.last_content.display_offset,
1066            );
1067
1068            if let Some(bytes) = mouse_button_report(point, e, false, self.last_content.mode) {
1069                self.pty_tx.notify(bytes);
1070            }
1071        } else {
1072            if e.button == MouseButton::Left && copy_on_select {
1073                self.copy();
1074            }
1075
1076            //Hyperlinks
1077            if self.selection_phase == SelectionPhase::Ended {
1078                let mouse_cell_index = content_index_for_mouse(position, &self.last_content);
1079                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1080                    open_uri(link.uri()).log_err();
1081                } else {
1082                    self.events
1083                        .push_back(InternalEvent::FindHyperlink(position, true));
1084                }
1085            }
1086        }
1087
1088        self.selection_phase = SelectionPhase::Ended;
1089        self.last_mouse = None;
1090    }
1091
1092    ///Scroll the terminal
1093    pub fn scroll_wheel(&mut self, e: MouseScrollWheel, origin: Vector2F) {
1094        let mouse_mode = self.mouse_mode(e.shift);
1095
1096        if let Some(scroll_lines) = self.determine_scroll_lines(&e, mouse_mode) {
1097            if mouse_mode {
1098                let point = grid_point(
1099                    e.position.sub(origin),
1100                    self.last_content.size,
1101                    self.last_content.display_offset,
1102                );
1103
1104                if let Some(scrolls) =
1105                    scroll_report(point, scroll_lines as i32, &e, self.last_content.mode)
1106                {
1107                    for scroll in scrolls {
1108                        self.pty_tx.notify(scroll);
1109                    }
1110                };
1111            } else if self
1112                .last_content
1113                .mode
1114                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1115                && !e.shift
1116            {
1117                self.pty_tx.notify(alt_scroll(scroll_lines))
1118            } else {
1119                if scroll_lines != 0 {
1120                    let scroll = AlacScroll::Delta(scroll_lines);
1121
1122                    self.events.push_back(InternalEvent::Scroll(scroll));
1123                }
1124            }
1125        }
1126    }
1127
1128    pub fn refresh_hyperlink(&mut self) {
1129        self.hyperlink_from_position(self.last_mouse_position);
1130    }
1131
1132    fn determine_scroll_lines(&mut self, e: &MouseScrollWheel, mouse_mode: bool) -> Option<i32> {
1133        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1134        let line_height = self.last_content.size.line_height;
1135        match e.phase {
1136            /* Reset scroll state on started */
1137            Some(gpui::TouchPhase::Started) => {
1138                self.scroll_px = 0.;
1139                None
1140            }
1141            /* Calculate the appropriate scroll lines */
1142            Some(gpui::TouchPhase::Moved) => {
1143                let old_offset = (self.scroll_px / line_height) as i32;
1144
1145                self.scroll_px += e.delta.pixel_delta(line_height).y() * scroll_multiplier;
1146
1147                let new_offset = (self.scroll_px / line_height) as i32;
1148
1149                // Whenever we hit the edges, reset our stored scroll to 0
1150                // so we can respond to changes in direction quickly
1151                self.scroll_px %= self.last_content.size.height;
1152
1153                Some(new_offset - old_offset)
1154            }
1155            /* Fall back to delta / line_height */
1156            None => Some(
1157                ((e.delta.pixel_delta(line_height).y() * scroll_multiplier) / line_height) as i32,
1158            ),
1159            _ => None,
1160        }
1161    }
1162
1163    pub fn find_matches(
1164        &mut self,
1165        searcher: RegexSearch,
1166        cx: &mut ModelContext<Self>,
1167    ) -> Task<Vec<RangeInclusive<Point>>> {
1168        let term = self.term.clone();
1169        cx.background().spawn(async move {
1170            let term = term.lock();
1171
1172            all_search_matches(&term, &searcher).collect()
1173        })
1174    }
1175}
1176
1177impl Drop for Terminal {
1178    fn drop(&mut self) {
1179        self.pty_tx.0.send(Msg::Shutdown).ok();
1180    }
1181}
1182
1183impl Entity for Terminal {
1184    type Event = Event;
1185}
1186
1187/// Based on alacritty/src/display/hint.rs > regex_match_at
1188/// Retrieve the match, if the specified point is inside the content matching the regex.
1189fn regex_match_at<T>(term: &Term<T>, point: Point, regex: &RegexSearch) -> Option<Match> {
1190    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1191}
1192
1193/// Copied from alacritty/src/display/hint.rs:
1194/// Iterate over all visible regex matches.
1195pub fn visible_regex_match_iter<'a, T>(
1196    term: &'a Term<T>,
1197    regex: &'a RegexSearch,
1198) -> impl Iterator<Item = Match> + 'a {
1199    let viewport_start = Line(-(term.grid().display_offset() as i32));
1200    let viewport_end = viewport_start + term.bottommost_line();
1201    let mut start = term.line_search_left(Point::new(viewport_start, Column(0)));
1202    let mut end = term.line_search_right(Point::new(viewport_end, Column(0)));
1203    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1204    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1205
1206    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1207        .skip_while(move |rm| rm.end().line < viewport_start)
1208        .take_while(move |rm| rm.start().line <= viewport_end)
1209}
1210
1211fn make_selection(range: &RangeInclusive<Point>) -> Selection {
1212    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1213    selection.update(*range.end(), AlacDirection::Right);
1214    selection
1215}
1216
1217fn all_search_matches<'a, T>(
1218    term: &'a Term<T>,
1219    regex: &'a RegexSearch,
1220) -> impl Iterator<Item = Match> + 'a {
1221    let start = Point::new(term.grid().topmost_line(), Column(0));
1222    let end = Point::new(term.grid().bottommost_line(), term.grid().last_column());
1223    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1224}
1225
1226fn content_index_for_mouse<'a>(pos: Vector2F, content: &'a TerminalContent) -> usize {
1227    let col = min(
1228        (pos.x() / content.size.cell_width()) as usize,
1229        content.size.columns() - 1,
1230    ) as usize;
1231    let line = min(
1232        (pos.y() / content.size.line_height()) as usize,
1233        content.size.screen_lines() - 1,
1234    ) as usize;
1235
1236    line * content.size.columns() + col
1237}
1238
1239fn open_uri(uri: &str) -> Result<(), std::io::Error> {
1240    let mut command = Command::new("open");
1241    command.arg(uri);
1242
1243    unsafe {
1244        command
1245            .pre_exec(|| {
1246                match libc::fork() {
1247                    -1 => return Err(io::Error::last_os_error()),
1248                    0 => (),
1249                    _ => libc::_exit(0),
1250                }
1251
1252                if libc::setsid() == -1 {
1253                    return Err(io::Error::last_os_error());
1254                }
1255
1256                Ok(())
1257            })
1258            .spawn()?
1259            .wait()
1260            .map(|_| ())
1261    }
1262}
1263
1264#[cfg(test)]
1265mod tests {
1266    use alacritty_terminal::{
1267        index::{Column, Line, Point},
1268        term::cell::Cell,
1269    };
1270    use gpui::geometry::vector::vec2f;
1271    use rand::{rngs::ThreadRng, thread_rng, Rng};
1272
1273    use crate::{content_index_for_mouse, IndexedCell, TerminalContent, TerminalSize};
1274
1275    #[test]
1276    fn test_mouse_to_cell() {
1277        let mut rng = thread_rng();
1278
1279        for _ in 0..10 {
1280            let viewport_cells = rng.gen_range(5..50);
1281            let cell_size = rng.gen_range(5.0..20.0);
1282
1283            let size = crate::TerminalSize {
1284                cell_width: cell_size,
1285                line_height: cell_size,
1286                height: cell_size * (viewport_cells as f32),
1287                width: cell_size * (viewport_cells as f32),
1288            };
1289
1290            let (content, cells) = create_terminal_content(size, &mut rng);
1291
1292            for i in 0..(viewport_cells - 1) {
1293                let i = i as usize;
1294                for j in 0..(viewport_cells - 1) {
1295                    let j = j as usize;
1296                    let min_row = i as f32 * cell_size;
1297                    let max_row = (i + 1) as f32 * cell_size;
1298                    let min_col = j as f32 * cell_size;
1299                    let max_col = (j + 1) as f32 * cell_size;
1300
1301                    let mouse_pos = vec2f(
1302                        rng.gen_range(min_row..max_row),
1303                        rng.gen_range(min_col..max_col),
1304                    );
1305
1306                    assert_eq!(
1307                        content.cells[content_index_for_mouse(mouse_pos, &content)].c,
1308                        cells[j][i]
1309                    );
1310                }
1311            }
1312        }
1313    }
1314
1315    #[test]
1316    fn test_mouse_to_cell_clamp() {
1317        let mut rng = thread_rng();
1318
1319        let size = crate::TerminalSize {
1320            cell_width: 10.,
1321            line_height: 10.,
1322            height: 100.,
1323            width: 100.,
1324        };
1325
1326        let (content, cells) = create_terminal_content(size, &mut rng);
1327
1328        assert_eq!(
1329            content.cells[content_index_for_mouse(vec2f(-10., -10.), &content)].c,
1330            cells[0][0]
1331        );
1332        assert_eq!(
1333            content.cells[content_index_for_mouse(vec2f(1000., 1000.), &content)].c,
1334            cells[9][9]
1335        );
1336    }
1337
1338    fn create_terminal_content(
1339        size: TerminalSize,
1340        rng: &mut ThreadRng,
1341    ) -> (TerminalContent, Vec<Vec<char>>) {
1342        let mut ic = Vec::new();
1343        let mut cells = Vec::new();
1344
1345        for row in 0..((size.height() / size.line_height()) as usize) {
1346            let mut row_vec = Vec::new();
1347            for col in 0..((size.width() / size.cell_width()) as usize) {
1348                let cell_char = rng.gen();
1349                ic.push(IndexedCell {
1350                    point: Point::new(Line(row as i32), Column(col)),
1351                    cell: Cell {
1352                        c: cell_char,
1353                        ..Default::default()
1354                    },
1355                });
1356                row_vec.push(cell_char)
1357            }
1358            cells.push(row_vec)
1359        }
1360
1361        (
1362            TerminalContent {
1363                cells: ic,
1364                size,
1365                ..Default::default()
1366            },
1367            cells,
1368        )
1369    }
1370}