terminal_element.rs

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