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