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
 411                    loop {
 412                        futures::select_biased! {
 413                            _ = timer => break,
 414                            event = self.events_rx.next() => {
 415                                if let Some(event) = event {
 416                                    events.push(event);
 417                                    if events.len() > 100 {
 418                                        break;
 419                                    }
 420                                } else {
 421                                    break;
 422                                }
 423                            },
 424                        }
 425                    }
 426
 427                    if events.is_empty() {
 428                        smol::future::yield_now().await;
 429                        break 'outer;
 430                    } else {
 431                        this.upgrade(&cx)?.update(&mut cx, |this, cx| {
 432                            for event in events {
 433                                this.process_event(&event, cx);
 434                            }
 435                        });
 436                        smol::future::yield_now().await;
 437                    }
 438                }
 439            }
 440
 441            Some(())
 442        })
 443        .detach();
 444
 445        self.terminal
 446    }
 447}
 448
 449#[derive(Debug, Clone)]
 450struct IndexedCell {
 451    point: Point,
 452    cell: Cell,
 453}
 454
 455impl Deref for IndexedCell {
 456    type Target = Cell;
 457
 458    #[inline]
 459    fn deref(&self) -> &Cell {
 460        &self.cell
 461    }
 462}
 463
 464#[derive(Clone)]
 465pub struct TerminalContent {
 466    cells: Vec<IndexedCell>,
 467    mode: TermMode,
 468    display_offset: usize,
 469    selection_text: Option<String>,
 470    selection: Option<SelectionRange>,
 471    cursor: RenderableCursor,
 472    cursor_char: char,
 473    size: TerminalSize,
 474    last_hovered_hyperlink: Option<(String, RangeInclusive<Point>, usize)>,
 475}
 476
 477impl Default for TerminalContent {
 478    fn default() -> Self {
 479        TerminalContent {
 480            cells: Default::default(),
 481            mode: Default::default(),
 482            display_offset: Default::default(),
 483            selection_text: Default::default(),
 484            selection: Default::default(),
 485            cursor: RenderableCursor {
 486                shape: alacritty_terminal::ansi::CursorShape::Block,
 487                point: Point::new(Line(0), Column(0)),
 488            },
 489            cursor_char: Default::default(),
 490            size: Default::default(),
 491            last_hovered_hyperlink: None,
 492        }
 493    }
 494}
 495
 496#[derive(PartialEq, Eq)]
 497pub enum SelectionPhase {
 498    Selecting,
 499    Ended,
 500}
 501
 502pub struct Terminal {
 503    pty_tx: Notifier,
 504    term: Arc<FairMutex<Term<ZedListener>>>,
 505    events: VecDeque<InternalEvent>,
 506    /// This is only used for mouse mode cell change detection
 507    last_mouse: Option<(Point, AlacDirection)>,
 508    /// This is only used for terminal hyperlink checking
 509    last_mouse_position: Option<Vector2F>,
 510    pub matches: Vec<RangeInclusive<Point>>,
 511    last_content: TerminalContent,
 512    last_synced: Instant,
 513    sync_task: Option<Task<()>>,
 514    selection_head: Option<Point>,
 515    breadcrumb_text: String,
 516    shell_pid: u32,
 517    shell_fd: u32,
 518    foreground_process_info: Option<LocalProcessInfo>,
 519    scroll_px: f32,
 520    next_link_id: usize,
 521    selection_phase: SelectionPhase,
 522}
 523
 524impl Terminal {
 525    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
 526        match event {
 527            AlacTermEvent::Title(title) => {
 528                self.breadcrumb_text = title.to_string();
 529                cx.emit(Event::BreadcrumbsChanged);
 530            }
 531            AlacTermEvent::ResetTitle => {
 532                self.breadcrumb_text = String::new();
 533                cx.emit(Event::BreadcrumbsChanged);
 534            }
 535            AlacTermEvent::ClipboardStore(_, data) => {
 536                cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
 537            }
 538            AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
 539                &cx.read_from_clipboard()
 540                    .map(|ci| ci.text().to_string())
 541                    .unwrap_or_else(|| "".to_string()),
 542            )),
 543            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 544            AlacTermEvent::TextAreaSizeRequest(format) => {
 545                self.write_to_pty(format(self.last_content.size.into()))
 546            }
 547            AlacTermEvent::CursorBlinkingChange => {
 548                cx.emit(Event::BlinkChanged);
 549            }
 550            AlacTermEvent::Bell => {
 551                cx.emit(Event::Bell);
 552            }
 553            AlacTermEvent::Exit => cx.emit(Event::CloseTerminal),
 554            AlacTermEvent::MouseCursorDirty => {
 555                //NOOP, Handled in render
 556            }
 557            AlacTermEvent::Wakeup => {
 558                cx.emit(Event::Wakeup);
 559
 560                if self.update_process_info() {
 561                    cx.emit(Event::TitleChanged)
 562                }
 563            }
 564            AlacTermEvent::ColorRequest(idx, fun_ptr) => {
 565                self.events
 566                    .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
 567            }
 568        }
 569    }
 570
 571    /// Update the cached process info, returns whether the Zed-relevant info has changed
 572    fn update_process_info(&mut self) -> bool {
 573        let mut pid = unsafe { libc::tcgetpgrp(self.shell_fd as i32) };
 574        if pid < 0 {
 575            pid = self.shell_pid as i32;
 576        }
 577
 578        if let Some(process_info) = LocalProcessInfo::with_root_pid(pid as u32) {
 579            let res = self
 580                .foreground_process_info
 581                .as_ref()
 582                .map(|old_info| {
 583                    process_info.cwd != old_info.cwd || process_info.name != old_info.name
 584                })
 585                .unwrap_or(true);
 586
 587            self.foreground_process_info = Some(process_info.clone());
 588
 589            res
 590        } else {
 591            false
 592        }
 593    }
 594
 595    ///Takes events from Alacritty and translates them to behavior on this view
 596    fn process_terminal_event(
 597        &mut self,
 598        event: &InternalEvent,
 599        term: &mut Term<ZedListener>,
 600        cx: &mut ModelContext<Self>,
 601    ) {
 602        match event {
 603            InternalEvent::ColorRequest(index, format) => {
 604                let color = term.colors()[*index].unwrap_or_else(|| {
 605                    let term_style = &cx.global::<Settings>().theme.terminal;
 606                    to_alac_rgb(get_color_at_index(index, &term_style))
 607                });
 608                self.write_to_pty(format(color))
 609            }
 610            InternalEvent::Resize(mut new_size) => {
 611                new_size.height = f32::max(new_size.line_height, new_size.height);
 612                new_size.width = f32::max(new_size.cell_width, new_size.width);
 613
 614                self.last_content.size = new_size.clone();
 615
 616                self.pty_tx.0.send(Msg::Resize((new_size).into())).ok();
 617
 618                term.resize(new_size);
 619            }
 620            InternalEvent::Clear => {
 621                // Clear back buffer
 622                term.clear_screen(ClearMode::Saved);
 623
 624                let cursor = term.grid().cursor.point;
 625
 626                // Clear the lines above
 627                term.grid_mut().reset_region(..cursor.line);
 628
 629                // Copy the current line up
 630                let line = term.grid()[cursor.line][..cursor.column]
 631                    .iter()
 632                    .cloned()
 633                    .enumerate()
 634                    .collect::<Vec<(usize, Cell)>>();
 635
 636                for (i, cell) in line {
 637                    term.grid_mut()[Line(0)][Column(i)] = cell;
 638                }
 639
 640                // Reset the cursor
 641                term.grid_mut().cursor.point =
 642                    Point::new(Line(0), term.grid_mut().cursor.point.column);
 643                let new_cursor = term.grid().cursor.point;
 644
 645                // Clear the lines below the new cursor
 646                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 647                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 648                }
 649            }
 650            InternalEvent::Scroll(scroll) => {
 651                term.scroll_display(*scroll);
 652                self.refresh_hyperlink();
 653            }
 654            InternalEvent::SetSelection(selection) => {
 655                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 656
 657                if let Some((_, head)) = selection {
 658                    self.selection_head = Some(*head);
 659                }
 660                cx.emit(Event::SelectionsChanged)
 661            }
 662            InternalEvent::UpdateSelection(position) => {
 663                if let Some(mut selection) = term.selection.take() {
 664                    let point = grid_point(
 665                        *position,
 666                        self.last_content.size,
 667                        term.grid().display_offset(),
 668                    );
 669                    let side = mouse_side(*position, self.last_content.size);
 670
 671                    selection.update(point, side);
 672                    term.selection = Some(selection);
 673
 674                    self.selection_head = Some(point);
 675                    cx.emit(Event::SelectionsChanged)
 676                }
 677            }
 678
 679            InternalEvent::Copy => {
 680                if let Some(txt) = term.selection_to_string() {
 681                    cx.write_to_clipboard(ClipboardItem::new(txt))
 682                }
 683            }
 684            InternalEvent::ScrollToPoint(point) => {
 685                term.scroll_to_point(*point);
 686                self.refresh_hyperlink();
 687            }
 688            InternalEvent::FindHyperlink(position, open) => {
 689                let prev_hyperlink = self.last_content.last_hovered_hyperlink.take();
 690
 691                let point = grid_point(
 692                    *position,
 693                    self.last_content.size,
 694                    term.grid().display_offset(),
 695                )
 696                .grid_clamp(term, alacritty_terminal::index::Boundary::Cursor);
 697
 698                let link = term.grid().index(point).hyperlink();
 699                let found_url = if link.is_some() {
 700                    let mut min_index = point;
 701                    loop {
 702                        let new_min_index =
 703                            min_index.sub(term, alacritty_terminal::index::Boundary::Cursor, 1);
 704                        if new_min_index == min_index {
 705                            break;
 706                        } else if term.grid().index(new_min_index).hyperlink() != link {
 707                            break;
 708                        } else {
 709                            min_index = new_min_index
 710                        }
 711                    }
 712
 713                    let mut max_index = point;
 714                    loop {
 715                        let new_max_index =
 716                            max_index.add(term, alacritty_terminal::index::Boundary::Cursor, 1);
 717                        if new_max_index == max_index {
 718                            break;
 719                        } else if term.grid().index(new_max_index).hyperlink() != link {
 720                            break;
 721                        } else {
 722                            max_index = new_max_index
 723                        }
 724                    }
 725
 726                    let url = link.unwrap().uri().to_owned();
 727                    let url_match = min_index..=max_index;
 728
 729                    Some((url, url_match))
 730                } else if let Some(url_match) = regex_match_at(term, point, &URL_REGEX) {
 731                    let url = term.bounds_to_string(*url_match.start(), *url_match.end());
 732
 733                    Some((url, url_match))
 734                } else {
 735                    None
 736                };
 737
 738                if let Some((url, url_match)) = found_url {
 739                    if *open {
 740                        open_uri(&url).log_err();
 741                    } else {
 742                        self.update_hyperlink(prev_hyperlink, url, url_match);
 743                    }
 744                }
 745            }
 746        }
 747    }
 748
 749    fn update_hyperlink(
 750        &mut self,
 751        prev_hyperlink: Option<(String, RangeInclusive<Point>, usize)>,
 752        url: String,
 753        url_match: RangeInclusive<Point>,
 754    ) {
 755        if let Some(prev_hyperlink) = prev_hyperlink {
 756            if prev_hyperlink.0 == url && prev_hyperlink.1 == url_match {
 757                self.last_content.last_hovered_hyperlink = Some((url, url_match, prev_hyperlink.2));
 758            } else {
 759                self.last_content.last_hovered_hyperlink =
 760                    Some((url, url_match, self.next_link_id()));
 761            }
 762        } else {
 763            self.last_content.last_hovered_hyperlink = Some((url, url_match, self.next_link_id()));
 764        }
 765    }
 766
 767    fn next_link_id(&mut self) -> usize {
 768        let res = self.next_link_id;
 769        self.next_link_id = self.next_link_id.wrapping_add(1);
 770        res
 771    }
 772
 773    pub fn last_content(&self) -> &TerminalContent {
 774        &self.last_content
 775    }
 776
 777    //To test:
 778    //- Activate match on terminal (scrolling and selection)
 779    //- Editor search snapping behavior
 780
 781    pub fn activate_match(&mut self, index: usize) {
 782        if let Some(search_match) = self.matches.get(index).cloned() {
 783            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 784
 785            self.events
 786                .push_back(InternalEvent::ScrollToPoint(*search_match.start()));
 787        }
 788    }
 789
 790    fn set_selection(&mut self, selection: Option<(Selection, Point)>) {
 791        self.events
 792            .push_back(InternalEvent::SetSelection(selection));
 793    }
 794
 795    pub fn copy(&mut self) {
 796        self.events.push_back(InternalEvent::Copy);
 797    }
 798
 799    pub fn clear(&mut self) {
 800        self.events.push_back(InternalEvent::Clear)
 801    }
 802
 803    ///Resize the terminal and the PTY.
 804    pub fn set_size(&mut self, new_size: TerminalSize) {
 805        self.events.push_back(InternalEvent::Resize(new_size))
 806    }
 807
 808    ///Write the Input payload to the tty.
 809    fn write_to_pty(&self, input: String) {
 810        self.pty_tx.notify(input.into_bytes());
 811    }
 812
 813    pub fn input(&mut self, input: String) {
 814        self.events
 815            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
 816        self.events.push_back(InternalEvent::SetSelection(None));
 817
 818        self.write_to_pty(input);
 819    }
 820
 821    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
 822        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
 823        if let Some(esc) = esc {
 824            self.input(esc);
 825            true
 826        } else {
 827            false
 828        }
 829    }
 830
 831    ///Paste text into the terminal
 832    pub fn paste(&mut self, text: &str) {
 833        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
 834            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
 835        } else {
 836            text.replace("\r\n", "\r").replace('\n', "\r")
 837        };
 838
 839        self.input(paste_text);
 840    }
 841
 842    pub fn try_sync(&mut self, cx: &mut ModelContext<Self>) {
 843        let term = self.term.clone();
 844
 845        let mut terminal = if let Some(term) = term.try_lock_unfair() {
 846            term
 847        } else if self.last_synced.elapsed().as_secs_f32() > 0.25 {
 848            term.lock_unfair() //It's been too long, force block
 849        } else if let None = self.sync_task {
 850            //Skip this frame
 851            let delay = cx.background().timer(Duration::from_millis(16));
 852            self.sync_task = Some(cx.spawn_weak(|weak_handle, mut cx| async move {
 853                delay.await;
 854                cx.update(|cx| {
 855                    if let Some(handle) = weak_handle.upgrade(cx) {
 856                        handle.update(cx, |terminal, cx| {
 857                            terminal.sync_task.take();
 858                            cx.notify();
 859                        });
 860                    }
 861                });
 862            }));
 863            return;
 864        } else {
 865            //No lock and delayed rendering already scheduled, nothing to do
 866            return;
 867        };
 868
 869        if self.update_process_info() {
 870            cx.emit(Event::TitleChanged);
 871        }
 872
 873        //Note that the ordering of events matters for event processing
 874        while let Some(e) = self.events.pop_front() {
 875            self.process_terminal_event(&e, &mut terminal, cx)
 876        }
 877
 878        self.last_content = Self::make_content(&terminal, &self.last_content);
 879        self.last_synced = Instant::now();
 880    }
 881
 882    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
 883        let content = term.renderable_content();
 884        TerminalContent {
 885            cells: content
 886                .display_iter
 887                //TODO: Add this once there's a way to retain empty lines
 888                // .filter(|ic| {
 889                //     !ic.flags.contains(Flags::HIDDEN)
 890                //         && !(ic.bg == Named(NamedColor::Background)
 891                //             && ic.c == ' '
 892                //             && !ic.flags.contains(Flags::INVERSE))
 893                // })
 894                .map(|ic| IndexedCell {
 895                    point: ic.point,
 896                    cell: ic.cell.clone(),
 897                })
 898                .collect::<Vec<IndexedCell>>(),
 899            mode: content.mode,
 900            display_offset: content.display_offset,
 901            selection_text: term.selection_to_string(),
 902            selection: content.selection,
 903            cursor: content.cursor,
 904            cursor_char: term.grid()[content.cursor.point].c,
 905            size: last_content.size,
 906            last_hovered_hyperlink: last_content.last_hovered_hyperlink.clone(),
 907        }
 908    }
 909
 910    pub fn focus_in(&self) {
 911        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
 912            self.write_to_pty("\x1b[I".to_string());
 913        }
 914    }
 915
 916    pub fn focus_out(&mut self) {
 917        self.last_mouse_position = None;
 918        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
 919            self.write_to_pty("\x1b[O".to_string());
 920        }
 921    }
 922
 923    pub fn mouse_changed(&mut self, point: Point, side: AlacDirection) -> bool {
 924        match self.last_mouse {
 925            Some((old_point, old_side)) => {
 926                if old_point == point && old_side == side {
 927                    false
 928                } else {
 929                    self.last_mouse = Some((point, side));
 930                    true
 931                }
 932            }
 933            None => {
 934                self.last_mouse = Some((point, side));
 935                true
 936            }
 937        }
 938    }
 939
 940    pub fn mouse_mode(&self, shift: bool) -> bool {
 941        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
 942    }
 943
 944    pub fn mouse_move(&mut self, e: &MouseMovedEvent, origin: Vector2F) {
 945        let position = e.position.sub(origin);
 946        self.last_mouse_position = Some(position);
 947        if self.mouse_mode(e.shift) {
 948            let point = grid_point(
 949                position,
 950                self.last_content.size,
 951                self.last_content.display_offset,
 952            );
 953            let side = mouse_side(position, self.last_content.size);
 954
 955            if self.mouse_changed(point, side) {
 956                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
 957                    self.pty_tx.notify(bytes);
 958                }
 959            }
 960        } else {
 961            self.hyperlink_from_position(Some(position));
 962        }
 963    }
 964
 965    fn hyperlink_from_position(&mut self, position: Option<Vector2F>) {
 966        if self.selection_phase == SelectionPhase::Selecting {
 967            self.last_content.last_hovered_hyperlink = None;
 968        } else if let Some(position) = position {
 969            self.events
 970                .push_back(InternalEvent::FindHyperlink(position, false));
 971        }
 972    }
 973
 974    pub fn mouse_drag(&mut self, e: MouseDrag, origin: Vector2F) {
 975        let position = e.position.sub(origin);
 976        self.last_mouse_position = Some(position);
 977
 978        if !self.mouse_mode(e.shift) {
 979            self.selection_phase = SelectionPhase::Selecting;
 980            // Alacritty has the same ordering, of first updating the selection
 981            // then scrolling 15ms later
 982            self.events
 983                .push_back(InternalEvent::UpdateSelection(position));
 984
 985            // Doesn't make sense to scroll the alt screen
 986            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
 987                let scroll_delta = match self.drag_line_delta(e) {
 988                    Some(value) => value,
 989                    None => return,
 990                };
 991
 992                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
 993
 994                self.events
 995                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
 996            }
 997        }
 998    }
 999
