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