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