connected_el.rs

  1use alacritty_terminal::{
  2    ansi::{Color as AnsiColor, Color::Named, CursorShape as AlacCursorShape, NamedColor},
  3    grid::Dimensions,
  4    index::Point,
  5    selection::SelectionRange,
  6    term::cell::{Cell, Flags},
  7};
  8use editor::{Cursor, CursorShape, HighlightedRange, HighlightedRangeLine};
  9use gpui::{
 10    color::Color,
 11    fonts::{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, Event, EventContext, FontCache, KeyDownEvent, ModelContext, MouseButton,
 19    MouseButtonEvent, MouseRegion, PaintContext, Quad, 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;
 29use std::{
 30    mem,
 31    ops::{Deref, Range},
 32};
 33
 34use crate::{
 35    connected_view::{ConnectedView, DeployContextMenu},
 36    mappings::colors::convert_color,
 37    Terminal, TerminalSize,
 38};
 39
 40///The information generated during layout that is nescessary for painting
 41pub struct LayoutState {
 42    cells: Vec<LayoutCell>,
 43    rects: Vec<LayoutRect>,
 44    highlights: Vec<RelativeHighlightedRange>,
 45    cursor: Option<Cursor>,
 46    background_color: Color,
 47    selection_color: Color,
 48    size: TerminalSize,
 49}
 50
 51#[derive(Debug)]
 52struct IndexedCell {
 53    point: Point,
 54    cell: Cell,
 55}
 56
 57impl Deref for IndexedCell {
 58    type Target = Cell;
 59
 60    #[inline]
 61    fn deref(&self) -> &Cell {
 62        &self.cell
 63    }
 64}
 65
 66///Helper struct for converting data between alacritty's cursor points, and displayed cursor points
 67struct DisplayCursor {
 68    line: i32,
 69    col: usize,
 70}
 71
 72impl DisplayCursor {
 73    fn from(cursor_point: Point, display_offset: usize) -> Self {
 74        Self {
 75            line: cursor_point.line.0 + display_offset as i32,
 76            col: cursor_point.column.0,
 77        }
 78    }
 79
 80    pub fn line(&self) -> i32 {
 81        self.line
 82    }
 83
 84    pub fn col(&self) -> usize {
 85        self.col
 86    }
 87}
 88
 89#[derive(Clone, Debug, Default)]
 90struct LayoutCell {
 91    point: Point<i32, i32>,
 92    text: Line,
 93}
 94
 95impl LayoutCell {
 96    fn new(point: Point<i32, i32>, text: Line) -> LayoutCell {
 97        LayoutCell { point, text }
 98    }
 99
100    fn paint(
101        &self,
102        origin: Vector2F,
103        layout: &LayoutState,
104        visible_bounds: RectF,
105        cx: &mut PaintContext,
106    ) {
107        let pos = {
108            let point = self.point;
109            vec2f(
110                (origin.x() + point.column as f32 * layout.size.cell_width).floor(),
111                origin.y() + point.line as f32 * layout.size.line_height,
112            )
113        };
114
115        self.text
116            .paint(pos, visible_bounds, layout.size.line_height, cx);
117    }
118}
119
120#[derive(Clone, Debug, Default)]
121struct LayoutRect {
122    point: Point<i32, i32>,
123    num_of_cells: usize,
124    color: Color,
125}
126
127impl LayoutRect {
128    fn new(point: Point<i32, i32>, num_of_cells: usize, color: Color) -> LayoutRect {
129        LayoutRect {
130            point,
131            num_of_cells,
132            color,
133        }
134    }
135
136    fn extend(&self) -> Self {
137        LayoutRect {
138            point: self.point,
139            num_of_cells: self.num_of_cells + 1,
140            color: self.color,
141        }
142    }
143
144    fn paint(&self, origin: Vector2F, layout: &LayoutState, cx: &mut PaintContext) {
145        let position = {
146            let point = self.point;
147            vec2f(
148                (origin.x() + point.column as f32 * layout.size.cell_width).floor(),
149                origin.y() + point.line as f32 * layout.size.line_height,
150            )
151        };
152        let size = vec2f(
153            (layout.size.cell_width * self.num_of_cells as f32).ceil(),
154            layout.size.line_height,
155        );
156
157        cx.scene.push_quad(Quad {
158            bounds: RectF::new(position, size),
159            background: Some(self.color),
160            border: Default::default(),
161            corner_radius: 0.,
162        })
163    }
164}
165
166#[derive(Clone, Debug, Default)]
167struct RelativeHighlightedRange {
168    line_index: usize,
169    range: Range<usize>,
170}
171
172impl RelativeHighlightedRange {
173    fn new(line_index: usize, range: Range<usize>) -> Self {
174        RelativeHighlightedRange { line_index, range }
175    }
176
177    fn to_highlighted_range_line(
178        &self,
179        origin: Vector2F,
180        layout: &LayoutState,
181    ) -> HighlightedRangeLine {
182        let start_x = origin.x() + self.range.start as f32 * layout.size.cell_width;
183        let end_x =
184            origin.x() + self.range.end as f32 * layout.size.cell_width + layout.size.cell_width;
185
186        HighlightedRangeLine { start_x, end_x }
187    }
188}
189
190///The GPUI element that paints the terminal.
191///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?
192pub struct TerminalEl {
193    terminal: WeakModelHandle<Terminal>,
194    view: WeakViewHandle<ConnectedView>,
195    modal: bool,
196    focused: bool,
197    cursor_visible: bool,
198}
199
200impl TerminalEl {
201    pub fn new(
202        view: WeakViewHandle<ConnectedView>,
203        terminal: WeakModelHandle<Terminal>,
204        modal: bool,
205        focused: bool,
206        cursor_visible: bool,
207    ) -> TerminalEl {
208        TerminalEl {
209            view,
210            terminal,
211            modal,
212            focused,
213            cursor_visible,
214        }
215    }
216
217    fn layout_grid(
218        grid: Vec<IndexedCell>,
219        text_style: &TextStyle,
220        terminal_theme: &TerminalStyle,
221        text_layout_cache: &TextLayoutCache,
222        font_cache: &FontCache,
223        modal: bool,
224        selection_range: Option<SelectionRange>,
225    ) -> (
226        Vec<LayoutCell>,
227        Vec<LayoutRect>,
228        Vec<RelativeHighlightedRange>,
229    ) {
230        let mut cells = vec![];
231        let mut rects = vec![];
232        let mut highlight_ranges = vec![];
233
234        let mut cur_rect: Option<LayoutRect> = None;
235        let mut cur_alac_color = None;
236        let mut highlighted_range = None;
237
238        let linegroups = grid.into_iter().group_by(|i| i.point.line);
239        for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
240            for (x_index, cell) in line.enumerate() {
241                let mut fg = cell.fg;
242                let mut bg = cell.bg;
243                if cell.flags.contains(Flags::INVERSE) {
244                    mem::swap(&mut fg, &mut bg);
245                }
246
247                //Increase selection range
248                {
249                    if selection_range
250                        .map(|range| range.contains(cell.point))
251                        .unwrap_or(false)
252                    {
253                        let mut range = highlighted_range.take().unwrap_or(x_index..x_index);
254                        range.end = range.end.max(x_index);
255                        highlighted_range = Some(range);
256                    }
257                }
258
259                //Expand background rect range
260                {
261                    if matches!(bg, Named(NamedColor::Background)) {
262                        //Continue to next cell, resetting variables if nescessary
263                        cur_alac_color = None;
264                        if let Some(rect) = cur_rect {
265                            rects.push(rect);
266                            cur_rect = None
267                        }
268                    } else {
269                        match cur_alac_color {
270                            Some(cur_color) => {
271                                if bg == cur_color {
272                                    cur_rect = cur_rect.take().map(|rect| rect.extend());
273                                } else {
274                                    cur_alac_color = Some(bg);
275                                    if cur_rect.is_some() {
276                                        rects.push(cur_rect.take().unwrap());
277                                    }
278                                    cur_rect = Some(LayoutRect::new(
279                                        Point::new(line_index as i32, cell.point.column.0 as i32),
280                                        1,
281                                        convert_color(&bg, &terminal_theme.colors, modal),
282                                    ));
283                                }
284                            }
285                            None => {
286                                cur_alac_color = Some(bg);
287                                cur_rect = Some(LayoutRect::new(
288                                    Point::new(line_index as i32, cell.point.column.0 as i32),
289                                    1,
290                                    convert_color(&bg, &terminal_theme.colors, modal),
291                                ));
292                            }
293                        }
294                    }
295                }
296
297                //Layout current cell text
298                {
299                    let cell_text = &cell.c.to_string();
300                    if cell_text != " " {
301                        let cell_style = TerminalEl::cell_style(
302                            &cell,
303                            fg,
304                            terminal_theme,
305                            text_style,
306                            font_cache,
307                            modal,
308                        );
309
310                        let layout_cell = text_layout_cache.layout_str(
311                            cell_text,
312                            text_style.font_size,
313                            &[(cell_text.len(), cell_style)],
314                        );
315
316                        cells.push(LayoutCell::new(
317                            Point::new(line_index as i32, cell.point.column.0 as i32),
318                            layout_cell,
319                        ))
320                    }
321                };
322            }
323
324            if highlighted_range.is_some() {
325                highlight_ranges.push(RelativeHighlightedRange::new(
326                    line_index,
327                    highlighted_range.take().unwrap(),
328                ))
329            }
330
331            if cur_rect.is_some() {
332                rects.push(cur_rect.take().unwrap());
333            }
334        }
335        (cells, rects, highlight_ranges)
336    }
337
338    // Compute the cursor position and expected block width, may return a zero width if x_for_index returns
339    // the same position for sequential indexes. Use em_width instead
340    fn shape_cursor(
341        cursor_point: DisplayCursor,
342        size: TerminalSize,
343        text_fragment: &Line,
344    ) -> Option<(Vector2F, f32)> {
345        if cursor_point.line() < size.total_lines() as i32 {
346            let cursor_width = if text_fragment.width() == 0. {
347                size.cell_width()
348            } else {
349                text_fragment.width()
350            };
351
352            //Cursor should always surround as much of the text as possible,
353            //hence when on pixel boundaries round the origin down and the width up
354            Some((
355                vec2f(
356                    (cursor_point.col() as f32 * size.cell_width()).floor(),
357                    (cursor_point.line() as f32 * size.line_height()).floor(),
358                ),
359                cursor_width.ceil(),
360            ))
361        } else {
362            None
363        }
364    }
365
366    ///Convert the Alacritty cell styles to GPUI text styles and background color
367    fn cell_style(
368        indexed: &IndexedCell,
369        fg: AnsiColor,
370        style: &TerminalStyle,
371        text_style: &TextStyle,
372        font_cache: &FontCache,
373        modal: bool,
374    ) -> RunStyle {
375        let flags = indexed.cell.flags;
376        let fg = convert_color(&fg, &style.colors, modal);
377
378        let underline = flags
379            .intersects(Flags::ALL_UNDERLINES)
380            .then(|| Underline {
381                color: Some(fg),
382                squiggly: flags.contains(Flags::UNDERCURL),
383                thickness: OrderedFloat(1.),
384            })
385            .unwrap_or_default();
386
387        let mut properties = Properties::new();
388        if indexed
389            .flags
390            .intersects(Flags::BOLD | Flags::BOLD_ITALIC | Flags::DIM_BOLD)
391        {
392            properties = *properties.weight(Weight::BOLD);
393        }
394        if indexed.flags.intersects(Flags::ITALIC | Flags::BOLD_ITALIC) {
395            properties = *properties.style(Italic);
396        }
397
398        let font_id = font_cache
399            .select_font(text_style.font_family_id, &properties)
400            .unwrap_or(text_style.font_id);
401
402        RunStyle {
403            color: fg,
404            font_id,
405            underline,
406        }
407    }
408
409    fn generic_button_handler(
410        connection: WeakModelHandle<Terminal>,
411        origin: Vector2F,
412        f: impl Fn(&mut Terminal, Vector2F, MouseButtonEvent, &mut ModelContext<Terminal>),
413    ) -> impl Fn(MouseButtonEvent, &mut EventContext) {
414        move |event, cx| {
415            cx.focus_parent_view();
416            if let Some(conn_handle) = connection.upgrade(cx.app) {
417                conn_handle.update(cx.app, |terminal, cx| {
418                    f(terminal, origin, event, cx);
419
420                    cx.notify();
421                })
422            }
423        }
424    }
425
426    fn attach_mouse_handlers(
427        &self,
428        origin: Vector2F,
429        view_id: usize,
430        visible_bounds: RectF,
431        cx: &mut PaintContext,
432    ) {
433        let connection = self.terminal;
434        cx.scene.push_mouse_region(
435            MouseRegion::new(view_id, None, visible_bounds)
436                .on_move(move |event, cx| {
437                    if cx.is_parent_view_focused() {
438                        if let Some(conn_handle) = connection.upgrade(cx.app) {
439                            conn_handle.update(cx.app, |terminal, cx| {
440                                terminal.mouse_move(&event, origin);
441                                cx.notify();
442                            })
443                        }
444                    }
445                })
446                .on_drag(MouseButton::Left, move |_prev, event, cx| {
447                    if cx.is_parent_view_focused() {
448                        if let Some(conn_handle) = connection.upgrade(cx.app) {
449                            conn_handle.update(cx.app, |terminal, cx| {
450                                terminal.mouse_drag(event, origin);
451                                cx.notify();
452                            })
453                        }
454                    }
455                })
456                .on_down(
457                    MouseButton::Left,
458                    TerminalEl::generic_button_handler(
459                        connection,
460                        origin,
461                        move |terminal, origin, e, _cx| {
462                            terminal.mouse_down(&e, origin);
463                        },
464                    ),
465                )
466                .on_down(
467                    MouseButton::Right,
468                    TerminalEl::generic_button_handler(
469                        connection,
470                        origin,
471                        move |terminal, origin, e, _cx| {
472                            terminal.mouse_down(&e, origin);
473                        },
474                    ),
475                )
476                .on_down(
477                    MouseButton::Middle,
478                    TerminalEl::generic_button_handler(
479                        connection,
480                        origin,
481                        move |terminal, origin, e, _cx| {
482                            terminal.mouse_down(&e, origin);
483                        },
484                    ),
485                )
486                .on_up(
487                    MouseButton::Left,
488                    TerminalEl::generic_button_handler(
489                        connection,
490                        origin,
491                        move |terminal, origin, e, _cx| {
492                            terminal.mouse_up(&e, origin);
493                        },
494                    ),
495                )
496                .on_up(
497                    MouseButton::Right,
498                    TerminalEl::generic_button_handler(
499                        connection,
500                        origin,
501                        move |terminal, origin, e, _cx| {
502                            terminal.mouse_up(&e, origin);
503                        },
504                    ),
505                )
506                .on_up(
507                    MouseButton::Middle,
508                    TerminalEl::generic_button_handler(
509                        connection,
510                        origin,
511                        move |terminal, origin, e, _cx| {
512                            terminal.mouse_up(&e, origin);
513                        },
514                    ),
515                )
516                .on_click(
517                    MouseButton::Left,
518                    TerminalEl::generic_button_handler(
519                        connection,
520                        origin,
521                        move |terminal, origin, e, _cx| {
522                            terminal.left_click(&e, origin);
523                        },
524                    ),
525                )
526                .on_click(
527                    MouseButton::Right,
528                    move |e @ MouseButtonEvent { position, .. }, cx| {
529                        let mouse_mode = if let Some(conn_handle) = connection.upgrade(cx.app) {
530                            conn_handle.update(cx.app, |terminal, _cx| terminal.mouse_mode(e.shift))
531                        } else {
532                            //If we can't get the model handle, probably can't deploy the context menu
533                            true
534                        };
535                        if !mouse_mode {
536                            cx.dispatch_action(DeployContextMenu { position });
537                        }
538                    },
539                ),
540        );
541    }
542
543    ///Configures a text style from the current settings.
544    pub fn make_text_style(font_cache: &FontCache, settings: &Settings) -> TextStyle {
545        // Pull the font family from settings properly overriding
546        let family_id = settings
547            .terminal_overrides
548            .font_family
549            .as_ref()
550            .or(settings.terminal_defaults.font_family.as_ref())
551            .and_then(|family_name| font_cache.load_family(&[family_name]).log_err())
552            .unwrap_or(settings.buffer_font_family);
553
554        let font_size = settings
555            .terminal_overrides
556            .font_size
557            .or(settings.terminal_defaults.font_size)
558            .unwrap_or(settings.buffer_font_size);
559
560        let font_id = font_cache
561            .select_font(family_id, &Default::default())
562            .unwrap();
563
564        TextStyle {
565            color: settings.theme.editor.text_color,
566            font_family_id: family_id,
567            font_family_name: font_cache.family_name(family_id).unwrap(),
568            font_id,
569            font_size,
570            font_properties: Default::default(),
571            underline: Default::default(),
572        }
573    }
574}
575
576impl Element for TerminalEl {
577    type LayoutState = LayoutState;
578    type PaintState = ();
579
580    fn layout(
581        &mut self,
582        constraint: gpui::SizeConstraint,
583        cx: &mut gpui::LayoutContext,
584    ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
585        let settings = cx.global::<Settings>();
586        let font_cache = cx.font_cache();
587
588        //Setup layout information
589        let terminal_theme = settings.theme.terminal.clone(); //TODO: Try to minimize this clone.
590        let text_style = TerminalEl::make_text_style(font_cache, settings);
591        let selection_color = settings.theme.editor.selection.selection;
592        let dimensions = {
593            let line_height = font_cache.line_height(text_style.font_size);
594            let cell_width = font_cache.em_advance(text_style.font_id, text_style.font_size);
595            TerminalSize::new(line_height, cell_width, constraint.max)
596        };
597
598        let background_color = if self.modal {
599            terminal_theme.colors.modal_background
600        } else {
601            terminal_theme.colors.background
602        };
603
604        let (cells, selection, cursor, display_offset, cursor_text) = self
605            .terminal
606            .upgrade(cx)
607            .unwrap()
608            .update(cx.app, |terminal, mcx| {
609                terminal.set_size(dimensions);
610                terminal.render_lock(mcx, |content, cursor_text| {
611                    let mut cells = vec![];
612                    cells.extend(
613                        content
614                            .display_iter
615                            //TODO: Add this once there's a way to retain empty lines
616                            // .filter(|ic| {
617                            //     !ic.flags.contains(Flags::HIDDEN)
618                            //         && !(ic.bg == Named(NamedColor::Background)
619                            //             && ic.c == ' '
620                            //             && !ic.flags.contains(Flags::INVERSE))
621                            // })
622                            .map(|ic| IndexedCell {
623                                point: ic.point,
624                                cell: ic.cell.clone(),
625                            }),
626                    );
627
628                    (
629                        cells,
630                        content.selection,
631                        content.cursor,
632                        content.display_offset,
633                        cursor_text,
634                    )
635                })
636            });
637
638        let (cells, rects, highlights) = TerminalEl::layout_grid(
639            cells,
640            &text_style,
641            &terminal_theme,
642            cx.text_layout_cache,
643            cx.font_cache(),
644            self.modal,
645            selection,
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_text.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            TerminalEl::shape_cursor(cursor_point, dimensions, &cursor_text).map(
678                move |(cursor_position, block_width)| {
679                    let shape = match cursor.shape {
680                        AlacCursorShape::Block if !self.focused => CursorShape::Hollow,
681                        AlacCursorShape::Block => CursorShape::Block,
682                        AlacCursorShape::Underline => CursorShape::Underscore,
683                        AlacCursorShape::Beam => CursorShape::Bar,
684                        AlacCursorShape::HollowBlock => CursorShape::Hollow,
685                        //This case is handled in the if wrapping the whole cursor layout
686                        AlacCursorShape::Hidden => unreachable!(),
687                    };
688
689                    Cursor::new(
690                        cursor_position,
691                        block_width,
692                        dimensions.line_height,
693                        terminal_theme.colors.cursor,
694                        shape,
695                        Some(cursor_text),
696                    )
697                },
698            )
699        };
700
701        //Done!
702        (
703            constraint.max,
704            LayoutState {
705                cells,
706                cursor,
707                background_color,
708                selection_color,
709                size: dimensions,
710                rects,
711                highlights,
712            },
713        )
714    }
715
716    fn paint(
717        &mut self,
718        bounds: gpui::geometry::rect::RectF,
719        visible_bounds: gpui::geometry::rect::RectF,
720        layout: &mut Self::LayoutState,
721        cx: &mut gpui::PaintContext,
722    ) -> Self::PaintState {
723        //Setup element stuff
724        let clip_bounds = Some(visible_bounds);
725
726        cx.paint_layer(clip_bounds, |cx| {
727            let origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
728
729            //Elements are ephemeral, only at paint time do we know what could be clicked by a mouse
730            self.attach_mouse_handlers(origin, self.view.id(), visible_bounds, cx);
731
732            cx.paint_layer(clip_bounds, |cx| {
733                //Start with a background color
734                cx.scene.push_quad(Quad {
735                    bounds: RectF::new(bounds.origin(), bounds.size()),
736                    background: Some(layout.background_color),
737                    border: Default::default(),
738                    corner_radius: 0.,
739                });
740
741                for rect in &layout.rects {
742                    rect.paint(origin, layout, cx)
743                }
744            });
745
746            //Draw Selection
747            cx.paint_layer(clip_bounds, |cx| {
748                let start_y = layout.highlights.get(0).map(|highlight| {
749                    origin.y() + highlight.line_index as f32 * layout.size.line_height
750                });
751
752                if let Some(y) = start_y {
753                    let range_lines = layout
754                        .highlights
755                        .iter()
756                        .map(|relative_highlight| {
757                            relative_highlight.to_highlighted_range_line(origin, layout)
758                        })
759                        .collect::<Vec<HighlightedRangeLine>>();
760
761                    let hr = HighlightedRange {
762                        start_y: y, //Need to change this
763                        line_height: layout.size.line_height,
764                        lines: range_lines,
765                        color: layout.selection_color,
766                        //Copied from editor. TODO: move to theme or something
767                        corner_radius: 0.15 * layout.size.line_height,
768                    };
769                    hr.paint(bounds, cx.scene);
770                }
771            });
772
773            //Draw the text cells
774            cx.paint_layer(clip_bounds, |cx| {
775                for cell in &layout.cells {
776                    cell.paint(origin, layout, visible_bounds, cx);
777                }
778            });
779
780            //Draw cursor
781            if self.cursor_visible {
782                if let Some(cursor) = &layout.cursor {
783                    cx.paint_layer(clip_bounds, |cx| {
784                        cursor.paint(origin, cx);
785                    })
786                }
787            }
788        });
789    }
790
791    fn dispatch_event(
792        &mut self,
793        event: &gpui::Event,
794        bounds: gpui::geometry::rect::RectF,
795        visible_bounds: gpui::geometry::rect::RectF,
796        layout: &mut Self::LayoutState,
797        _paint: &mut Self::PaintState,
798        cx: &mut gpui::EventContext,
799    ) -> bool {
800        match event {
801            Event::ScrollWheel(e) => visible_bounds
802                .contains_point(e.position)
803                .then(|| {
804                    let origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
805
806                    if let Some(terminal) = self.terminal.upgrade(cx.app) {
807                        terminal.update(cx.app, |term, _| term.scroll(e, origin));
808                        cx.notify();
809                    }
810                })
811                .is_some(),
812            Event::KeyDown(KeyDownEvent { keystroke, .. }) => {
813                if !cx.is_parent_view_focused() {
814                    return false;
815                }
816
817                if let Some(view) = self.view.upgrade(cx.app) {
818                    view.update(cx.app, |view, cx| {
819                        view.clear_bel(cx);
820                        view.pause_cursor_blinking(cx);
821                    })
822                }
823
824                self.terminal
825                    .upgrade(cx.app)
826                    .map(|model_handle| {
827                        model_handle.update(cx.app, |term, _| term.try_keystroke(keystroke))
828                    })
829                    .unwrap_or(false)
830            }
831            _ => false,
832        }
833    }
834
835    fn metadata(&self) -> Option<&dyn std::any::Any> {
836        None
837    }
838
839    fn debug(
840        &self,
841        _bounds: gpui::geometry::rect::RectF,
842        _layout: &Self::LayoutState,
843        _paint: &Self::PaintState,
844        _cx: &gpui::DebugContext,
845    ) -> gpui::serde_json::Value {
846        json!({
847            "type": "TerminalElement",
848        })
849    }
850
851    fn rect_for_text_range(
852        &self,
853        _: Range<usize>,
854        bounds: RectF,
855        _: RectF,
856        layout: &Self::LayoutState,
857        _: &Self::PaintState,
858        _: &gpui::MeasurementContext,
859    ) -> Option<RectF> {
860        // Use the same origin that's passed to `Cursor::paint` in the paint
861        // method bove.
862        let mut origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
863
864        // TODO - Why is it necessary to move downward one line to get correct
865        // positioning? I would think that we'd want the same rect that is
866        // painted for the cursor.
867        origin += vec2f(0., layout.size.line_height);
868
869        Some(layout.cursor.as_ref()?.bounding_rect(origin))
870    }
871}