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