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