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