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