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