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        };
571        let selection_color = settings.theme.editor.selection.selection;
572        let match_color = settings.theme.search.match_background;
573        let gutter;
574        let dimensions = {
575            let line_height = text_style.font_size * terminal_settings.line_height.value();
576            let cell_width = font_cache.em_advance(text_style.font_id, text_style.font_size);
577            gutter = cell_width;
578
579            let size = constraint.max - vec2f(gutter, 0.);
580            TerminalSize::new(line_height, cell_width, size)
581        };
582
583        let search_matches = if let Some(terminal_model) = self.terminal.upgrade(cx) {
584            terminal_model.read(cx).matches.clone()
585        } else {
586            Default::default()
587        };
588
589        let background_color = terminal_theme.background;
590        let terminal_handle = self.terminal.upgrade(cx).unwrap();
591
592        let last_hovered_word = terminal_handle.update(cx, |terminal, cx| {
593            terminal.set_size(dimensions);
594            terminal.try_sync(cx);
595            if self.can_navigate_to_selected_word && terminal.can_navigate_to_selected_word() {
596                terminal.last_content.last_hovered_word.clone()
597            } else {
598                None
599            }
600        });
601
602        let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
603            let mut tooltip = Overlay::new(
604                Empty::new()
605                    .contained()
606                    .constrained()
607                    .with_width(dimensions.width())
608                    .with_height(dimensions.height())
609                    .with_tooltip::<TerminalElement>(
610                        hovered_word.id,
611                        hovered_word.word,
612                        None,
613                        tooltip_style,
614                        cx,
615                    ),
616            )
617            .with_position_mode(gpui::elements::OverlayPositionMode::Local)
618            .into_any();
619
620            tooltip.layout(
621                SizeConstraint::new(Vector2F::zero(), cx.window_size()),
622                view,
623                cx,
624            );
625            tooltip
626        });
627
628        let TerminalContent {
629            cells,
630            mode,
631            display_offset,
632            cursor_char,
633            selection,
634            cursor,
635            ..
636        } = { &terminal_handle.read(cx).last_content };
637
638        // searches, highlights to a single range representations
639        let mut relative_highlighted_ranges = Vec::new();
640        for search_match in search_matches {
641            relative_highlighted_ranges.push((search_match, match_color))
642        }
643        if let Some(selection) = selection {
644            relative_highlighted_ranges.push((selection.start..=selection.end, selection_color));
645        }
646
647        // then have that representation be converted to the appropriate highlight data structure
648
649        let (cells, rects) = TerminalElement::layout_grid(
650            cells,
651            &text_style,
652            &terminal_theme,
653            cx.text_layout_cache(),
654            cx.font_cache(),
655            last_hovered_word
656                .as_ref()
657                .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
658        );
659
660        //Layout cursor. Rectangle is used for IME, so we should lay it out even
661        //if we don't end up showing it.
662        let cursor = if let AlacCursorShape::Hidden = cursor.shape {
663            None
664        } else {
665            let cursor_point = DisplayCursor::from(cursor.point, *display_offset);
666            let cursor_text = {
667                let str_trxt = cursor_char.to_string();
668
669                let color = if self.focused {
670                    terminal_theme.background
671                } else {
672                    terminal_theme.foreground
673                };
674
675                cx.text_layout_cache().layout_str(
676                    &str_trxt,
677                    text_style.font_size,
678                    &[(
679                        str_trxt.len(),
680                        RunStyle {
681                            font_id: text_style.font_id,
682                            color,
683                            underline: Default::default(),
684                        },
685                    )],
686                )
687            };
688
689            let focused = self.focused;
690            TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
691                move |(cursor_position, block_width)| {
692                    let (shape, text) = match cursor.shape {
693                        AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
694                        AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
695                        AlacCursorShape::Underline => (CursorShape::Underscore, None),
696                        AlacCursorShape::Beam => (CursorShape::Bar, None),
697                        AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
698                        //This case is handled in the if wrapping the whole cursor layout
699                        AlacCursorShape::Hidden => unreachable!(),
700                    };
701
702                    Cursor::new(
703                        cursor_position,
704                        block_width,
705                        dimensions.line_height,
706                        terminal_theme.cursor,
707                        shape,
708                        text,
709                    )
710                },
711            )
712        };
713
714        //Done!
715        (
716            constraint.max,
717            LayoutState {
718                cells,
719                cursor,
720                background_color,
721                size: dimensions,
722                rects,
723                relative_highlighted_ranges,
724                mode: *mode,
725                display_offset: *display_offset,
726                hyperlink_tooltip,
727                gutter,
728            },
729        )
730    }
731
732    fn paint(
733        &mut self,
734        scene: &mut SceneBuilder,
735        bounds: RectF,
736        visible_bounds: RectF,
737        layout: &mut Self::LayoutState,
738        view: &mut TerminalView,
739        cx: &mut PaintContext<TerminalView>,
740    ) -> Self::PaintState {
741        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
742
743        //Setup element stuff
744        let clip_bounds = Some(visible_bounds);
745
746        scene.paint_layer(clip_bounds, |scene| {
747            let origin = bounds.origin() + vec2f(layout.gutter, 0.);
748
749            // Elements are ephemeral, only at paint time do we know what could be clicked by a mouse
750            self.attach_mouse_handlers(scene, origin, visible_bounds, layout.mode, cx);
751
752            scene.push_cursor_region(gpui::CursorRegion {
753                bounds,
754                style: if layout.hyperlink_tooltip.is_some() {
755                    CursorStyle::PointingHand
756                } else {
757                    CursorStyle::IBeam
758                },
759            });
760
761            scene.paint_layer(clip_bounds, |scene| {
762                //Start with a background color
763                scene.push_quad(Quad {
764                    bounds: RectF::new(bounds.origin(), bounds.size()),
765                    background: Some(layout.background_color),
766                    border: Default::default(),
767                    corner_radii: Default::default(),
768                });
769
770                for rect in &layout.rects {
771                    rect.paint(scene, origin, layout, view, cx)
772                }
773            });
774
775            //Draw Highlighted Backgrounds
776            scene.paint_layer(clip_bounds, |scene| {
777                for (relative_highlighted_range, color) in layout.relative_highlighted_ranges.iter()
778                {
779                    if let Some((start_y, highlighted_range_lines)) =
780                        to_highlighted_range_lines(relative_highlighted_range, layout, origin)
781                    {
782                        let hr = HighlightedRange {
783                            start_y, //Need to change this
784                            line_height: layout.size.line_height,
785                            lines: highlighted_range_lines,
786                            color: color.clone(),
787                            //Copied from editor. TODO: move to theme or something
788                            corner_radius: 0.15 * layout.size.line_height,
789                        };
790                        hr.paint(bounds, scene);
791                    }
792                }
793            });
794
795            //Draw the text cells
796            scene.paint_layer(clip_bounds, |scene| {
797                for cell in &layout.cells {
798                    cell.paint(scene, origin, layout, visible_bounds, view, cx);
799                }
800            });
801
802            //Draw cursor
803            if self.cursor_visible {
804                if let Some(cursor) = &layout.cursor {
805                    scene.paint_layer(clip_bounds, |scene| {
806                        cursor.paint(scene, origin, cx);
807                    })
808                }
809            }
810
811            if let Some(element) = &mut layout.hyperlink_tooltip {
812                element.paint(scene, origin, visible_bounds, view, cx)
813            }
814        });
815    }
816
817    fn metadata(&self) -> Option<&dyn std::any::Any> {
818        None
819    }
820
821    fn debug(
822        &self,
823        _: RectF,
824        _: &Self::LayoutState,
825        _: &Self::PaintState,
826        _: &TerminalView,
827        _: &gpui::ViewContext<TerminalView>,
828    ) -> gpui::serde_json::Value {
829        json!({
830            "type": "TerminalElement",
831        })
832    }
833
834    fn rect_for_text_range(
835        &self,
836        _: Range<usize>,
837        bounds: RectF,
838        _: RectF,
839        layout: &Self::LayoutState,
840        _: &Self::PaintState,
841        _: &TerminalView,
842        _: &gpui::ViewContext<TerminalView>,
843    ) -> Option<RectF> {
844        // Use the same origin that's passed to `Cursor::paint` in the paint
845        // method bove.
846        let mut origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
847
848        // TODO - Why is it necessary to move downward one line to get correct
849        // positioning? I would think that we'd want the same rect that is
850        // painted for the cursor.
851        origin += vec2f(0., layout.size.line_height);
852
853        Some(layout.cursor.as_ref()?.bounding_rect(origin))
854    }
855}
856
857fn is_blank(cell: &IndexedCell) -> bool {
858    if cell.c != ' ' {
859        return false;
860    }
861
862    if cell.bg != AnsiColor::Named(NamedColor::Background) {
863        return false;
864    }
865
866    if cell.hyperlink().is_some() {
867        return false;
868    }
869
870    if cell
871        .flags
872        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
873    {
874        return false;
875    }
876
877    return true;
878}
879
880fn to_highlighted_range_lines(
881    range: &RangeInclusive<Point>,
882    layout: &LayoutState,
883    origin: Vector2F,
884) -> Option<(f32, Vec<HighlightedRangeLine>)> {
885    // Step 1. Normalize the points to be viewport relative.
886    // When display_offset = 1, here's how the grid is arranged:
887    //-2,0 -2,1...
888    //--- Viewport top
889    //-1,0 -1,1...
890    //--------- Terminal Top
891    // 0,0  0,1...
892    // 1,0  1,1...
893    //--- Viewport Bottom
894    // 2,0  2,1...
895    //--------- Terminal Bottom
896
897    // Normalize to viewport relative, from terminal relative.
898    // lines are i32s, which are negative above the top left corner of the terminal
899    // If the user has scrolled, we use the display_offset to tell us which offset
900    // of the grid data we should be looking at. But for the rendering step, we don't
901    // want negatives. We want things relative to the 'viewport' (the area of the grid
902    // which is currently shown according to the display offset)
903    let unclamped_start = Point::new(
904        range.start().line + layout.display_offset,
905        range.start().column,
906    );
907    let unclamped_end = Point::new(range.end().line + layout.display_offset, range.end().column);
908
909    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
910    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.size.num_lines() as i32 {
911        return None;
912    }
913
914    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
915    let clamped_end_line = unclamped_end.line.0.min(layout.size.num_lines() as i32) as usize;
916    //Convert the start of the range to pixels
917    let start_y = origin.y() + clamped_start_line as f32 * layout.size.line_height;
918
919    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
920    //  (also convert to pixels)
921    let mut highlighted_range_lines = Vec::new();
922    for line in clamped_start_line..=clamped_end_line {
923        let mut line_start = 0;
924        let mut line_end = layout.size.columns();
925
926        if line == clamped_start_line {
927            line_start = unclamped_start.column.0 as usize;
928        }
929        if line == clamped_end_line {
930            line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
931        }
932
933        highlighted_range_lines.push(HighlightedRangeLine {
934            start_x: origin.x() + line_start as f32 * layout.size.cell_width,
935            end_x: origin.x() + line_end as f32 * layout.size.cell_width,
936        });
937    }
938
939    Some((start_y, highlighted_range_lines))
940}