terminal_element.rs

   1use editor::{CursorLayout, HighlightedRange, HighlightedRangeLine};
   2use gpui::{
   3    div, fill, point, px, relative, size, AnyElement, App, AvailableSpace, Bounds, ContentMask,
   4    Context, DispatchPhase, Element, ElementId, Entity, FocusHandle, Font, FontStyle, FontWeight,
   5    GlobalElementId, HighlightStyle, Hitbox, Hsla, InputHandler, InteractiveElement, Interactivity,
   6    IntoElement, LayoutId, ModifiersChangedEvent, MouseButton, MouseMoveEvent, Pixels, Point,
   7    ShapedLine, StatefulInteractiveElement, StrikethroughStyle, Styled, TextRun, TextStyle,
   8    UTF16Selection, UnderlineStyle, WeakEntity, WhiteSpace, Window, WindowTextSystem,
   9};
  10use itertools::Itertools;
  11use language::CursorShape;
  12use settings::Settings;
  13use terminal::{
  14    alacritty_terminal::{
  15        grid::Dimensions,
  16        index::Point as AlacPoint,
  17        term::{cell::Flags, TermMode},
  18        vte::ansi::{
  19            Color::{self as AnsiColor, Named},
  20            CursorShape as AlacCursorShape, NamedColor,
  21        },
  22    },
  23    terminal_settings::TerminalSettings,
  24    IndexedCell, Terminal, TerminalBounds, TerminalContent,
  25};
  26use theme::{ActiveTheme, Theme, ThemeSettings};
  27use ui::{ParentElement, Tooltip};
  28use workspace::Workspace;
  29
  30use std::mem;
  31use std::{fmt::Debug, ops::RangeInclusive, rc::Rc};
  32
  33use crate::{BlockContext, BlockProperties, TerminalView};
  34
  35/// The information generated during layout that is necessary for painting.
  36pub struct LayoutState {
  37    hitbox: Hitbox,
  38    cells: Vec<LayoutCell>,
  39    rects: Vec<LayoutRect>,
  40    relative_highlighted_ranges: Vec<(RangeInclusive<AlacPoint>, Hsla)>,
  41    cursor: Option<CursorLayout>,
  42    background_color: Hsla,
  43    dimensions: TerminalBounds,
  44    mode: TermMode,
  45    display_offset: usize,
  46    hyperlink_tooltip: Option<AnyElement>,
  47    gutter: Pixels,
  48    block_below_cursor_element: Option<AnyElement>,
  49}
  50
  51/// Helper struct for converting data between Alacritty's cursor points, and displayed cursor points.
  52struct DisplayCursor {
  53    line: i32,
  54    col: usize,
  55}
  56
  57impl DisplayCursor {
  58    fn from(cursor_point: AlacPoint, display_offset: usize) -> Self {
  59        Self {
  60            line: cursor_point.line.0 + display_offset as i32,
  61            col: cursor_point.column.0,
  62        }
  63    }
  64
  65    pub fn line(&self) -> i32 {
  66        self.line
  67    }
  68
  69    pub fn col(&self) -> usize {
  70        self.col
  71    }
  72}
  73
  74#[derive(Debug, Default)]
  75pub struct LayoutCell {
  76    pub point: AlacPoint<i32, i32>,
  77    text: gpui::ShapedLine,
  78}
  79
  80impl LayoutCell {
  81    fn new(point: AlacPoint<i32, i32>, text: gpui::ShapedLine) -> LayoutCell {
  82        LayoutCell { point, text }
  83    }
  84
  85    pub fn paint(
  86        &self,
  87        origin: Point<Pixels>,
  88        dimensions: &TerminalBounds,
  89        _visible_bounds: Bounds<Pixels>,
  90        window: &mut Window,
  91        cx: &mut App,
  92    ) {
  93        let pos = {
  94            let point = self.point;
  95
  96            Point::new(
  97                (origin.x + point.column as f32 * dimensions.cell_width).floor(),
  98                origin.y + point.line as f32 * dimensions.line_height,
  99            )
 100        };
 101
 102        self.text
 103            .paint(pos, dimensions.line_height, window, cx)
 104            .ok();
 105    }
 106}
 107
 108#[derive(Clone, Debug, Default)]
 109pub struct LayoutRect {
 110    point: AlacPoint<i32, i32>,
 111    num_of_cells: usize,
 112    color: Hsla,
 113}
 114
 115impl LayoutRect {
 116    fn new(point: AlacPoint<i32, i32>, num_of_cells: usize, color: Hsla) -> LayoutRect {
 117        LayoutRect {
 118            point,
 119            num_of_cells,
 120            color,
 121        }
 122    }
 123
 124    fn extend(&self) -> Self {
 125        LayoutRect {
 126            point: self.point,
 127            num_of_cells: self.num_of_cells + 1,
 128            color: self.color,
 129        }
 130    }
 131
 132    pub fn paint(&self, origin: Point<Pixels>, dimensions: &TerminalBounds, window: &mut Window) {
 133        let position = {
 134            let alac_point = self.point;
 135            point(
 136                (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
 137                origin.y + alac_point.line as f32 * dimensions.line_height,
 138            )
 139        };
 140        let size = point(
 141            (dimensions.cell_width * self.num_of_cells as f32).ceil(),
 142            dimensions.line_height,
 143        )
 144        .into();
 145
 146        window.paint_quad(fill(Bounds::new(position, size), self.color));
 147    }
 148}
 149
 150/// The GPUI element that paints the terminal.
 151/// We need to keep a reference to the model for mouse events, do we need it for any other terminal stuff, or can we move that to connection?
 152pub struct TerminalElement {
 153    terminal: Entity<Terminal>,
 154    terminal_view: Entity<TerminalView>,
 155    workspace: WeakEntity<Workspace>,
 156    focus: FocusHandle,
 157    focused: bool,
 158    cursor_visible: bool,
 159    interactivity: Interactivity,
 160    block_below_cursor: Option<Rc<BlockProperties>>,
 161}
 162
 163impl InteractiveElement for TerminalElement {
 164    fn interactivity(&mut self) -> &mut Interactivity {
 165        &mut self.interactivity
 166    }
 167}
 168
 169impl StatefulInteractiveElement for TerminalElement {}
 170
 171impl TerminalElement {
 172    pub fn new(
 173        terminal: Entity<Terminal>,
 174        terminal_view: Entity<TerminalView>,
 175        workspace: WeakEntity<Workspace>,
 176        focus: FocusHandle,
 177        focused: bool,
 178        cursor_visible: bool,
 179        block_below_cursor: Option<Rc<BlockProperties>>,
 180    ) -> TerminalElement {
 181        TerminalElement {
 182            terminal,
 183            terminal_view,
 184            workspace,
 185            focused,
 186            focus: focus.clone(),
 187            cursor_visible,
 188            block_below_cursor,
 189            interactivity: Default::default(),
 190        }
 191        .track_focus(&focus)
 192        .element
 193    }
 194
 195    //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
 196
 197    pub fn layout_grid(
 198        grid: impl Iterator<Item = IndexedCell>,
 199        text_style: &TextStyle,
 200        // terminal_theme: &TerminalStyle,
 201        text_system: &WindowTextSystem,
 202        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 203        window: &Window,
 204        cx: &App,
 205    ) -> (Vec<LayoutCell>, Vec<LayoutRect>) {
 206        let theme = cx.theme();
 207        let mut cells = vec![];
 208        let mut rects = vec![];
 209
 210        let mut cur_rect: Option<LayoutRect> = None;
 211        let mut cur_alac_color = None;
 212
 213        let linegroups = grid.into_iter().chunk_by(|i| i.point.line);
 214        for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
 215            for cell in line {
 216                let mut fg = cell.fg;
 217                let mut bg = cell.bg;
 218                if cell.flags.contains(Flags::INVERSE) {
 219                    mem::swap(&mut fg, &mut bg);
 220                }
 221
 222                //Expand background rect range
 223                {
 224                    if matches!(bg, Named(NamedColor::Background)) {
 225                        //Continue to next cell, resetting variables if necessary
 226                        cur_alac_color = None;
 227                        if let Some(rect) = cur_rect {
 228                            rects.push(rect);
 229                            cur_rect = None
 230                        }
 231                    } else {
 232                        match cur_alac_color {
 233                            Some(cur_color) => {
 234                                if bg == cur_color {
 235                                    // `cur_rect` can be None if it was moved to the `rects` vec after wrapping around
 236                                    // from one line to the next. The variables are all set correctly but there is no current
 237                                    // rect, so we create one if necessary.
 238                                    cur_rect = cur_rect.map_or_else(
 239                                        || {
 240                                            Some(LayoutRect::new(
 241                                                AlacPoint::new(
 242                                                    line_index as i32,
 243                                                    cell.point.column.0 as i32,
 244                                                ),
 245                                                1,
 246                                                convert_color(&bg, theme),
 247                                            ))
 248                                        },
 249                                        |rect| Some(rect.extend()),
 250                                    );
 251                                } else {
 252                                    cur_alac_color = Some(bg);
 253                                    if cur_rect.is_some() {
 254                                        rects.push(cur_rect.take().unwrap());
 255                                    }
 256                                    cur_rect = Some(LayoutRect::new(
 257                                        AlacPoint::new(
 258                                            line_index as i32,
 259                                            cell.point.column.0 as i32,
 260                                        ),
 261                                        1,
 262                                        convert_color(&bg, theme),
 263                                    ));
 264                                }
 265                            }
 266                            None => {
 267                                cur_alac_color = Some(bg);
 268                                cur_rect = Some(LayoutRect::new(
 269                                    AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
 270                                    1,
 271                                    convert_color(&bg, theme),
 272                                ));
 273                            }
 274                        }
 275                    }
 276                }
 277
 278                //Layout current cell text
 279                {
 280                    if !is_blank(&cell) {
 281                        let cell_text = cell.c.to_string();
 282                        let cell_style =
 283                            TerminalElement::cell_style(&cell, fg, theme, text_style, hyperlink);
 284
 285                        let layout_cell = text_system
 286                            .shape_line(
 287                                cell_text.into(),
 288                                text_style.font_size.to_pixels(window.rem_size()),
 289                                &[cell_style],
 290                            )
 291                            .unwrap();
 292
 293                        cells.push(LayoutCell::new(
 294                            AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
 295                            layout_cell,
 296                        ))
 297                    };
 298                }
 299            }
 300
 301            if cur_rect.is_some() {
 302                rects.push(cur_rect.take().unwrap());
 303            }
 304        }
 305        (cells, rects)
 306    }
 307
 308    /// Computes the cursor position and expected block width, may return a zero width if x_for_index returns
 309    /// the same position for sequential indexes. Use em_width instead
 310    fn shape_cursor(
 311        cursor_point: DisplayCursor,
 312        size: TerminalBounds,
 313        text_fragment: &ShapedLine,
 314    ) -> Option<(Point<Pixels>, Pixels)> {
 315        if cursor_point.line() < size.total_lines() as i32 {
 316            let cursor_width = if text_fragment.width == Pixels::ZERO {
 317                size.cell_width()
 318            } else {
 319                text_fragment.width
 320            };
 321
 322            // Cursor should always surround as much of the text as possible,
 323            // hence when on pixel boundaries round the origin down and the width up
 324            Some((
 325                point(
 326                    (cursor_point.col() as f32 * size.cell_width()).floor(),
 327                    (cursor_point.line() as f32 * size.line_height()).floor(),
 328                ),
 329                cursor_width.ceil(),
 330            ))
 331        } else {
 332            None
 333        }
 334    }
 335
 336    /// Converts the Alacritty cell styles to GPUI text styles and background color.
 337    fn cell_style(
 338        indexed: &IndexedCell,
 339        fg: terminal::alacritty_terminal::vte::ansi::Color,
 340        // bg: terminal::alacritty_terminal::ansi::Color,
 341        colors: &Theme,
 342        text_style: &TextStyle,
 343        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 344    ) -> TextRun {
 345        let flags = indexed.cell.flags;
 346        let mut fg = convert_color(&fg, colors);
 347
 348        // Ghostty uses (175/255) as the multiplier (~0.69), Alacritty uses 0.66, Kitty
 349        // uses 0.75. We're using 0.7 because it's pretty well in the middle of that.
 350        if flags.intersects(Flags::DIM) {
 351            fg.a *= 0.7;
 352        }
 353
 354        let underline = (flags.intersects(Flags::ALL_UNDERLINES)
 355            || indexed.cell.hyperlink().is_some())
 356        .then(|| UnderlineStyle {
 357            color: Some(fg),
 358            thickness: Pixels::from(1.0),
 359            wavy: flags.contains(Flags::UNDERCURL),
 360        });
 361
 362        let strikethrough = flags
 363            .intersects(Flags::STRIKEOUT)
 364            .then(|| StrikethroughStyle {
 365                color: Some(fg),
 366                thickness: Pixels::from(1.0),
 367            });
 368
 369        let weight = if flags.intersects(Flags::BOLD) {
 370            FontWeight::BOLD
 371        } else {
 372            text_style.font_weight
 373        };
 374
 375        let style = if flags.intersects(Flags::ITALIC) {
 376            FontStyle::Italic
 377        } else {
 378            FontStyle::Normal
 379        };
 380
 381        let mut result = TextRun {
 382            len: indexed.c.len_utf8(),
 383            color: fg,
 384            background_color: None,
 385            font: Font {
 386                weight,
 387                style,
 388                ..text_style.font()
 389            },
 390            underline,
 391            strikethrough,
 392        };
 393
 394        if let Some((style, range)) = hyperlink {
 395            if range.contains(&indexed.point) {
 396                if let Some(underline) = style.underline {
 397                    result.underline = Some(underline);
 398                }
 399
 400                if let Some(color) = style.color {
 401                    result.color = color;
 402                }
 403            }
 404        }
 405
 406        result
 407    }
 408
 409    fn generic_button_handler<E>(
 410        connection: Entity<Terminal>,
 411        focus_handle: FocusHandle,
 412        f: impl Fn(&mut Terminal, &E, &mut Context<Terminal>),
 413    ) -> impl Fn(&E, &mut Window, &mut App) {
 414        move |event, window, cx| {
 415            window.focus(&focus_handle);
 416            connection.update(cx, |terminal, cx| {
 417                f(terminal, event, cx);
 418
 419                cx.notify();
 420            })
 421        }
 422    }
 423
 424    fn register_mouse_listeners(&mut self, mode: TermMode, hitbox: &Hitbox, window: &mut Window) {
 425        let focus = self.focus.clone();
 426        let terminal = self.terminal.clone();
 427
 428        self.interactivity.on_mouse_down(MouseButton::Left, {
 429            let terminal = terminal.clone();
 430            let focus = focus.clone();
 431            move |e, window, cx| {
 432                window.focus(&focus);
 433                terminal.update(cx, |terminal, cx| {
 434                    terminal.mouse_down(e, cx);
 435                    cx.notify();
 436                })
 437            }
 438        });
 439
 440        window.on_mouse_event({
 441            let terminal = self.terminal.clone();
 442            let hitbox = hitbox.clone();
 443            let focus = focus.clone();
 444            move |e: &MouseMoveEvent, phase, window, cx| {
 445                if phase != DispatchPhase::Bubble {
 446                    return;
 447                }
 448
 449                if e.pressed_button.is_some() && !cx.has_active_drag() && focus.is_focused(window) {
 450                    let hovered = hitbox.is_hovered(window);
 451                    terminal.update(cx, |terminal, cx| {
 452                        if terminal.selection_started() || hovered {
 453                            terminal.mouse_drag(e, hitbox.bounds, cx);
 454                            cx.notify();
 455                        }
 456                    })
 457                }
 458
 459                if hitbox.is_hovered(window) {
 460                    terminal.update(cx, |terminal, cx| {
 461                        terminal.mouse_move(e, cx);
 462                    })
 463                }
 464            }
 465        });
 466
 467        self.interactivity.on_mouse_up(
 468            MouseButton::Left,
 469            TerminalElement::generic_button_handler(
 470                terminal.clone(),
 471                focus.clone(),
 472                move |terminal, e, cx| {
 473                    terminal.mouse_up(e, cx);
 474                },
 475            ),
 476        );
 477        self.interactivity.on_mouse_down(
 478            MouseButton::Middle,
 479            TerminalElement::generic_button_handler(
 480                terminal.clone(),
 481                focus.clone(),
 482                move |terminal, e, cx| {
 483                    terminal.mouse_down(e, cx);
 484                },
 485            ),
 486        );
 487        self.interactivity.on_scroll_wheel({
 488            let terminal_view = self.terminal_view.downgrade();
 489            move |e, _, cx| {
 490                terminal_view
 491                    .update(cx, |terminal_view, cx| {
 492                        terminal_view.scroll_wheel(e, cx);
 493                        cx.notify();
 494                    })
 495                    .ok();
 496            }
 497        });
 498
 499        // Mouse mode handlers:
 500        // All mouse modes need the extra click handlers
 501        if mode.intersects(TermMode::MOUSE_MODE) {
 502            self.interactivity.on_mouse_down(
 503                MouseButton::Right,
 504                TerminalElement::generic_button_handler(
 505                    terminal.clone(),
 506                    focus.clone(),
 507                    move |terminal, e, cx| {
 508                        terminal.mouse_down(e, cx);
 509                    },
 510                ),
 511            );
 512            self.interactivity.on_mouse_up(
 513                MouseButton::Right,
 514                TerminalElement::generic_button_handler(
 515                    terminal.clone(),
 516                    focus.clone(),
 517                    move |terminal, e, cx| {
 518                        terminal.mouse_up(e, cx);
 519                    },
 520                ),
 521            );
 522            self.interactivity.on_mouse_up(
 523                MouseButton::Middle,
 524                TerminalElement::generic_button_handler(terminal, focus, move |terminal, e, cx| {
 525                    terminal.mouse_up(e, cx);
 526                }),
 527            );
 528        }
 529    }
 530
 531    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 532        let settings = ThemeSettings::get_global(cx).clone();
 533        let buffer_font_size = settings.buffer_font_size(cx);
 534        let rem_size_scale = {
 535            // Our default UI font size is 14px on a 16px base scale.
 536            // This means the default UI font size is 0.875rems.
 537            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 538
 539            // We then determine the delta between a single rem and the default font
 540            // size scale.
 541            let default_font_size_delta = 1. - default_font_size_scale;
 542
 543            // Finally, we add this delta to 1rem to get the scale factor that
 544            // should be used to scale up the UI.
 545            1. + default_font_size_delta
 546        };
 547
 548        Some(buffer_font_size * rem_size_scale)
 549    }
 550}
 551
 552impl Element for TerminalElement {
 553    type RequestLayoutState = ();
 554    type PrepaintState = LayoutState;
 555
 556    fn id(&self) -> Option<ElementId> {
 557        self.interactivity.element_id.clone()
 558    }
 559
 560    fn request_layout(
 561        &mut self,
 562        global_id: Option<&GlobalElementId>,
 563        window: &mut Window,
 564        cx: &mut App,
 565    ) -> (LayoutId, Self::RequestLayoutState) {
 566        let layout_id =
 567            self.interactivity
 568                .request_layout(global_id, window, cx, |mut style, window, cx| {
 569                    style.size.width = relative(1.).into();
 570                    style.size.height = relative(1.).into();
 571                    // style.overflow = point(Overflow::Hidden, Overflow::Hidden);
 572
 573                    window.request_layout(style, None, cx)
 574                });
 575        (layout_id, ())
 576    }
 577
 578    fn prepaint(
 579        &mut self,
 580        global_id: Option<&GlobalElementId>,
 581        bounds: Bounds<Pixels>,
 582        _: &mut Self::RequestLayoutState,
 583        window: &mut Window,
 584        cx: &mut App,
 585    ) -> Self::PrepaintState {
 586        let rem_size = self.rem_size(cx);
 587        self.interactivity.prepaint(
 588            global_id,
 589            bounds,
 590            bounds.size,
 591            window,
 592            cx,
 593            |_, _, hitbox, window, cx| {
 594                let hitbox = hitbox.unwrap();
 595                let settings = ThemeSettings::get_global(cx).clone();
 596
 597                let buffer_font_size = settings.buffer_font_size(cx);
 598
 599                let terminal_settings = TerminalSettings::get_global(cx);
 600
 601                let font_family = terminal_settings
 602                    .font_family
 603                    .as_ref()
 604                    .unwrap_or(&settings.buffer_font.family)
 605                    .clone();
 606
 607                let font_fallbacks = terminal_settings
 608                    .font_fallbacks
 609                    .as_ref()
 610                    .or(settings.buffer_font.fallbacks.as_ref())
 611                    .cloned();
 612
 613                let font_features = terminal_settings
 614                    .font_features
 615                    .as_ref()
 616                    .unwrap_or(&settings.buffer_font.features)
 617                    .clone();
 618
 619                let font_weight = terminal_settings.font_weight.unwrap_or_default();
 620
 621                let line_height = terminal_settings.line_height.value();
 622                let font_size = terminal_settings.font_size;
 623
 624                let font_size =
 625                    font_size.map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx));
 626
 627                let theme = cx.theme().clone();
 628
 629                let link_style = HighlightStyle {
 630                    color: Some(theme.colors().link_text_hover),
 631                    font_weight: Some(font_weight),
 632                    font_style: None,
 633                    background_color: None,
 634                    underline: Some(UnderlineStyle {
 635                        thickness: px(1.0),
 636                        color: Some(theme.colors().link_text_hover),
 637                        wavy: false,
 638                    }),
 639                    strikethrough: None,
 640                    fade_out: None,
 641                };
 642
 643                let text_style = TextStyle {
 644                    font_family,
 645                    font_features,
 646                    font_weight,
 647                    font_fallbacks,
 648                    font_size: font_size.into(),
 649                    font_style: FontStyle::Normal,
 650                    line_height: line_height.into(),
 651                    background_color: Some(theme.colors().terminal_ansi_background),
 652                    white_space: WhiteSpace::Normal,
 653                    // These are going to be overridden per-cell
 654                    color: theme.colors().terminal_foreground,
 655                    ..Default::default()
 656                };
 657
 658                let text_system = cx.text_system();
 659                let player_color = theme.players().local();
 660                let match_color = theme.colors().search_match_background;
 661                let gutter;
 662                let dimensions = {
 663                    let rem_size = window.rem_size();
 664                    let font_pixels = text_style.font_size.to_pixels(rem_size);
 665                    // TODO: line_height should be an f32 not an AbsoluteLength.
 666                    let line_height = font_pixels * line_height.to_pixels(rem_size).0;
 667                    let font_id = cx.text_system().resolve_font(&text_style.font());
 668
 669                    let cell_width = text_system
 670                        .advance(font_id, font_pixels, 'm')
 671                        .unwrap()
 672                        .width;
 673                    gutter = cell_width;
 674
 675                    let mut size = bounds.size;
 676                    size.width -= gutter;
 677
 678                    // https://github.com/zed-industries/zed/issues/2750
 679                    // if the terminal is one column wide, rendering 🦀
 680                    // causes alacritty to misbehave.
 681                    if size.width < cell_width * 2.0 {
 682                        size.width = cell_width * 2.0;
 683                    }
 684
 685                    let mut origin = bounds.origin;
 686                    origin.x += gutter;
 687
 688                    TerminalBounds::new(line_height, cell_width, Bounds { origin, size })
 689                };
 690
 691                let search_matches = self.terminal.read(cx).matches.clone();
 692
 693                let background_color = theme.colors().terminal_background;
 694
 695                let (last_hovered_word, hover_target) = self.terminal.update(cx, |terminal, cx| {
 696                    terminal.set_size(dimensions);
 697                    terminal.sync(window, cx);
 698
 699                    if window.modifiers().secondary()
 700                        && bounds.contains(&window.mouse_position())
 701                        && self.terminal_view.read(cx).hover_target_tooltip.is_some()
 702                    {
 703                        let hover_target = self.terminal_view.read(cx).hover_target_tooltip.clone();
 704                        let last_hovered_word = terminal.last_content.last_hovered_word.clone();
 705                        (last_hovered_word, hover_target)
 706                    } else {
 707                        (None, None)
 708                    }
 709                });
 710
 711                let scroll_top = self.terminal_view.read(cx).scroll_top;
 712                let hyperlink_tooltip = hover_target.as_ref().map(|hover_target| {
 713                    let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
 714                    let mut element = div()
 715                        .size_full()
 716                        .id("terminal-element")
 717                        .tooltip(Tooltip::text(hover_target.clone()))
 718                        .into_any_element();
 719                    element.prepaint_as_root(offset, bounds.size.into(), window, cx);
 720                    element
 721                });
 722
 723                let TerminalContent {
 724                    cells,
 725                    mode,
 726                    display_offset,
 727                    cursor_char,
 728                    selection,
 729                    cursor,
 730                    ..
 731                } = &self.terminal.read(cx).last_content;
 732                let mode = *mode;
 733                let display_offset = *display_offset;
 734
 735                // searches, highlights to a single range representations
 736                let mut relative_highlighted_ranges = Vec::new();
 737                for search_match in search_matches {
 738                    relative_highlighted_ranges.push((search_match, match_color))
 739                }
 740                if let Some(selection) = selection {
 741                    relative_highlighted_ranges
 742                        .push((selection.start..=selection.end, player_color.selection));
 743                }
 744
 745                // then have that representation be converted to the appropriate highlight data structure
 746
 747                let (cells, rects) = TerminalElement::layout_grid(
 748                    cells.iter().cloned(),
 749                    &text_style,
 750                    window.text_system(),
 751                    last_hovered_word
 752                        .as_ref()
 753                        .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
 754                    window,
 755                    cx,
 756                );
 757
 758                // Layout cursor. Rectangle is used for IME, so we should lay it out even
 759                // if we don't end up showing it.
 760                let cursor = if let AlacCursorShape::Hidden = cursor.shape {
 761                    None
 762                } else {
 763                    let cursor_point = DisplayCursor::from(cursor.point, display_offset);
 764                    let cursor_text = {
 765                        let str_trxt = cursor_char.to_string();
 766                        let len = str_trxt.len();
 767                        window
 768                            .text_system()
 769                            .shape_line(
 770                                str_trxt.into(),
 771                                text_style.font_size.to_pixels(window.rem_size()),
 772                                &[TextRun {
 773                                    len,
 774                                    font: text_style.font(),
 775                                    color: theme.colors().terminal_ansi_background,
 776                                    background_color: None,
 777                                    underline: Default::default(),
 778                                    strikethrough: None,
 779                                }],
 780                            )
 781                            .unwrap()
 782                    };
 783
 784                    let focused = self.focused;
 785                    TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
 786                        move |(cursor_position, block_width)| {
 787                            let (shape, text) = match cursor.shape {
 788                                AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
 789                                AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
 790                                AlacCursorShape::Underline => (CursorShape::Underline, None),
 791                                AlacCursorShape::Beam => (CursorShape::Bar, None),
 792                                AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
 793                                //This case is handled in the if wrapping the whole cursor layout
 794                                AlacCursorShape::Hidden => unreachable!(),
 795                            };
 796
 797                            CursorLayout::new(
 798                                cursor_position,
 799                                block_width,
 800                                dimensions.line_height,
 801                                theme.players().local().cursor,
 802                                shape,
 803                                text,
 804                            )
 805                        },
 806                    )
 807                };
 808
 809                let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
 810                    let terminal = self.terminal.read(cx);
 811                    if terminal.last_content.display_offset == 0 {
 812                        let target_line = terminal.last_content.cursor.point.line.0 + 1;
 813                        let render = &block.render;
 814                        let mut block_cx = BlockContext {
 815                            window,
 816                            context: cx,
 817                            dimensions,
 818                        };
 819                        let element = render(&mut block_cx);
 820                        let mut element = div().occlude().child(element).into_any_element();
 821                        let available_space = size(
 822                            AvailableSpace::Definite(dimensions.width() + gutter),
 823                            AvailableSpace::Definite(
 824                                block.height as f32 * dimensions.line_height(),
 825                            ),
 826                        );
 827                        let origin = bounds.origin
 828                            + point(px(0.), target_line as f32 * dimensions.line_height())
 829                            - point(px(0.), scroll_top);
 830                        window.with_rem_size(rem_size, |window| {
 831                            element.prepaint_as_root(origin, available_space, window, cx);
 832                        });
 833                        Some(element)
 834                    } else {
 835                        None
 836                    }
 837                } else {
 838                    None
 839                };
 840
 841                LayoutState {
 842                    hitbox,
 843                    cells,
 844                    cursor,
 845                    background_color,
 846                    dimensions,
 847                    rects,
 848                    relative_highlighted_ranges,
 849                    mode,
 850                    display_offset,
 851                    hyperlink_tooltip,
 852                    gutter,
 853                    block_below_cursor_element,
 854                }
 855            },
 856        )
 857    }
 858
 859    fn paint(
 860        &mut self,
 861        global_id: Option<&GlobalElementId>,
 862        bounds: Bounds<Pixels>,
 863        _: &mut Self::RequestLayoutState,
 864        layout: &mut Self::PrepaintState,
 865        window: &mut Window,
 866        cx: &mut App,
 867    ) {
 868        window.with_content_mask(Some(ContentMask { bounds }), |window| {
 869            let scroll_top = self.terminal_view.read(cx).scroll_top;
 870
 871            window.paint_quad(fill(bounds, layout.background_color));
 872            let origin =
 873                bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
 874
 875            let terminal_input_handler = TerminalInputHandler {
 876                terminal: self.terminal.clone(),
 877                cursor_bounds: layout
 878                    .cursor
 879                    .as_ref()
 880                    .map(|cursor| cursor.bounding_rect(origin)),
 881                workspace: self.workspace.clone(),
 882            };
 883
 884            self.register_mouse_listeners(layout.mode, &layout.hitbox, window);
 885            if window.modifiers().secondary()
 886                && bounds.contains(&window.mouse_position())
 887                && self.terminal_view.read(cx).hover_target_tooltip.is_some()
 888            {
 889                window.set_cursor_style(gpui::CursorStyle::PointingHand, Some(&layout.hitbox));
 890            } else {
 891                window.set_cursor_style(gpui::CursorStyle::IBeam, Some(&layout.hitbox));
 892            }
 893
 894            let cursor = layout.cursor.take();
 895            let hyperlink_tooltip = layout.hyperlink_tooltip.take();
 896            let block_below_cursor_element = layout.block_below_cursor_element.take();
 897            self.interactivity.paint(
 898                global_id,
 899                bounds,
 900                Some(&layout.hitbox),
 901                window,
 902                cx,
 903                |_, window, cx| {
 904                    window.handle_input(&self.focus, terminal_input_handler, cx);
 905
 906                    window.on_key_event({
 907                        let this = self.terminal.clone();
 908                        move |event: &ModifiersChangedEvent, phase, window, cx| {
 909                            if phase != DispatchPhase::Bubble {
 910                                return;
 911                            }
 912
 913                            this.update(cx, |term, cx| {
 914                                term.try_modifiers_change(&event.modifiers, window, cx)
 915                            });
 916                        }
 917                    });
 918
 919                    for rect in &layout.rects {
 920                        rect.paint(origin, &layout.dimensions, window);
 921                    }
 922
 923                    for (relative_highlighted_range, color) in
 924                        layout.relative_highlighted_ranges.iter()
 925                    {
 926                        if let Some((start_y, highlighted_range_lines)) =
 927                            to_highlighted_range_lines(relative_highlighted_range, layout, origin)
 928                        {
 929                            let hr = HighlightedRange {
 930                                start_y,
 931                                line_height: layout.dimensions.line_height,
 932                                lines: highlighted_range_lines,
 933                                color: *color,
 934                                corner_radius: 0.15 * layout.dimensions.line_height,
 935                            };
 936                            hr.paint(bounds, window);
 937                        }
 938                    }
 939
 940                    for cell in &layout.cells {
 941                        cell.paint(origin, &layout.dimensions, bounds, window, cx);
 942                    }
 943
 944                    if self.cursor_visible {
 945                        if let Some(mut cursor) = cursor {
 946                            cursor.paint(origin, window, cx);
 947                        }
 948                    }
 949
 950                    if let Some(mut element) = block_below_cursor_element {
 951                        element.paint(window, cx);
 952                    }
 953
 954                    if let Some(mut element) = hyperlink_tooltip {
 955                        element.paint(window, cx);
 956                    }
 957                },
 958            );
 959        });
 960    }
 961}
 962
 963impl IntoElement for TerminalElement {
 964    type Element = Self;
 965
 966    fn into_element(self) -> Self::Element {
 967        self
 968    }
 969}
 970
 971struct TerminalInputHandler {
 972    terminal: Entity<Terminal>,
 973    workspace: WeakEntity<Workspace>,
 974    cursor_bounds: Option<Bounds<Pixels>>,
 975}
 976
 977impl InputHandler for TerminalInputHandler {
 978    fn selected_text_range(
 979        &mut self,
 980        _ignore_disabled_input: bool,
 981        _: &mut Window,
 982        cx: &mut App,
 983    ) -> Option<UTF16Selection> {
 984        if self
 985            .terminal
 986            .read(cx)
 987            .last_content
 988            .mode
 989            .contains(TermMode::ALT_SCREEN)
 990        {
 991            None
 992        } else {
 993            Some(UTF16Selection {
 994                range: 0..0,
 995                reversed: false,
 996            })
 997        }
 998    }
 999
1000    fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<std::ops::Range<usize>> {
1001        Some(0..0)
1002    }
1003
1004    fn text_for_range(
1005        &mut self,
1006        _: std::ops::Range<usize>,
1007        _: &mut Option<std::ops::Range<usize>>,
1008        _: &mut Window,
1009        _: &mut App,
1010    ) -> Option<String> {
1011        None
1012    }
1013
1014    fn replace_text_in_range(
1015        &mut self,
1016        _replacement_range: Option<std::ops::Range<usize>>,
1017        text: &str,
1018        window: &mut Window,
1019        cx: &mut App,
1020    ) {
1021        self.terminal.update(cx, |terminal, _| {
1022            terminal.input(text.into());
1023        });
1024
1025        self.workspace
1026            .update(cx, |this, cx| {
1027                window.invalidate_character_coordinates();
1028                let project = this.project().read(cx);
1029                let telemetry = project.client().telemetry().clone();
1030                telemetry.log_edit_event("terminal", project.is_via_ssh());
1031            })
1032            .ok();
1033    }
1034
1035    fn replace_and_mark_text_in_range(
1036        &mut self,
1037        _range_utf16: Option<std::ops::Range<usize>>,
1038        _new_text: &str,
1039        _new_selected_range: Option<std::ops::Range<usize>>,
1040        _window: &mut Window,
1041        _cx: &mut App,
1042    ) {
1043    }
1044
1045    fn unmark_text(&mut self, _window: &mut Window, _cx: &mut App) {}
1046
1047    fn bounds_for_range(
1048        &mut self,
1049        _range_utf16: std::ops::Range<usize>,
1050        _window: &mut Window,
1051        _cx: &mut App,
1052    ) -> Option<Bounds<Pixels>> {
1053        self.cursor_bounds
1054    }
1055
1056    fn apple_press_and_hold_enabled(&mut self) -> bool {
1057        false
1058    }
1059
1060    fn character_index_for_point(
1061        &mut self,
1062        _point: Point<Pixels>,
1063        _window: &mut Window,
1064        _cx: &mut App,
1065    ) -> Option<usize> {
1066        None
1067    }
1068}
1069
1070pub fn is_blank(cell: &IndexedCell) -> bool {
1071    if cell.c != ' ' {
1072        return false;
1073    }
1074
1075    if cell.bg != AnsiColor::Named(NamedColor::Background) {
1076        return false;
1077    }
1078
1079    if cell.hyperlink().is_some() {
1080        return false;
1081    }
1082
1083    if cell
1084        .flags
1085        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1086    {
1087        return false;
1088    }
1089
1090    true
1091}
1092
1093fn to_highlighted_range_lines(
1094    range: &RangeInclusive<AlacPoint>,
1095    layout: &LayoutState,
1096    origin: Point<Pixels>,
1097) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1098    // Step 1. Normalize the points to be viewport relative.
1099    // When display_offset = 1, here's how the grid is arranged:
1100    //-2,0 -2,1...
1101    //--- Viewport top
1102    //-1,0 -1,1...
1103    //--------- Terminal Top
1104    // 0,0  0,1...
1105    // 1,0  1,1...
1106    //--- Viewport Bottom
1107    // 2,0  2,1...
1108    //--------- Terminal Bottom
1109
1110    // Normalize to viewport relative, from terminal relative.
1111    // lines are i32s, which are negative above the top left corner of the terminal
1112    // If the user has scrolled, we use the display_offset to tell us which offset
1113    // of the grid data we should be looking at. But for the rendering step, we don't
1114    // want negatives. We want things relative to the 'viewport' (the area of the grid
1115    // which is currently shown according to the display offset)
1116    let unclamped_start = AlacPoint::new(
1117        range.start().line + layout.display_offset,
1118        range.start().column,
1119    );
1120    let unclamped_end =
1121        AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1122
1123    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1124    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1125        return None;
1126    }
1127
1128    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1129    let clamped_end_line = unclamped_end
1130        .line
1131        .0
1132        .min(layout.dimensions.num_lines() as i32) as usize;
1133    //Convert the start of the range to pixels
1134    let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1135
1136    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1137    //  (also convert to pixels)
1138    let mut highlighted_range_lines = Vec::new();
1139    for line in clamped_start_line..=clamped_end_line {
1140        let mut line_start = 0;
1141        let mut line_end = layout.dimensions.columns();
1142
1143        if line == clamped_start_line {
1144            line_start = unclamped_start.column.0;
1145        }
1146        if line == clamped_end_line {
1147            line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1148        }
1149
1150        highlighted_range_lines.push(HighlightedRangeLine {
1151            start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1152            end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1153        });
1154    }
1155
1156    Some((start_y, highlighted_range_lines))
1157}
1158
1159/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1160pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1161    let colors = theme.colors();
1162    match fg {
1163        // Named and theme defined colors
1164        terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1165            NamedColor::Black => colors.terminal_ansi_black,
1166            NamedColor::Red => colors.terminal_ansi_red,
1167            NamedColor::Green => colors.terminal_ansi_green,
1168            NamedColor::Yellow => colors.terminal_ansi_yellow,
1169            NamedColor::Blue => colors.terminal_ansi_blue,
1170            NamedColor::Magenta => colors.terminal_ansi_magenta,
1171            NamedColor::Cyan => colors.terminal_ansi_cyan,
1172            NamedColor::White => colors.terminal_ansi_white,
1173            NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1174            NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1175            NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1176            NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1177            NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1178            NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1179            NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1180            NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1181            NamedColor::Foreground => colors.terminal_foreground,
1182            NamedColor::Background => colors.terminal_ansi_background,
1183            NamedColor::Cursor => theme.players().local().cursor,
1184            NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1185            NamedColor::DimRed => colors.terminal_ansi_dim_red,
1186            NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1187            NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1188            NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1189            NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1190            NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1191            NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1192            NamedColor::BrightForeground => colors.terminal_bright_foreground,
1193            NamedColor::DimForeground => colors.terminal_dim_foreground,
1194        },
1195        // 'True' colors
1196        terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1197            terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1198        }
1199        // 8 bit, indexed colors
1200        terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1201            terminal::get_color_at_index(*i as usize, theme)
1202        }
1203    }
1204}