terminal_element.rs

  1use editor::{Cursor, HighlightedRange, HighlightedRangeLine};
  2use gpui::{
  3    color::Color,
  4    elements::{Empty, Overlay},
  5    fonts::{HighlightStyle, Properties, Style::Italic, TextStyle, Underline, Weight},
  6    geometry::{
  7        rect::RectF,
  8        vector::{vec2f, Vector2F},
  9    },
 10    serde_json::json,
 11    text_layout::{Line, RunStyle},
 12    Element, ElementBox, EventContext, FontCache, ModelContext, MouseButton, MouseRegion,
 13    PaintContext, Quad, SizeConstraint, TextLayoutCache, WeakModelHandle, WeakViewHandle,
 14};
 15use itertools::Itertools;
 16use language::CursorShape;
 17use ordered_float::OrderedFloat;
 18use settings::Settings;
 19use terminal::{
 20    alacritty_terminal::{
 21        ansi::{Color as AnsiColor, Color::Named, CursorShape as AlacCursorShape, NamedColor},
 22        grid::Dimensions,
 23        index::Point,
 24        term::{cell::Flags, TermMode},
 25    },
 26    mappings::colors::convert_color,
 27    IndexedCell, Terminal, TerminalContent, TerminalSize,
 28};
 29use theme::TerminalStyle;
 30use util::ResultExt;
 31
 32use std::{fmt::Debug, ops::RangeInclusive};
 33use std::{mem, ops::Range};
 34
 35use crate::{DeployContextMenu, TerminalView};
 36
 37///The information generated during layout that is nescessary for painting
 38pub struct LayoutState {
 39    cells: Vec<LayoutCell>,
 40    rects: Vec<LayoutRect>,
 41    relative_highlighted_ranges: Vec<(RangeInclusive<Point>, Color)>,
 42    cursor: Option<Cursor>,
 43    background_color: Color,
 44    size: TerminalSize,
 45    mode: TermMode,
 46    display_offset: usize,
 47    hyperlink_tooltip: Option<ElementBox>,
 48}
 49
 50///Helper struct for converting data between alacritty's cursor points, and displayed cursor points
 51struct DisplayCursor {
 52    line: i32,
 53    col: usize,
 54}
 55
 56impl DisplayCursor {
 57    fn from(cursor_point: Point, display_offset: usize) -> Self {
 58        Self {
 59            line: cursor_point.line.0 + display_offset as i32,
 60            col: cursor_point.column.0,
 61        }
 62    }
 63
 64    pub fn line(&self) -> i32 {
 65        self.line
 66    }
 67
 68    pub fn col(&self) -> usize {
 69        self.col
 70    }
 71}
 72
 73#[derive(Clone, Debug, Default)]
 74struct LayoutCell {
 75    point: Point<i32, i32>,
 76    text: Line,
 77}
 78
 79impl LayoutCell {
 80    fn new(point: Point<i32, i32>, text: Line) -> LayoutCell {
 81        LayoutCell { point, text }
 82    }
 83
 84    fn paint(
 85        &self,
 86        origin: Vector2F,
 87        layout: &LayoutState,
 88        visible_bounds: RectF,
 89        cx: &mut PaintContext,
 90    ) {
 91        let pos = {
 92            let point = self.point;
 93            vec2f(
 94                (origin.x() + point.column as f32 * layout.size.cell_width).floor(),
 95                origin.y() + point.line as f32 * layout.size.line_height,
 96            )
 97        };
 98
 99        self.text
100            .paint(pos, visible_bounds, layout.size.line_height, cx);
101    }
102}
103
104#[derive(Clone, Debug, Default)]
105struct LayoutRect {
106    point: Point<i32, i32>,
107    num_of_cells: usize,
108    color: Color,
109}
110
111impl LayoutRect {
112    fn new(point: Point<i32, i32>, num_of_cells: usize, color: Color) -> LayoutRect {
113        LayoutRect {
114            point,
115            num_of_cells,
116            color,
117        }
118    }
119
120    fn extend(&self) -> Self {
121        LayoutRect {
122            point: self.point,
123            num_of_cells: self.num_of_cells + 1,
124            color: self.color,
125        }
126    }
127
128    fn paint(&self, origin: Vector2F, layout: &LayoutState, cx: &mut PaintContext) {
129        let position = {
130            let point = self.point;
131            vec2f(
132                (origin.x() + point.column as f32 * layout.size.cell_width).floor(),
133                origin.y() + point.line as f32 * layout.size.line_height,
134            )
135        };
136        let size = vec2f(
137            (layout.size.cell_width * self.num_of_cells as f32).ceil(),
138            layout.size.line_height,
139        );
140
141        cx.scene.push_quad(Quad {
142            bounds: RectF::new(position, size),
143            background: Some(self.color),
144            border: Default::default(),
145            corner_radius: 0.,
146        })
147    }
148}
149
150///The GPUI element that paints the terminal.
151///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?
152pub struct TerminalElement {
153    terminal: WeakModelHandle<Terminal>,
154    view: WeakViewHandle<TerminalView>,
155    focused: bool,
156    cursor_visible: bool,
157}
158
159impl TerminalElement {
160    pub fn new(
161        view: WeakViewHandle<TerminalView>,
162        terminal: WeakModelHandle<Terminal>,
163        focused: bool,
164        cursor_visible: bool,
165    ) -> TerminalElement {
166        TerminalElement {
167            view,
168            terminal,
169            focused,
170            cursor_visible,
171        }
172    }
173
174    //Vec<Range<Point>> -> Clip out the parts of the ranges
175
176    fn layout_grid(
177        grid: &Vec<IndexedCell>,
178        text_style: &TextStyle,
179        terminal_theme: &TerminalStyle,
180        text_layout_cache: &TextLayoutCache,
181        font_cache: &FontCache,
182        hyperlink: Option<(HighlightStyle, &RangeInclusive<Point>)>,
183    ) -> (Vec<LayoutCell>, Vec<LayoutRect>) {
184        let mut cells = vec![];
185        let mut rects = vec![];
186
187        let mut cur_rect: Option<LayoutRect> = None;
188        let mut cur_alac_color = None;
189
190        let linegroups = grid.into_iter().group_by(|i| i.point.line);
191        for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
192            for cell in line {
193                let mut fg = cell.fg;
194                let mut bg = cell.bg;
195                if cell.flags.contains(Flags::INVERSE) {
196                    mem::swap(&mut fg, &mut bg);
197                }
198
199                //Expand background rect range
200                {
201                    if matches!(bg, Named(NamedColor::Background)) {
202                        //Continue to next cell, resetting variables if nescessary
203                        cur_alac_color = None;
204                        if let Some(rect) = cur_rect {
205                            rects.push(rect);
206                            cur_rect = None
207                        }
208                    } else {
209                        match cur_alac_color {
210                            Some(cur_color) => {
211                                if bg == cur_color {
212                                    cur_rect = cur_rect.take().map(|rect| rect.extend());
213                                } else {
214                                    cur_alac_color = Some(bg);
215                                    if cur_rect.is_some() {
216                                        rects.push(cur_rect.take().unwrap());
217                                    }
218                                    cur_rect = Some(LayoutRect::new(
219                                        Point::new(line_index as i32, cell.point.column.0 as i32),
220                                        1,
221                                        convert_color(&bg, &terminal_theme),
222                                    ));
223                                }
224                            }
225                            None => {
226                                cur_alac_color = Some(bg);
227                                cur_rect = Some(LayoutRect::new(
228                                    Point::new(line_index as i32, cell.point.column.0 as i32),
229                                    1,
230                                    convert_color(&bg, &terminal_theme),
231                                ));
232                            }
233                        }
234                    }
235                }
236
237                //Layout current cell text
238                {
239                    let cell_text = &cell.c.to_string();
240                    if !is_blank(&cell) {
241                        let cell_style = TerminalElement::cell_style(
242                            &cell,
243                            fg,
244                            terminal_theme,
245                            text_style,
246                            font_cache,
247                            hyperlink,
248                        );
249
250                        let layout_cell = text_layout_cache.layout_str(
251                            cell_text,
252                            text_style.font_size,
253                            &[(cell_text.len(), cell_style)],
254                        );
255
256                        cells.push(LayoutCell::new(
257                            Point::new(line_index as i32, cell.point.column.0 as i32),
258                            layout_cell,
259                        ))
260                    };
261                }
262            }
263
264            if cur_rect.is_some() {
265                rects.push(cur_rect.take().unwrap());
266            }
267        }
268        (cells, rects)
269    }
270
271    // Compute the cursor position and expected block width, may return a zero width if x_for_index returns
272    // the same position for sequential indexes. Use em_width instead
273    fn shape_cursor(
274        cursor_point: DisplayCursor,
275        size: TerminalSize,
276        text_fragment: &Line,
277    ) -> Option<(Vector2F, f32)> {
278        if cursor_point.line() < size.total_lines() as i32 {
279            let cursor_width = if text_fragment.width() == 0. {
280                size.cell_width()
281            } else {
282                text_fragment.width()
283            };
284
285            //Cursor should always surround as much of the text as possible,
286            //hence when on pixel boundaries round the origin down and the width up
287            Some((
288                vec2f(
289                    (cursor_point.col() as f32 * size.cell_width()).floor(),
290                    (cursor_point.line() as f32 * size.line_height()).floor(),
291                ),
292                cursor_width.ceil(),
293            ))
294        } else {
295            None
296        }
297    }
298
299    ///Convert the Alacritty cell styles to GPUI text styles and background color
300    fn cell_style(
301        indexed: &IndexedCell,
302        fg: terminal::alacritty_terminal::ansi::Color,
303        style: &TerminalStyle,
304        text_style: &TextStyle,
305        font_cache: &FontCache,
306        hyperlink: Option<(HighlightStyle, &RangeInclusive<Point>)>,
307    ) -> RunStyle {
308        let flags = indexed.cell.flags;
309        let fg = convert_color(&fg, &style);
310
311        let mut underline = flags
312            .intersects(Flags::ALL_UNDERLINES)
313            .then(|| Underline {
314                color: Some(fg),
315                squiggly: flags.contains(Flags::UNDERCURL),
316                thickness: OrderedFloat(1.),
317            })
318            .unwrap_or_default();
319
320        if indexed.cell.hyperlink().is_some() {
321            if underline.thickness == OrderedFloat(0.) {
322                underline.thickness = OrderedFloat(1.);
323            }
324        }
325
326        let mut properties = Properties::new();
327        if indexed.flags.intersects(Flags::BOLD | Flags::DIM_BOLD) {
328            properties = *properties.weight(Weight::BOLD);
329        }
330        if indexed.flags.intersects(Flags::ITALIC) {
331            properties = *properties.style(Italic);
332        }
333
334        let font_id = font_cache
335            .select_font(text_style.font_family_id, &properties)
336            .unwrap_or(text_style.font_id);
337
338        let mut result = RunStyle {
339            color: fg,
340            font_id,
341            underline,
342        };
343
344        if let Some((style, range)) = hyperlink {
345            if range.contains(&indexed.point) {
346                if let Some(underline) = style.underline {
347                    result.underline = underline;
348                }
349
350                if let Some(color) = style.color {
351                    result.color = color;
352                }
353            }
354        }
355
356        result
357    }
358
359    fn generic_button_handler<E>(
360        connection: WeakModelHandle<Terminal>,
361        origin: Vector2F,
362        f: impl Fn(&mut Terminal, Vector2F, E, &mut ModelContext<Terminal>),
363    ) -> impl Fn(E, &mut EventContext) {
364        move |event, cx| {
365            cx.focus_parent_view();
366            if let Some(conn_handle) = connection.upgrade(cx.app) {
367                conn_handle.update(cx.app, |terminal, cx| {
368                    f(terminal, origin, event, cx);
369
370                    cx.notify();
371                })
372            }
373        }
374    }
375
376    fn attach_mouse_handlers(
377        &self,
378        origin: Vector2F,
379        view_id: usize,
380        visible_bounds: RectF,
381        mode: TermMode,
382        cx: &mut PaintContext,
383    ) {
384        let connection = self.terminal;
385
386        let mut region = MouseRegion::new::<Self>(view_id, 0, visible_bounds);
387
388        // Terminal Emulator controlled behavior:
389        region = region
390            // Start selections
391            .on_down(
392                MouseButton::Left,
393                TerminalElement::generic_button_handler(
394                    connection,
395                    origin,
396                    move |terminal, origin, e, _cx| {
397                        terminal.mouse_down(&e, origin);
398                    },
399                ),
400            )
401            // Update drag selections
402            .on_drag(MouseButton::Left, move |event, cx| {
403                if cx.is_parent_view_focused() {
404                    if let Some(conn_handle) = connection.upgrade(cx.app) {
405                        conn_handle.update(cx.app, |terminal, cx| {
406                            terminal.mouse_drag(event, origin);
407                            cx.notify();
408                        })
409                    }
410                }
411            })
412            // Copy on up behavior
413            .on_up(
414                MouseButton::Left,
415                TerminalElement::generic_button_handler(
416                    connection,
417                    origin,
418                    move |terminal, origin, e, cx| {
419                        terminal.mouse_up(&e, origin, cx);
420                    },
421                ),
422            )
423            // Context menu
424            .on_click(MouseButton::Right, move |e, cx| {
425                let mouse_mode = if let Some(conn_handle) = connection.upgrade(cx.app) {
426                    conn_handle.update(cx.app, |terminal, _cx| terminal.mouse_mode(e.shift))
427                } else {
428                    // If we can't get the model handle, probably can't deploy the context menu
429                    true
430                };
431                if !mouse_mode {
432                    cx.dispatch_action(DeployContextMenu {
433                        position: e.position,
434                    });
435                }
436            })
437            .on_move(move |event, cx| {
438                if cx.is_parent_view_focused() {
439                    if let Some(conn_handle) = connection.upgrade(cx.app) {
440                        conn_handle.update(cx.app, |terminal, cx| {
441                            terminal.mouse_move(&event, origin);
442                            cx.notify();
443                        })
444                    }
445                }
446            })
447            .on_scroll(move |event, cx| {
448                // cx.focus_parent_view();
449                if let Some(conn_handle) = connection.upgrade(cx.app) {
450                    conn_handle.update(cx.app, |terminal, cx| {
451                        terminal.scroll_wheel(event, origin);
452                        cx.notify();
453                    })
454                }
455            });
456
457        // Mouse mode handlers:
458        // All mouse modes need the extra click handlers
459        if mode.intersects(TermMode::MOUSE_MODE) {
460            region = region
461                .on_down(
462                    MouseButton::Right,
463                    TerminalElement::generic_button_handler(
464                        connection,
465                        origin,
466                        move |terminal, origin, e, _cx| {
467                            terminal.mouse_down(&e, origin);
468                        },
469                    ),
470                )
471                .on_down(
472                    MouseButton::Middle,
473                    TerminalElement::generic_button_handler(
474                        connection,
475                        origin,
476                        move |terminal, origin, e, _cx| {
477                            terminal.mouse_down(&e, origin);
478                        },
479                    ),
480                )
481                .on_up(
482                    MouseButton::Right,
483                    TerminalElement::generic_button_handler(
484                        connection,
485                        origin,
486                        move |terminal, origin, e, cx| {
487                            terminal.mouse_up(&e, origin, cx);
488                        },
489                    ),
490                )
491                .on_up(
492                    MouseButton::Middle,
493                    TerminalElement::generic_button_handler(
494                        connection,
495                        origin,
496                        move |terminal, origin, e, cx| {
497                            terminal.mouse_up(&e, origin, cx);
498                        },
499                    ),
500                )
501        }
502
503        cx.scene.push_mouse_region(region);
504    }
505
506    ///Configures a text style from the current settings.
507    pub fn make_text_style(font_cache: &FontCache, settings: &Settings) -> TextStyle {
508        let font_family_name = settings
509            .terminal_overrides
510            .font_family
511            .as_ref()
512            .or(settings.terminal_defaults.font_family.as_ref())
513            .unwrap_or(&settings.buffer_font_family_name);
514        let font_features = settings
515            .terminal_overrides
516            .font_features
517            .as_ref()
518            .or(settings.terminal_defaults.font_features.as_ref())
519            .unwrap_or(&settings.buffer_font_features);
520
521        let family_id = font_cache
522            .load_family(&[font_family_name], &font_features)
523            .log_err()
524            .unwrap_or(settings.buffer_font_family);
525
526        let font_size = settings
527            .terminal_overrides
528            .font_size
529            .or(settings.terminal_defaults.font_size)
530            .unwrap_or(settings.buffer_font_size);
531
532        let font_id = font_cache
533            .select_font(family_id, &Default::default())
534            .unwrap();
535
536        TextStyle {
537            color: settings.theme.editor.text_color,
538            font_family_id: family_id,
539            font_family_name: font_cache.family_name(family_id).unwrap(),
540            font_id,
541            font_size,
542            font_properties: Default::default(),
543            underline: Default::default(),
544        }
545    }
546}
547
548impl Element for TerminalElement {
549    type LayoutState = LayoutState;
550    type PaintState = ();
551
552    fn layout(
553        &mut self,
554        constraint: gpui::SizeConstraint,
555        cx: &mut gpui::LayoutContext,
556    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
557        let settings = cx.global::<Settings>();
558        let font_cache = cx.font_cache();
559
560        //Setup layout information
561        let terminal_theme = settings.theme.terminal.clone(); //TODO: Try to minimize this clone.
562        let link_style = settings.theme.editor.link_definition;
563        let tooltip_style = settings.theme.tooltip.clone();
564
565        let text_style = TerminalElement::make_text_style(font_cache, settings);
566        let selection_color = settings.theme.editor.selection.selection;
567        let match_color = settings.theme.search.match_background;
568        let dimensions = {
569            let line_height = font_cache.line_height(text_style.font_size);
570            let cell_width = font_cache.em_advance(text_style.font_id, text_style.font_size);
571            TerminalSize::new(line_height, cell_width, constraint.max)
572        };
573
574        let search_matches = if let Some(terminal_model) = self.terminal.upgrade(cx) {
575            terminal_model.read(cx).matches.clone()
576        } else {
577            Default::default()
578        };
579
580        let background_color = terminal_theme.background;
581        let terminal_handle = self.terminal.upgrade(cx).unwrap();
582
583        let last_hovered_hyperlink = terminal_handle.update(cx.app, |terminal, cx| {
584            terminal.set_size(dimensions);
585            terminal.try_sync(cx);
586            terminal.last_content.last_hovered_hyperlink.clone()
587        });
588
589        let view_handle = self.view.clone();
590        let hyperlink_tooltip = last_hovered_hyperlink.and_then(|(uri, _, id)| {
591            // last_mouse.and_then(|_last_mouse| {
592            view_handle.upgrade(cx).map(|handle| {
593                let mut tooltip = cx.render(&handle, |_, cx| {
594                    Overlay::new(
595                        Empty::new()
596                            .contained()
597                            .constrained()
598                            .with_width(dimensions.width())
599                            .with_height(dimensions.height())
600                            .with_tooltip::<TerminalElement, _>(id, uri, None, tooltip_style, cx)
601                            .boxed(),
602                    )
603                    .with_position_mode(gpui::elements::OverlayPositionMode::Local)
604                    .boxed()
605                });
606
607                tooltip.layout(SizeConstraint::new(Vector2F::zero(), cx.window_size), cx);
608                tooltip
609            })
610            // })
611        });
612
613        let TerminalContent {
614            cells,
615            mode,
616            display_offset,
617            cursor_char,
618            selection,
619            cursor,
620            last_hovered_hyperlink,
621            ..
622        } = { &terminal_handle.read(cx).last_content };
623
624        // searches, highlights to a single range representations
625        let mut relative_highlighted_ranges = Vec::new();
626        for search_match in search_matches {
627            relative_highlighted_ranges.push((search_match, match_color))
628        }
629        if let Some(selection) = selection {
630            relative_highlighted_ranges.push((selection.start..=selection.end, selection_color));
631        }
632
633        // then have that representation be converted to the appropriate highlight data structure
634
635        let (cells, rects) = TerminalElement::layout_grid(
636            cells,
637            &text_style,
638            &terminal_theme,
639            cx.text_layout_cache,
640            cx.font_cache(),
641            last_hovered_hyperlink
642                .as_ref()
643                .map(|(_, range, _)| (link_style, range)),
644        );
645
646        //Layout cursor. Rectangle is used for IME, so we should lay it out even
647        //if we don't end up showing it.
648        let cursor = if let AlacCursorShape::Hidden = cursor.shape {
649            None
650        } else {
651            let cursor_point = DisplayCursor::from(cursor.point, *display_offset);
652            let cursor_text = {
653                let str_trxt = cursor_char.to_string();
654
655                let color = if self.focused {
656                    terminal_theme.background
657                } else {
658                    terminal_theme.foreground
659                };
660
661                cx.text_layout_cache.layout_str(
662                    &str_trxt,
663                    text_style.font_size,
664                    &[(
665                        str_trxt.len(),
666                        RunStyle {
667                            font_id: text_style.font_id,
668                            color,
669                            underline: Default::default(),
670                        },
671                    )],
672                )
673            };
674
675            let focused = self.focused;
676            TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
677                move |(cursor_position, block_width)| {
678                    let (shape, text) = match cursor.shape {
679                        AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
680                        AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
681                        AlacCursorShape::Underline => (CursorShape::Underscore, None),
682                        AlacCursorShape::Beam => (CursorShape::Bar, None),
683                        AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
684                        //This case is handled in the if wrapping the whole cursor layout
685                        AlacCursorShape::Hidden => unreachable!(),
686                    };
687
688                    Cursor::new(
689                        cursor_position,
690                        block_width,
691                        dimensions.line_height,
692                        terminal_theme.cursor,
693                        shape,
694                        text,
695                    )
696                },
697            )
698        };
699
700        //Done!
701        (
702            constraint.max,
703            LayoutState {
704                cells,
705                cursor,
706                background_color,
707                size: dimensions,
708                rects,
709                relative_highlighted_ranges,
710                mode: *mode,
711                display_offset: *display_offset,
712                hyperlink_tooltip,
713            },
714        )
715    }
716
717    fn paint(
718        &mut self,
719        bounds: gpui::geometry::rect::RectF,
720        visible_bounds: gpui::geometry::rect::RectF,
721        layout: &mut Self::LayoutState,
722        cx: &mut gpui::PaintContext,
723    ) -> Self::PaintState {
724        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
725
726        //Setup element stuff
727        let clip_bounds = Some(visible_bounds);
728
729        cx.paint_layer(clip_bounds, |cx| {
730            let origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
731
732            // Elements are ephemeral, only at paint time do we know what could be clicked by a mouse
733            self.attach_mouse_handlers(origin, self.view.id(), visible_bounds, layout.mode, cx);
734
735            cx.scene.push_cursor_region(gpui::CursorRegion {
736                bounds,
737                style: if layout.hyperlink_tooltip.is_some() {
738                    gpui::CursorStyle::PointingHand
739                } else {
740                    gpui::CursorStyle::IBeam
741                },
742            });
743
744            cx.paint_layer(clip_bounds, |cx| {
745                //Start with a background color
746                cx.scene.push_quad(Quad {
747                    bounds: RectF::new(bounds.origin(), bounds.size()),
748                    background: Some(layout.background_color),
749                    border: Default::default(),
750                    corner_radius: 0.,
751                });
752
753                for rect in &layout.rects {
754                    rect.paint(origin, layout, cx)
755                }
756            });
757
758            //Draw Highlighted Backgrounds
759            cx.paint_layer(clip_bounds, |cx| {
760                for (relative_highlighted_range, color) in layout.relative_highlighted_ranges.iter()
761                {
762                    if let Some((start_y, highlighted_range_lines)) =
763                        to_highlighted_range_lines(relative_highlighted_range, layout, origin)
764                    {
765                        let hr = HighlightedRange {
766                            start_y, //Need to change this
767                            line_height: layout.size.line_height,
768                            lines: highlighted_range_lines,
769                            color: color.clone(),
770                            //Copied from editor. TODO: move to theme or something
771                            corner_radius: 0.15 * layout.size.line_height,
772                        };
773                        hr.paint(bounds, cx.scene);
774                    }
775                }
776            });
777
778            //Draw the text cells
779            cx.paint_layer(clip_bounds, |cx| {
780                for cell in &layout.cells {
781                    cell.paint(origin, layout, visible_bounds, cx);
782                }
783            });
784
785            //Draw cursor
786            if self.cursor_visible {
787                if let Some(cursor) = &layout.cursor {
788                    cx.paint_layer(clip_bounds, |cx| {
789                        cursor.paint(origin, cx);
790                    })
791                }
792            }
793
794            if let Some(element) = &mut layout.hyperlink_tooltip {
795                element.paint(origin, visible_bounds, cx)
796            }
797        });
798    }
799
800    fn metadata(&self) -> Option<&dyn std::any::Any> {
801        None
802    }
803
804    fn debug(
805        &self,
806        _bounds: gpui::geometry::rect::RectF,
807        _layout: &Self::LayoutState,
808        _paint: &Self::PaintState,
809        _cx: &gpui::DebugContext,
810    ) -> gpui::serde_json::Value {
811        json!({
812            "type": "TerminalElement",
813        })
814    }
815
816    fn rect_for_text_range(
817        &self,
818        _: Range<usize>,
819        bounds: RectF,
820        _: RectF,
821        layout: &Self::LayoutState,
822        _: &Self::PaintState,
823        _: &gpui::MeasurementContext,
824    ) -> Option<RectF> {
825        // Use the same origin that's passed to `Cursor::paint` in the paint
826        // method bove.
827        let mut origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
828
829        // TODO - Why is it necessary to move downward one line to get correct
830        // positioning? I would think that we'd want the same rect that is
831        // painted for the cursor.
832        origin += vec2f(0., layout.size.line_height);
833
834        Some(layout.cursor.as_ref()?.bounding_rect(origin))
835    }
836}
837
838fn is_blank(cell: &IndexedCell) -> bool {
839    if cell.c != ' ' {
840        return false;
841    }
842
843    if cell.bg != AnsiColor::Named(NamedColor::Background) {
844        return false;
845    }
846
847    if cell.hyperlink().is_some() {
848        return false;
849    }
850
851    if cell
852        .flags
853        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
854    {
855        return false;
856    }
857
858    return true;
859}
860
861fn to_highlighted_range_lines(
862    range: &RangeInclusive<Point>,
863    layout: &LayoutState,
864    origin: Vector2F,
865) -> Option<(f32, Vec<HighlightedRangeLine>)> {
866    // Step 1. Normalize the points to be viewport relative.
867    // When display_offset = 1, here's how the grid is arranged:
868    //-2,0 -2,1...
869    //--- Viewport top
870    //-1,0 -1,1...
871    //--------- Terminal Top
872    // 0,0  0,1...
873    // 1,0  1,1...
874    //--- Viewport Bottom
875    // 2,0  2,1...
876    //--------- Terminal Bottom
877
878    // Normalize to viewport relative, from terminal relative.
879    // lines are i32s, which are negative above the top left corner of the terminal
880    // If the user has scrolled, we use the display_offset to tell us which offset
881    // of the grid data we should be looking at. But for the rendering step, we don't
882    // want negatives. We want things relative to the 'viewport' (the area of the grid
883    // which is currently shown according to the display offset)
884    let unclamped_start = Point::new(
885        range.start().line + layout.display_offset,
886        range.start().column,
887    );
888    let unclamped_end = Point::new(range.end().line + layout.display_offset, range.end().column);
889
890    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
891    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.size.num_lines() as i32 {
892        return None;
893    }
894
895    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
896    let clamped_end_line = unclamped_end.line.0.min(layout.size.num_lines() as i32) as usize;
897    //Convert the start of the range to pixels
898    let start_y = origin.y() + clamped_start_line as f32 * layout.size.line_height;
899
900    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
901    //  (also convert to pixels)
902    let mut highlighted_range_lines = Vec::new();
903    for line in clamped_start_line..=clamped_end_line {
904        let mut line_start = 0;
905        let mut line_end = layout.size.columns();
906
907        if line == clamped_start_line {
908            line_start = unclamped_start.column.0 as usize;
909        }
910        if line == clamped_end_line {
911            line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
912        }
913
914        highlighted_range_lines.push(HighlightedRangeLine {
915            start_x: origin.x() + line_start as f32 * layout.size.cell_width,
916            end_x: origin.x() + line_end as f32 * layout.size.cell_width,
917        });
918    }
919
920    Some((start_y, highlighted_range_lines))
921}