1use alacritty_terminal::{
2 ansi::{Color as AnsiColor, Color::Named, 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, TerminalBlink};
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 blink_state: bool,
205}
206
207impl TerminalEl {
208 pub fn new(
209 view: WeakViewHandle<ConnectedView>,
210 terminal: WeakModelHandle<Terminal>,
211 modal: bool,
212 focused: bool,
213 blink_state: bool,
214 ) -> TerminalEl {
215 TerminalEl {
216 view,
217 terminal,
218 modal,
219 focused,
220 blink_state,
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 pub fn should_show_cursor(
576 settings: Option<TerminalBlink>,
577 blinking_on: bool,
578 focused: bool,
579 blink_show: bool,
580 ) -> bool {
581 if !focused {
582 true
583 } else {
584 match settings {
585 Some(setting) => match setting {
586 TerminalBlink::Never => true,
587 TerminalBlink::On | TerminalBlink::Off if blinking_on => blink_show,
588 TerminalBlink::On | TerminalBlink::Off /*if !blinking_on */ => true,
589 TerminalBlink::Always => focused && blink_show,
590 },
591 None => {
592 if blinking_on {
593 blink_show
594 } else {
595 false
596 }
597 }
598 }
599 }
600 }
601}
602
603impl Element for TerminalEl {
604 type LayoutState = LayoutState;
605 type PaintState = ();
606
607 fn layout(
608 &mut self,
609 constraint: gpui::SizeConstraint,
610 cx: &mut gpui::LayoutContext,
611 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
612 let settings = cx.global::<Settings>();
613 let blink_settings = settings.terminal_overrides.blinking.clone();
614 let font_cache = cx.font_cache();
615
616 //Setup layout information
617 let terminal_theme = settings.theme.terminal.clone(); //TODO: Try to minimize this clone.
618 let text_style = TerminalEl::make_text_style(font_cache, settings);
619 let selection_color = settings.theme.editor.selection.selection;
620 let dimensions = {
621 let line_height = font_cache.line_height(text_style.font_size);
622 let cell_width = font_cache.em_advance(text_style.font_id, text_style.font_size);
623 TerminalSize::new(line_height, cell_width, constraint.max)
624 };
625
626 let background_color = if self.modal {
627 terminal_theme.colors.modal_background
628 } else {
629 terminal_theme.colors.background
630 };
631
632 let (cells, selection, cursor, display_offset, cursor_text, blink_mode) = self
633 .terminal
634 .upgrade(cx)
635 .unwrap()
636 .update(cx.app, |terminal, mcx| {
637 terminal.set_size(dimensions);
638 terminal.render_lock(mcx, |content, cursor_text, blink_mode| {
639 let mut cells = vec![];
640 cells.extend(
641 content
642 .display_iter
643 //TODO: Add this once there's a way to retain empty lines
644 // .filter(|ic| {
645 // !ic.flags.contains(Flags::HIDDEN)
646 // && !(ic.bg == Named(NamedColor::Background)
647 // && ic.c == ' '
648 // && !ic.flags.contains(Flags::INVERSE))
649 // })
650 .map(|ic| IndexedCell {
651 point: ic.point,
652 cell: ic.cell.clone(),
653 }),
654 );
655
656 (
657 cells,
658 content.selection,
659 content.cursor,
660 content.display_offset,
661 cursor_text,
662 blink_mode,
663 )
664 })
665 });
666
667 let (cells, rects, highlights) = TerminalEl::layout_grid(
668 cells,
669 &text_style,
670 &terminal_theme,
671 cx.text_layout_cache,
672 cx.font_cache(),
673 self.modal,
674 selection,
675 );
676
677 //Layout cursor
678 let cursor = {
679 if !TerminalEl::should_show_cursor(
680 blink_settings,
681 blink_mode,
682 self.focused,
683 self.blink_state,
684 ) {
685 None
686 } else {
687 let cursor_point = DisplayCursor::from(cursor.point, display_offset);
688 let cursor_text = {
689 let str_trxt = cursor_text.to_string();
690
691 let color = if self.focused {
692 terminal_theme.colors.background
693 } else {
694 terminal_theme.colors.foreground
695 };
696
697 cx.text_layout_cache.layout_str(
698 &str_trxt,
699 text_style.font_size,
700 &[(
701 str_trxt.len(),
702 RunStyle {
703 font_id: text_style.font_id,
704 color,
705 underline: Default::default(),
706 },
707 )],
708 )
709 };
710
711 TerminalEl::shape_cursor(cursor_point, dimensions, &cursor_text).map(
712 move |(cursor_position, block_width)| {
713 let (shape, color) = if self.focused {
714 (CursorShape::Block, terminal_theme.colors.cursor)
715 } else {
716 (CursorShape::Hollow, terminal_theme.colors.foreground)
717 };
718
719 Cursor::new(
720 cursor_position,
721 block_width,
722 dimensions.line_height,
723 color,
724 shape,
725 Some(cursor_text),
726 )
727 },
728 )
729 }
730 };
731
732 //Done!
733 (
734 constraint.max,
735 LayoutState {
736 cells,
737 cursor,
738 background_color,
739 selection_color,
740 size: dimensions,
741 rects,
742 highlights,
743 display_offset,
744 },
745 )
746 }
747
748 fn paint(
749 &mut self,
750 bounds: gpui::geometry::rect::RectF,
751 visible_bounds: gpui::geometry::rect::RectF,
752 layout: &mut Self::LayoutState,
753 cx: &mut gpui::PaintContext,
754 ) -> Self::PaintState {
755 //Setup element stuff
756 let clip_bounds = Some(visible_bounds);
757
758 cx.paint_layer(clip_bounds, |cx| {
759 let origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
760
761 //Elements are ephemeral, only at paint time do we know what could be clicked by a mouse
762 self.attach_mouse_handlers(
763 origin,
764 self.view.id(),
765 visible_bounds,
766 layout.size,
767 layout.display_offset,
768 cx,
769 );
770
771 cx.paint_layer(clip_bounds, |cx| {
772 //Start with a background color
773 cx.scene.push_quad(Quad {
774 bounds: RectF::new(bounds.origin(), bounds.size()),
775 background: Some(layout.background_color),
776 border: Default::default(),
777 corner_radius: 0.,
778 });
779
780 for rect in &layout.rects {
781 rect.paint(origin, layout, cx)
782 }
783 });
784
785 //Draw Selection
786 cx.paint_layer(clip_bounds, |cx| {
787 let start_y = layout.highlights.get(0).map(|highlight| {
788 origin.y() + highlight.line_index as f32 * layout.size.line_height
789 });
790
791 if let Some(y) = start_y {
792 let range_lines = layout
793 .highlights
794 .iter()
795 .map(|relative_highlight| {
796 relative_highlight.to_highlighted_range_line(origin, layout)
797 })
798 .collect::<Vec<HighlightedRangeLine>>();
799
800 let hr = HighlightedRange {
801 start_y: y, //Need to change this
802 line_height: layout.size.line_height,
803 lines: range_lines,
804 color: layout.selection_color,
805 //Copied from editor. TODO: move to theme or something
806 corner_radius: 0.15 * layout.size.line_height,
807 };
808 hr.paint(bounds, cx.scene);
809 }
810 });
811
812 //Draw the text cells
813 cx.paint_layer(clip_bounds, |cx| {
814 for cell in &layout.cells {
815 cell.paint(origin, layout, visible_bounds, cx);
816 }
817 });
818
819 //Draw cursor
820 if let Some(cursor) = &layout.cursor {
821 cx.paint_layer(clip_bounds, |cx| {
822 cursor.paint(origin, cx);
823 })
824 }
825 });
826 }
827
828 fn dispatch_event(
829 &mut self,
830 event: &gpui::Event,
831 _bounds: gpui::geometry::rect::RectF,
832 visible_bounds: gpui::geometry::rect::RectF,
833 layout: &mut Self::LayoutState,
834 _paint: &mut Self::PaintState,
835 cx: &mut gpui::EventContext,
836 ) -> bool {
837 match event {
838 Event::ScrollWheel(ScrollWheelEvent {
839 delta, position, ..
840 }) => visible_bounds
841 .contains_point(*position)
842 .then(|| {
843 let vertical_scroll =
844 (delta.y() / layout.size.line_height) * ALACRITTY_SCROLL_MULTIPLIER;
845
846 if let Some(terminal) = self.terminal.upgrade(cx.app) {
847 terminal.update(cx.app, |term, _| {
848 term.scroll(Scroll::Delta(vertical_scroll.round() as i32))
849 });
850 }
851
852 cx.notify();
853 })
854 .is_some(),
855 Event::KeyDown(KeyDownEvent { keystroke, .. }) => {
856 if !cx.is_parent_view_focused() {
857 return false;
858 }
859
860 //TODO Talk to keith about how to catch events emitted from an element.
861 if let Some(view) = self.view.upgrade(cx.app) {
862 view.update(cx.app, |view, cx| {
863 view.clear_bel(cx);
864 view.pause_cursor_blinking(cx);
865 })
866 }
867
868 self.terminal
869 .upgrade(cx.app)
870 .map(|model_handle| {
871 model_handle.update(cx.app, |term, _| term.try_keystroke(keystroke))
872 })
873 .unwrap_or(false)
874 }
875 _ => false,
876 }
877 }
878
879 fn metadata(&self) -> Option<&dyn std::any::Any> {
880 None
881 }
882
883 fn debug(
884 &self,
885 _bounds: gpui::geometry::rect::RectF,
886 _layout: &Self::LayoutState,
887 _paint: &Self::PaintState,
888 _cx: &gpui::DebugContext,
889 ) -> gpui::serde_json::Value {
890 json!({
891 "type": "TerminalElement",
892 })
893 }
894
895 fn rect_for_text_range(
896 &self,
897 _: Range<usize>,
898 bounds: RectF,
899 _: RectF,
900 layout: &Self::LayoutState,
901 _: &Self::PaintState,
902 _: &gpui::MeasurementContext,
903 ) -> Option<RectF> {
904 // Use the same origin that's passed to `Cursor::paint` in the paint
905 // method bove.
906 let mut origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
907
908 // TODO - Why is it necessary to move downward one line to get correct
909 // positioning? I would think that we'd want the same rect that is
910 // painted for the cursor.
911 origin += vec2f(0., layout.size.line_height);
912
913 Some(layout.cursor.as_ref()?.bounding_rect(origin))
914 }
915}
916
917mod test {
918
919 #[test]
920 fn test_mouse_to_selection() {
921 let term_width = 100.;
922 let term_height = 200.;
923 let cell_width = 10.;
924 let line_height = 20.;
925 let mouse_pos_x = 100.; //Window relative
926 let mouse_pos_y = 100.; //Window relative
927 let origin_x = 10.;
928 let origin_y = 20.;
929
930 let cur_size = crate::connected_el::TerminalSize::new(
931 line_height,
932 cell_width,
933 gpui::geometry::vector::vec2f(term_width, term_height),
934 );
935
936 let mouse_pos = gpui::geometry::vector::vec2f(mouse_pos_x, mouse_pos_y);
937 let origin = gpui::geometry::vector::vec2f(origin_x, origin_y); //Position of terminal window, 1 'cell' in
938 let (point, _) =
939 crate::connected_el::TerminalEl::mouse_to_cell_data(mouse_pos, origin, cur_size, 0);
940 assert_eq!(
941 point,
942 alacritty_terminal::index::Point::new(
943 alacritty_terminal::index::Line(((mouse_pos_y - origin_y) / line_height) as i32),
944 alacritty_terminal::index::Column(((mouse_pos_x - origin_x) / cell_width) as usize),
945 )
946 );
947 }
948}