terminal.rs

   1pub mod mappings;
   2
   3pub use alacritty_terminal;
   4
   5pub mod terminal_settings;
   6
   7use alacritty_terminal::{
   8    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
   9    event_loop::{EventLoop, Msg, Notifier},
  10    grid::{Dimensions, Scroll as AlacScroll},
  11    index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
  12    selection::{Selection, SelectionRange, SelectionType},
  13    sync::FairMutex,
  14    term::{
  15        cell::Cell,
  16        search::{Match, RegexIter, RegexSearch},
  17        Config, RenderableCursor, TermMode,
  18    },
  19    tty::{self, setup_env},
  20    vte::ansi::{ClearMode, Handler, NamedPrivateMode, PrivateMode, Rgb},
  21    Term,
  22};
  23use anyhow::{bail, Result};
  24
  25use futures::{
  26    channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender},
  27    FutureExt,
  28};
  29
  30use mappings::mouse::{
  31    alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
  32    scroll_report,
  33};
  34
  35use collections::{HashMap, VecDeque};
  36use futures::StreamExt;
  37use procinfo::LocalProcessInfo;
  38use serde::{Deserialize, Serialize};
  39use settings::Settings;
  40use smol::channel::{Receiver, Sender};
  41use task::TaskId;
  42use terminal_settings::{AlternateScroll, Shell, TerminalBlink, TerminalSettings};
  43use theme::{ActiveTheme, Theme};
  44use util::truncate_and_trailoff;
  45
  46use std::{
  47    cmp::{self, min},
  48    fmt::Display,
  49    ops::{Deref, Index, RangeInclusive},
  50    path::PathBuf,
  51    sync::Arc,
  52    time::Duration,
  53};
  54use thiserror::Error;
  55
  56#[cfg(unix)]
  57use std::os::unix::prelude::AsRawFd;
  58
  59use gpui::{
  60    actions, black, px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla,
  61    Keystroke, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
  62    Pixels, Point, Rgba, ScrollWheelEvent, Size, Task, TouchPhase,
  63};
  64
  65use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
  66
  67actions!(
  68    terminal,
  69    [Clear, Copy, Paste, ShowCharacterPalette, SearchTest,]
  70);
  71
  72///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  73///Scroll multiplier that is set to 3 by default. This will be removed when I
  74///Implement scroll bars.
  75const SCROLL_MULTIPLIER: f32 = 4.;
  76const MAX_SEARCH_LINES: usize = 100;
  77const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
  78const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
  79const DEBUG_CELL_WIDTH: Pixels = px(5.);
  80const DEBUG_LINE_HEIGHT: Pixels = px(5.);
  81
  82///Upward flowing events, for changing the title and such
  83#[derive(Clone, Debug)]
  84pub enum Event {
  85    TitleChanged,
  86    BreadcrumbsChanged,
  87    CloseTerminal,
  88    Bell,
  89    Wakeup,
  90    BlinkChanged,
  91    SelectionsChanged,
  92    NewNavigationTarget(Option<MaybeNavigationTarget>),
  93    Open(MaybeNavigationTarget),
  94}
  95
  96#[derive(Clone, Debug)]
  97pub struct PathLikeTarget {
  98    /// File system path, absolute or relative, existing or not.
  99    /// Might have line and column number(s) attached as `file.rs:1:23`
 100    pub maybe_path: String,
 101    /// Current working directory of the terminal
 102    pub terminal_dir: Option<PathBuf>,
 103}
 104
 105/// A string inside terminal, potentially useful as a URI that can be opened.
 106#[derive(Clone, Debug)]
 107pub enum MaybeNavigationTarget {
 108    /// HTTP, git, etc. string determined by the [`URL_REGEX`] regex.
 109    Url(String),
 110    /// File system path, absolute or relative, existing or not.
 111    /// Might have line and column number(s) attached as `file.rs:1:23`
 112    PathLike(PathLikeTarget),
 113}
 114
 115#[derive(Clone)]
 116enum InternalEvent {
 117    ColorRequest(usize, Arc<dyn Fn(Rgb) -> String + Sync + Send + 'static>),
 118    Resize(TerminalSize),
 119    Clear,
 120    // FocusNextMatch,
 121    Scroll(AlacScroll),
 122    ScrollToAlacPoint(AlacPoint),
 123    SetSelection(Option<(Selection, AlacPoint)>),
 124    UpdateSelection(Point<Pixels>),
 125    // Adjusted mouse position, should open
 126    FindHyperlink(Point<Pixels>, bool),
 127    Copy,
 128}
 129
 130///A translation struct for Alacritty to communicate with us from their event loop
 131#[derive(Clone)]
 132pub struct ZedListener(UnboundedSender<AlacTermEvent>);
 133
 134impl EventListener for ZedListener {
 135    fn send_event(&self, event: AlacTermEvent) {
 136        self.0.unbounded_send(event).ok();
 137    }
 138}
 139
 140pub fn init(cx: &mut AppContext) {
 141    TerminalSettings::register(cx);
 142}
 143
 144#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
 145pub struct TerminalSize {
 146    pub cell_width: Pixels,
 147    pub line_height: Pixels,
 148    pub size: Size<Pixels>,
 149}
 150
 151impl TerminalSize {
 152    pub fn new(line_height: Pixels, cell_width: Pixels, size: Size<Pixels>) -> Self {
 153        TerminalSize {
 154            cell_width,
 155            line_height,
 156            size,
 157        }
 158    }
 159
 160    pub fn num_lines(&self) -> usize {
 161        (self.size.height / self.line_height).floor() as usize
 162    }
 163
 164    pub fn num_columns(&self) -> usize {
 165        (self.size.width / self.cell_width).floor() as usize
 166    }
 167
 168    pub fn height(&self) -> Pixels {
 169        self.size.height
 170    }
 171
 172    pub fn width(&self) -> Pixels {
 173        self.size.width
 174    }
 175
 176    pub fn cell_width(&self) -> Pixels {
 177        self.cell_width
 178    }
 179
 180    pub fn line_height(&self) -> Pixels {
 181        self.line_height
 182    }
 183}
 184
 185impl Default for TerminalSize {
 186    fn default() -> Self {
 187        TerminalSize::new(
 188            DEBUG_LINE_HEIGHT,
 189            DEBUG_CELL_WIDTH,
 190            Size {
 191                width: DEBUG_TERMINAL_WIDTH,
 192                height: DEBUG_TERMINAL_HEIGHT,
 193            },
 194        )
 195    }
 196}
 197
 198impl From<TerminalSize> for WindowSize {
 199    fn from(val: TerminalSize) -> Self {
 200        WindowSize {
 201            num_lines: val.num_lines() as u16,
 202            num_cols: val.num_columns() as u16,
 203            cell_width: f32::from(val.cell_width()) as u16,
 204            cell_height: f32::from(val.line_height()) as u16,
 205        }
 206    }
 207}
 208
 209impl Dimensions for TerminalSize {
 210    /// Note: this is supposed to be for the back buffer's length,
 211    /// but we exclusively use it to resize the terminal, which does not
 212    /// use this method. We still have to implement it for the trait though,
 213    /// hence, this comment.
 214    fn total_lines(&self) -> usize {
 215        self.screen_lines()
 216    }
 217
 218    fn screen_lines(&self) -> usize {
 219        self.num_lines()
 220    }
 221
 222    fn columns(&self) -> usize {
 223        self.num_columns()
 224    }
 225}
 226
 227#[derive(Error, Debug)]
 228pub struct TerminalError {
 229    pub directory: Option<PathBuf>,
 230    pub shell: Shell,
 231    pub source: std::io::Error,
 232}
 233
 234impl TerminalError {
 235    pub fn fmt_directory(&self) -> String {
 236        self.directory
 237            .clone()
 238            .map(|path| {
 239                match path
 240                    .into_os_string()
 241                    .into_string()
 242                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 243                {
 244                    Ok(s) => s,
 245                    Err(s) => s,
 246                }
 247            })
 248            .unwrap_or_else(|| {
 249                let default_dir =
 250                    dirs::home_dir().map(|buf| buf.into_os_string().to_string_lossy().to_string());
 251                match default_dir {
 252                    Some(dir) => format!("<none specified, using home directory> {}", dir),
 253                    None => "<none specified, could not find home directory>".to_string(),
 254                }
 255            })
 256    }
 257
 258    pub fn shell_to_string(&self) -> String {
 259        match &self.shell {
 260            Shell::System => "<system shell>".to_string(),
 261            Shell::Program(p) => p.to_string(),
 262            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 263        }
 264    }
 265
 266    pub fn fmt_shell(&self) -> String {
 267        match &self.shell {
 268            Shell::System => "<system defined shell>".to_string(),
 269            Shell::Program(s) => s.to_string(),
 270            Shell::WithArguments { program, args } => format!("{} {}", program, args.join(" ")),
 271        }
 272    }
 273}
 274
 275impl Display for TerminalError {
 276    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 277        let dir_string: String = self.fmt_directory();
 278        let shell = self.fmt_shell();
 279
 280        write!(
 281            f,
 282            "Working directory: {} Shell command: `{}`, IOError: {}",
 283            dir_string, shell, self.source
 284        )
 285    }
 286}
 287
 288pub struct SpawnTask {
 289    pub id: TaskId,
 290    pub label: String,
 291    pub command: String,
 292    pub args: Vec<String>,
 293    pub env: HashMap<String, String>,
 294}
 295
 296// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
 297const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
 298const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
 299
 300pub struct TerminalBuilder {
 301    terminal: Terminal,
 302    events_rx: UnboundedReceiver<AlacTermEvent>,
 303}
 304
 305impl TerminalBuilder {
 306    #[allow(clippy::too_many_arguments)]
 307    pub fn new(
 308        working_directory: Option<PathBuf>,
 309        task: Option<TaskState>,
 310        shell: Shell,
 311        env: HashMap<String, String>,
 312        blink_settings: Option<TerminalBlink>,
 313        alternate_scroll: AlternateScroll,
 314        max_scroll_history_lines: Option<usize>,
 315        window: AnyWindowHandle,
 316        completion_tx: Sender<()>,
 317    ) -> Result<TerminalBuilder> {
 318        let pty_options = {
 319            let alac_shell = match shell.clone() {
 320                Shell::System => None,
 321                Shell::Program(program) => {
 322                    Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
 323                }
 324                Shell::WithArguments { program, args } => {
 325                    Some(alacritty_terminal::tty::Shell::new(program, args))
 326                }
 327            };
 328
 329            alacritty_terminal::tty::Options {
 330                shell: alac_shell,
 331                working_directory: working_directory.clone(),
 332                hold: false,
 333            }
 334        };
 335
 336        // First, setup Alacritty's env
 337        setup_env();
 338
 339        // Then setup configured environment variables
 340        for (key, value) in env {
 341            std::env::set_var(key, value);
 342        }
 343        //TODO: Properly set the current locale,
 344        std::env::set_var("LC_ALL", "en_US.UTF-8");
 345        std::env::set_var("ZED_TERM", "true");
 346
 347        let scrolling_history = if task.is_some() {
 348            // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
 349            // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
 350            // cause excessive memory usage over time.
 351            MAX_SCROLL_HISTORY_LINES
 352        } else {
 353            max_scroll_history_lines
 354                .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
 355                .min(MAX_SCROLL_HISTORY_LINES)
 356        };
 357        let config = Config {
 358            scrolling_history,
 359            ..Config::default()
 360        };
 361
 362        //Spawn a task so the Alacritty EventLoop can communicate with us in a view context
 363        //TODO: Remove with a bounded sender which can be dispatched on &self
 364        let (events_tx, events_rx) = unbounded();
 365        //Set up the terminal...
 366        let mut term = Term::new(
 367            config,
 368            &TerminalSize::default(),
 369            ZedListener(events_tx.clone()),
 370        );
 371
 372        //Start off blinking if we need to
 373        if let Some(TerminalBlink::On) = blink_settings {
 374            term.set_private_mode(PrivateMode::Named(NamedPrivateMode::BlinkingCursor));
 375        }
 376
 377        //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
 378        if let AlternateScroll::Off = alternate_scroll {
 379            term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
 380        }
 381
 382        let term = Arc::new(FairMutex::new(term));
 383
 384        //Setup the pty...
 385        let pty = match tty::new(
 386            &pty_options,
 387            TerminalSize::default().into(),
 388            window.window_id().as_u64(),
 389        ) {
 390            Ok(pty) => pty,
 391            Err(error) => {
 392                bail!(TerminalError {
 393                    directory: working_directory,
 394                    shell,
 395                    source: error,
 396                });
 397            }
 398        };
 399
 400        #[cfg(unix)]
 401        let (fd, shell_pid) = (pty.file().as_raw_fd(), pty.child().id());
 402
 403        // todo("windows")
 404        #[cfg(windows)]
 405        let (fd, shell_pid) = (-1, 0);
 406
 407        //And connect them together
 408        let event_loop = EventLoop::new(
 409            term.clone(),
 410            ZedListener(events_tx.clone()),
 411            pty,
 412            pty_options.hold,
 413            false,
 414        )?;
 415
 416        //Kick things off
 417        let pty_tx = event_loop.channel();
 418        let _io_thread = event_loop.spawn(); // DANGER
 419
 420        let url_regex = RegexSearch::new(r#"(ipfs:|ipns:|magnet:|mailto:|gemini://|gopher://|https://|http://|news:|file://|git://|ssh:|ftp://)[^\u{0000}-\u{001F}\u{007F}-\u{009F}<>"\s{-}\^⟨⟩`]+"#).unwrap();
 421        let word_regex = RegexSearch::new(r#"[\$\+\w.\[\]:/@\-~]+"#).unwrap();
 422
 423        let terminal = Terminal {
 424            task,
 425            pty_tx: Notifier(pty_tx),
 426            completion_tx,
 427            term,
 428            events: VecDeque::with_capacity(10), //Should never get this high.
 429            last_content: Default::default(),
 430            last_mouse: None,
 431            matches: Vec::new(),
 432            selection_head: None,
 433            shell_fd: fd as u32,
 434            shell_pid,
 435            foreground_process_info: None,
 436            breadcrumb_text: String::new(),
 437            scroll_px: px(0.),
 438            last_mouse_position: None,
 439            next_link_id: 0,
 440            selection_phase: SelectionPhase::Ended,
 441            cmd_pressed: false,
 442            hovered_word: false,
 443            url_regex,
 444            word_regex,
 445        };
 446
 447        Ok(TerminalBuilder {
 448            terminal,
 449            events_rx,
 450        })
 451    }
 452
 453    pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
 454        //Event loop
 455        cx.spawn(|terminal, mut cx| async move {
 456            while let Some(event) = self.events_rx.next().await {
 457                terminal.update(&mut cx, |terminal, cx| {
 458                    //Process the first event immediately for lowered latency
 459                    terminal.process_event(&event, cx);
 460                })?;
 461
 462                'outer: loop {
 463                    let mut events = Vec::new();
 464                    let mut timer = cx
 465                        .background_executor()
 466                        .timer(Duration::from_millis(4))
 467                        .fuse();
 468                    let mut wakeup = false;
 469                    loop {
 470                        futures::select_biased! {
 471                            _ = timer => break,
 472                            event = self.events_rx.next() => {
 473                                if let Some(event) = event {
 474                                    if matches!(event, AlacTermEvent::Wakeup) {
 475                                        wakeup = true;
 476                                    } else {
 477                                        events.push(event);
 478                                    }
 479
 480                                    if events.len() > 100 {
 481                                        break;
 482                                    }
 483                                } else {
 484                                    break;
 485                                }
 486                            },
 487                        }
 488                    }
 489
 490                    if events.is_empty() && !wakeup {
 491                        smol::future::yield_now().await;
 492                        break 'outer;
 493                    }
 494
 495                    terminal.update(&mut cx, |this, cx| {
 496                        if wakeup {
 497                            this.process_event(&AlacTermEvent::Wakeup, cx);
 498                        }
 499
 500                        for event in events {
 501                            this.process_event(&event, cx);
 502                        }
 503                    })?;
 504                    smol::future::yield_now().await;
 505                }
 506            }
 507
 508            anyhow::Ok(())
 509        })
 510        .detach();
 511
 512        self.terminal
 513    }
 514}
 515
 516#[derive(Debug, Clone, Deserialize, Serialize)]
 517pub struct IndexedCell {
 518    pub point: AlacPoint,
 519    pub cell: Cell,
 520}
 521
 522impl Deref for IndexedCell {
 523    type Target = Cell;
 524
 525    #[inline]
 526    fn deref(&self) -> &Cell {
 527        &self.cell
 528    }
 529}
 530
 531// TODO: Un-pub
 532#[derive(Clone)]
 533pub struct TerminalContent {
 534    pub cells: Vec<IndexedCell>,
 535    pub mode: TermMode,
 536    pub display_offset: usize,
 537    pub selection_text: Option<String>,
 538    pub selection: Option<SelectionRange>,
 539    pub cursor: RenderableCursor,
 540    pub cursor_char: char,
 541    pub size: TerminalSize,
 542    pub last_hovered_word: Option<HoveredWord>,
 543}
 544
 545#[derive(Clone)]
 546pub struct HoveredWord {
 547    pub word: String,
 548    pub word_match: RangeInclusive<AlacPoint>,
 549    pub id: usize,
 550}
 551
 552impl Default for TerminalContent {
 553    fn default() -> Self {
 554        TerminalContent {
 555            cells: Default::default(),
 556            mode: Default::default(),
 557            display_offset: Default::default(),
 558            selection_text: Default::default(),
 559            selection: Default::default(),
 560            cursor: RenderableCursor {
 561                shape: alacritty_terminal::vte::ansi::CursorShape::Block,
 562                point: AlacPoint::new(Line(0), Column(0)),
 563            },
 564            cursor_char: Default::default(),
 565            size: Default::default(),
 566            last_hovered_word: None,
 567        }
 568    }
 569}
 570
 571#[derive(PartialEq, Eq)]
 572pub enum SelectionPhase {
 573    Selecting,
 574    Ended,
 575}
 576
 577pub struct Terminal {
 578    pty_tx: Notifier,
 579    completion_tx: Sender<()>,
 580    term: Arc<FairMutex<Term<ZedListener>>>,
 581    events: VecDeque<InternalEvent>,
 582    /// This is only used for mouse mode cell change detection
 583    last_mouse: Option<(AlacPoint, AlacDirection)>,
 584    /// This is only used for terminal hovered word checking
 585    last_mouse_position: Option<Point<Pixels>>,
 586    pub matches: Vec<RangeInclusive<AlacPoint>>,
 587    pub last_content: TerminalContent,
 588    pub selection_head: Option<AlacPoint>,
 589    pub breadcrumb_text: String,
 590    shell_pid: u32,
 591    shell_fd: u32,
 592    pub foreground_process_info: Option<LocalProcessInfo>,
 593    scroll_px: Pixels,
 594    next_link_id: usize,
 595    selection_phase: SelectionPhase,
 596    cmd_pressed: bool,
 597    hovered_word: bool,
 598    url_regex: RegexSearch,
 599    word_regex: RegexSearch,
 600    task: Option<TaskState>,
 601}
 602
 603pub struct TaskState {
 604    pub id: TaskId,
 605    pub label: String,
 606    pub completed: bool,
 607    pub completion_rx: Receiver<()>,
 608}
 609
 610impl Terminal {
 611    fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
 612        match event {
 613            AlacTermEvent::Title(title) => {
 614                self.breadcrumb_text = title.to_string();
 615                cx.emit(Event::BreadcrumbsChanged);
 616            }
 617            AlacTermEvent::ResetTitle => {
 618                self.breadcrumb_text = String::new();
 619                cx.emit(Event::BreadcrumbsChanged);
 620            }
 621            AlacTermEvent::ClipboardStore(_, data) => {
 622                cx.write_to_clipboard(ClipboardItem::new(data.to_string()))
 623            }
 624            AlacTermEvent::ClipboardLoad(_, format) => self.write_to_pty(format(
 625                &cx.read_from_clipboard()
 626                    .map(|ci| ci.text().to_string())
 627                    .unwrap_or_else(|| "".to_string()),
 628            )),
 629            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.clone()),
 630            AlacTermEvent::TextAreaSizeRequest(format) => {
 631                self.write_to_pty(format(self.last_content.size.into()))
 632            }
 633            AlacTermEvent::CursorBlinkingChange => {
 634                cx.emit(Event::BlinkChanged);
 635            }
 636            AlacTermEvent::Bell => {
 637                cx.emit(Event::Bell);
 638            }
 639            AlacTermEvent::Exit => match &mut self.task {
 640                Some(task) => {
 641                    task.completed = true;
 642                    self.completion_tx.try_send(()).ok();
 643                }
 644                None => cx.emit(Event::CloseTerminal),
 645            },
 646            AlacTermEvent::MouseCursorDirty => {
 647                //NOOP, Handled in render
 648            }
 649            AlacTermEvent::Wakeup => {
 650                cx.emit(Event::Wakeup);
 651
 652                if self.update_process_info() {
 653                    cx.emit(Event::TitleChanged);
 654                }
 655            }
 656            AlacTermEvent::ColorRequest(idx, fun_ptr) => {
 657                self.events
 658                    .push_back(InternalEvent::ColorRequest(*idx, fun_ptr.clone()));
 659            }
 660        }
 661    }
 662
 663    pub fn selection_started(&self) -> bool {
 664        self.selection_phase == SelectionPhase::Selecting
 665    }
 666
 667    /// Updates the cached process info, returns whether the Zed-relevant info has changed
 668    fn update_process_info(&mut self) -> bool {
 669        #[cfg(unix)]
 670        let mut pid = unsafe { libc::tcgetpgrp(self.shell_fd as i32) };
 671        // todo("windows")
 672        #[cfg(windows)]
 673        let mut pid = unsafe { windows::Win32::System::Threading::GetCurrentProcessId() } as i32;
 674        if pid < 0 {
 675            pid = self.shell_pid as i32;
 676        }
 677
 678        if let Some(process_info) = LocalProcessInfo::with_root_pid(pid as u32) {
 679            let res = self
 680                .foreground_process_info
 681                .as_ref()
 682                .map(|old_info| {
 683                    process_info.cwd != old_info.cwd || process_info.name != old_info.name
 684                })
 685                .unwrap_or(true);
 686
 687            self.foreground_process_info = Some(process_info.clone());
 688
 689            res
 690        } else {
 691            false
 692        }
 693    }
 694
 695    fn get_cwd(&self) -> Option<PathBuf> {
 696        self.foreground_process_info
 697            .as_ref()
 698            .map(|info| info.cwd.clone())
 699    }
 700
 701    ///Takes events from Alacritty and translates them to behavior on this view
 702    fn process_terminal_event(
 703        &mut self,
 704        event: &InternalEvent,
 705        term: &mut Term<ZedListener>,
 706        cx: &mut ModelContext<Self>,
 707    ) {
 708        match event {
 709            InternalEvent::ColorRequest(index, format) => {
 710                let color = term.colors()[*index].unwrap_or_else(|| {
 711                    to_alac_rgb(get_color_at_index(*index, cx.theme().as_ref()))
 712                });
 713                self.write_to_pty(format(color))
 714            }
 715            InternalEvent::Resize(mut new_size) => {
 716                new_size.size.height = cmp::max(new_size.line_height, new_size.height());
 717                new_size.size.width = cmp::max(new_size.cell_width, new_size.width());
 718
 719                self.last_content.size = new_size;
 720
 721                self.pty_tx.0.send(Msg::Resize(new_size.into())).ok();
 722
 723                term.resize(new_size);
 724            }
 725            InternalEvent::Clear => {
 726                // Clear back buffer
 727                term.clear_screen(ClearMode::Saved);
 728
 729                let cursor = term.grid().cursor.point;
 730
 731                // Clear the lines above
 732                term.grid_mut().reset_region(..cursor.line);
 733
 734                // Copy the current line up
 735                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 736                    .iter()
 737                    .cloned()
 738                    .enumerate()
 739                    .collect::<Vec<(usize, Cell)>>();
 740
 741                for (i, cell) in line {
 742                    term.grid_mut()[Line(0)][Column(i)] = cell;
 743                }
 744
 745                // Reset the cursor
 746                term.grid_mut().cursor.point =
 747                    AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
 748                let new_cursor = term.grid().cursor.point;
 749
 750                // Clear the lines below the new cursor
 751                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 752                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 753                }
 754
 755                cx.emit(Event::Wakeup);
 756            }
 757            InternalEvent::Scroll(scroll) => {
 758                term.scroll_display(*scroll);
 759                self.refresh_hovered_word();
 760            }
 761            InternalEvent::SetSelection(selection) => {
 762                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 763
 764                if let Some((_, head)) = selection {
 765                    self.selection_head = Some(*head);
 766                }
 767                cx.emit(Event::SelectionsChanged)
 768            }
 769            InternalEvent::UpdateSelection(position) => {
 770                if let Some(mut selection) = term.selection.take() {
 771                    let (point, side) = grid_point_and_side(
 772                        *position,
 773                        self.last_content.size,
 774                        term.grid().display_offset(),
 775                    );
 776
 777                    selection.update(point, side);
 778                    term.selection = Some(selection);
 779
 780                    self.selection_head = Some(point);
 781                    cx.emit(Event::SelectionsChanged)
 782                }
 783            }
 784
 785            InternalEvent::Copy => {
 786                if let Some(txt) = term.selection_to_string() {
 787                    cx.write_to_clipboard(ClipboardItem::new(txt))
 788                }
 789            }
 790            InternalEvent::ScrollToAlacPoint(point) => {
 791                term.scroll_to_point(*point);
 792                self.refresh_hovered_word();
 793            }
 794            InternalEvent::FindHyperlink(position, open) => {
 795                let prev_hovered_word = self.last_content.last_hovered_word.take();
 796
 797                let point = grid_point(
 798                    *position,
 799                    self.last_content.size,
 800                    term.grid().display_offset(),
 801                )
 802                .grid_clamp(term, Boundary::Grid);
 803
 804                let link = term.grid().index(point).hyperlink();
 805                let found_word = if link.is_some() {
 806                    let mut min_index = point;
 807                    loop {
 808                        let new_min_index = min_index.sub(term, Boundary::Cursor, 1);
 809                        if new_min_index == min_index {
 810                            break;
 811                        } else if term.grid().index(new_min_index).hyperlink() != link {
 812                            break;
 813                        } else {
 814                            min_index = new_min_index
 815                        }
 816                    }
 817
 818                    let mut max_index = point;
 819                    loop {
 820                        let new_max_index = max_index.add(term, Boundary::Cursor, 1);
 821                        if new_max_index == max_index {
 822                            break;
 823                        } else if term.grid().index(new_max_index).hyperlink() != link {
 824                            break;
 825                        } else {
 826                            max_index = new_max_index
 827                        }
 828                    }
 829
 830                    let url = link.unwrap().uri().to_owned();
 831                    let url_match = min_index..=max_index;
 832
 833                    Some((url, true, url_match))
 834                } else if let Some(word_match) = regex_match_at(term, point, &mut self.word_regex) {
 835                    let maybe_url_or_path =
 836                        term.bounds_to_string(*word_match.start(), *word_match.end());
 837                    let original_match = word_match.clone();
 838                    let (sanitized_match, sanitized_word) =
 839                        if maybe_url_or_path.starts_with('[') && maybe_url_or_path.ends_with(']') {
 840                            (
 841                                Match::new(
 842                                    word_match.start().add(term, Boundary::Cursor, 1),
 843                                    word_match.end().sub(term, Boundary::Cursor, 1),
 844                                ),
 845                                maybe_url_or_path[1..maybe_url_or_path.len() - 1].to_owned(),
 846                            )
 847                        } else {
 848                            (word_match, maybe_url_or_path)
 849                        };
 850
 851                    let is_url = match regex_match_at(term, point, &mut self.url_regex) {
 852                        Some(url_match) => {
 853                            // `]` is a valid symbol in the `file://` URL, so the regex match will include it
 854                            // consider that when ensuring that the URL match is the same as the original word
 855                            if sanitized_match != original_match {
 856                                url_match.start() == sanitized_match.start()
 857                                    && url_match.end() == original_match.end()
 858                            } else {
 859                                url_match == sanitized_match
 860                            }
 861                        }
 862                        None => false,
 863                    };
 864                    Some((sanitized_word, is_url, sanitized_match))
 865                } else {
 866                    None
 867                };
 868
 869                match found_word {
 870                    Some((maybe_url_or_path, is_url, url_match)) => {
 871                        if *open {
 872                            let target = if is_url {
 873                                MaybeNavigationTarget::Url(maybe_url_or_path)
 874                            } else {
 875                                MaybeNavigationTarget::PathLike(PathLikeTarget {
 876                                    maybe_path: maybe_url_or_path,
 877                                    terminal_dir: self.get_cwd(),
 878                                })
 879                            };
 880                            cx.emit(Event::Open(target));
 881                        } else {
 882                            self.update_selected_word(
 883                                prev_hovered_word,
 884                                url_match,
 885                                maybe_url_or_path,
 886                                is_url,
 887                                cx,
 888                            );
 889                        }
 890                        self.hovered_word = true;
 891                    }
 892                    None => {
 893                        if self.hovered_word {
 894                            cx.emit(Event::NewNavigationTarget(None));
 895                        }
 896                        self.hovered_word = false;
 897                    }
 898                }
 899            }
 900        }
 901    }
 902
 903    fn update_selected_word(
 904        &mut self,
 905        prev_word: Option<HoveredWord>,
 906        word_match: RangeInclusive<AlacPoint>,
 907        word: String,
 908        is_url: bool,
 909        cx: &mut ModelContext<Self>,
 910    ) {
 911        if let Some(prev_word) = prev_word {
 912            if prev_word.word == word && prev_word.word_match == word_match {
 913                self.last_content.last_hovered_word = Some(HoveredWord {
 914                    word,
 915                    word_match,
 916                    id: prev_word.id,
 917                });
 918                return;
 919            }
 920        }
 921
 922        self.last_content.last_hovered_word = Some(HoveredWord {
 923            word: word.clone(),
 924            word_match,
 925            id: self.next_link_id(),
 926        });
 927        let navigation_target = if is_url {
 928            MaybeNavigationTarget::Url(word)
 929        } else {
 930            MaybeNavigationTarget::PathLike(PathLikeTarget {
 931                maybe_path: word,
 932                terminal_dir: self.get_cwd(),
 933            })
 934        };
 935        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
 936    }
 937
 938    fn next_link_id(&mut self) -> usize {
 939        let res = self.next_link_id;
 940        self.next_link_id = self.next_link_id.wrapping_add(1);
 941        res
 942    }
 943
 944    pub fn last_content(&self) -> &TerminalContent {
 945        &self.last_content
 946    }
 947
 948    //To test:
 949    //- Activate match on terminal (scrolling and selection)
 950    //- Editor search snapping behavior
 951
 952    pub fn activate_match(&mut self, index: usize) {
 953        if let Some(search_match) = self.matches.get(index).cloned() {
 954            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
 955
 956            self.events
 957                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
 958        }
 959    }
 960
 961    pub fn select_matches(&mut self, matches: Vec<RangeInclusive<AlacPoint>>) {
 962        let matches_to_select = self
 963            .matches
 964            .iter()
 965            .filter(|self_match| matches.contains(self_match))
 966            .cloned()
 967            .collect::<Vec<_>>();
 968        for match_to_select in matches_to_select {
 969            self.set_selection(Some((
 970                make_selection(&match_to_select),
 971                *match_to_select.end(),
 972            )));
 973        }
 974    }
 975
 976    pub fn select_all(&mut self) {
 977        let term = self.term.lock();
 978        let start = AlacPoint::new(term.topmost_line(), Column(0));
 979        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
 980        drop(term);
 981        self.set_selection(Some((make_selection(&(start..=end)), end)));
 982    }
 983
 984    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
 985        self.events
 986            .push_back(InternalEvent::SetSelection(selection));
 987    }
 988
 989    pub fn copy(&mut self) {
 990        self.events.push_back(InternalEvent::Copy);
 991    }
 992
 993    pub fn clear(&mut self) {
 994        self.events.push_back(InternalEvent::Clear)
 995    }
 996
 997    ///Resize the terminal and the PTY.
 998    pub fn set_size(&mut self, new_size: TerminalSize) {
 999        self.events.push_back(InternalEvent::Resize(new_size))
1000    }
1001
1002    ///Write the Input payload to the tty.
1003    fn write_to_pty(&self, input: String) {
1004        self.pty_tx.notify(input.into_bytes());
1005    }
1006
1007    fn write_bytes_to_pty(&self, input: Vec<u8>) {
1008        self.pty_tx.notify(input);
1009    }
1010
1011    pub fn input(&mut self, input: String) {
1012        self.events
1013            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1014        self.events.push_back(InternalEvent::SetSelection(None));
1015
1016        self.write_to_pty(input);
1017    }
1018
1019    pub fn input_bytes(&mut self, input: Vec<u8>) {
1020        self.events
1021            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1022        self.events.push_back(InternalEvent::SetSelection(None));
1023
1024        self.write_bytes_to_pty(input);
1025    }
1026
1027    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1028        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1029        if let Some(esc) = esc {
1030            self.input(esc);
1031            true
1032        } else {
1033            false
1034        }
1035    }
1036
1037    pub fn try_modifiers_change(&mut self, modifiers: &Modifiers) -> bool {
1038        let changed = self.cmd_pressed != modifiers.command;
1039        if !self.cmd_pressed && modifiers.command {
1040            self.refresh_hovered_word();
1041        }
1042        self.cmd_pressed = modifiers.command;
1043        changed
1044    }
1045
1046    ///Paste text into the terminal
1047    pub fn paste(&mut self, text: &str) {
1048        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1049            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1050        } else {
1051            text.replace("\r\n", "\r").replace('\n', "\r")
1052        };
1053
1054        self.input(paste_text);
1055    }
1056
1057    pub fn sync(&mut self, cx: &mut ModelContext<Self>) {
1058        let term = self.term.clone();
1059        let mut terminal = term.lock_unfair();
1060        //Note that the ordering of events matters for event processing
1061        while let Some(e) = self.events.pop_front() {
1062            self.process_terminal_event(&e, &mut terminal, cx)
1063        }
1064
1065        self.last_content = Self::make_content(&terminal, &self.last_content);
1066    }
1067
1068    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1069        let content = term.renderable_content();
1070        TerminalContent {
1071            cells: content
1072                .display_iter
1073                //TODO: Add this once there's a way to retain empty lines
1074                // .filter(|ic| {
1075                //     !ic.flags.contains(Flags::HIDDEN)
1076                //         && !(ic.bg == Named(NamedColor::Background)
1077                //             && ic.c == ' '
1078                //             && !ic.flags.contains(Flags::INVERSE))
1079                // })
1080                .map(|ic| IndexedCell {
1081                    point: ic.point,
1082                    cell: ic.cell.clone(),
1083                })
1084                .collect::<Vec<IndexedCell>>(),
1085            mode: content.mode,
1086            display_offset: content.display_offset,
1087            selection_text: term.selection_to_string(),
1088            selection: content.selection,
1089            cursor: content.cursor,
1090            cursor_char: term.grid()[content.cursor.point].c,
1091            size: last_content.size,
1092            last_hovered_word: last_content.last_hovered_word.clone(),
1093        }
1094    }
1095
1096    pub fn focus_in(&self) {
1097        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1098            self.write_to_pty("\x1b[I".to_string());
1099        }
1100    }
1101
1102    pub fn focus_out(&mut self) {
1103        self.last_mouse_position = None;
1104        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1105            self.write_to_pty("\x1b[O".to_string());
1106        }
1107    }
1108
1109    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1110        match self.last_mouse {
1111            Some((old_point, old_side)) => {
1112                if old_point == point && old_side == side {
1113                    false
1114                } else {
1115                    self.last_mouse = Some((point, side));
1116                    true
1117                }
1118            }
1119            None => {
1120                self.last_mouse = Some((point, side));
1121                true
1122            }
1123        }
1124    }
1125
1126    pub fn mouse_mode(&self, shift: bool) -> bool {
1127        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1128    }
1129
1130    pub fn mouse_move(&mut self, e: &MouseMoveEvent, origin: Point<Pixels>) {
1131        let position = e.position - origin;
1132        self.last_mouse_position = Some(position);
1133        if self.mouse_mode(e.modifiers.shift) {
1134            let (point, side) = grid_point_and_side(
1135                position,
1136                self.last_content.size,
1137                self.last_content.display_offset,
1138            );
1139
1140            if self.mouse_changed(point, side) {
1141                if let Some(bytes) = mouse_moved_report(point, e, self.last_content.mode) {
1142                    self.pty_tx.notify(bytes);
1143                }
1144            }
1145        } else if self.cmd_pressed {
1146            self.word_from_position(Some(position));
1147        }
1148    }
1149
1150    fn word_from_position(&mut self, position: Option<Point<Pixels>>) {
1151        if self.selection_phase == SelectionPhase::Selecting {
1152            self.last_content.last_hovered_word = None;
1153        } else if let Some(position) = position {
1154            self.events
1155                .push_back(InternalEvent::FindHyperlink(position, false));
1156        }
1157    }
1158
1159    pub fn mouse_drag(
1160        &mut self,
1161        e: &MouseMoveEvent,
1162        origin: Point<Pixels>,
1163        region: Bounds<Pixels>,
1164    ) {
1165        let position = e.position - origin;
1166        self.last_mouse_position = Some(position);
1167
1168        if !self.mouse_mode(e.modifiers.shift) {
1169            self.selection_phase = SelectionPhase::Selecting;
1170            // Alacritty has the same ordering, of first updating the selection
1171            // then scrolling 15ms later
1172            self.events
1173                .push_back(InternalEvent::UpdateSelection(position));
1174
1175            // Doesn't make sense to scroll the alt screen
1176            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1177                let scroll_delta = match self.drag_line_delta(e, region) {
1178                    Some(value) => value,
1179                    None => return,
1180                };
1181
1182                let scroll_lines = (scroll_delta / self.last_content.size.line_height) as i32;
1183
1184                self.events
1185                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1186            }
1187        }
1188    }
1189
1190    fn drag_line_delta(&mut self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<Pixels> {
1191        //TODO: Why do these need to be doubled? Probably the same problem that the IME has
1192        let top = region.origin.y + (self.last_content.size.line_height * 2.);
1193        let bottom = region.lower_left().y - (self.last_content.size.line_height * 2.);
1194        let scroll_delta = if e.position.y < top {
1195            (top - e.position.y).pow(1.1)
1196        } else if e.position.y > bottom {
1197            -((e.position.y - bottom).pow(1.1))
1198        } else {
1199            return None; //Nothing to do
1200        };
1201        Some(scroll_delta)
1202    }
1203
1204    pub fn mouse_down(&mut self, e: &MouseDownEvent, origin: Point<Pixels>) {
1205        let position = e.position - origin;
1206        let point = grid_point(
1207            position,
1208            self.last_content.size,
1209            self.last_content.display_offset,
1210        );
1211
1212        if self.mouse_mode(e.modifiers.shift) {
1213            if let Some(bytes) =
1214                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1215            {
1216                self.pty_tx.notify(bytes);
1217            }
1218        } else if e.button == MouseButton::Left {
1219            let position = e.position - origin;
1220            let (point, side) = grid_point_and_side(
1221                position,
1222                self.last_content.size,
1223                self.last_content.display_offset,
1224            );
1225
1226            let selection_type = match e.click_count {
1227                0 => return, //This is a release
1228                1 => Some(SelectionType::Simple),
1229                2 => Some(SelectionType::Semantic),
1230                3 => Some(SelectionType::Lines),
1231                _ => None,
1232            };
1233
1234            let selection =
1235                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
1236
1237            if let Some(sel) = selection {
1238                self.events
1239                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
1240            }
1241        }
1242    }
1243
1244    pub fn mouse_up(
1245        &mut self,
1246        e: &MouseUpEvent,
1247        origin: Point<Pixels>,
1248        cx: &mut ModelContext<Self>,
1249    ) {
1250        let setting = TerminalSettings::get_global(cx);
1251
1252        let position = e.position - origin;
1253        if self.mouse_mode(e.modifiers.shift) {
1254            let point = grid_point(
1255                position,
1256                self.last_content.size,
1257                self.last_content.display_offset,
1258            );
1259
1260            if let Some(bytes) =
1261                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1262            {
1263                self.pty_tx.notify(bytes);
1264            }
1265        } else {
1266            if e.button == MouseButton::Left && setting.copy_on_select {
1267                self.copy();
1268            }
1269
1270            //Hyperlinks
1271            if self.selection_phase == SelectionPhase::Ended {
1272                let mouse_cell_index = content_index_for_mouse(position, &self.last_content.size);
1273                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1274                    cx.open_url(link.uri());
1275                } else if self.cmd_pressed {
1276                    self.events
1277                        .push_back(InternalEvent::FindHyperlink(position, true));
1278                }
1279            }
1280        }
1281
1282        self.selection_phase = SelectionPhase::Ended;
1283        self.last_mouse = None;
1284    }
1285
1286    ///Scroll the terminal
1287    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent, origin: Point<Pixels>) {
1288        let mouse_mode = self.mouse_mode(e.shift);
1289
1290        if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1291            if mouse_mode {
1292                let point = grid_point(
1293                    e.position - origin,
1294                    self.last_content.size,
1295                    self.last_content.display_offset,
1296                );
1297
1298                if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1299                {
1300                    for scroll in scrolls {
1301                        self.pty_tx.notify(scroll);
1302                    }
1303                };
1304            } else if self
1305                .last_content
1306                .mode
1307                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1308                && !e.shift
1309            {
1310                self.pty_tx.notify(alt_scroll(scroll_lines))
1311            } else {
1312                if scroll_lines != 0 {
1313                    let scroll = AlacScroll::Delta(scroll_lines);
1314
1315                    self.events.push_back(InternalEvent::Scroll(scroll));
1316                }
1317            }
1318        }
1319    }
1320
1321    fn refresh_hovered_word(&mut self) {
1322        self.word_from_position(self.last_mouse_position);
1323    }
1324
1325    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1326        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1327        let line_height = self.last_content.size.line_height;
1328        match e.touch_phase {
1329            /* Reset scroll state on started */
1330            TouchPhase::Started => {
1331                self.scroll_px = px(0.);
1332                None
1333            }
1334            /* Calculate the appropriate scroll lines */
1335            TouchPhase::Moved => {
1336                let old_offset = (self.scroll_px / line_height) as i32;
1337
1338                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1339
1340                let new_offset = (self.scroll_px / line_height) as i32;
1341
1342                // Whenever we hit the edges, reset our stored scroll to 0
1343                // so we can respond to changes in direction quickly
1344                self.scroll_px %= self.last_content.size.height();
1345
1346                Some(new_offset - old_offset)
1347            }
1348            TouchPhase::Ended => None,
1349        }
1350    }
1351
1352    pub fn find_matches(
1353        &mut self,
1354        mut searcher: RegexSearch,
1355        cx: &mut ModelContext<Self>,
1356    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1357        let term = self.term.clone();
1358        cx.background_executor().spawn(async move {
1359            let term = term.lock();
1360
1361            all_search_matches(&term, &mut searcher).collect()
1362        })
1363    }
1364
1365    pub fn title(&self, truncate: bool) -> String {
1366        const MAX_CHARS: usize = 25;
1367        match &self.task {
1368            Some(task_state) => truncate_and_trailoff(&task_state.label, MAX_CHARS),
1369            None => self
1370                .foreground_process_info
1371                .as_ref()
1372                .map(|fpi| {
1373                    let process_file = fpi
1374                        .cwd
1375                        .file_name()
1376                        .map(|name| name.to_string_lossy().to_string())
1377                        .unwrap_or_default();
1378                    let process_name = format!(
1379                        "{}{}",
1380                        fpi.name,
1381                        if fpi.argv.len() >= 1 {
1382                            format!(" {}", (fpi.argv[1..]).join(" "))
1383                        } else {
1384                            "".to_string()
1385                        }
1386                    );
1387                    let (process_file, process_name) = if truncate {
1388                        (
1389                            truncate_and_trailoff(&process_file, MAX_CHARS),
1390                            truncate_and_trailoff(&process_name, MAX_CHARS),
1391                        )
1392                    } else {
1393                        (process_file, process_name)
1394                    };
1395                    format!("{process_file}{process_name}")
1396                })
1397                .unwrap_or_else(|| "Terminal".to_string()),
1398        }
1399    }
1400
1401    pub fn can_navigate_to_selected_word(&self) -> bool {
1402        self.cmd_pressed && self.hovered_word
1403    }
1404
1405    pub fn task(&self) -> Option<&TaskState> {
1406        self.task.as_ref()
1407    }
1408
1409    pub fn wait_for_completed_task(&self, cx: &mut AppContext) -> Task<()> {
1410        match self.task() {
1411            Some(task) => {
1412                if task.completed {
1413                    Task::ready(())
1414                } else {
1415                    let mut completion_receiver = task.completion_rx.clone();
1416                    cx.spawn(|_| async move {
1417                        completion_receiver.next().await;
1418                    })
1419                }
1420            }
1421            None => Task::ready(()),
1422        }
1423    }
1424}
1425
1426impl Drop for Terminal {
1427    fn drop(&mut self) {
1428        self.pty_tx.0.send(Msg::Shutdown).ok();
1429    }
1430}
1431
1432impl EventEmitter<Event> for Terminal {}
1433
1434/// Based on alacritty/src/display/hint.rs > regex_match_at
1435/// Retrieve the match, if the specified point is inside the content matching the regex.
1436fn regex_match_at<T>(term: &Term<T>, point: AlacPoint, regex: &mut RegexSearch) -> Option<Match> {
1437    visible_regex_match_iter(term, regex).find(|rm| rm.contains(&point))
1438}
1439
1440/// Copied from alacritty/src/display/hint.rs:
1441/// Iterate over all visible regex matches.
1442pub fn visible_regex_match_iter<'a, T>(
1443    term: &'a Term<T>,
1444    regex: &'a mut RegexSearch,
1445) -> impl Iterator<Item = Match> + 'a {
1446    let viewport_start = Line(-(term.grid().display_offset() as i32));
1447    let viewport_end = viewport_start + term.bottommost_line();
1448    let mut start = term.line_search_left(AlacPoint::new(viewport_start, Column(0)));
1449    let mut end = term.line_search_right(AlacPoint::new(viewport_end, Column(0)));
1450    start.line = start.line.max(viewport_start - MAX_SEARCH_LINES);
1451    end.line = end.line.min(viewport_end + MAX_SEARCH_LINES);
1452
1453    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1454        .skip_while(move |rm| rm.end().line < viewport_start)
1455        .take_while(move |rm| rm.start().line <= viewport_end)
1456}
1457
1458fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1459    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1460    selection.update(*range.end(), AlacDirection::Right);
1461    selection
1462}
1463
1464fn all_search_matches<'a, T>(
1465    term: &'a Term<T>,
1466    regex: &'a mut RegexSearch,
1467) -> impl Iterator<Item = Match> + 'a {
1468    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1469    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1470    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1471}
1472
1473fn content_index_for_mouse(pos: Point<Pixels>, size: &TerminalSize) -> usize {
1474    let col = (pos.x / size.cell_width()).round() as usize;
1475    let clamped_col = min(col, size.columns() - 1);
1476    let row = (pos.y / size.line_height()).round() as usize;
1477    let clamped_row = min(row, size.screen_lines() - 1);
1478    clamped_row * size.columns() + clamped_col
1479}
1480
1481/// Converts an 8 bit ANSI color to its GPUI equivalent.
1482/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1483/// Other than that use case, should only be called with values in the [0,255] range
1484pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1485    let colors = theme.colors();
1486
1487    match index {
1488        // 0-15 are the same as the named colors above
1489        0 => colors.terminal_ansi_black,
1490        1 => colors.terminal_ansi_red,
1491        2 => colors.terminal_ansi_green,
1492        3 => colors.terminal_ansi_yellow,
1493        4 => colors.terminal_ansi_blue,
1494        5 => colors.terminal_ansi_magenta,
1495        6 => colors.terminal_ansi_cyan,
1496        7 => colors.terminal_ansi_white,
1497        8 => colors.terminal_ansi_bright_black,
1498        9 => colors.terminal_ansi_bright_red,
1499        10 => colors.terminal_ansi_bright_green,
1500        11 => colors.terminal_ansi_bright_yellow,
1501        12 => colors.terminal_ansi_bright_blue,
1502        13 => colors.terminal_ansi_bright_magenta,
1503        14 => colors.terminal_ansi_bright_cyan,
1504        15 => colors.terminal_ansi_bright_white,
1505        // 16-231 are mapped to their RGB colors on a 0-5 range per channel
1506        16..=231 => {
1507            let (r, g, b) = rgb_for_index(index as u8); // Split the index into its ANSI-RGB components
1508            let step = (u8::MAX as f32 / 5.).floor() as u8; // Split the RGB range into 5 chunks, with floor so no overflow
1509            rgba_color(r * step, g * step, b * step) // Map the ANSI-RGB components to an RGB color
1510        }
1511        // 232-255 are a 24 step grayscale from black to white
1512        232..=255 => {
1513            let i = index as u8 - 232; // Align index to 0..24
1514            let step = (u8::MAX as f32 / 24.).floor() as u8; // Split the RGB grayscale values into 24 chunks
1515            rgba_color(i * step, i * step, i * step) // Map the ANSI-grayscale components to the RGB-grayscale
1516        }
1517        // For compatibility with the alacritty::Colors interface
1518        256 => colors.text,
1519        257 => colors.background,
1520        258 => theme.players().local().cursor,
1521        259 => colors.terminal_ansi_dim_black,
1522        260 => colors.terminal_ansi_dim_red,
1523        261 => colors.terminal_ansi_dim_green,
1524        262 => colors.terminal_ansi_dim_yellow,
1525        263 => colors.terminal_ansi_dim_blue,
1526        264 => colors.terminal_ansi_dim_magenta,
1527        265 => colors.terminal_ansi_dim_cyan,
1528        266 => colors.terminal_ansi_dim_white,
1529        267 => colors.terminal_bright_foreground,
1530        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1531
1532        _ => black(),
1533    }
1534}
1535
1536/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1537/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1538///
1539/// Wikipedia gives a formula for calculating the index for a given color:
1540///
1541/// ```
1542/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1543/// ```
1544///
1545/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
1546fn rgb_for_index(i: u8) -> (u8, u8, u8) {
1547    debug_assert!((16..=231).contains(&i));
1548    let i = i - 16;
1549    let r = (i - (i % 36)) / 36;
1550    let g = ((i % 36) - (i % 6)) / 6;
1551    let b = (i % 36) % 6;
1552    (r, g, b)
1553}
1554
1555pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1556    Rgba {
1557        r: (r as f32 / 255.),
1558        g: (g as f32 / 255.),
1559        b: (b as f32 / 255.),
1560        a: 1.,
1561    }
1562    .into()
1563}
1564
1565#[cfg(test)]
1566mod tests {
1567    use alacritty_terminal::{
1568        index::{Column, Line, Point as AlacPoint},
1569        term::cell::Cell,
1570    };
1571    use gpui::{point, size, Pixels};
1572    use rand::{distributions::Alphanumeric, rngs::ThreadRng, thread_rng, Rng};
1573
1574    use crate::{
1575        content_index_for_mouse, rgb_for_index, IndexedCell, TerminalContent, TerminalSize,
1576    };
1577
1578    #[test]
1579    fn test_rgb_for_index() {
1580        // Test every possible value in the color cube.
1581        for i in 16..=231 {
1582            let (r, g, b) = rgb_for_index(i);
1583            assert_eq!(i, 16 + 36 * r + 6 * g + b);
1584        }
1585    }
1586
1587    #[test]
1588    fn test_mouse_to_cell_test() {
1589        let mut rng = thread_rng();
1590        const ITERATIONS: usize = 10;
1591        const PRECISION: usize = 1000;
1592
1593        for _ in 0..ITERATIONS {
1594            let viewport_cells = rng.gen_range(15..20);
1595            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
1596
1597            let size = crate::TerminalSize {
1598                cell_width: Pixels::from(cell_size),
1599                line_height: Pixels::from(cell_size),
1600                size: size(
1601                    Pixels::from(cell_size * (viewport_cells as f32)),
1602                    Pixels::from(cell_size * (viewport_cells as f32)),
1603                ),
1604            };
1605
1606            let cells = get_cells(size, &mut rng);
1607            let content = convert_cells_to_content(size, &cells);
1608
1609            for row in 0..(viewport_cells - 1) {
1610                let row = row as usize;
1611                for col in 0..(viewport_cells - 1) {
1612                    let col = col as usize;
1613
1614                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1615                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
1616
1617                    let mouse_pos = point(
1618                        Pixels::from(col as f32 * cell_size + col_offset),
1619                        Pixels::from(row as f32 * cell_size + row_offset),
1620                    );
1621
1622                    let content_index = content_index_for_mouse(mouse_pos, &content.size);
1623                    let mouse_cell = content.cells[content_index].c;
1624                    let real_cell = cells[row][col];
1625
1626                    assert_eq!(mouse_cell, real_cell);
1627                }
1628            }
1629        }
1630    }
1631
1632    #[test]
1633    fn test_mouse_to_cell_clamp() {
1634        let mut rng = thread_rng();
1635
1636        let size = crate::TerminalSize {
1637            cell_width: Pixels::from(10.),
1638            line_height: Pixels::from(10.),
1639            size: size(Pixels::from(100.), Pixels::from(100.)),
1640        };
1641
1642        let cells = get_cells(size, &mut rng);
1643        let content = convert_cells_to_content(size, &cells);
1644
1645        assert_eq!(
1646            content.cells[content_index_for_mouse(
1647                point(Pixels::from(-10.), Pixels::from(-10.)),
1648                &content.size,
1649            )]
1650            .c,
1651            cells[0][0]
1652        );
1653        assert_eq!(
1654            content.cells[content_index_for_mouse(
1655                point(Pixels::from(1000.), Pixels::from(1000.)),
1656                &content.size,
1657            )]
1658            .c,
1659            cells[9][9]
1660        );
1661    }
1662
1663    fn get_cells(size: TerminalSize, rng: &mut ThreadRng) -> Vec<Vec<char>> {
1664        let mut cells = Vec::new();
1665
1666        for _ in 0..((size.height() / size.line_height()) as usize) {
1667            let mut row_vec = Vec::new();
1668            for _ in 0..((size.width() / size.cell_width()) as usize) {
1669                let cell_char = rng.sample(Alphanumeric) as char;
1670                row_vec.push(cell_char)
1671            }
1672            cells.push(row_vec)
1673        }
1674
1675        cells
1676    }
1677
1678    fn convert_cells_to_content(size: TerminalSize, cells: &Vec<Vec<char>>) -> TerminalContent {
1679        let mut ic = Vec::new();
1680
1681        for row in 0..cells.len() {
1682            for col in 0..cells[row].len() {
1683                let cell_char = cells[row][col];
1684                ic.push(IndexedCell {
1685                    point: AlacPoint::new(Line(row as i32), Column(col)),
1686                    cell: Cell {
1687                        c: cell_char,
1688                        ..Default::default()
1689                    },
1690                });
1691            }
1692        }
1693
1694        TerminalContent {
1695            cells: ic,
1696            size,
1697            ..Default::default()
1698        }
1699    }
1700}