1000    fn drag_line_delta(&mut self, e: MouseDrag) -> Option<f32> {
1001        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1002        let top = e.region.origin_y() + (self.last_content.size.line_height * 2.);
1003        let bottom = e.region.lower_left().y() - (self.last_content.size.line_height * 2.);
1004        let scroll_delta = if e.position.y() < top {
1005            (top - e.position.y()).powf(1.1)
1006        } else if e.position.y() > bottom {
1007            -((e.position.y() - bottom).powf(1.1))
1008        } else {
1009            return None; //Nothing to do
1010        };
1011        Some(scroll_delta)
1012    }
1013
1014    pub fn mouse_down(&mut self, e: &MouseDown, origin: Vector2F) {
1015        let position = e.position.sub(origin);
1016        let point = grid_point(
1017            position,
1018            self.last_content.size,
1019            self.last_content.display_offset,
1020        );
1021
1022        if self.mouse_mode(e.shift) {
1023            if let Some(bytes) = mouse_button_report(point, e, true, self.last_content.mode) {
1024                self.pty_tx.notify(bytes);
1025            }
1026        } else if e.button == MouseButton::Left {
1027            let position = e.position.sub(origin);
1028            let point = grid_point(
1029                position,
1030                self.last_content.size,
1031                self.last_content.display_offset,
1032            );
1033            let side = mouse_side(position, self.last_content.size);
1034
1035            let selection_type = match e.click_count {
1036                0 => return, //This is a release
1037                1 => Some(SelectionType::Simple),
1038                2 => Some(SelectionType::Semantic),
1039                3 => Some(SelectionType::Lines),
1040                _ => None,
1041            };
1042
1043            let selection =
1044                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1045
1046            if let Some(sel) = selection {
1047                self.events
1048                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
1049            }
1050        }
1051    }
1052
1053    pub fn mouse_up(&mut self, e: &MouseUp, origin: Vector2F, cx: &mut ModelContext<Self>) {
1054        let settings = cx.global::<Settings>();
1055        let copy_on_select = settings
1056            .terminal_overrides
1057            .copy_on_select
1058            .unwrap_or_else(|| {
1059                settings
1060                    .terminal_defaults
1061                    .copy_on_select
1062                    .expect("Should be set in defaults")
1063            });
1064
1065        let position = e.position.sub(origin);
1066        if self.mouse_mode(e.shift) {
1067            let point = grid_point(
1068                position,
1069                self.last_content.size,
1070                self.last_content.display_offset,
1071            );
1072
1073            if let Some(bytes) = mouse_button_report(point, e, false, self.last_content.mode) {
1074                self.pty_tx.notify(bytes);
1075            }
1076        } else {
1077            if e.button == MouseButton::Left && copy_on_select {
1078                self.copy();
1079            }
1080
1081            //Hyperlinks
1082            if self.selection_phase == SelectionPhase::Ended {
1083                let mouse_cell_index = content_index_for_mouse(position, &self.last_content);
1084                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1085                    open_uri(link.uri()).log_err();
1086                } else {
1087                    self.events
1088                        .push_back(InternalEvent::FindHyperlink(position, true));
1089                }
1090            }
1091        }
1092
1093        self.selection_phase = SelectionPhase::Ended;
1094        self.last_mouse = None;
1095    }
1096
1097    ///Scroll the terminal
1098    pub fn scroll_wheel(&mut self, e: MouseScrollWheel, origin: Vector2F) {
1099        let mouse_mode = self.mouse_mode(e.shift);
1100
1101        if let Some(scroll_lines) = self.determine_scroll_lines(&e, mouse_mode) {
1102            if mouse_mode {
1103                let point = grid_point(
1104                    e.position.sub(origin),
1105                    self.last_content.size,
1106                    self.last_content.display_offset,
1107                );
1108
1109                if let Some(scrolls) =
1110                    scroll_report(point, scroll_lines as i32, &e, self.last_content.mode)
1111                {
1112                    for scroll in scrolls {
1113                        self.pty_tx.notify(scroll);
1114                    }
1115                };
1116            } else if self
1117                .last_content
1118                .mode
1119                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1120                && !e.shift
1121            {
1122                self.pty_tx.notify(alt_scroll(scroll_lines))
1123            } else {
1124                if scroll_lines != 0 {
1125                    let scroll = AlacScroll::Delta(scroll_lines);
1126
1127                    self.events.push_back(InternalEvent::Scroll(scroll));
1128                }
1129            }
1130        }
1131    }
1132
1133    pub fn refresh_hyperlink(&mut self) {
1134        self.hyperlink_from_position(self.last_mouse_position);
1135    }
1136
1137    fn determine_scroll_lines(&mut self, e: &MouseScrollWheel, mouse_mode: bool) -> Option<i32> {
1138        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1139
1140        match e.phase {
1141            /* Reset scroll state on started */
1142            Some(gpui::TouchPhase::Started) => {
1143                self.scroll_px = 0.;
1144                None
1145            }
1146            /* Calculate the appropriate scroll lines */
1147            Some(gpui::TouchPhase::Moved) => {
1148                let old_offset = (self.scroll_px / self.last_content.size.line_height) as i32;
1149
1150                self.scroll_px += e.delta.y() * scroll_multiplier;
1151
1152                let new_offset = (self.scroll_px / self.last_content.size.line_height) as i32;
1153
1154                // Whenever we hit the edges, reset our stored scroll to 0
1155                // so we can respond to changes in direction quickly
1156                self.scroll_px %= self.last_content.size.height;
1157
1158                Some(new_offset - old_offset)
1159            }
1160            /* Fall back to delta / line_height */
1161            None => Some(
1162                ((e.delta.y() * scroll_multiplier) / self.last_content.size.line_height) as i32,
1163            ),
1164            _ => None,
1165        }
1166    }
1167
1168    pub fn find_matches(
1169        &mut self,
1170        query: project::search::SearchQuery,
1171        cx: &mut ModelContext<Self>,
1172    ) -> Task<Vec<RangeInclusive<Point>>> {
1173        let term = self.term.clone();
1174        cx.background().spawn(async move {
1175            let searcher = match query {
1176                project::search::SearchQuery::Text { query, .. } => {
1177                    RegexSearch::new(query.as_ref())
1178                }
1179                project::search::SearchQuery::Regex { query, .. } => {
1180                    RegexSearch::new(query.as_ref())
1181                }
1182            };
1183
1184            if searcher.is_err() {
1185                return Vec::new();
1186            }
1187            let searcher = searcher.unwrap();
1188
1189            let term = term.lock();
1190
1191            all_search_matches(&term, &searcher).collect()
1192        })
1193    }
1194}
1195
1196impl Drop for Terminal {
1197    fn drop(&mut self) {
1198        self.pty_tx.0.send(Msg::Shutdown).ok();
1199    }
1200}
1201
1202impl Entity for Terminal {
1203    type Event = Event;
1204}
1205
1206/// Based on alacritty/src/display/hint.rs > regex_match_at
1207/// Retrieve the match, if the specified point is inside the content matching the regex.
1208fn regex_match_at<T>(term: &Term<T>, point: Point, regex: &RegexSearch) -> Option<Match> {
1209    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1210}
1211
1212/// Copied from alacritty/src/display/hint.rs:
1213/// Iterate over all visible regex matches.
1214pub fn visible_regex_match_iter<'a, T>(
1215    term: &'a Term<T>,
1216    regex: &'a RegexSearch,
1217) -> impl Iterator<Item = Match> + 'a {
1218    let viewport_start = Line(-(term.grid().display_offset() as i32));
1219    let viewport_end = viewport_start + term.bottommost_line();
1220    let mut start = term.line_search_left(Point::new(viewport_start, Column(0)));
1221    let mut end = term.line_search_right(Point::new(viewport_end, Column(0)));
1222    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1223    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1224
1225    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1226        .skip_while(move |rm| rm.end().line < viewport_start)
1227        .take_while(move |rm| rm.start().line <= viewport_end)
1228}
1229
1230fn make_selection(range: &RangeInclusive<Point>) -> Selection {
1231    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1232    selection.update(*range.end(), AlacDirection::Right);
1233    selection
1234}
1235
1236fn all_search_matches<'a, T>(
1237    term: &'a Term<T>,
1238    regex: &'a RegexSearch,
1239) -> impl Iterator<Item = Match> + 'a {
1240    let start = Point::new(term.grid().topmost_line(), Column(0));
1241    let end = Point::new(term.grid().bottommost_line(), term.grid().last_column());
1242    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1243}
1244
1245fn content_index_for_mouse<'a>(pos: Vector2F, content: &'a TerminalContent) -> usize {
1246    let col = min(
1247        (pos.x() / content.size.cell_width()) as usize,
1248        content.size.columns() - 1,
1249    ) as usize;
1250    let line = min(
1251        (pos.y() / content.size.line_height()) as usize,
1252        content.size.screen_lines() - 1,
1253    ) as usize;
1254
1255    line * content.size.columns() + col
1256}
1257
1258fn open_uri(uri: &str) -> Result<(), std::io::Error> {
1259    let mut command = Command::new("open");
1260    command.arg(uri);
1261
1262    unsafe {
1263        command
1264            .pre_exec(|| {
1265                match libc::fork() {
1266                    -1 => return Err(io::Error::last_os_error()),
1267                    0 => (),
1268                    _ => libc::_exit(0),
1269                }
1270
1271                if libc::setsid() == -1 {
1272                    return Err(io::Error::last_os_error());
1273                }
1274
1275                Ok(())
1276            })
1277            .spawn()?
1278            .wait()
1279            .map(|_| ())
1280    }
1281}
1282
1283#[cfg(test)]
1284mod tests {
1285    use gpui::geometry::vector::vec2f;
1286    use rand::{thread_rng, Rng};
1287
1288    use crate::content_index_for_mouse;
1289
1290    use self::terminal_test_context::TerminalTestContext;
1291
1292    pub mod terminal_test_context;
1293
1294    #[test]
1295    fn test_mouse_to_cell() {
1296        let mut rng = thread_rng();
1297
1298        for _ in 0..10 {
1299            let viewport_cells = rng.gen_range(5..50);
1300            let cell_size = rng.gen_range(5.0..20.0);
1301
1302            let size = crate::TerminalSize {
1303                cell_width: cell_size,
1304                line_height: cell_size,
1305                height: cell_size * (viewport_cells as f32),
1306                width: cell_size * (viewport_cells as f32),
1307            };
1308
1309            let (content, cells) = TerminalTestContext::create_terminal_content(size, &mut rng);
1310
1311            for i in 0..(viewport_cells - 1) {
1312                let i = i as usize;
1313                for j in 0..(viewport_cells - 1) {
1314                    let j = j as usize;
1315                    let min_row = i as f32 * cell_size;
1316                    let max_row = (i + 1) as f32 * cell_size;
1317                    let min_col = j as f32 * cell_size;
1318                    let max_col = (j + 1) as f32 * cell_size;
1319
1320                    let mouse_pos = vec2f(
1321                        rng.gen_range(min_row..max_row),
1322                        rng.gen_range(min_col..max_col),
1323                    );
1324
1325                    assert_eq!(
1326                        content.cells[content_index_for_mouse(mouse_pos, &content)].c,
1327                        cells[j][i]
1328                    );
1329                }
1330            }
1331        }
1332    }
1333
1334    #[test]
1335    fn test_mouse_to_cell_clamp() {
1336        let mut rng = thread_rng();
1337
1338        let size = crate::TerminalSize {
1339            cell_width: 10.,
1340            line_height: 10.,
1341            height: 100.,
1342            width: 100.,
1343        };
1344
1345        let (content, cells) = TerminalTestContext::create_terminal_content(size, &mut rng);
1346
1347        assert_eq!(
1348            content.cells[content_index_for_mouse(vec2f(-10., -10.), &content)].c,
1349            cells[0][0]
1350        );
1351        assert_eq!(
1352            content.cells[content_index_for_mouse(vec2f(1000., 1000.), &content)].c,
1353            cells[9][9]
1354        );
1355    }
1356}