terminal.rs

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