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