terminal_element.rs

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