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 cx.is_self_focused() {
415                    if let Some(conn_handle) = connection.upgrade(cx) {
416                        conn_handle.update(cx, |terminal, cx| {
417                            terminal.mouse_drag(event, origin);
418                            cx.notify();
419                        })
420                    }
421                }
422            })
423            // Copy on up behavior
424            .on_up(
425                MouseButton::Left,
426                TerminalElement::generic_button_handler(
427                    connection,
428                    origin,
429                    move |terminal, origin, e, cx| {
430                        terminal.mouse_up(&e, origin, cx);
431                    },
432                ),
433            )
434            // Context menu
435            .on_click(
436                MouseButton::Right,
437                move |event, view: &mut TerminalView, cx| {
438                    let mouse_mode = if let Some(conn_handle) = connection.upgrade(cx) {
439                        conn_handle.update(cx, |terminal, _cx| terminal.mouse_mode(event.shift))
440                    } else {
441                        // If we can't get the model handle, probably can't deploy the context menu
442                        true
443                    };
444                    if !mouse_mode {
445                        view.deploy_context_menu(event.position, cx);
446                    }
447                },
448            )
449            .on_move(move |event, _: &mut TerminalView, cx| {
450                if cx.is_self_focused() {
451                    if let Some(conn_handle) = connection.upgrade(cx) {
452                        conn_handle.update(cx, |terminal, cx| {
453                            terminal.mouse_move(&event, origin);
454                            cx.notify();
455                        })
456                    }
457                }
458            })
459            .on_scroll(move |event, _: &mut TerminalView, cx| {
460                if let Some(conn_handle) = connection.upgrade(cx) {
461                    conn_handle.update(cx, |terminal, cx| {
462                        terminal.scroll_wheel(event, origin);
463                        cx.notify();
464                    })
465                }
466            });
467
468        // Mouse mode handlers:
469        // All mouse modes need the extra click handlers
470        if mode.intersects(TermMode::MOUSE_MODE) {
471            region = region
472                .on_down(
473                    MouseButton::Right,
474                    TerminalElement::generic_button_handler(
475                        connection,
476                        origin,
477                        move |terminal, origin, e, _cx| {
478                            terminal.mouse_down(&e, origin);
479                        },
480                    ),
481                )
482                .on_down(
483                    MouseButton::Middle,
484                    TerminalElement::generic_button_handler(
485                        connection,
486                        origin,
487                        move |terminal, origin, e, _cx| {
488                            terminal.mouse_down(&e, origin);
489                        },
490                    ),
491                )
492                .on_up(
493                    MouseButton::Right,
494                    TerminalElement::generic_button_handler(
495                        connection,
496                        origin,
497                        move |terminal, origin, e, cx| {
498                            terminal.mouse_up(&e, origin, cx);
499                        },
500                    ),
501                )
502                .on_up(
503                    MouseButton::Middle,
504                    TerminalElement::generic_button_handler(
505                        connection,
506                        origin,
507                        move |terminal, origin, e, cx| {
508                            terminal.mouse_up(&e, origin, cx);
509                        },
510                    ),
511                )
512        }
513
514        scene.push_mouse_region(region);
515    }
516}
517
518impl Element<TerminalView> for TerminalElement {
519    type LayoutState = LayoutState;
520    type PaintState = ();
521
522    fn layout(
523        &mut self,
524        constraint: gpui::SizeConstraint,
525        view: &mut TerminalView,
526        cx: &mut LayoutContext<TerminalView>,
527    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
528        let settings = settings::get::<ThemeSettings>(cx);
529        let terminal_settings = settings::get::<TerminalSettings>(cx);
530
531        //Setup layout information
532        let terminal_theme = settings.theme.terminal.clone(); //TODO: Try to minimize this clone.
533        let link_style = settings.theme.editor.link_definition;
534        let tooltip_style = settings.theme.tooltip.clone();
535
536        let font_cache = cx.font_cache();
537        let font_size = terminal_settings
538            .font_size(cx)
539            .unwrap_or(settings.buffer_font_size(cx));
540        let font_family_name = terminal_settings
541            .font_family
542            .as_ref()
543            .unwrap_or(&settings.buffer_font_family_name);
544        let font_features = terminal_settings
545            .font_features
546            .as_ref()
547            .unwrap_or(&settings.buffer_font_features);
548        let family_id = font_cache
549            .load_family(&[font_family_name], &font_features)
550            .log_err()
551            .unwrap_or(settings.buffer_font_family);
552        let font_id = font_cache
553            .select_font(family_id, &Default::default())
554            .unwrap();
555
556        let text_style = TextStyle {
557            color: settings.theme.editor.text_color,
558            font_family_id: family_id,
559            font_family_name: font_cache.family_name(family_id).unwrap(),
560            font_id,
561            font_size,
562            font_properties: Default::default(),
563            underline: Default::default(),
564        };
565        let selection_color = settings.theme.editor.selection.selection;
566        let match_color = settings.theme.search.match_background;
567        let gutter;
568        let dimensions = {
569            let line_height = text_style.font_size * terminal_settings.line_height.value();
570            let cell_width = font_cache.em_advance(text_style.font_id, text_style.font_size);
571            gutter = cell_width;
572
573            let size = constraint.max - vec2f(gutter, 0.);
574            TerminalSize::new(line_height, cell_width, size)
575        };
576
577        let search_matches = if let Some(terminal_model) = self.terminal.upgrade(cx) {
578            terminal_model.read(cx).matches.clone()
579        } else {
580            Default::default()
581        };
582
583        let background_color = terminal_theme.background;
584        let terminal_handle = self.terminal.upgrade(cx).unwrap();
585
586        let last_hovered_word = terminal_handle.update(cx, |terminal, cx| {
587            terminal.set_size(dimensions);
588            terminal.try_sync(cx);
589            if self.can_navigate_to_selected_word && terminal.can_navigate_to_selected_word() {
590                terminal.last_content.last_hovered_word.clone()
591            } else {
592                None
593            }
594        });
595
596        let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
597            let mut tooltip = Overlay::new(
598                Empty::new()
599                    .contained()
600                    .constrained()
601                    .with_width(dimensions.width())
602                    .with_height(dimensions.height())
603                    .with_tooltip::<TerminalElement>(
604                        hovered_word.id,
605                        hovered_word.word,
606                        None,
607                        tooltip_style,
608                        cx,
609                    ),
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            ..
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_word
650                .as_ref()
651                .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
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}