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