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