terminal.rs

   1pub mod mappings;
   2
   3pub use alacritty_terminal;
   4
   5mod pty_info;
   6mod terminal_hyperlinks;
   7pub mod terminal_settings;
   8
   9use alacritty_terminal::{
  10    Term,
  11    event::{Event as AlacTermEvent, EventListener, Notify, WindowSize},
  12    event_loop::{EventLoop, Msg, Notifier},
  13    grid::{Dimensions, Grid, Row, Scroll as AlacScroll},
  14    index::{Boundary, Column, Direction as AlacDirection, Line, Point as AlacPoint},
  15    selection::{Selection, SelectionRange, SelectionType},
  16    sync::FairMutex,
  17    term::{
  18        Config, RenderableCursor, TermMode,
  19        cell::{Cell, Flags},
  20        search::{Match, RegexIter, RegexSearch},
  21    },
  22    tty::{self},
  23    vi_mode::{ViModeCursor, ViMotion},
  24    vte::ansi::{
  25        ClearMode, CursorStyle as AlacCursorStyle, Handler, NamedPrivateMode, PrivateMode,
  26    },
  27};
  28use anyhow::{Result, bail};
  29
  30use futures::{
  31    FutureExt,
  32    channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded},
  33};
  34
  35use mappings::mouse::{
  36    alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report,
  37    scroll_report,
  38};
  39
  40use collections::{HashMap, VecDeque};
  41use futures::StreamExt;
  42use pty_info::PtyProcessInfo;
  43use serde::{Deserialize, Serialize};
  44use settings::Settings;
  45use smol::channel::{Receiver, Sender};
  46use task::{HideStrategy, Shell, TaskId};
  47use terminal_hyperlinks::RegexSearches;
  48use terminal_settings::{AlternateScroll, CursorShape, TerminalSettings};
  49use theme::{ActiveTheme, Theme};
  50use urlencoding;
  51use util::{paths::home_dir, truncate_and_trailoff};
  52
  53use std::{
  54    borrow::Cow,
  55    cmp::{self, min},
  56    fmt::Display,
  57    ops::{Deref, RangeInclusive},
  58    path::PathBuf,
  59    process::ExitStatus,
  60    sync::Arc,
  61    time::Duration,
  62};
  63use thiserror::Error;
  64
  65use gpui::{
  66    AnyWindowHandle, App, AppContext as _, Bounds, ClipboardItem, Context, EventEmitter, Hsla,
  67    Keystroke, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point,
  68    Rgba, ScrollWheelEvent, SharedString, Size, Task, TouchPhase, Window, actions, black, px,
  69};
  70
  71use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
  72
  73actions!(
  74    terminal,
  75    [
  76        Clear,
  77        Copy,
  78        Paste,
  79        ShowCharacterPalette,
  80        SearchTest,
  81        ScrollLineUp,
  82        ScrollLineDown,
  83        ScrollPageUp,
  84        ScrollPageDown,
  85        ScrollToTop,
  86        ScrollToBottom,
  87        ToggleViMode,
  88    ]
  89);
  90
  91///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
  92///Scroll multiplier that is set to 3 by default. This will be removed when I
  93///Implement scroll bars.
  94#[cfg(target_os = "macos")]
  95const SCROLL_MULTIPLIER: f32 = 4.;
  96#[cfg(not(target_os = "macos"))]
  97const SCROLL_MULTIPLIER: f32 = 1.;
  98const DEBUG_TERMINAL_WIDTH: Pixels = px(500.);
  99const DEBUG_TERMINAL_HEIGHT: Pixels = px(30.);
 100const DEBUG_CELL_WIDTH: Pixels = px(5.);
 101const DEBUG_LINE_HEIGHT: Pixels = px(5.);
 102
 103///Upward flowing events, for changing the title and such
 104#[derive(Clone, Debug)]
 105pub enum Event {
 106    TitleChanged,
 107    BreadcrumbsChanged,
 108    CloseTerminal,
 109    Bell,
 110    Wakeup,
 111    BlinkChanged(bool),
 112    SelectionsChanged,
 113    NewNavigationTarget(Option<MaybeNavigationTarget>),
 114    Open(MaybeNavigationTarget),
 115}
 116
 117#[derive(Clone, Debug)]
 118pub struct PathLikeTarget {
 119    /// File system path, absolute or relative, existing or not.
 120    /// Might have line and column number(s) attached as `file.rs:1:23`
 121    pub maybe_path: String,
 122    /// Current working directory of the terminal
 123    pub terminal_dir: Option<PathBuf>,
 124}
 125
 126/// A string inside terminal, potentially useful as a URI that can be opened.
 127#[derive(Clone, Debug)]
 128pub enum MaybeNavigationTarget {
 129    /// HTTP, git, etc. string determined by the `URL_REGEX` regex.
 130    Url(String),
 131    /// File system path, absolute or relative, existing or not.
 132    /// Might have line and column number(s) attached as `file.rs:1:23`
 133    PathLike(PathLikeTarget),
 134}
 135
 136#[derive(Clone)]
 137enum InternalEvent {
 138    Resize(TerminalBounds),
 139    Clear,
 140    // FocusNextMatch,
 141    Scroll(AlacScroll),
 142    ScrollToAlacPoint(AlacPoint),
 143    SetSelection(Option<(Selection, AlacPoint)>),
 144    UpdateSelection(Point<Pixels>),
 145    // Adjusted mouse position, should open
 146    FindHyperlink(Point<Pixels>, bool),
 147    Copy,
 148    // Vi mode events
 149    ToggleViMode,
 150    ViMotion(ViMotion),
 151}
 152
 153///A translation struct for Alacritty to communicate with us from their event loop
 154#[derive(Clone)]
 155pub struct ZedListener(pub UnboundedSender<AlacTermEvent>);
 156
 157impl EventListener for ZedListener {
 158    fn send_event(&self, event: AlacTermEvent) {
 159        self.0.unbounded_send(event).ok();
 160    }
 161}
 162
 163pub fn init(cx: &mut App) {
 164    TerminalSettings::register(cx);
 165}
 166
 167#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
 168pub struct TerminalBounds {
 169    pub cell_width: Pixels,
 170    pub line_height: Pixels,
 171    pub bounds: Bounds<Pixels>,
 172}
 173
 174impl TerminalBounds {
 175    pub fn new(line_height: Pixels, cell_width: Pixels, bounds: Bounds<Pixels>) -> Self {
 176        TerminalBounds {
 177            cell_width,
 178            line_height,
 179            bounds,
 180        }
 181    }
 182
 183    pub fn num_lines(&self) -> usize {
 184        (self.bounds.size.height / self.line_height).floor() as usize
 185    }
 186
 187    pub fn num_columns(&self) -> usize {
 188        (self.bounds.size.width / self.cell_width).floor() as usize
 189    }
 190
 191    pub fn height(&self) -> Pixels {
 192        self.bounds.size.height
 193    }
 194
 195    pub fn width(&self) -> Pixels {
 196        self.bounds.size.width
 197    }
 198
 199    pub fn cell_width(&self) -> Pixels {
 200        self.cell_width
 201    }
 202
 203    pub fn line_height(&self) -> Pixels {
 204        self.line_height
 205    }
 206}
 207
 208impl Default for TerminalBounds {
 209    fn default() -> Self {
 210        TerminalBounds::new(
 211            DEBUG_LINE_HEIGHT,
 212            DEBUG_CELL_WIDTH,
 213            Bounds {
 214                origin: Point::default(),
 215                size: Size {
 216                    width: DEBUG_TERMINAL_WIDTH,
 217                    height: DEBUG_TERMINAL_HEIGHT,
 218                },
 219            },
 220        )
 221    }
 222}
 223
 224impl From<TerminalBounds> for WindowSize {
 225    fn from(val: TerminalBounds) -> Self {
 226        WindowSize {
 227            num_lines: val.num_lines() as u16,
 228            num_cols: val.num_columns() as u16,
 229            cell_width: f32::from(val.cell_width()) as u16,
 230            cell_height: f32::from(val.line_height()) as u16,
 231        }
 232    }
 233}
 234
 235impl Dimensions for TerminalBounds {
 236    /// Note: this is supposed to be for the back buffer's length,
 237    /// but we exclusively use it to resize the terminal, which does not
 238    /// use this method. We still have to implement it for the trait though,
 239    /// hence, this comment.
 240    fn total_lines(&self) -> usize {
 241        self.screen_lines()
 242    }
 243
 244    fn screen_lines(&self) -> usize {
 245        self.num_lines()
 246    }
 247
 248    fn columns(&self) -> usize {
 249        self.num_columns()
 250    }
 251}
 252
 253#[derive(Error, Debug)]
 254pub struct TerminalError {
 255    pub directory: Option<PathBuf>,
 256    pub shell: Shell,
 257    pub source: std::io::Error,
 258}
 259
 260impl TerminalError {
 261    pub fn fmt_directory(&self) -> String {
 262        self.directory
 263            .clone()
 264            .map(|path| {
 265                match path
 266                    .into_os_string()
 267                    .into_string()
 268                    .map_err(|os_str| format!("<non-utf8 path> {}", os_str.to_string_lossy()))
 269                {
 270                    Ok(s) => s,
 271                    Err(s) => s,
 272                }
 273            })
 274            .unwrap_or_else(|| match dirs::home_dir() {
 275                Some(dir) => format!(
 276                    "<none specified, using home directory> {}",
 277                    dir.into_os_string().to_string_lossy()
 278                ),
 279                None => "<none specified, could not find home directory>".to_string(),
 280            })
 281    }
 282
 283    pub fn fmt_shell(&self) -> String {
 284        match &self.shell {
 285            Shell::System => "<system defined shell>".to_string(),
 286            Shell::Program(s) => s.to_string(),
 287            Shell::WithArguments {
 288                program,
 289                args,
 290                title_override,
 291            } => {
 292                if let Some(title_override) = title_override {
 293                    format!("{} {} ({})", program, args.join(" "), title_override)
 294                } else {
 295                    format!("{} {}", program, args.join(" "))
 296                }
 297            }
 298        }
 299    }
 300}
 301
 302impl Display for TerminalError {
 303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 304        let dir_string: String = self.fmt_directory();
 305        let shell = self.fmt_shell();
 306
 307        write!(
 308            f,
 309            "Working directory: {} Shell command: `{}`, IOError: {}",
 310            dir_string, shell, self.source
 311        )
 312    }
 313}
 314
 315// https://github.com/alacritty/alacritty/blob/cb3a79dbf6472740daca8440d5166c1d4af5029e/extra/man/alacritty.5.scd?plain=1#L207-L213
 316const DEFAULT_SCROLL_HISTORY_LINES: usize = 10_000;
 317pub const MAX_SCROLL_HISTORY_LINES: usize = 100_000;
 318
 319pub struct TerminalBuilder {
 320    terminal: Terminal,
 321    events_rx: UnboundedReceiver<AlacTermEvent>,
 322}
 323
 324impl TerminalBuilder {
 325    pub fn new(
 326        working_directory: Option<PathBuf>,
 327        python_venv_directory: Option<PathBuf>,
 328        task: Option<TaskState>,
 329        shell: Shell,
 330        mut env: HashMap<String, String>,
 331        cursor_shape: CursorShape,
 332        alternate_scroll: AlternateScroll,
 333        max_scroll_history_lines: Option<usize>,
 334        is_ssh_terminal: bool,
 335        window: AnyWindowHandle,
 336        completion_tx: Sender<Option<ExitStatus>>,
 337        cx: &App,
 338    ) -> Result<TerminalBuilder> {
 339        // If the parent environment doesn't have a locale set
 340        // (As is the case when launched from a .app on MacOS),
 341        // and the Project doesn't have a locale set, then
 342        // set a fallback for our child environment to use.
 343        if std::env::var("LANG").is_err() {
 344            env.entry("LANG".to_string())
 345                .or_insert_with(|| "en_US.UTF-8".to_string());
 346        }
 347
 348        env.insert("ZED_TERM".to_string(), "true".to_string());
 349        env.insert("TERM_PROGRAM".to_string(), "zed".to_string());
 350        env.insert("TERM".to_string(), "xterm-256color".to_string());
 351        env.insert(
 352            "TERM_PROGRAM_VERSION".to_string(),
 353            release_channel::AppVersion::global(cx).to_string(),
 354        );
 355
 356        let mut terminal_title_override = None;
 357
 358        let pty_options = {
 359            let alac_shell = match shell.clone() {
 360                Shell::System => {
 361                    #[cfg(target_os = "windows")]
 362                    {
 363                        Some(alacritty_terminal::tty::Shell::new(
 364                            util::get_windows_system_shell(),
 365                            Vec::new(),
 366                        ))
 367                    }
 368                    #[cfg(not(target_os = "windows"))]
 369                    {
 370                        None
 371                    }
 372                }
 373                Shell::Program(program) => {
 374                    Some(alacritty_terminal::tty::Shell::new(program, Vec::new()))
 375                }
 376                Shell::WithArguments {
 377                    program,
 378                    args,
 379                    title_override,
 380                } => {
 381                    terminal_title_override = title_override;
 382                    Some(alacritty_terminal::tty::Shell::new(program, args))
 383                }
 384            };
 385
 386            alacritty_terminal::tty::Options {
 387                shell: alac_shell,
 388                working_directory: working_directory
 389                    .clone()
 390                    .or_else(|| Some(home_dir().to_path_buf())),
 391                drain_on_exit: true,
 392                env: env.into_iter().collect(),
 393            }
 394        };
 395
 396        // Setup Alacritty's env, which modifies the current process's environment
 397        alacritty_terminal::tty::setup_env();
 398
 399        let default_cursor_style = AlacCursorStyle::from(cursor_shape);
 400        let scrolling_history = if task.is_some() {
 401            // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
 402            // After the task finishes, we do not allow appending to that terminal, so small tasks output should not
 403            // cause excessive memory usage over time.
 404            MAX_SCROLL_HISTORY_LINES
 405        } else {
 406            max_scroll_history_lines
 407                .unwrap_or(DEFAULT_SCROLL_HISTORY_LINES)
 408                .min(MAX_SCROLL_HISTORY_LINES)
 409        };
 410        let config = Config {
 411            scrolling_history,
 412            default_cursor_style,
 413            ..Config::default()
 414        };
 415
 416        //Spawn a task so the Alacritty EventLoop can communicate with us
 417        //TODO: Remove with a bounded sender which can be dispatched on &self
 418        let (events_tx, events_rx) = unbounded();
 419        //Set up the terminal...
 420        let mut term = Term::new(
 421            config.clone(),
 422            &TerminalBounds::default(),
 423            ZedListener(events_tx.clone()),
 424        );
 425
 426        //Alacritty defaults to alternate scrolling being on, so we just need to turn it off.
 427        if let AlternateScroll::Off = alternate_scroll {
 428            term.unset_private_mode(PrivateMode::Named(NamedPrivateMode::AlternateScroll));
 429        }
 430
 431        let term = Arc::new(FairMutex::new(term));
 432
 433        //Setup the pty...
 434        let pty = match tty::new(
 435            &pty_options,
 436            TerminalBounds::default().into(),
 437            window.window_id().as_u64(),
 438        ) {
 439            Ok(pty) => pty,
 440            Err(error) => {
 441                bail!(TerminalError {
 442                    directory: working_directory,
 443                    shell,
 444                    source: error,
 445                });
 446            }
 447        };
 448
 449        let pty_info = PtyProcessInfo::new(&pty);
 450
 451        //And connect them together
 452        let event_loop = EventLoop::new(
 453            term.clone(),
 454            ZedListener(events_tx.clone()),
 455            pty,
 456            pty_options.drain_on_exit,
 457            false,
 458        )?;
 459
 460        //Kick things off
 461        let pty_tx = event_loop.channel();
 462        let _io_thread = event_loop.spawn(); // DANGER
 463
 464        let terminal = Terminal {
 465            task,
 466            pty_tx: Notifier(pty_tx),
 467            completion_tx,
 468            term,
 469            term_config: config,
 470            title_override: terminal_title_override,
 471            events: VecDeque::with_capacity(10), //Should never get this high.
 472            last_content: Default::default(),
 473            last_mouse: None,
 474            matches: Vec::new(),
 475            selection_head: None,
 476            pty_info,
 477            breadcrumb_text: String::new(),
 478            scroll_px: px(0.),
 479            next_link_id: 0,
 480            selection_phase: SelectionPhase::Ended,
 481            // hovered_word: false,
 482            hyperlink_regex_searches: RegexSearches::new(),
 483            vi_mode_enabled: false,
 484            is_ssh_terminal,
 485            python_venv_directory,
 486        };
 487
 488        Ok(TerminalBuilder {
 489            terminal,
 490            events_rx,
 491        })
 492    }
 493
 494    pub fn subscribe(mut self, cx: &Context<Terminal>) -> Terminal {
 495        //Event loop
 496        cx.spawn(async move |terminal, cx| {
 497            while let Some(event) = self.events_rx.next().await {
 498                terminal.update(cx, |terminal, cx| {
 499                    //Process the first event immediately for lowered latency
 500                    terminal.process_event(event, cx);
 501                })?;
 502
 503                'outer: loop {
 504                    let mut events = Vec::new();
 505                    let mut timer = cx
 506                        .background_executor()
 507                        .timer(Duration::from_millis(4))
 508                        .fuse();
 509                    let mut wakeup = false;
 510                    loop {
 511                        futures::select_biased! {
 512                            _ = timer => break,
 513                            event = self.events_rx.next() => {
 514                                if let Some(event) = event {
 515                                    if matches!(event, AlacTermEvent::Wakeup) {
 516                                        wakeup = true;
 517                                    } else {
 518                                        events.push(event);
 519                                    }
 520
 521                                    if events.len() > 100 {
 522                                        break;
 523                                    }
 524                                } else {
 525                                    break;
 526                                }
 527                            },
 528                        }
 529                    }
 530
 531                    if events.is_empty() && !wakeup {
 532                        smol::future::yield_now().await;
 533                        break 'outer;
 534                    }
 535
 536                    terminal.update(cx, |this, cx| {
 537                        if wakeup {
 538                            this.process_event(AlacTermEvent::Wakeup, cx);
 539                        }
 540
 541                        for event in events {
 542                            this.process_event(event, cx);
 543                        }
 544                    })?;
 545                    smol::future::yield_now().await;
 546                }
 547            }
 548
 549            anyhow::Ok(())
 550        })
 551        .detach();
 552
 553        self.terminal
 554    }
 555}
 556
 557#[derive(Debug, Clone, Deserialize, Serialize)]
 558pub struct IndexedCell {
 559    pub point: AlacPoint,
 560    pub cell: Cell,
 561}
 562
 563impl Deref for IndexedCell {
 564    type Target = Cell;
 565
 566    #[inline]
 567    fn deref(&self) -> &Cell {
 568        &self.cell
 569    }
 570}
 571
 572// TODO: Un-pub
 573#[derive(Clone)]
 574pub struct TerminalContent {
 575    pub cells: Vec<IndexedCell>,
 576    pub mode: TermMode,
 577    pub display_offset: usize,
 578    pub selection_text: Option<String>,
 579    pub selection: Option<SelectionRange>,
 580    pub cursor: RenderableCursor,
 581    pub cursor_char: char,
 582    pub terminal_bounds: TerminalBounds,
 583    pub last_hovered_word: Option<HoveredWord>,
 584    pub scrolled_to_top: bool,
 585    pub scrolled_to_bottom: bool,
 586}
 587
 588#[derive(Debug, Clone, Eq, PartialEq)]
 589pub struct HoveredWord {
 590    pub word: String,
 591    pub word_match: RangeInclusive<AlacPoint>,
 592    pub id: usize,
 593}
 594
 595impl Default for TerminalContent {
 596    fn default() -> Self {
 597        TerminalContent {
 598            cells: Default::default(),
 599            mode: Default::default(),
 600            display_offset: Default::default(),
 601            selection_text: Default::default(),
 602            selection: Default::default(),
 603            cursor: RenderableCursor {
 604                shape: alacritty_terminal::vte::ansi::CursorShape::Block,
 605                point: AlacPoint::new(Line(0), Column(0)),
 606            },
 607            cursor_char: Default::default(),
 608            terminal_bounds: Default::default(),
 609            last_hovered_word: None,
 610            scrolled_to_top: false,
 611            scrolled_to_bottom: false,
 612        }
 613    }
 614}
 615
 616#[derive(PartialEq, Eq)]
 617pub enum SelectionPhase {
 618    Selecting,
 619    Ended,
 620}
 621
 622pub struct Terminal {
 623    pty_tx: Notifier,
 624    completion_tx: Sender<Option<ExitStatus>>,
 625    term: Arc<FairMutex<Term<ZedListener>>>,
 626    term_config: Config,
 627    events: VecDeque<InternalEvent>,
 628    /// This is only used for mouse mode cell change detection
 629    last_mouse: Option<(AlacPoint, AlacDirection)>,
 630    pub matches: Vec<RangeInclusive<AlacPoint>>,
 631    pub last_content: TerminalContent,
 632    pub selection_head: Option<AlacPoint>,
 633    pub breadcrumb_text: String,
 634    pub pty_info: PtyProcessInfo,
 635    title_override: Option<SharedString>,
 636    pub python_venv_directory: Option<PathBuf>,
 637    scroll_px: Pixels,
 638    next_link_id: usize,
 639    selection_phase: SelectionPhase,
 640    hyperlink_regex_searches: RegexSearches,
 641    task: Option<TaskState>,
 642    vi_mode_enabled: bool,
 643    is_ssh_terminal: bool,
 644}
 645
 646pub struct TaskState {
 647    pub id: TaskId,
 648    pub full_label: String,
 649    pub label: String,
 650    pub command_label: String,
 651    pub status: TaskStatus,
 652    pub completion_rx: Receiver<Option<ExitStatus>>,
 653    pub hide: HideStrategy,
 654    pub show_summary: bool,
 655    pub show_command: bool,
 656    pub show_rerun: bool,
 657}
 658
 659/// A status of the current terminal tab's task.
 660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 661pub enum TaskStatus {
 662    /// The task had been started, but got cancelled or somehow otherwise it did not
 663    /// report its exit code before the terminal event loop was shut down.
 664    Unknown,
 665    /// The task is started and running currently.
 666    Running,
 667    /// After the start, the task stopped running and reported its error code back.
 668    Completed { success: bool },
 669}
 670
 671impl TaskStatus {
 672    fn register_terminal_exit(&mut self) {
 673        if self == &Self::Running {
 674            *self = Self::Unknown;
 675        }
 676    }
 677
 678    fn register_task_exit(&mut self, error_code: i32) {
 679        *self = TaskStatus::Completed {
 680            success: error_code == 0,
 681        };
 682    }
 683}
 684
 685impl Terminal {
 686    fn process_event(&mut self, event: AlacTermEvent, cx: &mut Context<Self>) {
 687        match event {
 688            AlacTermEvent::Title(title) => {
 689                self.breadcrumb_text = title;
 690                cx.emit(Event::BreadcrumbsChanged);
 691            }
 692            AlacTermEvent::ResetTitle => {
 693                self.breadcrumb_text = String::new();
 694                cx.emit(Event::BreadcrumbsChanged);
 695            }
 696            AlacTermEvent::ClipboardStore(_, data) => {
 697                cx.write_to_clipboard(ClipboardItem::new_string(data))
 698            }
 699            AlacTermEvent::ClipboardLoad(_, format) => {
 700                self.write_to_pty(
 701                    match &cx.read_from_clipboard().and_then(|item| item.text()) {
 702                        // The terminal only supports pasting strings, not images.
 703                        Some(text) => format(text),
 704                        _ => format(""),
 705                    }
 706                    .into_bytes(),
 707                )
 708            }
 709            AlacTermEvent::PtyWrite(out) => self.write_to_pty(out.into_bytes()),
 710            AlacTermEvent::TextAreaSizeRequest(format) => {
 711                self.write_to_pty(format(self.last_content.terminal_bounds.into()).into_bytes())
 712            }
 713            AlacTermEvent::CursorBlinkingChange => {
 714                let terminal = self.term.lock();
 715                let blinking = terminal.cursor_style().blinking;
 716                cx.emit(Event::BlinkChanged(blinking));
 717            }
 718            AlacTermEvent::Bell => {
 719                cx.emit(Event::Bell);
 720            }
 721            AlacTermEvent::Exit => self.register_task_finished(None, cx),
 722            AlacTermEvent::MouseCursorDirty => {
 723                //NOOP, Handled in render
 724            }
 725            AlacTermEvent::Wakeup => {
 726                cx.emit(Event::Wakeup);
 727
 728                if self.pty_info.has_changed() {
 729                    cx.emit(Event::TitleChanged);
 730                }
 731            }
 732            AlacTermEvent::ColorRequest(index, format) => {
 733                // It's important that the color request is processed here to retain relative order
 734                // with other PTY writes. Otherwise applications might witness out-of-order
 735                // responses to requests. For example: An application sending `OSC 11 ; ? ST`
 736                // (color request) followed by `CSI c` (request device attributes) would receive
 737                // the response to `CSI c` first.
 738                // Instead of locking, we could store the colors in `self.last_content`. But then
 739                // we might respond with out of date value if a "set color" sequence is immediately
 740                // followed by a color request sequence.
 741                let color = self.term.lock().colors()[index]
 742                    .unwrap_or_else(|| to_alac_rgb(get_color_at_index(index, cx.theme().as_ref())));
 743                self.write_to_pty(format(color).into_bytes());
 744            }
 745            AlacTermEvent::ChildExit(error_code) => {
 746                self.register_task_finished(Some(error_code), cx);
 747            }
 748        }
 749    }
 750
 751    pub fn selection_started(&self) -> bool {
 752        self.selection_phase == SelectionPhase::Selecting
 753    }
 754
 755    fn process_terminal_event(
 756        &mut self,
 757        event: &InternalEvent,
 758        term: &mut Term<ZedListener>,
 759        window: &mut Window,
 760        cx: &mut Context<Self>,
 761    ) {
 762        match event {
 763            &InternalEvent::Resize(mut new_bounds) => {
 764                new_bounds.bounds.size.height =
 765                    cmp::max(new_bounds.line_height, new_bounds.height());
 766                new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
 767
 768                self.last_content.terminal_bounds = new_bounds;
 769
 770                self.pty_tx.0.send(Msg::Resize(new_bounds.into())).ok();
 771
 772                term.resize(new_bounds);
 773            }
 774            InternalEvent::Clear => {
 775                // Clear back buffer
 776                term.clear_screen(ClearMode::Saved);
 777
 778                let cursor = term.grid().cursor.point;
 779
 780                // Clear the lines above
 781                term.grid_mut().reset_region(..cursor.line);
 782
 783                // Copy the current line up
 784                let line = term.grid()[cursor.line][..Column(term.grid().columns())]
 785                    .iter()
 786                    .cloned()
 787                    .enumerate()
 788                    .collect::<Vec<(usize, Cell)>>();
 789
 790                for (i, cell) in line {
 791                    term.grid_mut()[Line(0)][Column(i)] = cell;
 792                }
 793
 794                // Reset the cursor
 795                term.grid_mut().cursor.point =
 796                    AlacPoint::new(Line(0), term.grid_mut().cursor.point.column);
 797                let new_cursor = term.grid().cursor.point;
 798
 799                // Clear the lines below the new cursor
 800                if (new_cursor.line.0 as usize) < term.screen_lines() - 1 {
 801                    term.grid_mut().reset_region((new_cursor.line + 1)..);
 802                }
 803
 804                cx.emit(Event::Wakeup);
 805            }
 806            InternalEvent::Scroll(scroll) => {
 807                term.scroll_display(*scroll);
 808                self.refresh_hovered_word(window);
 809
 810                if self.vi_mode_enabled {
 811                    match *scroll {
 812                        AlacScroll::Delta(delta) => {
 813                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, delta);
 814                        }
 815                        AlacScroll::PageUp => {
 816                            let lines = term.screen_lines() as i32;
 817                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
 818                        }
 819                        AlacScroll::PageDown => {
 820                            let lines = -(term.screen_lines() as i32);
 821                            term.vi_mode_cursor = term.vi_mode_cursor.scroll(&term, lines);
 822                        }
 823                        AlacScroll::Top => {
 824                            let point = AlacPoint::new(term.topmost_line(), Column(0));
 825                            term.vi_mode_cursor = ViModeCursor::new(point);
 826                        }
 827                        AlacScroll::Bottom => {
 828                            let point = AlacPoint::new(term.bottommost_line(), Column(0));
 829                            term.vi_mode_cursor = ViModeCursor::new(point);
 830                        }
 831                    }
 832                    if let Some(mut selection) = term.selection.take() {
 833                        let point = term.vi_mode_cursor.point;
 834                        selection.update(point, AlacDirection::Right);
 835                        term.selection = Some(selection);
 836
 837                        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 838                        if let Some(selection_text) = term.selection_to_string() {
 839                            cx.write_to_primary(ClipboardItem::new_string(selection_text));
 840                        }
 841
 842                        self.selection_head = Some(point);
 843                        cx.emit(Event::SelectionsChanged)
 844                    }
 845                }
 846            }
 847            InternalEvent::SetSelection(selection) => {
 848                term.selection = selection.as_ref().map(|(sel, _)| sel.clone());
 849
 850                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 851                if let Some(selection_text) = term.selection_to_string() {
 852                    cx.write_to_primary(ClipboardItem::new_string(selection_text));
 853                }
 854
 855                if let Some((_, head)) = selection {
 856                    self.selection_head = Some(*head);
 857                }
 858                cx.emit(Event::SelectionsChanged)
 859            }
 860            InternalEvent::UpdateSelection(position) => {
 861                if let Some(mut selection) = term.selection.take() {
 862                    let (point, side) = grid_point_and_side(
 863                        *position,
 864                        self.last_content.terminal_bounds,
 865                        term.grid().display_offset(),
 866                    );
 867
 868                    selection.update(point, side);
 869                    term.selection = Some(selection);
 870
 871                    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 872                    if let Some(selection_text) = term.selection_to_string() {
 873                        cx.write_to_primary(ClipboardItem::new_string(selection_text));
 874                    }
 875
 876                    self.selection_head = Some(point);
 877                    cx.emit(Event::SelectionsChanged)
 878                }
 879            }
 880
 881            InternalEvent::Copy => {
 882                if let Some(txt) = term.selection_to_string() {
 883                    cx.write_to_clipboard(ClipboardItem::new_string(txt))
 884                }
 885            }
 886            InternalEvent::ScrollToAlacPoint(point) => {
 887                term.scroll_to_point(*point);
 888                self.refresh_hovered_word(window);
 889            }
 890            InternalEvent::ToggleViMode => {
 891                self.vi_mode_enabled = !self.vi_mode_enabled;
 892                term.toggle_vi_mode();
 893            }
 894            InternalEvent::ViMotion(motion) => {
 895                term.vi_motion(*motion);
 896            }
 897            InternalEvent::FindHyperlink(position, open) => {
 898                let prev_hovered_word = self.last_content.last_hovered_word.take();
 899
 900                let point = grid_point(
 901                    *position,
 902                    self.last_content.terminal_bounds,
 903                    term.grid().display_offset(),
 904                )
 905                .grid_clamp(term, Boundary::Grid);
 906
 907                match terminal_hyperlinks::find_from_grid_point(
 908                    term,
 909                    point,
 910                    &mut self.hyperlink_regex_searches,
 911                ) {
 912                    Some((maybe_url_or_path, is_url, url_match)) => {
 913                        let target = if is_url {
 914                            // Treat "file://" URLs like file paths to ensure
 915                            // that line numbers at the end of the path are
 916                            // handled correctly.
 917                            // file://{path} should be urldecoded, returning a urldecoded {path}
 918                            if let Some(path) = maybe_url_or_path.strip_prefix("file://") {
 919                                let decoded_path = urlencoding::decode(path)
 920                                    .map(|decoded| decoded.into_owned())
 921                                    .unwrap_or(path.to_owned());
 922
 923                                MaybeNavigationTarget::PathLike(PathLikeTarget {
 924                                    maybe_path: decoded_path,
 925                                    terminal_dir: self.working_directory(),
 926                                })
 927                            } else {
 928                                MaybeNavigationTarget::Url(maybe_url_or_path.clone())
 929                            }
 930                        } else {
 931                            MaybeNavigationTarget::PathLike(PathLikeTarget {
 932                                maybe_path: maybe_url_or_path.clone(),
 933                                terminal_dir: self.working_directory(),
 934                            })
 935                        };
 936                        if *open {
 937                            cx.emit(Event::Open(target));
 938                        } else {
 939                            self.update_selected_word(
 940                                prev_hovered_word,
 941                                url_match,
 942                                maybe_url_or_path,
 943                                target,
 944                                cx,
 945                            );
 946                        }
 947                    }
 948                    None => {
 949                        cx.emit(Event::NewNavigationTarget(None));
 950                    }
 951                }
 952            }
 953        }
 954    }
 955
 956    fn update_selected_word(
 957        &mut self,
 958        prev_word: Option<HoveredWord>,
 959        word_match: RangeInclusive<AlacPoint>,
 960        word: String,
 961        navigation_target: MaybeNavigationTarget,
 962        cx: &mut Context<Self>,
 963    ) {
 964        if let Some(prev_word) = prev_word {
 965            if prev_word.word == word && prev_word.word_match == word_match {
 966                self.last_content.last_hovered_word = Some(HoveredWord {
 967                    word,
 968                    word_match,
 969                    id: prev_word.id,
 970                });
 971                return;
 972            }
 973        }
 974
 975        self.last_content.last_hovered_word = Some(HoveredWord {
 976            word,
 977            word_match,
 978            id: self.next_link_id(),
 979        });
 980        cx.emit(Event::NewNavigationTarget(Some(navigation_target)));
 981        cx.notify()
 982    }
 983
 984    fn next_link_id(&mut self) -> usize {
 985        let res = self.next_link_id;
 986        self.next_link_id = self.next_link_id.wrapping_add(1);
 987        res
 988    }
 989
 990    pub fn last_content(&self) -> &TerminalContent {
 991        &self.last_content
 992    }
 993
 994    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape) {
 995        self.term_config.default_cursor_style = cursor_shape.into();
 996        self.term.lock().set_options(self.term_config.clone());
 997    }
 998
 999    pub fn total_lines(&self) -> usize {
1000        let term = self.term.clone();
1001        let terminal = term.lock_unfair();
1002        terminal.total_lines()
1003    }
1004
1005    pub fn viewport_lines(&self) -> usize {
1006        let term = self.term.clone();
1007        let terminal = term.lock_unfair();
1008        terminal.screen_lines()
1009    }
1010
1011    //To test:
1012    //- Activate match on terminal (scrolling and selection)
1013    //- Editor search snapping behavior
1014
1015    pub fn activate_match(&mut self, index: usize) {
1016        if let Some(search_match) = self.matches.get(index).cloned() {
1017            self.set_selection(Some((make_selection(&search_match), *search_match.end())));
1018
1019            self.events
1020                .push_back(InternalEvent::ScrollToAlacPoint(*search_match.start()));
1021        }
1022    }
1023
1024    pub fn select_matches(&mut self, matches: &[RangeInclusive<AlacPoint>]) {
1025        let matches_to_select = self
1026            .matches
1027            .iter()
1028            .filter(|self_match| matches.contains(self_match))
1029            .cloned()
1030            .collect::<Vec<_>>();
1031        for match_to_select in matches_to_select {
1032            self.set_selection(Some((
1033                make_selection(&match_to_select),
1034                *match_to_select.end(),
1035            )));
1036        }
1037    }
1038
1039    pub fn select_all(&mut self) {
1040        let term = self.term.lock();
1041        let start = AlacPoint::new(term.topmost_line(), Column(0));
1042        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1043        drop(term);
1044        self.set_selection(Some((make_selection(&(start..=end)), end)));
1045    }
1046
1047    fn set_selection(&mut self, selection: Option<(Selection, AlacPoint)>) {
1048        self.events
1049            .push_back(InternalEvent::SetSelection(selection));
1050    }
1051
1052    pub fn copy(&mut self) {
1053        self.events.push_back(InternalEvent::Copy);
1054    }
1055
1056    pub fn clear(&mut self) {
1057        self.events.push_back(InternalEvent::Clear)
1058    }
1059
1060    pub fn scroll_line_up(&mut self) {
1061        self.events
1062            .push_back(InternalEvent::Scroll(AlacScroll::Delta(1)));
1063    }
1064
1065    pub fn scroll_up_by(&mut self, lines: usize) {
1066        self.events
1067            .push_back(InternalEvent::Scroll(AlacScroll::Delta(lines as i32)));
1068    }
1069
1070    pub fn scroll_line_down(&mut self) {
1071        self.events
1072            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-1)));
1073    }
1074
1075    pub fn scroll_down_by(&mut self, lines: usize) {
1076        self.events
1077            .push_back(InternalEvent::Scroll(AlacScroll::Delta(-(lines as i32))));
1078    }
1079
1080    pub fn scroll_page_up(&mut self) {
1081        self.events
1082            .push_back(InternalEvent::Scroll(AlacScroll::PageUp));
1083    }
1084
1085    pub fn scroll_page_down(&mut self) {
1086        self.events
1087            .push_back(InternalEvent::Scroll(AlacScroll::PageDown));
1088    }
1089
1090    pub fn scroll_to_top(&mut self) {
1091        self.events
1092            .push_back(InternalEvent::Scroll(AlacScroll::Top));
1093    }
1094
1095    pub fn scroll_to_bottom(&mut self) {
1096        self.events
1097            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1098    }
1099
1100    pub fn scrolled_to_top(&self) -> bool {
1101        self.last_content.scrolled_to_top
1102    }
1103
1104    pub fn scrolled_to_bottom(&self) -> bool {
1105        self.last_content.scrolled_to_bottom
1106    }
1107
1108    ///Resize the terminal and the PTY.
1109    pub fn set_size(&mut self, new_bounds: TerminalBounds) {
1110        if self.last_content.terminal_bounds != new_bounds {
1111            self.events.push_back(InternalEvent::Resize(new_bounds))
1112        }
1113    }
1114
1115    ///Write the Input payload to the tty.
1116    fn write_to_pty(&self, input: impl Into<Cow<'static, [u8]>>) {
1117        self.pty_tx.notify(input.into());
1118    }
1119
1120    pub fn input(&mut self, input: impl Into<Cow<'static, [u8]>>) {
1121        self.events
1122            .push_back(InternalEvent::Scroll(AlacScroll::Bottom));
1123        self.events.push_back(InternalEvent::SetSelection(None));
1124
1125        self.write_to_pty(input);
1126    }
1127
1128    pub fn toggle_vi_mode(&mut self) {
1129        self.events.push_back(InternalEvent::ToggleViMode);
1130    }
1131
1132    pub fn vi_motion(&mut self, keystroke: &Keystroke) {
1133        if !self.vi_mode_enabled {
1134            return;
1135        }
1136
1137        let key: Cow<'_, str> = if keystroke.modifiers.shift {
1138            Cow::Owned(keystroke.key.to_uppercase())
1139        } else {
1140            Cow::Borrowed(keystroke.key.as_str())
1141        };
1142
1143        let motion: Option<ViMotion> = match key.as_ref() {
1144            "h" | "left" => Some(ViMotion::Left),
1145            "j" | "down" => Some(ViMotion::Down),
1146            "k" | "up" => Some(ViMotion::Up),
1147            "l" | "right" => Some(ViMotion::Right),
1148            "w" => Some(ViMotion::WordRight),
1149            "b" if !keystroke.modifiers.control => Some(ViMotion::WordLeft),
1150            "e" => Some(ViMotion::WordRightEnd),
1151            "%" => Some(ViMotion::Bracket),
1152            "$" => Some(ViMotion::Last),
1153            "0" => Some(ViMotion::First),
1154            "^" => Some(ViMotion::FirstOccupied),
1155            "H" => Some(ViMotion::High),
1156            "M" => Some(ViMotion::Middle),
1157            "L" => Some(ViMotion::Low),
1158            _ => None,
1159        };
1160
1161        if let Some(motion) = motion {
1162            let cursor = self.last_content.cursor.point;
1163            let cursor_pos = Point {
1164                x: cursor.column.0 as f32 * self.last_content.terminal_bounds.cell_width,
1165                y: cursor.line.0 as f32 * self.last_content.terminal_bounds.line_height,
1166            };
1167            self.events
1168                .push_back(InternalEvent::UpdateSelection(cursor_pos));
1169            self.events.push_back(InternalEvent::ViMotion(motion));
1170            return;
1171        }
1172
1173        let scroll_motion = match key.as_ref() {
1174            "g" => Some(AlacScroll::Top),
1175            "G" => Some(AlacScroll::Bottom),
1176            "b" if keystroke.modifiers.control => Some(AlacScroll::PageUp),
1177            "f" if keystroke.modifiers.control => Some(AlacScroll::PageDown),
1178            "d" if keystroke.modifiers.control => {
1179                let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1180                Some(AlacScroll::Delta(-amount))
1181            }
1182            "u" if keystroke.modifiers.control => {
1183                let amount = self.last_content.terminal_bounds.line_height().to_f64() as i32 / 2;
1184                Some(AlacScroll::Delta(amount))
1185            }
1186            _ => None,
1187        };
1188
1189        if let Some(scroll_motion) = scroll_motion {
1190            self.events.push_back(InternalEvent::Scroll(scroll_motion));
1191            return;
1192        }
1193
1194        match key.as_ref() {
1195            "v" => {
1196                let point = self.last_content.cursor.point;
1197                let selection_type = SelectionType::Simple;
1198                let side = AlacDirection::Right;
1199                let selection = Selection::new(selection_type, point, side);
1200                self.events
1201                    .push_back(InternalEvent::SetSelection(Some((selection, point))));
1202                return;
1203            }
1204
1205            "escape" => {
1206                self.events.push_back(InternalEvent::SetSelection(None));
1207                return;
1208            }
1209
1210            "y" => {
1211                self.events.push_back(InternalEvent::Copy);
1212                self.events.push_back(InternalEvent::SetSelection(None));
1213                return;
1214            }
1215
1216            "i" => {
1217                self.scroll_to_bottom();
1218                self.toggle_vi_mode();
1219                return;
1220            }
1221            _ => {}
1222        }
1223    }
1224
1225    pub fn try_keystroke(&mut self, keystroke: &Keystroke, alt_is_meta: bool) -> bool {
1226        if self.vi_mode_enabled {
1227            self.vi_motion(keystroke);
1228            return true;
1229        }
1230
1231        // Keep default terminal behavior
1232        let esc = to_esc_str(keystroke, &self.last_content.mode, alt_is_meta);
1233        if let Some(esc) = esc {
1234            match esc {
1235                Cow::Borrowed(string) => self.input(string.as_bytes()),
1236                Cow::Owned(string) => self.input(string.into_bytes()),
1237            };
1238            true
1239        } else {
1240            false
1241        }
1242    }
1243
1244    pub fn try_modifiers_change(
1245        &mut self,
1246        modifiers: &Modifiers,
1247        window: &Window,
1248        cx: &mut Context<Self>,
1249    ) {
1250        if self
1251            .last_content
1252            .terminal_bounds
1253            .bounds
1254            .contains(&window.mouse_position())
1255            && modifiers.secondary()
1256        {
1257            self.refresh_hovered_word(window);
1258        }
1259        cx.notify();
1260    }
1261
1262    ///Paste text into the terminal
1263    pub fn paste(&mut self, text: &str) {
1264        let paste_text = if self.last_content.mode.contains(TermMode::BRACKETED_PASTE) {
1265            format!("{}{}{}", "\x1b[200~", text.replace('\x1b', ""), "\x1b[201~")
1266        } else {
1267            text.replace("\r\n", "\r").replace('\n', "\r")
1268        };
1269
1270        self.input(paste_text.into_bytes());
1271    }
1272
1273    pub fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1274        let term = self.term.clone();
1275        let mut terminal = term.lock_unfair();
1276        //Note that the ordering of events matters for event processing
1277        while let Some(e) = self.events.pop_front() {
1278            self.process_terminal_event(&e, &mut terminal, window, cx)
1279        }
1280
1281        self.last_content = Self::make_content(&terminal, &self.last_content);
1282    }
1283
1284    fn make_content(term: &Term<ZedListener>, last_content: &TerminalContent) -> TerminalContent {
1285        let content = term.renderable_content();
1286        TerminalContent {
1287            cells: content
1288                .display_iter
1289                //TODO: Add this once there's a way to retain empty lines
1290                // .filter(|ic| {
1291                //     !ic.flags.contains(Flags::HIDDEN)
1292                //         && !(ic.bg == Named(NamedColor::Background)
1293                //             && ic.c == ' '
1294                //             && !ic.flags.contains(Flags::INVERSE))
1295                // })
1296                .map(|ic| IndexedCell {
1297                    point: ic.point,
1298                    cell: ic.cell.clone(),
1299                })
1300                .collect::<Vec<IndexedCell>>(),
1301            mode: content.mode,
1302            display_offset: content.display_offset,
1303            selection_text: term.selection_to_string(),
1304            selection: content.selection,
1305            cursor: content.cursor,
1306            cursor_char: term.grid()[content.cursor.point].c,
1307            terminal_bounds: last_content.terminal_bounds,
1308            last_hovered_word: last_content.last_hovered_word.clone(),
1309            scrolled_to_top: content.display_offset == term.history_size(),
1310            scrolled_to_bottom: content.display_offset == 0,
1311        }
1312    }
1313
1314    pub fn get_content(&self) -> String {
1315        let term = self.term.lock_unfair();
1316        let start = AlacPoint::new(term.topmost_line(), Column(0));
1317        let end = AlacPoint::new(term.bottommost_line(), term.last_column());
1318        term.bounds_to_string(start, end)
1319    }
1320
1321    pub fn last_n_non_empty_lines(&self, n: usize) -> Vec<String> {
1322        let term = self.term.clone();
1323        let terminal = term.lock_unfair();
1324        let grid = terminal.grid();
1325        let mut lines = Vec::new();
1326
1327        let mut current_line = grid.bottommost_line().0;
1328        let topmost_line = grid.topmost_line().0;
1329
1330        while current_line >= topmost_line && lines.len() < n {
1331            let logical_line_start = self.find_logical_line_start(grid, current_line, topmost_line);
1332            let logical_line = self.construct_logical_line(grid, logical_line_start, current_line);
1333
1334            if let Some(line) = self.process_line(logical_line) {
1335                lines.push(line);
1336            }
1337
1338            // Move to the line above the start of the current logical line
1339            current_line = logical_line_start - 1;
1340        }
1341
1342        lines.reverse();
1343        lines
1344    }
1345
1346    fn find_logical_line_start(&self, grid: &Grid<Cell>, current: i32, topmost: i32) -> i32 {
1347        let mut line_start = current;
1348        while line_start > topmost {
1349            let prev_line = Line(line_start - 1);
1350            let last_cell = &grid[prev_line][Column(grid.columns() - 1)];
1351            if !last_cell.flags.contains(Flags::WRAPLINE) {
1352                break;
1353            }
1354            line_start -= 1;
1355        }
1356        line_start
1357    }
1358
1359    fn construct_logical_line(&self, grid: &Grid<Cell>, start: i32, end: i32) -> String {
1360        let mut logical_line = String::new();
1361        for row in start..=end {
1362            let grid_row = &grid[Line(row)];
1363            logical_line.push_str(&row_to_string(grid_row));
1364        }
1365        logical_line
1366    }
1367
1368    fn process_line(&self, line: String) -> Option<String> {
1369        let trimmed = line.trim_end().to_string();
1370        if !trimmed.is_empty() {
1371            Some(trimmed)
1372        } else {
1373            None
1374        }
1375    }
1376
1377    pub fn focus_in(&self) {
1378        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1379            self.write_to_pty("\x1b[I".as_bytes());
1380        }
1381    }
1382
1383    pub fn focus_out(&mut self) {
1384        if self.last_content.mode.contains(TermMode::FOCUS_IN_OUT) {
1385            self.write_to_pty("\x1b[O".as_bytes());
1386        }
1387    }
1388
1389    pub fn mouse_changed(&mut self, point: AlacPoint, side: AlacDirection) -> bool {
1390        match self.last_mouse {
1391            Some((old_point, old_side)) => {
1392                if old_point == point && old_side == side {
1393                    false
1394                } else {
1395                    self.last_mouse = Some((point, side));
1396                    true
1397                }
1398            }
1399            None => {
1400                self.last_mouse = Some((point, side));
1401                true
1402            }
1403        }
1404    }
1405
1406    pub fn mouse_mode(&self, shift: bool) -> bool {
1407        self.last_content.mode.intersects(TermMode::MOUSE_MODE) && !shift
1408    }
1409
1410    pub fn mouse_move(&mut self, e: &MouseMoveEvent, cx: &mut Context<Self>) {
1411        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1412        if self.mouse_mode(e.modifiers.shift) {
1413            let (point, side) = grid_point_and_side(
1414                position,
1415                self.last_content.terminal_bounds,
1416                self.last_content.display_offset,
1417            );
1418
1419            if self.mouse_changed(point, side) {
1420                if let Some(bytes) =
1421                    mouse_moved_report(point, e.pressed_button, e.modifiers, self.last_content.mode)
1422                {
1423                    self.pty_tx.notify(bytes);
1424                }
1425            }
1426        } else if e.modifiers.secondary() {
1427            self.word_from_position(e.position);
1428        }
1429        cx.notify();
1430    }
1431
1432    fn word_from_position(&mut self, position: Point<Pixels>) {
1433        if self.selection_phase == SelectionPhase::Selecting {
1434            self.last_content.last_hovered_word = None;
1435        } else if self.last_content.terminal_bounds.bounds.contains(&position) {
1436            self.events.push_back(InternalEvent::FindHyperlink(
1437                position - self.last_content.terminal_bounds.bounds.origin,
1438                false,
1439            ));
1440        } else {
1441            self.last_content.last_hovered_word = None;
1442        }
1443    }
1444
1445    pub fn select_word_at_event_position(&mut self, e: &MouseDownEvent) {
1446        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1447        let (point, side) = grid_point_and_side(
1448            position,
1449            self.last_content.terminal_bounds,
1450            self.last_content.display_offset,
1451        );
1452        let selection = Selection::new(SelectionType::Semantic, point, side);
1453        self.events
1454            .push_back(InternalEvent::SetSelection(Some((selection, point))));
1455    }
1456
1457    pub fn mouse_drag(
1458        &mut self,
1459        e: &MouseMoveEvent,
1460        region: Bounds<Pixels>,
1461        cx: &mut Context<Self>,
1462    ) {
1463        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1464        if !self.mouse_mode(e.modifiers.shift) {
1465            self.selection_phase = SelectionPhase::Selecting;
1466            // Alacritty has the same ordering, of first updating the selection
1467            // then scrolling 15ms later
1468            self.events
1469                .push_back(InternalEvent::UpdateSelection(position));
1470
1471            // Doesn't make sense to scroll the alt screen
1472            if !self.last_content.mode.contains(TermMode::ALT_SCREEN) {
1473                let scroll_lines = match self.drag_line_delta(e, region) {
1474                    Some(value) => value,
1475                    None => return,
1476                };
1477
1478                self.events
1479                    .push_back(InternalEvent::Scroll(AlacScroll::Delta(scroll_lines)));
1480            }
1481
1482            cx.notify();
1483        }
1484    }
1485
1486    fn drag_line_delta(&self, e: &MouseMoveEvent, region: Bounds<Pixels>) -> Option<i32> {
1487        let top = region.origin.y;
1488        let bottom = region.bottom_left().y;
1489
1490        let scroll_lines = if e.position.y < top {
1491            let scroll_delta = (top - e.position.y).pow(1.1);
1492            (scroll_delta / self.last_content.terminal_bounds.line_height).ceil() as i32
1493        } else if e.position.y > bottom {
1494            let scroll_delta = -((e.position.y - bottom).pow(1.1));
1495            (scroll_delta / self.last_content.terminal_bounds.line_height).floor() as i32
1496        } else {
1497            return None;
1498        };
1499
1500        Some(scroll_lines.clamp(-3, 3))
1501    }
1502
1503    pub fn mouse_down(&mut self, e: &MouseDownEvent, _cx: &mut Context<Self>) {
1504        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1505        let point = grid_point(
1506            position,
1507            self.last_content.terminal_bounds,
1508            self.last_content.display_offset,
1509        );
1510
1511        if self.mouse_mode(e.modifiers.shift) {
1512            if let Some(bytes) =
1513                mouse_button_report(point, e.button, e.modifiers, true, self.last_content.mode)
1514            {
1515                self.pty_tx.notify(bytes);
1516            }
1517        } else {
1518            match e.button {
1519                MouseButton::Left => {
1520                    let (point, side) = grid_point_and_side(
1521                        position,
1522                        self.last_content.terminal_bounds,
1523                        self.last_content.display_offset,
1524                    );
1525
1526                    let selection_type = match e.click_count {
1527                        0 => return, //This is a release
1528                        1 => Some(SelectionType::Simple),
1529                        2 => Some(SelectionType::Semantic),
1530                        3 => Some(SelectionType::Lines),
1531                        _ => None,
1532                    };
1533
1534                    if selection_type == Some(SelectionType::Simple) && e.modifiers.shift {
1535                        self.events
1536                            .push_back(InternalEvent::UpdateSelection(position));
1537                        return;
1538                    }
1539
1540                    let selection = selection_type
1541                        .map(|selection_type| Selection::new(selection_type, point, side));
1542
1543                    if let Some(sel) = selection {
1544                        self.events
1545                            .push_back(InternalEvent::SetSelection(Some((sel, point))));
1546                    }
1547                }
1548                #[cfg(any(target_os = "linux", target_os = "freebsd"))]
1549                MouseButton::Middle => {
1550                    if let Some(item) = _cx.read_from_primary() {
1551                        let text = item.text().unwrap_or_default().to_string();
1552                        self.input(text.into_bytes());
1553                    }
1554                }
1555                _ => {}
1556            }
1557        }
1558    }
1559
1560    pub fn mouse_up(&mut self, e: &MouseUpEvent, cx: &Context<Self>) {
1561        let setting = TerminalSettings::get_global(cx);
1562
1563        let position = e.position - self.last_content.terminal_bounds.bounds.origin;
1564        if self.mouse_mode(e.modifiers.shift) {
1565            let point = grid_point(
1566                position,
1567                self.last_content.terminal_bounds,
1568                self.last_content.display_offset,
1569            );
1570
1571            if let Some(bytes) =
1572                mouse_button_report(point, e.button, e.modifiers, false, self.last_content.mode)
1573            {
1574                self.pty_tx.notify(bytes);
1575            }
1576        } else {
1577            if e.button == MouseButton::Left && setting.copy_on_select {
1578                self.copy();
1579            }
1580
1581            //Hyperlinks
1582            if self.selection_phase == SelectionPhase::Ended {
1583                let mouse_cell_index =
1584                    content_index_for_mouse(position, &self.last_content.terminal_bounds);
1585                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
1586                    cx.open_url(link.uri());
1587                } else if e.modifiers.secondary() {
1588                    self.events
1589                        .push_back(InternalEvent::FindHyperlink(position, true));
1590                }
1591            }
1592        }
1593
1594        self.selection_phase = SelectionPhase::Ended;
1595        self.last_mouse = None;
1596    }
1597
1598    ///Scroll the terminal
1599    pub fn scroll_wheel(&mut self, e: &ScrollWheelEvent) {
1600        let mouse_mode = self.mouse_mode(e.shift);
1601
1602        if let Some(scroll_lines) = self.determine_scroll_lines(e, mouse_mode) {
1603            if mouse_mode {
1604                let point = grid_point(
1605                    e.position - self.last_content.terminal_bounds.bounds.origin,
1606                    self.last_content.terminal_bounds,
1607                    self.last_content.display_offset,
1608                );
1609
1610                if let Some(scrolls) = scroll_report(point, scroll_lines, e, self.last_content.mode)
1611                {
1612                    for scroll in scrolls {
1613                        self.pty_tx.notify(scroll);
1614                    }
1615                };
1616            } else if self
1617                .last_content
1618                .mode
1619                .contains(TermMode::ALT_SCREEN | TermMode::ALTERNATE_SCROLL)
1620                && !e.shift
1621            {
1622                self.pty_tx.notify(alt_scroll(scroll_lines))
1623            } else if scroll_lines != 0 {
1624                let scroll = AlacScroll::Delta(scroll_lines);
1625
1626                self.events.push_back(InternalEvent::Scroll(scroll));
1627            }
1628        }
1629    }
1630
1631    fn refresh_hovered_word(&mut self, window: &Window) {
1632        self.word_from_position(window.mouse_position());
1633    }
1634
1635    fn determine_scroll_lines(&mut self, e: &ScrollWheelEvent, mouse_mode: bool) -> Option<i32> {
1636        let scroll_multiplier = if mouse_mode { 1. } else { SCROLL_MULTIPLIER };
1637        let line_height = self.last_content.terminal_bounds.line_height;
1638        match e.touch_phase {
1639            /* Reset scroll state on started */
1640            TouchPhase::Started => {
1641                self.scroll_px = px(0.);
1642                None
1643            }
1644            /* Calculate the appropriate scroll lines */
1645            TouchPhase::Moved => {
1646                let old_offset = (self.scroll_px / line_height) as i32;
1647
1648                self.scroll_px += e.delta.pixel_delta(line_height).y * scroll_multiplier;
1649
1650                let new_offset = (self.scroll_px / line_height) as i32;
1651
1652                // Whenever we hit the edges, reset our stored scroll to 0
1653                // so we can respond to changes in direction quickly
1654                self.scroll_px %= self.last_content.terminal_bounds.height();
1655
1656                Some(new_offset - old_offset)
1657            }
1658            TouchPhase::Ended => None,
1659        }
1660    }
1661
1662    pub fn find_matches(
1663        &self,
1664        mut searcher: RegexSearch,
1665        cx: &Context<Self>,
1666    ) -> Task<Vec<RangeInclusive<AlacPoint>>> {
1667        let term = self.term.clone();
1668        cx.background_spawn(async move {
1669            let term = term.lock();
1670
1671            all_search_matches(&term, &mut searcher).collect()
1672        })
1673    }
1674
1675    pub fn working_directory(&self) -> Option<PathBuf> {
1676        if self.is_ssh_terminal {
1677            // We can't yet reliably detect the working directory of a shell on the
1678            // SSH host. Until we can do that, it doesn't make sense to display
1679            // the working directory on the client and persist that.
1680            None
1681        } else {
1682            self.client_side_working_directory()
1683        }
1684    }
1685
1686    /// Returns the working directory of the process that's connected to the PTY.
1687    /// That means it returns the working directory of the local shell or program
1688    /// that's running inside the terminal.
1689    ///
1690    /// This does *not* return the working directory of the shell that runs on the
1691    /// remote host, in case Zed is connected to a remote host.
1692    fn client_side_working_directory(&self) -> Option<PathBuf> {
1693        self.pty_info
1694            .current
1695            .as_ref()
1696            .map(|process| process.cwd.clone())
1697    }
1698
1699    pub fn title(&self, truncate: bool) -> String {
1700        const MAX_CHARS: usize = 25;
1701        match &self.task {
1702            Some(task_state) => {
1703                if truncate {
1704                    truncate_and_trailoff(&task_state.label, MAX_CHARS)
1705                } else {
1706                    task_state.full_label.clone()
1707                }
1708            }
1709            None => self
1710                .title_override
1711                .as_ref()
1712                .map(|title_override| title_override.to_string())
1713                .unwrap_or_else(|| {
1714                    self.pty_info
1715                        .current
1716                        .as_ref()
1717                        .map(|fpi| {
1718                            let process_file = fpi
1719                                .cwd
1720                                .file_name()
1721                                .map(|name| name.to_string_lossy().to_string())
1722                                .unwrap_or_default();
1723
1724                            let argv = fpi.argv.as_slice();
1725                            let process_name = format!(
1726                                "{}{}",
1727                                fpi.name,
1728                                if !argv.is_empty() {
1729                                    format!(" {}", (argv[1..]).join(" "))
1730                                } else {
1731                                    "".to_string()
1732                                }
1733                            );
1734                            let (process_file, process_name) = if truncate {
1735                                (
1736                                    truncate_and_trailoff(&process_file, MAX_CHARS),
1737                                    truncate_and_trailoff(&process_name, MAX_CHARS),
1738                                )
1739                            } else {
1740                                (process_file, process_name)
1741                            };
1742                            format!("{process_file}{process_name}")
1743                        })
1744                        .unwrap_or_else(|| "Terminal".to_string())
1745                }),
1746        }
1747    }
1748
1749    pub fn task(&self) -> Option<&TaskState> {
1750        self.task.as_ref()
1751    }
1752
1753    pub fn wait_for_completed_task(&self, cx: &App) -> Task<Option<ExitStatus>> {
1754        if let Some(task) = self.task() {
1755            if task.status == TaskStatus::Running {
1756                let completion_receiver = task.completion_rx.clone();
1757                return cx.spawn(async move |_| completion_receiver.recv().await.ok().flatten());
1758            } else if let Ok(status) = task.completion_rx.try_recv() {
1759                return Task::ready(status);
1760            }
1761        }
1762        Task::ready(None)
1763    }
1764
1765    fn register_task_finished(&mut self, error_code: Option<i32>, cx: &mut Context<Terminal>) {
1766        let e: Option<ExitStatus> = error_code.map(|code| {
1767            #[cfg(unix)]
1768            {
1769                return std::os::unix::process::ExitStatusExt::from_raw(code);
1770            }
1771            #[cfg(windows)]
1772            {
1773                return std::os::windows::process::ExitStatusExt::from_raw(code as u32);
1774            }
1775        });
1776
1777        self.completion_tx.try_send(e).ok();
1778        let task = match &mut self.task {
1779            Some(task) => task,
1780            None => {
1781                if error_code.is_none() {
1782                    cx.emit(Event::CloseTerminal);
1783                }
1784                return;
1785            }
1786        };
1787        if task.status != TaskStatus::Running {
1788            return;
1789        }
1790        match error_code {
1791            Some(error_code) => {
1792                task.status.register_task_exit(error_code);
1793            }
1794            None => {
1795                task.status.register_terminal_exit();
1796            }
1797        };
1798
1799        let (finished_successfully, task_line, command_line) = task_summary(task, error_code);
1800        let mut lines_to_show = Vec::new();
1801        if task.show_summary {
1802            lines_to_show.push(task_line.as_str());
1803        }
1804        if task.show_command {
1805            lines_to_show.push(command_line.as_str());
1806        }
1807
1808        if !lines_to_show.is_empty() {
1809            // SAFETY: the invocation happens on non `TaskStatus::Running` tasks, once,
1810            // after either `AlacTermEvent::Exit` or `AlacTermEvent::ChildExit` events that are spawned
1811            // when Zed task finishes and no more output is made.
1812            // After the task summary is output once, no more text is appended to the terminal.
1813            unsafe { append_text_to_term(&mut self.term.lock(), &lines_to_show) };
1814        }
1815
1816        match task.hide {
1817            HideStrategy::Never => {}
1818            HideStrategy::Always => {
1819                cx.emit(Event::CloseTerminal);
1820            }
1821            HideStrategy::OnSuccess => {
1822                if finished_successfully {
1823                    cx.emit(Event::CloseTerminal);
1824                }
1825            }
1826        }
1827    }
1828
1829    pub fn vi_mode_enabled(&self) -> bool {
1830        self.vi_mode_enabled
1831    }
1832}
1833
1834// Helper function to convert a grid row to a string
1835pub fn row_to_string(row: &Row<Cell>) -> String {
1836    row[..Column(row.len())]
1837        .iter()
1838        .map(|cell| cell.c)
1839        .collect::<String>()
1840}
1841
1842const TASK_DELIMITER: &str = "";
1843fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
1844    let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
1845    let (success, task_line) = match error_code {
1846        Some(0) => (
1847            true,
1848            format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
1849        ),
1850        Some(error_code) => (
1851            false,
1852            format!(
1853                "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
1854            ),
1855        ),
1856        None => (
1857            false,
1858            format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
1859        ),
1860    };
1861    let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
1862    let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");
1863    (success, task_line, command_line)
1864}
1865
1866/// Appends a stringified task summary to the terminal, after its output.
1867///
1868/// SAFETY: This function should only be called after terminal's PTY is no longer alive.
1869/// New text being added to the terminal here, uses "less public" APIs,
1870/// which are not maintaining the entire terminal state intact.
1871///
1872///
1873/// The library
1874///
1875/// * does not increment inner grid cursor's _lines_ on `input` calls
1876///   (but displaying the lines correctly and incrementing cursor's columns)
1877///
1878/// * ignores `\n` and \r` character input, requiring the `newline` call instead
1879///
1880/// * does not alter grid state after `newline` call
1881///   so its `bottommost_line` is always the same additions, and
1882///   the cursor's `point` is not updated to the new line and column values
1883///
1884/// * ??? there could be more consequences, and any further "proper" streaming from the PTY might bug and/or panic.
1885///   Still, subsequent `append_text_to_term` invocations are possible and display the contents correctly.
1886///
1887/// Despite the quirks, this is the simplest approach to appending text to the terminal: its alternative, `grid_mut` manipulations,
1888/// do not properly set the scrolling state and display odd text after appending; also those manipulations are more tedious and error-prone.
1889/// The function achieves proper display and scrolling capabilities, at a cost of grid state not properly synchronized.
1890/// This is enough for printing moderately-sized texts like task summaries, but might break or perform poorly for larger texts.
1891unsafe fn append_text_to_term(term: &mut Term<ZedListener>, text_lines: &[&str]) {
1892    term.newline();
1893    term.grid_mut().cursor.point.column = Column(0);
1894    for line in text_lines {
1895        for c in line.chars() {
1896            term.input(c);
1897        }
1898        term.newline();
1899        term.grid_mut().cursor.point.column = Column(0);
1900    }
1901}
1902
1903impl Drop for Terminal {
1904    fn drop(&mut self) {
1905        self.pty_tx.0.send(Msg::Shutdown).ok();
1906    }
1907}
1908
1909impl EventEmitter<Event> for Terminal {}
1910
1911fn make_selection(range: &RangeInclusive<AlacPoint>) -> Selection {
1912    let mut selection = Selection::new(SelectionType::Simple, *range.start(), AlacDirection::Left);
1913    selection.update(*range.end(), AlacDirection::Right);
1914    selection
1915}
1916
1917fn all_search_matches<'a, T>(
1918    term: &'a Term<T>,
1919    regex: &'a mut RegexSearch,
1920) -> impl Iterator<Item = Match> + 'a {
1921    let start = AlacPoint::new(term.grid().topmost_line(), Column(0));
1922    let end = AlacPoint::new(term.grid().bottommost_line(), term.grid().last_column());
1923    RegexIter::new(start, end, AlacDirection::Right, term, regex)
1924}
1925
1926fn content_index_for_mouse(pos: Point<Pixels>, terminal_bounds: &TerminalBounds) -> usize {
1927    let col = (pos.x / terminal_bounds.cell_width()).round() as usize;
1928    let clamped_col = min(col, terminal_bounds.columns() - 1);
1929    let row = (pos.y / terminal_bounds.line_height()).round() as usize;
1930    let clamped_row = min(row, terminal_bounds.screen_lines() - 1);
1931    clamped_row * terminal_bounds.columns() + clamped_col
1932}
1933
1934/// Converts an 8 bit ANSI color to its GPUI equivalent.
1935/// Accepts `usize` for compatibility with the `alacritty::Colors` interface,
1936/// Other than that use case, should only be called with values in the `[0,255]` range
1937pub fn get_color_at_index(index: usize, theme: &Theme) -> Hsla {
1938    let colors = theme.colors();
1939
1940    match index {
1941        // 0-15 are the same as the named colors above
1942        0 => colors.terminal_ansi_black,
1943        1 => colors.terminal_ansi_red,
1944        2 => colors.terminal_ansi_green,
1945        3 => colors.terminal_ansi_yellow,
1946        4 => colors.terminal_ansi_blue,
1947        5 => colors.terminal_ansi_magenta,
1948        6 => colors.terminal_ansi_cyan,
1949        7 => colors.terminal_ansi_white,
1950        8 => colors.terminal_ansi_bright_black,
1951        9 => colors.terminal_ansi_bright_red,
1952        10 => colors.terminal_ansi_bright_green,
1953        11 => colors.terminal_ansi_bright_yellow,
1954        12 => colors.terminal_ansi_bright_blue,
1955        13 => colors.terminal_ansi_bright_magenta,
1956        14 => colors.terminal_ansi_bright_cyan,
1957        15 => colors.terminal_ansi_bright_white,
1958        // 16-231 are a 6x6x6 RGB color cube, mapped to 0-255 using steps defined by XTerm.
1959        // See: https://github.com/xterm-x11/xterm-snapshots/blob/master/256colres.pl
1960        16..=231 => {
1961            let (r, g, b) = rgb_for_index(index as u8);
1962            rgba_color(
1963                if r == 0 { 0 } else { r * 40 + 55 },
1964                if g == 0 { 0 } else { g * 40 + 55 },
1965                if b == 0 { 0 } else { b * 40 + 55 },
1966            )
1967        }
1968        // 232-255 are a 24-step grayscale ramp from (8, 8, 8) to (238, 238, 238).
1969        232..=255 => {
1970            let i = index as u8 - 232; // Align index to 0..24
1971            let value = i * 10 + 8;
1972            rgba_color(value, value, value)
1973        }
1974        // For compatibility with the alacritty::Colors interface
1975        // See: https://github.com/alacritty/alacritty/blob/master/alacritty_terminal/src/term/color.rs
1976        256 => colors.terminal_foreground,
1977        257 => colors.terminal_background,
1978        258 => theme.players().local().cursor,
1979        259 => colors.terminal_ansi_dim_black,
1980        260 => colors.terminal_ansi_dim_red,
1981        261 => colors.terminal_ansi_dim_green,
1982        262 => colors.terminal_ansi_dim_yellow,
1983        263 => colors.terminal_ansi_dim_blue,
1984        264 => colors.terminal_ansi_dim_magenta,
1985        265 => colors.terminal_ansi_dim_cyan,
1986        266 => colors.terminal_ansi_dim_white,
1987        267 => colors.terminal_bright_foreground,
1988        268 => colors.terminal_ansi_black, // 'Dim Background', non-standard color
1989
1990        _ => black(),
1991    }
1992}
1993
1994/// Generates the RGB channels in [0, 5] for a given index into the 6x6x6 ANSI color cube.
1995/// See: [8 bit ANSI color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1996///
1997/// Wikipedia gives a formula for calculating the index for a given color:
1998///
1999/// ```
2000/// index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
2001/// ```
2002///
2003/// This function does the reverse, calculating the `r`, `g`, and `b` components from a given index.
2004fn rgb_for_index(i: u8) -> (u8, u8, u8) {
2005    debug_assert!((16..=231).contains(&i));
2006    let i = i - 16;
2007    let r = (i - (i % 36)) / 36;
2008    let g = ((i % 36) - (i % 6)) / 6;
2009    let b = (i % 36) % 6;
2010    (r, g, b)
2011}
2012
2013pub fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
2014    Rgba {
2015        r: (r as f32 / 255.),
2016        g: (g as f32 / 255.),
2017        b: (b as f32 / 255.),
2018        a: 1.,
2019    }
2020    .into()
2021}
2022
2023#[cfg(test)]
2024mod tests {
2025    use alacritty_terminal::{
2026        index::{Column, Line, Point as AlacPoint},
2027        term::cell::Cell,
2028    };
2029    use gpui::{Pixels, Point, bounds, point, size};
2030    use rand::{Rng, distributions::Alphanumeric, rngs::ThreadRng, thread_rng};
2031
2032    use crate::{
2033        IndexedCell, TerminalBounds, TerminalContent, content_index_for_mouse, rgb_for_index,
2034    };
2035
2036    #[test]
2037    fn test_rgb_for_index() {
2038        // Test every possible value in the color cube.
2039        for i in 16..=231 {
2040            let (r, g, b) = rgb_for_index(i);
2041            assert_eq!(i, 16 + 36 * r + 6 * g + b);
2042        }
2043    }
2044
2045    #[test]
2046    fn test_mouse_to_cell_test() {
2047        let mut rng = thread_rng();
2048        const ITERATIONS: usize = 10;
2049        const PRECISION: usize = 1000;
2050
2051        for _ in 0..ITERATIONS {
2052            let viewport_cells = rng.gen_range(15..20);
2053            let cell_size = rng.gen_range(5 * PRECISION..20 * PRECISION) as f32 / PRECISION as f32;
2054
2055            let size = crate::TerminalBounds {
2056                cell_width: Pixels::from(cell_size),
2057                line_height: Pixels::from(cell_size),
2058                bounds: bounds(
2059                    Point::default(),
2060                    size(
2061                        Pixels::from(cell_size * (viewport_cells as f32)),
2062                        Pixels::from(cell_size * (viewport_cells as f32)),
2063                    ),
2064                ),
2065            };
2066
2067            let cells = get_cells(size, &mut rng);
2068            let content = convert_cells_to_content(size, &cells);
2069
2070            for row in 0..(viewport_cells - 1) {
2071                let row = row as usize;
2072                for col in 0..(viewport_cells - 1) {
2073                    let col = col as usize;
2074
2075                    let row_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2076                    let col_offset = rng.gen_range(0..PRECISION) as f32 / PRECISION as f32;
2077
2078                    let mouse_pos = point(
2079                        Pixels::from(col as f32 * cell_size + col_offset),
2080                        Pixels::from(row as f32 * cell_size + row_offset),
2081                    );
2082
2083                    let content_index =
2084                        content_index_for_mouse(mouse_pos, &content.terminal_bounds);
2085                    let mouse_cell = content.cells[content_index].c;
2086                    let real_cell = cells[row][col];
2087
2088                    assert_eq!(mouse_cell, real_cell);
2089                }
2090            }
2091        }
2092    }
2093
2094    #[test]
2095    fn test_mouse_to_cell_clamp() {
2096        let mut rng = thread_rng();
2097
2098        let size = crate::TerminalBounds {
2099            cell_width: Pixels::from(10.),
2100            line_height: Pixels::from(10.),
2101            bounds: bounds(
2102                Point::default(),
2103                size(Pixels::from(100.), Pixels::from(100.)),
2104            ),
2105        };
2106
2107        let cells = get_cells(size, &mut rng);
2108        let content = convert_cells_to_content(size, &cells);
2109
2110        assert_eq!(
2111            content.cells[content_index_for_mouse(
2112                point(Pixels::from(-10.), Pixels::from(-10.)),
2113                &content.terminal_bounds,
2114            )]
2115            .c,
2116            cells[0][0]
2117        );
2118        assert_eq!(
2119            content.cells[content_index_for_mouse(
2120                point(Pixels::from(1000.), Pixels::from(1000.)),
2121                &content.terminal_bounds,
2122            )]
2123            .c,
2124            cells[9][9]
2125        );
2126    }
2127
2128    fn get_cells(size: TerminalBounds, rng: &mut ThreadRng) -> Vec<Vec<char>> {
2129        let mut cells = Vec::new();
2130
2131        for _ in 0..((size.height() / size.line_height()) as usize) {
2132            let mut row_vec = Vec::new();
2133            for _ in 0..((size.width() / size.cell_width()) as usize) {
2134                let cell_char = rng.sample(Alphanumeric) as char;
2135                row_vec.push(cell_char)
2136            }
2137            cells.push(row_vec)
2138        }
2139
2140        cells
2141    }
2142
2143    fn convert_cells_to_content(
2144        terminal_bounds: TerminalBounds,
2145        cells: &[Vec<char>],
2146    ) -> TerminalContent {
2147        let mut ic = Vec::new();
2148
2149        for (index, row) in cells.iter().enumerate() {
2150            for (cell_index, cell_char) in row.iter().enumerate() {
2151                ic.push(IndexedCell {
2152                    point: AlacPoint::new(Line(index as i32), Column(cell_index)),
2153                    cell: Cell {
2154                        c: *cell_char,
2155                        ..Default::default()
2156                    },
2157                });
2158            }
2159        }
2160
2161        TerminalContent {
2162            cells: ic,
2163            terminal_bounds,
2164            ..Default::default()
2165        }
2166    }
2167}