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