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