terminal.rs

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