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