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