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    UTF16Selection, 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)]
  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: &TerminalSize,
  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 * dimensions.cell_width).floor(),
  98                origin.y + point.line as f32 * dimensions.line_height,
  99            )
 100        };
 101
 102        self.text.paint(pos, dimensions.line_height, cx).ok();
 103    }
 104}
 105
 106#[derive(Clone, Debug, Default)]
 107pub struct 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    pub fn paint(&self, origin: Point<Pixels>, dimensions: &TerminalSize, cx: &mut WindowContext) {
 131        let position = {
 132            let alac_point = self.point;
 133            point(
 134                (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
 135                origin.y + alac_point.line as f32 * dimensions.line_height,
 136            )
 137        };
 138        let size = point(
 139            (dimensions.cell_width * self.num_of_cells as f32).ceil(),
 140            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    pub fn layout_grid(
 200        grid: impl Iterator<Item = 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().chunk_by(|i| i.point.line);
 215        for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
 216            for cell in line {
 217                let mut fg = cell.fg;
 218                let mut bg = cell.bg;
 219                if cell.flags.contains(Flags::INVERSE) {
 220                    mem::swap(&mut fg, &mut bg);
 221                }
 222
 223                //Expand background rect range
 224                {
 225                    if matches!(bg, Named(NamedColor::Background)) {
 226                        //Continue to next cell, resetting variables if necessary
 227                        cur_alac_color = None;
 228                        if let Some(rect) = cur_rect {
 229                            rects.push(rect);
 230                            cur_rect = None
 231                        }
 232                    } else {
 233                        match cur_alac_color {
 234                            Some(cur_color) => {
 235                                if bg == cur_color {
 236                                    // `cur_rect` can be None if it was moved to the `rects` vec after wrapping around
 237                                    // from one line to the next. The variables are all set correctly but there is no current
 238                                    // rect, so we create one if necessary.
 239                                    cur_rect = cur_rect.map_or_else(
 240                                        || {
 241                                            Some(LayoutRect::new(
 242                                                AlacPoint::new(
 243                                                    line_index as i32,
 244                                                    cell.point.column.0 as i32,
 245                                                ),
 246                                                1,
 247                                                convert_color(&bg, theme),
 248                                            ))
 249                                        },
 250                                        |rect| Some(rect.extend()),
 251                                    );
 252                                } else {
 253                                    cur_alac_color = Some(bg);
 254                                    if cur_rect.is_some() {
 255                                        rects.push(cur_rect.take().unwrap());
 256                                    }
 257                                    cur_rect = Some(LayoutRect::new(
 258                                        AlacPoint::new(
 259                                            line_index as i32,
 260                                            cell.point.column.0 as i32,
 261                                        ),
 262                                        1,
 263                                        convert_color(&bg, theme),
 264                                    ));
 265                                }
 266                            }
 267                            None => {
 268                                cur_alac_color = Some(bg);
 269                                cur_rect = Some(LayoutRect::new(
 270                                    AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
 271                                    1,
 272                                    convert_color(&bg, theme),
 273                                ));
 274                            }
 275                        }
 276                    }
 277                }
 278
 279                //Layout current cell text
 280                {
 281                    if !is_blank(&cell) {
 282                        let cell_text = cell.c.to_string();
 283                        let cell_style =
 284                            TerminalElement::cell_style(&cell, fg, theme, text_style, hyperlink);
 285
 286                        let layout_cell = text_system
 287                            .shape_line(
 288                                cell_text.into(),
 289                                text_style.font_size.to_pixels(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 if hovered {
 464                            terminal.mouse_drag(e, origin, hitbox.bounds);
 465                            cx.notify();
 466                        }
 467                    })
 468                }
 469
 470                if hitbox.is_hovered(cx) {
 471                    terminal.update(cx, |terminal, cx| {
 472                        terminal.mouse_move(e, origin);
 473                        cx.notify();
 474                    })
 475                }
 476            }
 477        });
 478
 479        self.interactivity.on_mouse_up(
 480            MouseButton::Left,
 481            TerminalElement::generic_button_handler(
 482                terminal.clone(),
 483                origin,
 484                focus.clone(),
 485                move |terminal, origin, e, cx| {
 486                    terminal.mouse_up(e, origin, cx);
 487                },
 488            ),
 489        );
 490        self.interactivity.on_mouse_down(
 491            MouseButton::Middle,
 492            TerminalElement::generic_button_handler(
 493                terminal.clone(),
 494                origin,
 495                focus.clone(),
 496                move |terminal, origin, e, cx| {
 497                    terminal.mouse_down(e, origin, cx);
 498                },
 499            ),
 500        );
 501        self.interactivity.on_scroll_wheel({
 502            let terminal_view = self.terminal_view.downgrade();
 503            move |e, cx| {
 504                terminal_view
 505                    .update(cx, |terminal_view, cx| {
 506                        terminal_view.scroll_wheel(e, origin, cx);
 507                        cx.notify();
 508                    })
 509                    .ok();
 510            }
 511        });
 512
 513        // Mouse mode handlers:
 514        // All mouse modes need the extra click handlers
 515        if mode.intersects(TermMode::MOUSE_MODE) {
 516            self.interactivity.on_mouse_down(
 517                MouseButton::Right,
 518                TerminalElement::generic_button_handler(
 519                    terminal.clone(),
 520                    origin,
 521                    focus.clone(),
 522                    move |terminal, origin, e, cx| {
 523                        terminal.mouse_down(e, origin, cx);
 524                    },
 525                ),
 526            );
 527            self.interactivity.on_mouse_up(
 528                MouseButton::Right,
 529                TerminalElement::generic_button_handler(
 530                    terminal.clone(),
 531                    origin,
 532                    focus.clone(),
 533                    move |terminal, origin, e, cx| {
 534                        terminal.mouse_up(e, origin, cx);
 535                    },
 536                ),
 537            );
 538            self.interactivity.on_mouse_up(
 539                MouseButton::Middle,
 540                TerminalElement::generic_button_handler(
 541                    terminal,
 542                    origin,
 543                    focus,
 544                    move |terminal, origin, e, cx| {
 545                        terminal.mouse_up(e, origin, cx);
 546                    },
 547                ),
 548            );
 549        }
 550    }
 551
 552    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
 553        let settings = ThemeSettings::get_global(cx).clone();
 554        let buffer_font_size = settings.buffer_font_size();
 555        let rem_size_scale = {
 556            // Our default UI font size is 14px on a 16px base scale.
 557            // This means the default UI font size is 0.875rems.
 558            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 559
 560            // We then determine the delta between a single rem and the default font
 561            // size scale.
 562            let default_font_size_delta = 1. - default_font_size_scale;
 563
 564            // Finally, we add this delta to 1rem to get the scale factor that
 565            // should be used to scale up the UI.
 566            1. + default_font_size_delta
 567        };
 568
 569        Some(buffer_font_size * rem_size_scale)
 570    }
 571}
 572
 573impl Element for TerminalElement {
 574    type RequestLayoutState = ();
 575    type PrepaintState = LayoutState;
 576
 577    fn id(&self) -> Option<ElementId> {
 578        self.interactivity.element_id.clone()
 579    }
 580
 581    fn request_layout(
 582        &mut self,
 583        global_id: Option<&GlobalElementId>,
 584        cx: &mut WindowContext,
 585    ) -> (LayoutId, Self::RequestLayoutState) {
 586        let layout_id = self
 587            .interactivity
 588            .request_layout(global_id, cx, |mut style, cx| {
 589                style.size.width = relative(1.).into();
 590                style.size.height = relative(1.).into();
 591                // style.overflow = point(Overflow::Hidden, Overflow::Hidden);
 592
 593                cx.request_layout(style, None)
 594            });
 595        (layout_id, ())
 596    }
 597
 598    fn prepaint(
 599        &mut self,
 600        global_id: Option<&GlobalElementId>,
 601        bounds: Bounds<Pixels>,
 602        _: &mut Self::RequestLayoutState,
 603        cx: &mut WindowContext,
 604    ) -> Self::PrepaintState {
 605        let rem_size = self.rem_size(cx);
 606        self.interactivity
 607            .prepaint(global_id, bounds, bounds.size, cx, |_, _, hitbox, cx| {
 608                let hitbox = hitbox.unwrap();
 609                let settings = ThemeSettings::get_global(cx).clone();
 610
 611                let buffer_font_size = settings.buffer_font_size();
 612
 613                let terminal_settings = TerminalSettings::get_global(cx);
 614
 615                let font_family = terminal_settings
 616                    .font_family
 617                    .as_ref()
 618                    .unwrap_or(&settings.buffer_font.family)
 619                    .clone();
 620
 621                let font_fallbacks = terminal_settings
 622                    .font_fallbacks
 623                    .as_ref()
 624                    .or(settings.buffer_font.fallbacks.as_ref())
 625                    .cloned();
 626
 627                let font_features = terminal_settings
 628                    .font_features
 629                    .as_ref()
 630                    .unwrap_or(&settings.buffer_font.features)
 631                    .clone();
 632
 633                let font_weight = terminal_settings.font_weight.unwrap_or_default();
 634
 635                let line_height = terminal_settings.line_height.value();
 636                let font_size = terminal_settings.font_size;
 637
 638                let font_size = font_size.unwrap_or(buffer_font_size);
 639
 640                let theme = cx.theme().clone();
 641
 642                let link_style = HighlightStyle {
 643                    color: Some(theme.colors().link_text_hover),
 644                    font_weight: Some(font_weight),
 645                    font_style: None,
 646                    background_color: None,
 647                    underline: Some(UnderlineStyle {
 648                        thickness: px(1.0),
 649                        color: Some(theme.colors().link_text_hover),
 650                        wavy: false,
 651                    }),
 652                    strikethrough: None,
 653                    fade_out: None,
 654                };
 655
 656                let text_style = TextStyle {
 657                    font_family,
 658                    font_features,
 659                    font_weight,
 660                    font_fallbacks,
 661                    font_size: font_size.into(),
 662                    font_style: FontStyle::Normal,
 663                    line_height: line_height.into(),
 664                    background_color: Some(theme.colors().terminal_ansi_background),
 665                    white_space: WhiteSpace::Normal,
 666                    truncate: None,
 667                    // These are going to be overridden per-cell
 668                    underline: None,
 669                    strikethrough: None,
 670                    color: theme.colors().terminal_foreground,
 671                };
 672
 673                let text_system = cx.text_system();
 674                let player_color = theme.players().local();
 675                let match_color = theme.colors().search_match_background;
 676                let gutter;
 677                let dimensions = {
 678                    let rem_size = cx.rem_size();
 679                    let font_pixels = text_style.font_size.to_pixels(rem_size);
 680                    let line_height = font_pixels * line_height.to_pixels(rem_size);
 681                    let font_id = cx.text_system().resolve_font(&text_style.font());
 682
 683                    let cell_width = text_system
 684                        .advance(font_id, font_pixels, 'm')
 685                        .unwrap()
 686                        .width;
 687                    gutter = cell_width;
 688
 689                    let mut size = bounds.size;
 690                    size.width -= gutter;
 691
 692                    // https://github.com/zed-industries/zed/issues/2750
 693                    // if the terminal is one column wide, rendering 🦀
 694                    // causes alacritty to misbehave.
 695                    if size.width < cell_width * 2.0 {
 696                        size.width = cell_width * 2.0;
 697                    }
 698
 699                    TerminalSize::new(line_height, cell_width, size)
 700                };
 701
 702                let search_matches = self.terminal.read(cx).matches.clone();
 703
 704                let background_color = theme.colors().terminal_background;
 705
 706                let last_hovered_word = self.terminal.update(cx, |terminal, cx| {
 707                    terminal.set_size(dimensions);
 708                    terminal.sync(cx);
 709                    if self.can_navigate_to_selected_word
 710                        && terminal.can_navigate_to_selected_word()
 711                    {
 712                        terminal.last_content.last_hovered_word.clone()
 713                    } else {
 714                        None
 715                    }
 716                });
 717
 718                let scroll_top = self.terminal_view.read(cx).scroll_top;
 719                let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
 720                    let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
 721                    let mut element = div()
 722                        .size_full()
 723                        .id("terminal-element")
 724                        .tooltip(move |cx| Tooltip::text(hovered_word.word.clone(), cx))
 725                        .into_any_element();
 726                    element.prepaint_as_root(offset, bounds.size.into(), cx);
 727                    element
 728                });
 729
 730                let TerminalContent {
 731                    cells,
 732                    mode,
 733                    display_offset,
 734                    cursor_char,
 735                    selection,
 736                    cursor,
 737                    ..
 738                } = &self.terminal.read(cx).last_content;
 739                let mode = *mode;
 740                let display_offset = *display_offset;
 741
 742                // searches, highlights to a single range representations
 743                let mut relative_highlighted_ranges = Vec::new();
 744                for search_match in search_matches {
 745                    relative_highlighted_ranges.push((search_match, match_color))
 746                }
 747                if let Some(selection) = selection {
 748                    relative_highlighted_ranges
 749                        .push((selection.start..=selection.end, player_color.selection));
 750                }
 751
 752                // then have that representation be converted to the appropriate highlight data structure
 753
 754                let (cells, rects) = TerminalElement::layout_grid(
 755                    cells.iter().cloned(),
 756                    &text_style,
 757                    cx.text_system(),
 758                    last_hovered_word
 759                        .as_ref()
 760                        .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
 761                    cx,
 762                );
 763
 764                // Layout cursor. Rectangle is used for IME, so we should lay it out even
 765                // if we don't end up showing it.
 766                let cursor = if let AlacCursorShape::Hidden = cursor.shape {
 767                    None
 768                } else {
 769                    let cursor_point = DisplayCursor::from(cursor.point, display_offset);
 770                    let cursor_text = {
 771                        let str_trxt = cursor_char.to_string();
 772                        let len = str_trxt.len();
 773                        cx.text_system()
 774                            .shape_line(
 775                                str_trxt.into(),
 776                                text_style.font_size.to_pixels(cx.rem_size()),
 777                                &[TextRun {
 778                                    len,
 779                                    font: text_style.font(),
 780                                    color: theme.colors().terminal_ansi_background,
 781                                    background_color: None,
 782                                    underline: Default::default(),
 783                                    strikethrough: None,
 784                                }],
 785                            )
 786                            .unwrap()
 787                    };
 788
 789                    let focused = self.focused;
 790                    TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
 791                        move |(cursor_position, block_width)| {
 792                            let (shape, text) = match cursor.shape {
 793                                AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
 794                                AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
 795                                AlacCursorShape::Underline => (CursorShape::Underline, None),
 796                                AlacCursorShape::Beam => (CursorShape::Bar, None),
 797                                AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
 798                                //This case is handled in the if wrapping the whole cursor layout
 799                                AlacCursorShape::Hidden => unreachable!(),
 800                            };
 801
 802                            CursorLayout::new(
 803                                cursor_position,
 804                                block_width,
 805                                dimensions.line_height,
 806                                theme.players().local().cursor,
 807                                shape,
 808                                text,
 809                            )
 810                        },
 811                    )
 812                };
 813
 814                let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
 815                    let terminal = self.terminal.read(cx);
 816                    if terminal.last_content.display_offset == 0 {
 817                        let target_line = terminal.last_content.cursor.point.line.0 + 1;
 818                        let render = &block.render;
 819                        let mut block_cx = BlockContext {
 820                            context: cx,
 821                            dimensions,
 822                        };
 823                        let element = render(&mut block_cx);
 824                        let mut element = div().occlude().child(element).into_any_element();
 825                        let available_space = size(
 826                            AvailableSpace::Definite(dimensions.width() + gutter),
 827                            AvailableSpace::Definite(
 828                                block.height as f32 * dimensions.line_height(),
 829                            ),
 830                        );
 831                        let origin = bounds.origin
 832                            + point(px(0.), target_line as f32 * dimensions.line_height())
 833                            - point(px(0.), scroll_top);
 834                        cx.with_rem_size(rem_size, |cx| {
 835                            element.prepaint_as_root(origin, available_space, cx);
 836                        });
 837                        Some(element)
 838                    } else {
 839                        None
 840                    }
 841                } else {
 842                    None
 843                };
 844
 845                LayoutState {
 846                    hitbox,
 847                    cells,
 848                    cursor,
 849                    background_color,
 850                    dimensions,
 851                    rects,
 852                    relative_highlighted_ranges,
 853                    mode,
 854                    display_offset,
 855                    hyperlink_tooltip,
 856                    gutter,
 857                    last_hovered_word,
 858                    block_below_cursor_element,
 859                }
 860            })
 861    }
 862
 863    fn paint(
 864        &mut self,
 865        global_id: Option<&GlobalElementId>,
 866        bounds: Bounds<Pixels>,
 867        _: &mut Self::RequestLayoutState,
 868        layout: &mut Self::PrepaintState,
 869        cx: &mut WindowContext,
 870    ) {
 871        cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
 872            let scroll_top = self.terminal_view.read(cx).scroll_top;
 873
 874            cx.paint_quad(fill(bounds, layout.background_color));
 875            let origin =
 876                bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
 877
 878            let terminal_input_handler = TerminalInputHandler {
 879                terminal: self.terminal.clone(),
 880                cursor_bounds: layout
 881                    .cursor
 882                    .as_ref()
 883                    .map(|cursor| cursor.bounding_rect(origin)),
 884                workspace: self.workspace.clone(),
 885            };
 886
 887            self.register_mouse_listeners(origin, layout.mode, &layout.hitbox, cx);
 888            if self.can_navigate_to_selected_word && layout.last_hovered_word.is_some() {
 889                cx.set_cursor_style(gpui::CursorStyle::PointingHand, &layout.hitbox);
 890            } else {
 891                cx.set_cursor_style(gpui::CursorStyle::IBeam, &layout.hitbox);
 892            }
 893
 894            let cursor = layout.cursor.take();
 895            let hyperlink_tooltip = layout.hyperlink_tooltip.take();
 896            let block_below_cursor_element = layout.block_below_cursor_element.take();
 897            self.interactivity
 898                .paint(global_id, bounds, Some(&layout.hitbox), cx, |_, cx| {
 899                    cx.handle_input(&self.focus, terminal_input_handler);
 900
 901                    cx.on_key_event({
 902                        let this = self.terminal.clone();
 903                        move |event: &ModifiersChangedEvent, phase, cx| {
 904                            if phase != DispatchPhase::Bubble {
 905                                return;
 906                            }
 907
 908                            let handled = this
 909                                .update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
 910
 911                            if handled {
 912                                cx.refresh();
 913                            }
 914                        }
 915                    });
 916
 917                    for rect in &layout.rects {
 918                        rect.paint(origin, &layout.dimensions, cx);
 919                    }
 920
 921                    for (relative_highlighted_range, color) in
 922                        layout.relative_highlighted_ranges.iter()
 923                    {
 924                        if let Some((start_y, highlighted_range_lines)) =
 925                            to_highlighted_range_lines(relative_highlighted_range, layout, origin)
 926                        {
 927                            let hr = HighlightedRange {
 928                                start_y,
 929                                line_height: layout.dimensions.line_height,
 930                                lines: highlighted_range_lines,
 931                                color: *color,
 932                                corner_radius: 0.15 * layout.dimensions.line_height,
 933                            };
 934                            hr.paint(bounds, cx);
 935                        }
 936                    }
 937
 938                    for cell in &layout.cells {
 939                        cell.paint(origin, &layout.dimensions, bounds, cx);
 940                    }
 941
 942                    if self.cursor_visible {
 943                        if let Some(mut cursor) = cursor {
 944                            cursor.paint(origin, cx);
 945                        }
 946                    }
 947
 948                    if let Some(mut element) = block_below_cursor_element {
 949                        element.paint(cx);
 950                    }
 951
 952                    if let Some(mut element) = hyperlink_tooltip {
 953                        element.paint(cx);
 954                    }
 955                });
 956        });
 957    }
 958}
 959
 960impl IntoElement for TerminalElement {
 961    type Element = Self;
 962
 963    fn into_element(self) -> Self::Element {
 964        self
 965    }
 966}
 967
 968struct TerminalInputHandler {
 969    terminal: Model<Terminal>,
 970    workspace: WeakView<Workspace>,
 971    cursor_bounds: Option<Bounds<Pixels>>,
 972}
 973
 974impl InputHandler for TerminalInputHandler {
 975    fn selected_text_range(
 976        &mut self,
 977        _ignore_disabled_input: bool,
 978        cx: &mut WindowContext,
 979    ) -> Option<UTF16Selection> {
 980        if self
 981            .terminal
 982            .read(cx)
 983            .last_content
 984            .mode
 985            .contains(TermMode::ALT_SCREEN)
 986        {
 987            None
 988        } else {
 989            Some(UTF16Selection {
 990                range: 0..0,
 991                reversed: false,
 992            })
 993        }
 994    }
 995
 996    fn marked_text_range(&mut self, _: &mut WindowContext) -> Option<std::ops::Range<usize>> {
 997        None
 998    }
 999
1000    fn text_for_range(
1001        &mut self,
1002        _: std::ops::Range<usize>,
1003        _: &mut Option<std::ops::Range<usize>>,
1004        _: &mut WindowContext,
1005    ) -> Option<String> {
1006        None
1007    }
1008
1009    fn replace_text_in_range(
1010        &mut self,
1011        _replacement_range: Option<std::ops::Range<usize>>,
1012        text: &str,
1013        cx: &mut WindowContext,
1014    ) {
1015        self.terminal.update(cx, |terminal, _| {
1016            terminal.input(text.into());
1017        });
1018
1019        self.workspace
1020            .update(cx, |this, cx| {
1021                cx.invalidate_character_coordinates();
1022                let project = this.project().read(cx);
1023                let telemetry = project.client().telemetry().clone();
1024                telemetry.log_edit_event("terminal", project.is_via_ssh());
1025            })
1026            .ok();
1027    }
1028
1029    fn replace_and_mark_text_in_range(
1030        &mut self,
1031        _range_utf16: Option<std::ops::Range<usize>>,
1032        _new_text: &str,
1033        _new_selected_range: Option<std::ops::Range<usize>>,
1034        _: &mut WindowContext,
1035    ) {
1036    }
1037
1038    fn unmark_text(&mut self, _: &mut WindowContext) {}
1039
1040    fn bounds_for_range(
1041        &mut self,
1042        _range_utf16: std::ops::Range<usize>,
1043        _: &mut WindowContext,
1044    ) -> Option<Bounds<Pixels>> {
1045        self.cursor_bounds
1046    }
1047
1048    fn apple_press_and_hold_enabled(&mut self) -> bool {
1049        false
1050    }
1051}
1052
1053pub fn is_blank(cell: &IndexedCell) -> bool {
1054    if cell.c != ' ' {
1055        return false;
1056    }
1057
1058    if cell.bg != AnsiColor::Named(NamedColor::Background) {
1059        return false;
1060    }
1061
1062    if cell.hyperlink().is_some() {
1063        return false;
1064    }
1065
1066    if cell
1067        .flags
1068        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1069    {
1070        return false;
1071    }
1072
1073    true
1074}
1075
1076fn to_highlighted_range_lines(
1077    range: &RangeInclusive<AlacPoint>,
1078    layout: &LayoutState,
1079    origin: Point<Pixels>,
1080) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1081    // Step 1. Normalize the points to be viewport relative.
1082    // When display_offset = 1, here's how the grid is arranged:
1083    //-2,0 -2,1...
1084    //--- Viewport top
1085    //-1,0 -1,1...
1086    //--------- Terminal Top
1087    // 0,0  0,1...
1088    // 1,0  1,1...
1089    //--- Viewport Bottom
1090    // 2,0  2,1...
1091    //--------- Terminal Bottom
1092
1093    // Normalize to viewport relative, from terminal relative.
1094    // lines are i32s, which are negative above the top left corner of the terminal
1095    // If the user has scrolled, we use the display_offset to tell us which offset
1096    // of the grid data we should be looking at. But for the rendering step, we don't
1097    // want negatives. We want things relative to the 'viewport' (the area of the grid
1098    // which is currently shown according to the display offset)
1099    let unclamped_start = AlacPoint::new(
1100        range.start().line + layout.display_offset,
1101        range.start().column,
1102    );
1103    let unclamped_end =
1104        AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1105
1106    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1107    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1108        return None;
1109    }
1110
1111    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1112    let clamped_end_line = unclamped_end
1113        .line
1114        .0
1115        .min(layout.dimensions.num_lines() as i32) as usize;
1116    //Convert the start of the range to pixels
1117    let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1118
1119    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1120    //  (also convert to pixels)
1121    let mut highlighted_range_lines = Vec::new();
1122    for line in clamped_start_line..=clamped_end_line {
1123        let mut line_start = 0;
1124        let mut line_end = layout.dimensions.columns();
1125
1126        if line == clamped_start_line {
1127            line_start = unclamped_start.column.0;
1128        }
1129        if line == clamped_end_line {
1130            line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1131        }
1132
1133        highlighted_range_lines.push(HighlightedRangeLine {
1134            start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1135            end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1136        });
1137    }
1138
1139    Some((start_y, highlighted_range_lines))
1140}
1141
1142/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1143pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1144    let colors = theme.colors();
1145    match fg {
1146        // Named and theme defined colors
1147        terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1148            NamedColor::Black => colors.terminal_ansi_black,
1149            NamedColor::Red => colors.terminal_ansi_red,
1150            NamedColor::Green => colors.terminal_ansi_green,
1151            NamedColor::Yellow => colors.terminal_ansi_yellow,
1152            NamedColor::Blue => colors.terminal_ansi_blue,
1153            NamedColor::Magenta => colors.terminal_ansi_magenta,
1154            NamedColor::Cyan => colors.terminal_ansi_cyan,
1155            NamedColor::White => colors.terminal_ansi_white,
1156            NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1157            NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1158            NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1159            NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1160            NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1161            NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1162            NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1163            NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1164            NamedColor::Foreground => colors.terminal_foreground,
1165            NamedColor::Background => colors.terminal_ansi_background,
1166            NamedColor::Cursor => theme.players().local().cursor,
1167            NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1168            NamedColor::DimRed => colors.terminal_ansi_dim_red,
1169            NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1170            NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1171            NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1172            NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1173            NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1174            NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1175            NamedColor::BrightForeground => colors.terminal_bright_foreground,
1176            NamedColor::DimForeground => colors.terminal_dim_foreground,
1177        },
1178        // 'True' colors
1179        terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1180            terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1181        }
1182        // 8 bit, indexed colors
1183        terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1184            terminal::get_color_at_index(*i as usize, theme)
1185        }
1186    }
1187}