terminal_element.rs

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