terminal_element.rs

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