terminal.rs

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