terminal.rs

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