terminal_element.rs

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