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