terminal.rs

   1pub mod mappings;
   2pub mod modal;
   3pub mod terminal_container_view;
   4pub mod terminal_element;
   5pub mod terminal_view;
   6
   7use alacritty_terminal::{
   8    ansi::{ClearMode, Handler},
   9    config::{Config, Program, PtyConfig, Scrolling},
  10    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
  11    event_loop::{EventLoop, Msg, Notifier},
  12    grid::{Dimensions, Scroll as AlacScroll},
  13    index::{Column, Direction as AlacDirection, Line, Point},
  14    selection::{Selection, SelectionRange, SelectionType},
  15    sync::FairMutex,
  16    term::{
  17        cell::Cell,
  18        color::Rgb,
  19        search::{Match, RegexIter, RegexSearch},
  20        RenderableCursor, TermMode,
  21    },
  22    tty::{self, setup_env},
  23    Term,
  24};
  25use anyhow::{bail, Result};
  26
  27use futures::{
  28    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
  29    FutureExt,
  30};
  31
  32use mappings::mouse::{
  33    alt_scroll, mouse_button_report, mouse_moved_report, mouse_point, mouse_side, scroll_report,
  34};
  35use modal::deploy_modal;
  36
  37use settings::{AlternateScroll, Settings, Shell, TerminalBlink};
  38use std::{
  39    collections::{HashMap, VecDeque},
  40    fmt::Display,
  41    ops::{Deref, RangeInclusive, Sub},
  42    path::PathBuf,
  43    sync::Arc,
  44    time::{Duration, Instant},
  45};
  46use thiserror::Error;
  47
  48use gpui::{
  49    geometry::vector::{vec2f, Vector2F},
  50    keymap::Keystroke,
  51    scene::{ClickRegionEvent, DownRegionEvent, DragRegionEvent, UpRegionEvent},
  52    ClipboardItem, Entity, ModelContext, MouseButton, MouseMovedEvent, MutableAppContext,
  53    ScrollWheelEvent, Task,
  54};
  55
  56use crate::mappings::{
  57    colors::{get_color_at_index, to_alac_rgb},
  58    keys::to_esc_str,
  59};
  60
  61///Initialize and register all of our action handlers
  62pub fn init(cx: &mut MutableAppContext) {
  63    cx.add_action(deploy_modal);
  64
  65    terminal_view::init(cx);
  66    terminal_container_view::init(cx);
  67}
  68
  69///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  70///Scroll multiplier that is set to 3 by default. This will be removed when I
  71///Implement scroll bars.
  72const ALACRITTY_SCROLL_MULTIPLIER: f32 = 3.;
  73const MAX_SEARCH_LINES: usize = 100;
  74const DEBUG_TERMINAL_WIDTH: f32 = 500.;
  75const DEBUG_TERMINAL_HEIGHT: f32 = 30.;
  76const DEBUG_CELL_WIDTH: f32 = 5.;
  77const DEBUG_LINE_HEIGHT: f32 = 5.;
  78
  79///Upward flowing events, for changing the title and such
  80#[derive(Clone, Copy, Debug)]
  81pub enum Event {
  82    TitleChanged,
  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    Copy,
 101}
 102
 103///A translation struct for Alacritty to communicate with us from their event loop
 104#[derive(Clone)]
 105pub struct ZedListener(UnboundedSender<AlacTermEvent>);
 106
 107impl EventListener for ZedListener {
 108    fn send_event(&self, event: AlacTermEvent) {
 109        self.0.unbounded_send(event).ok();
 110    }
 111}
 112
 113#[derive(Clone, Copy, Debug)]
 114pub struct TerminalSize {
 115    cell_width: f32,
 116    line_height: f32,
 117    height: f32,
 118    width: f32,
 119}
 120
 121impl TerminalSize {
 122    pub fn new(line_height: f32, cell_width: f32, size: Vector2F) -> Self {
 123        TerminalSize {
 124            cell_width,
 125            line_height,
 126            width: size.x(),
 127            height: size.y(),
 128        }
 129    }
 130
 131    pub fn num_lines(&self) -> usize {
 132        (self.height / self.line_height).floor() as usize
 133    }
 134
 135    pub fn num_columns(&self) -> usize {
 136        (self.width / self.cell_width).floor() as usize
 137    }
 138
 139    pub fn height(&self) -> f32 {
 140        self.height
 141    }
 142
 143    pub fn width(&self) -> f32 {
 144        self.width
 145    }
 146
 147    pub fn cell_width(&self) -> f32 {
 148        self.cell_width
 149    }
 150
 151    pub fn line_height(&self) -> f32 {
 152        self.line_height
 153    }
 154}
 155impl Default for TerminalSize {
 156    fn default() -> Self {
 157        TerminalSize::new(
 158            DEBUG_LINE_HEIGHT,
 159            DEBUG_CELL_WIDTH,
 160            vec2f(DEBUG_TERMINAL_WIDTH, DEBUG_TERMINAL_HEIGHT),
 161        )
 162    }
 163}
 164
 165impl From<TerminalSize> for WindowSize {
 166    fn from(val: TerminalSize) -> Self {
 167        WindowSize {
 168            num_lines: val.num_lines() as u16,
 169            num_cols: val.num_columns() as u16,
 170            cell_width: val.cell_width() as u16,
 171            cell_height: val.line_height() as u16,
 172        }
 173    }
 174}
 175
 176impl Dimensions for TerminalSize {
 177    /// Note: this is supposed to be for the back buffer's length,
 178    /// but we exclusively use it to resize the terminal, which does not
 179    /// use this method. We still have to implement it for the trait though,
 180    /// hence, this comment.
 181    fn total_lines(&self) -> usize {
 182        self.screen_lines()
 183    }
 184
 185    fn screen_lines(&self) -> usize {
 186        self.num_lines()
 187    }
 188
 189    fn columns(&self) -> usize {
 190        self.num_columns()
 191    }
 192}
 193
 194#[derive(Error, Debug)]
 195pub struct TerminalError {
 196    pub directory: Option<PathBuf>,
 197    pub shell: Option<Shell>,
 198    pub source: std::io::Error,
 199}
 200
 201impl TerminalError {
 202    pub fn fmt_directory(&self) -> String {
 203        self.directory
 204            .clone()
 205            .map(|path| {
 206                match path
 207                    .into_os_string()
 208                    .into_string()
 209                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 210                {
 211                    Ok(s) => s,
 212                    Err(s) => s,
 213                }
 214            })
 215            .unwrap_or_else(|| {
 216                let default_dir =
 217                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
 218                match default_dir {
 219                    Some(dir) => format!("<none specified, using home directory> {}", dir),
 220                    None => "<none specified, could not find home directory>".to_string(),
 221                }
 222            })
 223    }
 224
 225    pub fn shell_to_string(&self) -> Option<String> {
 226        self.shell.as_ref().map(|shell| match shell {
 227            Shell::System => "<system shell>".to_string(),
 228            Shell::Program(p) => p.to_string(),
 229            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 230        })
 231    }
 232
 233    pub fn fmt_shell(&self) -> String {
 234        self.shell
 235            .clone()
 236            .map(|shell| match shell {
 237                Shell::System => {
 238                    let mut buf = [0; 1024];
 239                    let pw = alacritty_unix::get_pw_entry(&mut buf).ok();
 240
 241                    match pw {
 242                        Some(pw) => format!("<system defined shell> {}", pw.shell),
 243                        None => "<could not access the password file>".to_string(),
 244                    }
 245                }
 246                Shell::Program(s) => s,
 247                Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 248            })
 249            .unwrap_or_else(|| {
 250                let mut buf = [0; 1024];
 251                let pw = alacritty_unix::get_pw_entry(&mut buf).ok();
 252                match pw {
 253                    Some(pw) => {
 254                        format!("<none specified, using system defined shell> {}", pw.shell)
 255                    }
 256                    None => "<none specified, could not access the password file> {}".to_string(),
 257                }
 258            })
 259    }
 260}
 261
 262impl Display for TerminalError {
 263    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 264        let dir_string: String = self.fmt_directory();
 265        let shell = self.fmt_shell();
 266
 267        write!(
 268            f,
 269            "Working directory: {} Shell command: `{}`, IOError: {}",
 270            dir_string, shell, self.source
 271        )
 272    }
 273}
 274
 275pub struct TerminalBuilder {
 276    terminal: Terminal,
 277    events_rx: UnboundedReceiver<AlacTermEvent>,
 278}
 279
 280impl TerminalBuilder {
 281    pub fn new(
 282        working_directory: Option<PathBuf>,
 283        shell: Option<Shell>,
 284        env: Option<HashMap<String, String>>,
 285        initial_size: TerminalSize,
 286        blink_settings: Option<TerminalBlink>,
 287        alternate_scroll: &AlternateScroll,
 288    ) -> Result<TerminalBuilder> {
 289        let pty_config = {
 290            let alac_shell = shell.clone().and_then(|shell| match shell {
 291                Shell::System => None,
 292                Shell::Program(program) => Some(Program::Just(program)),
 293                Shell::WithArguments { program, args } => Some(Program::WithArgs { program, args }),
 294            });
 295
 296            PtyConfig {
 297                shell: alac_shell,
 298                working_directory: working_directory.clone(),
 299                hold: false,
 300            }
 301        };
 302
 303        let mut env = env.unwrap_or_default();
 304
 305        //TODO: Properly set the current locale,
 306        env.insert("LC_ALL".to_string(), "en_US.UTF-8".to_string());
 307
 308        let alac_scrolling = Scrolling::default();
 309        // alac_scrolling.set_history((BACK_BUFFER_SIZE * 2) as u32);
 310
 311        let config = Config {
 312            pty_config: pty_config.clone(),
 313            env,
 314            scrolling: alac_scrolling,
 315            ..Default::default()
 316        };
 317
 318        setup_env(&config);
 319
 320        //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
 321        //TODO: Remove with a bounded sender which can be dispatched on &self
 322        let (events_tx, events_rx) = unbounded();
 323        //Set up the terminal...
 324        let mut term = Term::new(&config, &initial_size, ZedListener(events_tx.clone()));
 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(&pty_config, initial_size.into(), None) {
 340            Ok(pty) => pty,
 341            Err(error) => {
 342                bail!(TerminalError {
 343                    directory: working_directory,
 344                    shell,
 345                    source: error,
 346                });
 347            }
 348        };
 349
 350        let shell_txt = {
 351            match shell {
 352                Some(Shell::System) | None => {
 353                    let mut buf = [0; 1024];
 354                    let pw = alacritty_unix::get_pw_entry(&mut buf).unwrap();
 355                    pw.shell.to_string()
 356                }
 357                Some(Shell::Program(program)) => program,
 358                Some(Shell::WithArguments { program, args }) => {
 359                    format!("{} {}", program, args.join(" "))
 360                }
 361            }
 362        };
 363
 364        //And connect them together
 365        let event_loop = EventLoop::new(
 366            term.clone(),
 367            ZedListener(events_tx.clone()),
 368            pty,
 369            pty_config.hold,
 370            false,
 371        );
 372
 373        //Kick things off
 374        let pty_tx = event_loop.channel();
 375        let _io_thread = event_loop.spawn();
 376
 377        let terminal = Terminal {
 378            pty_tx: Notifier(pty_tx),
 379            term,
 380            events: VecDeque::with_capacity(10), //Should never get this high.
 381            title: shell_txt.clone(),
 382            default_title: shell_txt,
 383            last_content: Default::default(),
 384            cur_size: initial_size,
 385            last_mouse: None,
 386            matches: Vec::new(),
 387            last_synced: Instant::now(),
 388            sync_task: None,
 389            selection_head: None,
 390        };
 391
 392        Ok(TerminalBuilder {
 393            terminal,
 394            events_rx,
 395        })
 396    }
 397
 398    pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
 399        //Event loop
 400        cx.spawn_weak(|this, mut cx| async move {
 401            use futures::StreamExt;
 402
 403            while let Some(event) = self.events_rx.next().await {
 404                this.upgrade(&cx)?.update(&mut cx, |this, cx| {
 405                    //Process the first event immediately for lowered latency
 406                    this.process_event(&event, cx);
 407                });
 408
 409                'outer: loop {
 410                    let mut events = vec![];
 411                    let mut timer = cx.background().timer(Duration::from_millis(4)).fuse();
 412
 413                    loop {
 414                        futures::select_biased! {
 415                            _ = timer => break,
 416                            event = self.events_rx.next() => {
 417                                if let Some(event) = event {
 418                                    events.push(event);
 419                                    if events.len() > 100 {
 420                                        break;
 421                                    }
 422                                } else {
 423                                    break;
 424                                }
 425                            },
 426                        }
 427                    }
 428
 429                    if events.is_empty() {
 430                        smol::future::yield_now().await;
 431                        break 'outer;
 432                    } else {
 433                        this.upgrade(&cx)?.update(&mut cx, |this, cx| {
 434                            for event in events {
 435                                this.process_event(&event, cx);
 436                            }
 437                        });
 438                        smol::future::yield_now().await;
 439                    }
 440                }
 441            }
 442
 443            Some(())
 444        })
 445        .detach();
 446
 447        self.terminal
 448    }
 449}
 450
 451#[derive(Debug, Clone)]
 452struct IndexedCell {
 453    point: Point,
 454    cell: Cell,
 455}
 456
 457impl Deref for IndexedCell {
 458    type Target = Cell;
 459
 460    #[inline]
 461    fn deref(&self) -> &Cell {
 462        &self.cell
 463    }
 464}
 465
 466#[derive(Clone)]
 467pub struct TerminalContent {
 468    cells: Vec<IndexedCell>,
 469    mode: TermMode,
 470    display_offset: usize,
 471    selection_text: Option<String>,
 472    selection: Option<SelectionRange>,
 473    cursor: RenderableCursor,
 474    cursor_char: char,
 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        }
 491    }
 492}
 493
 494pub struct Terminal {
 495    pty_tx: Notifier,
 496    term: Arc<FairMutex<Term<ZedListener>>>,
 497    events: VecDeque<InternalEvent>,
 498    default_title: String,
 499    title: String,
 500    last_mouse: Option<(Point, AlacDirection)>,
 501    pub matches: Vec<RangeInclusive<Point>>,
 502    cur_size: TerminalSize,
 503    last_content: TerminalContent,
 504    last_synced: Instant,
 505    sync_task: Option<Task<()>>,
 506    selection_head: Option<Point>,
 507}
 508
 509impl Terminal {
 510    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
 511        match event {
 512            AlacTermEvent::Title(title) => {
 513                self.title = title.to_string();
 514                cx.emit(Event::TitleChanged);
 515            }
 516            AlacTermEvent::ResetTitle => {
 517                self.title = self.default_title.clone();
 518                cx.emit(Event::TitleChanged);
 519            }
 520            AlacTermEvent::ClipboardStore(_, data) => {
 521                cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
 522            }
 523            AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
 524                &cx.read_from_clipboard()
 525                    .map(|ci| ci.text().to_string())
 526                    .unwrap_or_else(|| "".to_string()),
 527            )),
 528            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 529            AlacTermEvent::TextAreaSizeRequest(format) => {
 530                self.write_to_pty(format(self.cur_size.into()))
 531            }
 532            AlacTermEvent::CursorBlinkingChange => {
 533                cx.emit(Event::BlinkChanged);
 534            }
 535            AlacTermEvent::Bell => {
 536                cx.emit(Event::Bell);
 537            }
 538            AlacTermEvent::Exit => cx.emit(Event::CloseTerminal),
 539            AlacTermEvent::MouseCursorDirty => {
 540                //NOOP, Handled in render
 541            }
 542            AlacTermEvent::Wakeup => {
 543                cx.emit(Event::Wakeup);
 544                cx.notify();
 545            }
 546            AlacTermEvent::ColorRequest(idx, fun_ptr) => {
 547                self.events
 548                    .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
 549                cx.notify(); //Immediately schedule a render to respond to the color request
 550            }
 551        }
 552    }
 553
 554    ///Takes events from Alacritty and translates them to behavior on this view
 555    fn process_terminal_event(
 556        &mut self,
 557        event: &InternalEvent,
 558        term: &mut Term<ZedListener>,
 559        cx: &mut ModelContext<Self>,
 560    ) {
 561        match event {
 562            InternalEvent::ColorRequest(index, format) => {
 563                let color = term.colors()[*index].unwrap_or_else(|| {
 564                    let term_style = &cx.global::<Settings>().theme.terminal;
 565                    to_alac_rgb(get_color_at_index(index, &term_style.colors))
 566                });
 567                self.write_to_pty(format(color))
 568            }
 569            InternalEvent::Resize(new_size) => {
 570                self.cur_size = *new_size;
 571
 572                self.pty_tx.0.send(Msg::Resize((*new_size).into())).ok();
 573
 574                term.resize(*new_size);
 575            }
 576            InternalEvent::Clear => {
 577                self.write_to_pty("\x0c".to_string());
 578                term.clear_screen(ClearMode::Saved);
 579            }
 580            InternalEvent::Scroll(scroll) => {
 581                term.scroll_display(*scroll);
 582            }
 583            InternalEvent::SetSelection(selection) => {
 584                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 585
 586                if let Some((_, head)) = selection {
 587                    self.selection_head = Some(*head);
 588                }
 589                cx.emit(Event::SelectionsChanged)
 590            }
 591            InternalEvent::UpdateSelection(position) => {
 592                if let Some(mut selection) = term.selection.take() {
 593                    let point = mouse_point(*position, self.cur_size, term.grid().display_offset());
 594                    let side = mouse_side(*position, self.cur_size);
 595
 596                    selection.update(point, side);
 597                    term.selection = Some(selection);
 598
 599                    self.selection_head = Some(point);
 600                    cx.emit(Event::SelectionsChanged)
 601                }
 602            }
 603
 604            InternalEvent::Copy => {
 605                if let Some(txt) = term.selection_to_string() {
 606                    cx.write_to_clipboard(ClipboardItem::new(txt))
 607                }
 608            }
 609            InternalEvent::ScrollToPoint(point) => term.scroll_to_point(*point),
 610        }
 611    }
 612
 613    pub fn last_content(&self) -> &TerminalContent {
 614        &self.last_content
 615    }
 616
 617    //To test:
 618    //- Activate match on terminal (scrolling and selection)
 619    //- Editor search snapping behavior
 620
 621    pub fn activate_match(&mut self, index: usize) {
 622        if let Some(search_match) = self.matches.get(index).cloned() {
 623            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 624
 625            self.events
 626                .push_back(InternalEvent::ScrollToPoint(*search_match.start()));
 627        }
 628    }
 629
 630    fn set_selection(&mut self, selection: Option<(Selection, Point)>) {
 631        self.events
 632            .push_back(InternalEvent::SetSelection(selection));
 633    }
 634
 635    pub fn copy(&mut self) {
 636        self.events.push_back(InternalEvent::Copy);
 637    }
 638
 639    pub fn clear(&mut self) {
 640        self.events.push_back(InternalEvent::Clear)
 641    }
 642
 643    ///Resize the terminal and the PTY.
 644    pub fn set_size(&mut self, new_size: TerminalSize) {
 645        self.events.push_back(InternalEvent::Resize(new_size))
 646    }
 647
 648    ///Write the Input payload to the tty.
 649    fn write_to_pty(&self, input: String) {
 650        self.pty_tx.notify(input.into_bytes());
 651    }
 652
 653    pub fn input(&mut self, input: String) {
 654        self.events
 655            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
 656        self.events.push_back(InternalEvent::SetSelection(None));
 657
 658        self.write_to_pty(input);
 659    }
 660
 661    pub fn try_keystroke(&mut self, keystroke: &Keystroke) -> bool {
 662        let esc = to_esc_str(keystroke, &self.last_content.mode);
 663        if let Some(esc) = esc {
 664            self.input(esc);
 665            true
 666        } else {
 667            false
 668        }
 669    }
 670
 671    ///Paste text into the terminal
 672    pub fn paste(&mut self, text: &str) {
 673        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
 674            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
 675        } else {
 676            text.replace("\r\n", "\r").replace('\n', "\r")
 677        };
 678        self.input(paste_text)
 679    }
 680
 681    pub fn try_sync(&mut self, cx: &mut ModelContext<Self>) {
 682        let term = self.term.clone();
 683
 684        let mut terminal = if let Some(term) = term.try_lock_unfair() {
 685            term
 686        } else if self.last_synced.elapsed().as_secs_f32() > 0.25 {
 687            term.lock_unfair()
 688        } else if let None = self.sync_task {
 689            //Skip this frame
 690            let delay = cx.background().timer(Duration::from_millis(16));
 691            self.sync_task = Some(cx.spawn_weak(|weak_handle, mut cx| async move {
 692                delay.await;
 693                cx.update(|cx| {
 694                    if let Some(handle) = weak_handle.upgrade(cx) {
 695                        handle.update(cx, |terminal, cx| {
 696                            terminal.sync_task.take();
 697                            cx.notify();
 698                        });
 699                    }
 700                });
 701            }));
 702            return;
 703        } else {
 704            //No lock and delayed rendering already scheduled, nothing to do
 705            return;
 706        };
 707
 708        //Note that this ordering matters for event processing
 709        while let Some(e) = self.events.pop_front() {
 710            self.process_terminal_event(&e, &mut terminal, cx)
 711        }
 712
 713        self.last_content = Self::make_content(&terminal);
 714        self.last_synced = Instant::now();
 715    }
 716
 717    fn make_content(term: &Term<ZedListener>) -> TerminalContent {
 718        let content = term.renderable_content();
 719        TerminalContent {
 720            cells: content
 721                .display_iter
 722                //TODO: Add this once there's a way to retain empty lines
 723                // .filter(|ic| {
 724                //     !ic.flags.contains(Flags::HIDDEN)
 725                //         && !(ic.bg == Named(NamedColor::Background)
 726                //             && ic.c == ' '
 727                //             && !ic.flags.contains(Flags::INVERSE))
 728                // })
 729                .map(|ic| IndexedCell {
 730                    point: ic.point,
 731                    cell: ic.cell.clone(),
 732                })
 733                .collect::<Vec<IndexedCell>>(),
 734            mode: content.mode,
 735            display_offset: content.display_offset,
 736            selection_text: term.selection_to_string(),
 737            selection: content.selection,
 738            cursor: content.cursor,
 739            cursor_char: term.grid()[content.cursor.point].c,
 740        }
 741    }
 742
 743    pub fn focus_in(&self) {
 744        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
 745            self.write_to_pty("\x1b[I".to_string());
 746        }
 747    }
 748
 749    pub fn focus_out(&self) {
 750        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
 751            self.write_to_pty("\x1b[O".to_string());
 752        }
 753    }
 754
 755    pub fn mouse_changed(&mut self, point: Point, side: AlacDirection) -> bool {
 756        match self.last_mouse {
 757            Some((old_point, old_side)) => {
 758                if old_point == point && old_side == side {
 759                    false
 760                } else {
 761                    self.last_mouse = Some((point, side));
 762                    true
 763                }
 764            }
 765            None => {
 766                self.last_mouse = Some((point, side));
 767                true
 768            }
 769        }
 770    }
 771
 772    pub fn mouse_mode(&self, shift: bool) -> bool {
 773        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
 774    }
 775
 776    pub fn mouse_move(&mut self, e: &MouseMovedEvent, origin: Vector2F) {
 777        let position = e.position.sub(origin);
 778
 779        let point = mouse_point(position, self.cur_size, self.last_content.display_offset);
 780        let side = mouse_side(position, self.cur_size);
 781
 782        if self.mouse_changed(point, side) && self.mouse_mode(e.shift) {
 783            if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
 784                self.pty_tx.notify(bytes);
 785            }
 786        }
 787    }
 788
 789    pub fn mouse_drag(&mut self, e: DragRegionEvent, origin: Vector2F) {
 790        let position = e.position.sub(origin);
 791
 792        if !self.mouse_mode(e.shift) {
 793            // Alacritty has the same ordering, of first updating the selection
 794            // then scrolling 15ms later
 795            self.events
 796                .push_back(InternalEvent::UpdateSelection(position));
 797
 798            // Doesn't make sense to scroll the alt screen
 799            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
 800                let scroll_delta = match self.drag_line_delta(e) {
 801                    Some(value) => value,
 802                    None => return,
 803                };
 804
 805                let scroll_lines = (scroll_delta / self.cur_size.line_height) as i32;
 806
 807                self.events
 808                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
 809                self.events
 810                    .push_back(InternalEvent::UpdateSelection(position))
 811            }
 812        }
 813    }
 814
 815    fn drag_line_delta(&mut self, e: DragRegionEvent) -> Option<f32> {
 816        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
 817        let top = e.region.origin_y() + (self.cur_size.line_height * 2.);
 818        let bottom = e.region.lower_left().y() - (self.cur_size.line_height * 2.);
 819        let scroll_delta = if e.position.y() < top {
 820            (top - e.position.y()).powf(1.1)
 821        } else if e.position.y() > bottom {
 822            -((e.position.y() - bottom).powf(1.1))
 823        } else {
 824            return None; //Nothing to do
 825        };
 826        Some(scroll_delta)
 827    }
 828
 829    pub fn mouse_down(&mut self, e: &DownRegionEvent, origin: Vector2F) {
 830        let position = e.position.sub(origin);
 831        let point = mouse_point(position, self.cur_size, self.last_content.display_offset);
 832        let side = mouse_side(position, self.cur_size);
 833
 834        if self.mouse_mode(e.shift) {
 835            if let Some(bytes) = mouse_button_report(point, e, true, self.last_content.mode) {
 836                self.pty_tx.notify(bytes);
 837            }
 838        } else if e.button == MouseButton::Left {
 839            self.events.push_back(InternalEvent::SetSelection(Some((
 840                Selection::new(SelectionType::Simple, point, side),
 841                point,
 842            ))));
 843        }
 844    }
 845
 846    pub fn left_click(&mut self, e: &ClickRegionEvent, origin: Vector2F) {
 847        let position = e.position.sub(origin);
 848
 849        if !self.mouse_mode(e.shift) {
 850            let point = mouse_point(position, self.cur_size, self.last_content.display_offset);
 851            let side = mouse_side(position, self.cur_size);
 852
 853            let selection_type = match e.click_count {
 854                0 => return, //This is a release
 855                1 => Some(SelectionType::Simple),
 856                2 => Some(SelectionType::Semantic),
 857                3 => Some(SelectionType::Lines),
 858                _ => None,
 859            };
 860
 861            let selection =
 862                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
 863
 864            if let Some(sel) = selection {
 865                self.events
 866                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
 867            }
 868        }
 869    }
 870
 871    pub fn mouse_up(&mut self, e: &UpRegionEvent, origin: Vector2F) {
 872        let position = e.position.sub(origin);
 873        if self.mouse_mode(e.shift) {
 874            let point = mouse_point(position, self.cur_size, self.last_content.display_offset);
 875
 876            if let Some(bytes) = mouse_button_report(point, e, false, self.last_content.mode) {
 877                self.pty_tx.notify(bytes);
 878            }
 879        } else if e.button == MouseButton::Left {
 880            // Seems pretty standard to automatically copy on mouse_up for terminals,
 881            // so let's do that here
 882            self.copy();
 883        }
 884        self.last_mouse = None;
 885    }
 886
 887    ///Scroll the terminal
 888    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Vector2F) {
 889        if self.mouse_mode(e.shift) {
 890            //TODO: Currently this only sends the current scroll reports as they come in. Alacritty
 891            //Sends the *entire* scroll delta on *every* scroll event, only resetting it when
 892            //The scroll enters 'TouchPhase::Started'. Do I need to replicate this?
 893            //This would be consistent with a scroll model based on 'distance from origin'...
 894            let scroll_lines = (e.delta.y() / self.cur_size.line_height) as i32;
 895            let point = mouse_point(
 896                e.position.sub(origin),
 897                self.cur_size,
 898                self.last_content.display_offset,
 899            );
 900
 901            if let Some(scrolls) =
 902                scroll_report(point, scroll_lines as i32, e, self.last_content.mode)
 903            {
 904                for scroll in scrolls {
 905                    self.pty_tx.notify(scroll);
 906                }
 907            };
 908        } else if self
 909            .last_content
 910            .mode
 911            .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
 912            && !e.shift
 913        {
 914            //TODO: See above TODO, also applies here.
 915            let scroll_lines =
 916                ((e.delta.y() * ALACRITTY_SCROLL_MULTIPLIER) / self.cur_size.line_height) as i32;
 917
 918            self.pty_tx.notify(alt_scroll(scroll_lines))
 919        } else {
 920            let scroll_lines =
 921                ((e.delta.y() * ALACRITTY_SCROLL_MULTIPLIER) / self.cur_size.line_height) as i32;
 922            if scroll_lines != 0 {
 923                let scroll = AlacScroll::Delta(scroll_lines);
 924
 925                self.events.push_back(InternalEvent::Scroll(scroll));
 926            }
 927        }
 928    }
 929
 930    pub fn find_matches(
 931        &mut self,
 932        query: project::search::SearchQuery,
 933        cx: &mut ModelContext<Self>,
 934    ) -> Task<Vec<RangeInclusive<Point>>> {
 935        let term = self.term.clone();
 936        cx.background().spawn(async move {
 937            let searcher = match query {
 938                project::search::SearchQuery::Text { query, .. } => {
 939                    RegexSearch::new(query.as_ref())
 940                }
 941                project::search::SearchQuery::Regex { query, .. } => {
 942                    RegexSearch::new(query.as_ref())
 943                }
 944            };
 945
 946            if searcher.is_err() {
 947                return Vec::new();
 948            }
 949            let searcher = searcher.unwrap();
 950
 951            let term = term.lock();
 952
 953            make_search_matches(&term, &searcher).collect()
 954        })
 955    }
 956}
 957
 958impl Drop for Terminal {
 959    fn drop(&mut self) {
 960        self.pty_tx.0.send(Msg::Shutdown).ok();
 961    }
 962}
 963
 964impl Entity for Terminal {
 965    type Event = Event;
 966}
 967
 968fn make_selection(range: &RangeInclusive<Point>) -> Selection {
 969    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
 970    selection.update(*range.end(), AlacDirection::Right);
 971    selection
 972}
 973
 974/// Copied from alacritty/src/display/hint.rs HintMatches::visible_regex_matches()
 975/// Iterate over all visible regex matches.
 976fn make_search_matches<'a, T>(
 977    term: &'a Term<T>,
 978    regex: &'a RegexSearch,
 979) -> impl Iterator<Item = Match> + 'a {
 980    let viewport_start = Line(-(term.grid().display_offset() as i32));
 981    let viewport_end = viewport_start + term.bottommost_line();
 982    let mut start = term.line_search_left(Point::new(viewport_start, Column(0)));
 983    let mut end = term.line_search_right(Point::new(viewport_end, Column(0)));
 984    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
 985    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
 986
 987    RegexIter::new(start, end, AlacDirection::Right, term, regex)
 988        .skip_while(move |rm| rm.end().line < viewport_start)
 989        .take_while(move |rm| rm.start().line <= viewport_end)
 990}
 991
 992#[cfg(test)]
 993mod tests {
 994    pub mod terminal_test_context;
 995}
 996
 997//TODO Move this around and clean up the code
 998mod alacritty_unix {
 999    use alacritty_terminal::config::Program;
1000    use gpui::anyhow::{bail, Result};
1001
1002    use std::ffi::CStr;
1003    use std::mem::MaybeUninit;
1004    use std::ptr;
1005
1006    #[derive(Debug)]
1007    pub struct Passwd<'a> {
1008        _name: &'a str,
1009        _dir: &'a str,
1010        pub shell: &'a str,
1011    }
1012
1013    /// Return a Passwd struct with pointers into the provided buf.
1014    ///
1015    /// # Unsafety
1016    ///
1017    /// If `buf` is changed while `Passwd` is alive, bad thing will almost certainly happen.
1018    pub fn get_pw_entry(buf: &mut [i8; 1024]) -> Result<Passwd<'_>> {
1019        // Create zeroed passwd struct.
1020        let mut entry: MaybeUninit<libc::passwd> = MaybeUninit::uninit();
1021
1022        let mut res: *mut libc::passwd = ptr::null_mut();
1023
1024        // Try and read the pw file.
1025        let uid = unsafe { libc::getuid() };
1026        let status = unsafe {
1027            libc::getpwuid_r(
1028                uid,
1029                entry.as_mut_ptr(),
1030                buf.as_mut_ptr() as *mut _,
1031                buf.len(),
1032                &mut res,
1033            )
1034        };
1035        let entry = unsafe { entry.assume_init() };
1036
1037        if status < 0 {
1038            bail!("getpwuid_r failed");
1039        }
1040
1041        if res.is_null() {
1042            bail!("pw not found");
1043        }
1044
1045        // Sanity check.
1046        assert_eq!(entry.pw_uid, uid);
1047
1048        // Build a borrowed Passwd struct.
1049        Ok(Passwd {
1050            _name: unsafe { CStr::from_ptr(entry.pw_name).to_str().unwrap() },
1051            _dir: unsafe { CStr::from_ptr(entry.pw_dir).to_str().unwrap() },
1052            shell: unsafe { CStr::from_ptr(entry.pw_shell).to_str().unwrap() },
1053        })
1054    }
1055
1056    #[cfg(target_os = "macos")]
1057    pub fn _default_shell(pw: &Passwd<'_>) -> Program {
1058        let shell_name = pw.shell.rsplit('/').next().unwrap();
1059        let argv = vec![
1060            String::from("-c"),
1061            format!("exec -a -{} {}", shell_name, pw.shell),
1062        ];
1063
1064        Program::WithArgs {
1065            program: "/bin/bash".to_owned(),
1066            args: argv,
1067        }
1068    }
1069
1070    #[cfg(not(target_os = "macos"))]
1071    pub fn default_shell(pw: &Passwd<'_>) -> Program {
1072        Program::Just(env::var("SHELL").unwrap_or_else(|_| pw.shell.to_owned()))
1073    }
1074}