connected_el.rs

  1use alacritty_terminal::{
  2    ansi::{Color as AnsiColor, Color::Named, CursorShape as AlacCursorShape, NamedColor},
  3    grid::{Dimensions, Scroll},
  4    index::{Column as GridCol, Line as GridLine, Point, Side},
  5    selection::SelectionRange,
  6    term::cell::{Cell, Flags},
  7};
  8use editor::{Cursor, CursorShape, HighlightedRange, HighlightedRangeLine};
  9use gpui::{
 10    color::Color,
 11    elements::*,
 12    fonts::{Properties, Style::Italic, TextStyle, Underline, Weight},
 13    geometry::{
 14        rect::RectF,
 15        vector::{vec2f, Vector2F},
 16    },
 17    json::json,
 18    text_layout::{Line, RunStyle},
 19    Event, FontCache, KeyDownEvent, MouseButton, MouseButtonEvent, MouseMovedEvent, MouseRegion,
 20    PaintContext, Quad, ScrollWheelEvent, TextLayoutCache, WeakModelHandle, WeakViewHandle,
 21};
 22use itertools::Itertools;
 23use ordered_float::OrderedFloat;
 24use settings::Settings;
 25use theme::TerminalStyle;
 26use util::ResultExt;
 27
 28use std::{
 29    cmp::min,
 30    mem,
 31    ops::{Deref, Range},
 32};
 33use std::{fmt::Debug, ops::Sub};
 34
 35use crate::{
 36    connected_view::{ConnectedView, DeployContextMenu},
 37    mappings::colors::convert_color,
 38    Terminal, TerminalSize,
 39};
 40
 41///Scrolling is unbearably sluggish by default. Alacritty supports a configurable
 42///Scroll multiplier that is set to 3 by default. This will be removed when I
 43///Implement scroll bars.
 44pub const ALACRITTY_SCROLL_MULTIPLIER: f32 = 3.;
 45
 46///The information generated during layout that is nescessary for painting
 47pub struct LayoutState {
 48    cells: Vec<LayoutCell>,
 49    rects: Vec<LayoutRect>,
 50    highlights: Vec<RelativeHighlightedRange>,
 51    cursor: Option<Cursor>,
 52    background_color: Color,
 53    selection_color: Color,
 54    size: TerminalSize,
 55    display_offset: usize,
 56}
 57
 58#[derive(Debug)]
 59struct IndexedCell {
 60    point: Point,
 61    cell: Cell,
 62}
 63
 64impl Deref for IndexedCell {
 65    type Target = Cell;
 66
 67    #[inline]
 68    fn deref(&self) -> &Cell {
 69        &self.cell
 70    }
 71}
 72
 73///Helper struct for converting data between alacritty's cursor points, and displayed cursor points
 74struct DisplayCursor {
 75    line: i32,
 76    col: usize,
 77}
 78
 79impl DisplayCursor {
 80    fn from(cursor_point: Point, display_offset: usize) -> Self {
 81        Self {
 82            line: cursor_point.line.0 + display_offset as i32,
 83            col: cursor_point.column.0,
 84        }
 85    }
 86
 87    pub fn line(&self) -> i32 {
 88        self.line
 89    }
 90
 91    pub fn col(&self) -> usize {
 92        self.col
 93    }
 94}
 95
 96#[derive(Clone, Debug, Default)]
 97struct LayoutCell {
 98    point: Point<i32, i32>,
 99    text: Line,
100}
101
102impl LayoutCell {
103    fn new(point: Point<i32, i32>, text: Line) -> LayoutCell {
104        LayoutCell { point, text }
105    }
106
107    fn paint(
108        &self,
109        origin: Vector2F,
110        layout: &LayoutState,
111        visible_bounds: RectF,
112        cx: &mut PaintContext,
113    ) {
114        let pos = {
115            let point = self.point;
116            vec2f(
117                (origin.x() + point.column as f32 * layout.size.cell_width).floor(),
118                origin.y() + point.line as f32 * layout.size.line_height,
119            )
120        };
121
122        self.text
123            .paint(pos, visible_bounds, layout.size.line_height, cx);
124    }
125}
126
127#[derive(Clone, Debug, Default)]
128struct LayoutRect {
129    point: Point<i32, i32>,
130    num_of_cells: usize,
131    color: Color,
132}
133
134impl LayoutRect {
135    fn new(point: Point<i32, i32>, num_of_cells: usize, color: Color) -> LayoutRect {
136        LayoutRect {
137            point,
138            num_of_cells,
139            color,
140        }
141    }
142
143    fn extend(&self) -> Self {
144        LayoutRect {
145            point: self.point,
146            num_of_cells: self.num_of_cells + 1,
147            color: self.color,
148        }
149    }
150
151    fn paint(&self, origin: Vector2F, layout: &LayoutState, cx: &mut PaintContext) {
152        let position = {
153            let point = self.point;
154            vec2f(
155                (origin.x() + point.column as f32 * layout.size.cell_width).floor(),
156                origin.y() + point.line as f32 * layout.size.line_height,
157            )
158        };
159        let size = vec2f(
160            (layout.size.cell_width * self.num_of_cells as f32).ceil(),
161            layout.size.line_height,
162        );
163
164        cx.scene.push_quad(Quad {
165            bounds: RectF::new(position, size),
166            background: Some(self.color),
167            border: Default::default(),
168            corner_radius: 0.,
169        })
170    }
171}
172
173#[derive(Clone, Debug, Default)]
174struct RelativeHighlightedRange {
175    line_index: usize,
176    range: Range<usize>,
177}
178
179impl RelativeHighlightedRange {
180    fn new(line_index: usize, range: Range<usize>) -> Self {
181        RelativeHighlightedRange { line_index, range }
182    }
183
184    fn to_highlighted_range_line(
185        &self,
186        origin: Vector2F,
187        layout: &LayoutState,
188    ) -> HighlightedRangeLine {
189        let start_x = origin.x() + self.range.start as f32 * layout.size.cell_width;
190        let end_x =
191            origin.x() + self.range.end as f32 * layout.size.cell_width + layout.size.cell_width;
192
193        HighlightedRangeLine { start_x, end_x }
194    }
195}
196
197///The GPUI element that paints the terminal.
198///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?
199pub struct TerminalEl {
200    terminal: WeakModelHandle<Terminal>,
201    view: WeakViewHandle<ConnectedView>,
202    modal: bool,
203    focused: bool,
204    cursor_visible: bool,
205}
206
207impl TerminalEl {
208    pub fn new(
209        view: WeakViewHandle<ConnectedView>,
210        terminal: WeakModelHandle<Terminal>,
211        modal: bool,
212        focused: bool,
213        cursor_visible: bool,
214    ) -> TerminalEl {
215        TerminalEl {
216            view,
217            terminal,
218            modal,
219            focused,
220            cursor_visible,
221        }
222    }
223
224    fn layout_grid(
225        grid: Vec<IndexedCell>,
226        text_style: &TextStyle,
227        terminal_theme: &TerminalStyle,
228        text_layout_cache: &TextLayoutCache,
229        font_cache: &FontCache,
230        modal: bool,
231        selection_range: Option<SelectionRange>,
232    ) -> (
233        Vec<LayoutCell>,
234        Vec<LayoutRect>,
235        Vec<RelativeHighlightedRange>,
236    ) {
237        let mut cells = vec![];
238        let mut rects = vec![];
239        let mut highlight_ranges = vec![];
240
241        let mut cur_rect: Option<LayoutRect> = None;
242        let mut cur_alac_color = None;
243        let mut highlighted_range = None;
244
245        let linegroups = grid.into_iter().group_by(|i| i.point.line);
246        for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
247            for (x_index, cell) in line.enumerate() {
248                let mut fg = cell.fg;
249                let mut bg = cell.bg;
250                if cell.flags.contains(Flags::INVERSE) {
251                    mem::swap(&mut fg, &mut bg);
252                }
253
254                //Increase selection range
255                {
256                    if selection_range
257                        .map(|range| range.contains(cell.point))
258                        .unwrap_or(false)
259                    {
260                        let mut range = highlighted_range.take().unwrap_or(x_index..x_index);
261                        range.end = range.end.max(x_index);
262                        highlighted_range = Some(range);
263                    }
264                }
265
266                //Expand background rect range
267                {
268                    if matches!(bg, Named(NamedColor::Background)) {
269                        //Continue to next cell, resetting variables if nescessary
270                        cur_alac_color = None;
271                        if let Some(rect) = cur_rect {
272                            rects.push(rect);
273                            cur_rect = None
274                        }
275                    } else {
276                        match cur_alac_color {
277                            Some(cur_color) => {
278                                if bg == cur_color {
279                                    cur_rect = cur_rect.take().map(|rect| rect.extend());
280                                } else {
281                                    cur_alac_color = Some(bg);
282                                    if cur_rect.is_some() {
283                                        rects.push(cur_rect.take().unwrap());
284                                    }
285                                    cur_rect = Some(LayoutRect::new(
286                                        Point::new(line_index as i32, cell.point.column.0 as i32),
287                                        1,
288                                        convert_color(&bg, &terminal_theme.colors, modal),
289                                    ));
290                                }
291                            }
292                            None => {
293                                cur_alac_color = Some(bg);
294                                cur_rect = Some(LayoutRect::new(
295                                    Point::new(line_index as i32, cell.point.column.0 as i32),
296                                    1,
297                                    convert_color(&bg, &terminal_theme.colors, modal),
298                                ));
299                            }
300                        }
301                    }
302                }
303
304                //Layout current cell text
305                {
306                    let cell_text = &cell.c.to_string();
307                    if cell_text != " " {
308                        let cell_style = TerminalEl::cell_style(
309                            &cell,
310                            fg,
311                            terminal_theme,
312                            text_style,
313                            font_cache,
314                            modal,
315                        );
316
317                        let layout_cell = text_layout_cache.layout_str(
318                            cell_text,
319                            text_style.font_size,
320                            &[(cell_text.len(), cell_style)],
321                        );
322
323                        cells.push(LayoutCell::new(
324                            Point::new(line_index as i32, cell.point.column.0 as i32),
325                            layout_cell,
326                        ))
327                    }
328                };
329            }
330
331            if highlighted_range.is_some() {
332                highlight_ranges.push(RelativeHighlightedRange::new(
333                    line_index,
334                    highlighted_range.take().unwrap(),
335                ))
336            }
337
338            if cur_rect.is_some() {
339                rects.push(cur_rect.take().unwrap());
340            }
341        }
342        (cells, rects, highlight_ranges)
343    }
344
345    // Compute the cursor position and expected block width, may return a zero width if x_for_index returns
346    // the same position for sequential indexes. Use em_width instead
347    fn shape_cursor(
348        cursor_point: DisplayCursor,
349        size: TerminalSize,
350        text_fragment: &Line,
351    ) -> Option<(Vector2F, f32)> {
352        if cursor_point.line() < size.total_lines() as i32 {
353            let cursor_width = if text_fragment.width() == 0. {
354                size.cell_width()
355            } else {
356                text_fragment.width()
357            };
358
359            //Cursor should always surround as much of the text as possible,
360            //hence when on pixel boundaries round the origin down and the width up
361            Some((
362                vec2f(
363                    (cursor_point.col() as f32 * size.cell_width()).floor(),
364                    (cursor_point.line() as f32 * size.line_height()).floor(),
365                ),
366                cursor_width.ceil(),
367            ))
368        } else {
369            None
370        }
371    }
372
373    ///Convert the Alacritty cell styles to GPUI text styles and background color
374    fn cell_style(
375        indexed: &IndexedCell,
376        fg: AnsiColor,
377        style: &TerminalStyle,
378        text_style: &TextStyle,
379        font_cache: &FontCache,
380        modal: bool,
381    ) -> RunStyle {
382        let flags = indexed.cell.flags;
383        let fg = convert_color(&fg, &style.colors, modal);
384
385        let underline = flags
386            .intersects(Flags::ALL_UNDERLINES)
387            .then(|| Underline {
388                color: Some(fg),
389                squiggly: flags.contains(Flags::UNDERCURL),
390                thickness: OrderedFloat(1.),
391            })
392            .unwrap_or_default();
393
394        let mut properties = Properties::new();
395        if indexed
396            .flags
397            .intersects(Flags::BOLD | Flags::BOLD_ITALIC | Flags::DIM_BOLD)
398        {
399            properties = *properties.weight(Weight::BOLD);
400        }
401        if indexed.flags.intersects(Flags::ITALIC | Flags::BOLD_ITALIC) {
402            properties = *properties.style(Italic);
403        }
404
405        let font_id = font_cache
406            .select_font(text_style.font_family_id, &properties)
407            .unwrap_or(text_style.font_id);
408
409        RunStyle {
410            color: fg,
411            font_id,
412            underline,
413        }
414    }
415
416    fn attach_mouse_handlers(
417        &self,
418        origin: Vector2F,
419        view_id: usize,
420        visible_bounds: RectF,
421        cur_size: TerminalSize,
422        display_offset: usize,
423        cx: &mut PaintContext,
424    ) {
425        let mouse_down_connection = self.terminal;
426        let click_connection = self.terminal;
427        let drag_connection = self.terminal;
428        cx.scene.push_mouse_region(
429            MouseRegion::new(view_id, None, visible_bounds)
430                .on_down(
431                    MouseButton::Left,
432                    move |MouseButtonEvent { position, .. }, cx| {
433                        if let Some(conn_handle) = mouse_down_connection.upgrade(cx.app) {
434                            conn_handle.update(cx.app, |terminal, cx| {
435                                let (point, side) = TerminalEl::mouse_to_cell_data(
436                                    position,
437                                    origin,
438                                    cur_size,
439                                    display_offset,
440                                );
441
442                                terminal.mouse_down(point, side);
443
444                                cx.notify();
445                            })
446                        }
447                    },
448                )
449                .on_click(
450                    MouseButton::Left,
451                    move |MouseButtonEvent {
452                              position,
453                              click_count,
454                              ..
455                          },
456                          cx| {
457                        cx.focus_parent_view();
458                        if let Some(conn_handle) = click_connection.upgrade(cx.app) {
459                            conn_handle.update(cx.app, |terminal, cx| {
460                                let (point, side) = TerminalEl::mouse_to_cell_data(
461                                    position,
462                                    origin,
463                                    cur_size,
464                                    display_offset,
465                                );
466
467                                terminal.click(point, side, click_count);
468
469                                cx.notify();
470                            });
471                        }
472                    },
473                )
474                .on_click(
475                    MouseButton::Right,
476                    move |MouseButtonEvent { position, .. }, cx| {
477                        cx.dispatch_action(DeployContextMenu { position });
478                    },
479                )
480                .on_drag(
481                    MouseButton::Left,
482                    move |_, MouseMovedEvent { position, .. }, cx| {
483                        if let Some(conn_handle) = drag_connection.upgrade(cx.app) {
484                            conn_handle.update(cx.app, |terminal, cx| {
485                                let (point, side) = TerminalEl::mouse_to_cell_data(
486                                    position,
487                                    origin,
488                                    cur_size,
489                                    display_offset,
490                                );
491
492                                terminal.drag(point, side);
493
494                                cx.notify()
495                            });
496                        }
497                    },
498                ),
499        );
500    }
501
502    ///Configures a text style from the current settings.
503    pub fn make_text_style(font_cache: &FontCache, settings: &Settings) -> TextStyle {
504        // Pull the font family from settings properly overriding
505        let family_id = settings
506            .terminal_overrides
507            .font_family
508            .as_ref()
509            .or(settings.terminal_defaults.font_family.as_ref())
510            .and_then(|family_name| font_cache.load_family(&[family_name]).log_err())
511            .unwrap_or(settings.buffer_font_family);
512
513        let font_size = settings
514            .terminal_overrides
515            .font_size
516            .or(settings.terminal_defaults.font_size)
517            .unwrap_or(settings.buffer_font_size);
518
519        let font_id = font_cache
520            .select_font(family_id, &Default::default())
521            .unwrap();
522
523        TextStyle {
524            color: settings.theme.editor.text_color,
525            font_family_id: family_id,
526            font_family_name: font_cache.family_name(family_id).unwrap(),
527            font_id,
528            font_size,
529            font_properties: Default::default(),
530            underline: Default::default(),
531        }
532    }
533
534    pub fn mouse_to_cell_data(
535        pos: Vector2F,
536        origin: Vector2F,
537        cur_size: TerminalSize,
538        display_offset: usize,
539    ) -> (Point, alacritty_terminal::index::Direction) {
540        let pos = pos.sub(origin);
541        let point = {
542            let col = pos.x() / cur_size.cell_width; //TODO: underflow...
543            let col = min(GridCol(col as usize), cur_size.last_column());
544
545            let line = pos.y() / cur_size.line_height;
546            let line = min(line as i32, cur_size.bottommost_line().0);
547
548            Point::new(GridLine(line - display_offset as i32), col)
549        };
550
551        //Copied (with modifications) from alacritty/src/input.rs > Processor::cell_side()
552        let side = {
553            let x = pos.0.x() as usize;
554            let cell_x =
555                x.saturating_sub(cur_size.cell_width as usize) % cur_size.cell_width as usize;
556            let half_cell_width = (cur_size.cell_width / 2.0) as usize;
557
558            let additional_padding =
559                (cur_size.width() - cur_size.cell_width * 2.) % cur_size.cell_width;
560            let end_of_grid = cur_size.width() - cur_size.cell_width - additional_padding;
561            //Width: Pixels or columns?
562            if cell_x > half_cell_width
563            // Edge case when mouse leaves the window.
564            || x as f32 >= end_of_grid
565            {
566                Side::Right
567            } else {
568                Side::Left
569            }
570        };
571
572        (point, side)
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                display_offset,
713            },
714        )
715    }
716
717    fn paint(
718        &mut self,
719        bounds: gpui::geometry::rect::RectF,
720        visible_bounds: gpui::geometry::rect::RectF,
721        layout: &mut Self::LayoutState,
722        cx: &mut gpui::PaintContext,
723    ) -> Self::PaintState {
724        //Setup element stuff
725        let clip_bounds = Some(visible_bounds);
726
727        cx.paint_layer(clip_bounds, |cx| {
728            let origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
729
730            //Elements are ephemeral, only at paint time do we know what could be clicked by a mouse
731            self.attach_mouse_handlers(
732                origin,
733                self.view.id(),
734                visible_bounds,
735                layout.size,
736                layout.display_offset,
737                cx,
738            );
739
740            cx.paint_layer(clip_bounds, |cx| {
741                //Start with a background color
742                cx.scene.push_quad(Quad {
743                    bounds: RectF::new(bounds.origin(), bounds.size()),
744                    background: Some(layout.background_color),
745                    border: Default::default(),
746                    corner_radius: 0.,
747                });
748
749                for rect in &layout.rects {
750                    rect.paint(origin, layout, cx)
751                }
752            });
753
754            //Draw Selection
755            cx.paint_layer(clip_bounds, |cx| {
756                let start_y = layout.highlights.get(0).map(|highlight| {
757                    origin.y() + highlight.line_index as f32 * layout.size.line_height
758                });
759
760                if let Some(y) = start_y {
761                    let range_lines = layout
762                        .highlights
763                        .iter()
764                        .map(|relative_highlight| {
765                            relative_highlight.to_highlighted_range_line(origin, layout)
766                        })
767                        .collect::<Vec<HighlightedRangeLine>>();
768
769                    let hr = HighlightedRange {
770                        start_y: y, //Need to change this
771                        line_height: layout.size.line_height,
772                        lines: range_lines,
773                        color: layout.selection_color,
774                        //Copied from editor. TODO: move to theme or something
775                        corner_radius: 0.15 * layout.size.line_height,
776                    };
777                    hr.paint(bounds, cx.scene);
778                }
779            });
780
781            //Draw the text cells
782            cx.paint_layer(clip_bounds, |cx| {
783                for cell in &layout.cells {
784                    cell.paint(origin, layout, visible_bounds, cx);
785                }
786            });
787
788            //Draw cursor
789            if self.cursor_visible {
790                if let Some(cursor) = &layout.cursor {
791                    cx.paint_layer(clip_bounds, |cx| {
792                        cursor.paint(origin, cx);
793                    })
794                }
795            }
796        });
797    }
798
799    fn dispatch_event(
800        &mut self,
801        event: &gpui::Event,
802        _bounds: gpui::geometry::rect::RectF,
803        visible_bounds: gpui::geometry::rect::RectF,
804        layout: &mut Self::LayoutState,
805        _paint: &mut Self::PaintState,
806        cx: &mut gpui::EventContext,
807    ) -> bool {
808        match event {
809            Event::ScrollWheel(ScrollWheelEvent {
810                delta, position, ..
811            }) => visible_bounds
812                .contains_point(*position)
813                .then(|| {
814                    let vertical_scroll =
815                        (delta.y() / layout.size.line_height) * ALACRITTY_SCROLL_MULTIPLIER;
816
817                    if let Some(terminal) = self.terminal.upgrade(cx.app) {
818                        terminal.update(cx.app, |term, _| {
819                            term.scroll(Scroll::Delta(vertical_scroll.round() as i32))
820                        });
821                    }
822
823                    cx.notify();
824                })
825                .is_some(),
826            Event::KeyDown(KeyDownEvent { keystroke, .. }) => {
827                if !cx.is_parent_view_focused() {
828                    return false;
829                }
830
831                //TODO Talk to keith about how to catch events emitted from an element.
832                if let Some(view) = self.view.upgrade(cx.app) {
833                    view.update(cx.app, |view, cx| {
834                        view.clear_bel(cx);
835                        view.pause_cursor_blinking(cx);
836                    })
837                }
838
839                self.terminal
840                    .upgrade(cx.app)
841                    .map(|model_handle| {
842                        model_handle.update(cx.app, |term, _| term.try_keystroke(keystroke))
843                    })
844                    .unwrap_or(false)
845            }
846            _ => false,
847        }
848    }
849
850    fn metadata(&self) -> Option<&dyn std::any::Any> {
851        None
852    }
853
854    fn debug(
855        &self,
856        _bounds: gpui::geometry::rect::RectF,
857        _layout: &Self::LayoutState,
858        _paint: &Self::PaintState,
859        _cx: &gpui::DebugContext,
860    ) -> gpui::serde_json::Value {
861        json!({
862            "type": "TerminalElement",
863        })
864    }
865
866    fn rect_for_text_range(
867        &self,
868        _: Range<usize>,
869        bounds: RectF,
870        _: RectF,
871        layout: &Self::LayoutState,
872        _: &Self::PaintState,
873        _: &gpui::MeasurementContext,
874    ) -> Option<RectF> {
875        // Use the same origin that's passed to `Cursor::paint` in the paint
876        // method bove.
877        let mut origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
878
879        // TODO - Why is it necessary to move downward one line to get correct
880        // positioning? I would think that we'd want the same rect that is
881        // painted for the cursor.
882        origin += vec2f(0., layout.size.line_height);
883
884        Some(layout.cursor.as_ref()?.bounding_rect(origin))
885    }
886}
887
888mod test {
889
890    #[test]
891    fn test_mouse_to_selection() {
892        let term_width = 100.;
893        let term_height = 200.;
894        let cell_width = 10.;
895        let line_height = 20.;
896        let mouse_pos_x = 100.; //Window relative
897        let mouse_pos_y = 100.; //Window relative
898        let origin_x = 10.;
899        let origin_y = 20.;
900
901        let cur_size = crate::connected_el::TerminalSize::new(
902            line_height,
903            cell_width,
904            gpui::geometry::vector::vec2f(term_width, term_height),
905        );
906
907        let mouse_pos = gpui::geometry::vector::vec2f(mouse_pos_x, mouse_pos_y);
908        let origin = gpui::geometry::vector::vec2f(origin_x, origin_y); //Position of terminal window, 1 'cell' in
909        let (point, _) =
910            crate::connected_el::TerminalEl::mouse_to_cell_data(mouse_pos, origin, cur_size, 0);
911        assert_eq!(
912            point,
913            alacritty_terminal::index::Point::new(
914                alacritty_terminal::index::Line(((mouse_pos_y - origin_y) / line_height) as i32),
915                alacritty_terminal::index::Column(((mouse_pos_x - origin_x) / cell_width) as usize),
916            )
917        );
918    }
919}