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 hyperlink_tooltip = last_hovered_hyperlink.map(|(uri, _, id)| {
601 let mut tooltip = Overlay::new(
602 Empty::new()
603 .contained()
604 .constrained()
605 .with_width(dimensions.width())
606 .with_height(dimensions.height())
607 .with_tooltip::<TerminalElement>(id, uri, None, tooltip_style, cx)
608 .boxed(),
609 )
610 .with_position_mode(gpui::elements::OverlayPositionMode::Local)
611 .boxed();
612
613 tooltip.layout(
614 SizeConstraint::new(Vector2F::zero(), cx.window_size()),
615 view,
616 cx,
617 );
618 tooltip
619 });
620
621 let TerminalContent {
622 cells,
623 mode,
624 display_offset,
625 cursor_char,
626 selection,
627 cursor,
628 last_hovered_hyperlink,
629 ..
630 } = { &terminal_handle.read(cx).last_content };
631
632 // searches, highlights to a single range representations
633 let mut relative_highlighted_ranges = Vec::new();
634 for search_match in search_matches {
635 relative_highlighted_ranges.push((search_match, match_color))
636 }
637 if let Some(selection) = selection {
638 relative_highlighted_ranges.push((selection.start..=selection.end, selection_color));
639 }
640
641 // then have that representation be converted to the appropriate highlight data structure
642
643 let (cells, rects) = TerminalElement::layout_grid(
644 cells,
645 &text_style,
646 &terminal_theme,
647 cx.text_layout_cache(),
648 cx.font_cache(),
649 last_hovered_hyperlink
650 .as_ref()
651 .map(|(_, range, _)| (link_style, range)),
652 );
653
654 //Layout cursor. Rectangle is used for IME, so we should lay it out even
655 //if we don't end up showing it.
656 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
657 None
658 } else {
659 let cursor_point = DisplayCursor::from(cursor.point, *display_offset);
660 let cursor_text = {
661 let str_trxt = cursor_char.to_string();
662
663 let color = if self.focused {
664 terminal_theme.background
665 } else {
666 terminal_theme.foreground
667 };
668
669 cx.text_layout_cache().layout_str(
670 &str_trxt,
671 text_style.font_size,
672 &[(
673 str_trxt.len(),
674 RunStyle {
675 font_id: text_style.font_id,
676 color,
677 underline: Default::default(),
678 },
679 )],
680 )
681 };
682
683 let focused = self.focused;
684 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
685 move |(cursor_position, block_width)| {
686 let (shape, text) = match cursor.shape {
687 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
688 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
689 AlacCursorShape::Underline => (CursorShape::Underscore, None),
690 AlacCursorShape::Beam => (CursorShape::Bar, None),
691 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
692 //This case is handled in the if wrapping the whole cursor layout
693 AlacCursorShape::Hidden => unreachable!(),
694 };
695
696 Cursor::new(
697 cursor_position,
698 block_width,
699 dimensions.line_height,
700 terminal_theme.cursor,
701 shape,
702 text,
703 )
704 },
705 )
706 };
707
708 //Done!
709 (
710 constraint.max,
711 LayoutState {
712 cells,
713 cursor,
714 background_color,
715 size: dimensions,
716 rects,
717 relative_highlighted_ranges,
718 mode: *mode,
719 display_offset: *display_offset,
720 hyperlink_tooltip,
721 },
722 )
723 }
724
725 fn paint(
726 &mut self,
727 scene: &mut SceneBuilder,
728 bounds: RectF,
729 visible_bounds: RectF,
730 layout: &mut Self::LayoutState,
731 view: &mut TerminalView,
732 cx: &mut ViewContext<TerminalView>,
733 ) -> Self::PaintState {
734 let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
735
736 //Setup element stuff
737 let clip_bounds = Some(visible_bounds);
738
739 scene.paint_layer(clip_bounds, |scene| {
740 let origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
741
742 // Elements are ephemeral, only at paint time do we know what could be clicked by a mouse
743 self.attach_mouse_handlers(
744 scene,
745 origin,
746 self.view.id(),
747 visible_bounds,
748 layout.mode,
749 cx,
750 );
751
752 scene.push_cursor_region(gpui::CursorRegion {
753 bounds,
754 style: if layout.hyperlink_tooltip.is_some() {
755 CursorStyle::PointingHand
756 } else {
757 CursorStyle::IBeam
758 },
759 });
760
761 scene.paint_layer(clip_bounds, |scene| {
762 //Start with a background color
763 scene.push_quad(Quad {
764 bounds: RectF::new(bounds.origin(), bounds.size()),
765 background: Some(layout.background_color),
766 border: Default::default(),
767 corner_radius: 0.,
768 });
769
770 for rect in &layout.rects {
771 rect.paint(scene, origin, layout, view, cx)
772 }
773 });
774
775 //Draw Highlighted Backgrounds
776 scene.paint_layer(clip_bounds, |scene| {
777 for (relative_highlighted_range, color) in layout.relative_highlighted_ranges.iter()
778 {
779 if let Some((start_y, highlighted_range_lines)) =
780 to_highlighted_range_lines(relative_highlighted_range, layout, origin)
781 {
782 let hr = HighlightedRange {
783 start_y, //Need to change this
784 line_height: layout.size.line_height,
785 lines: highlighted_range_lines,
786 color: color.clone(),
787 //Copied from editor. TODO: move to theme or something
788 corner_radius: 0.15 * layout.size.line_height,
789 };
790 hr.paint(bounds, scene);
791 }
792 }
793 });
794
795 //Draw the text cells
796 scene.paint_layer(clip_bounds, |scene| {
797 for cell in &layout.cells {
798 cell.paint(scene, origin, layout, visible_bounds, view, cx);
799 }
800 });
801
802 //Draw cursor
803 if self.cursor_visible {
804 if let Some(cursor) = &layout.cursor {
805 scene.paint_layer(clip_bounds, |scene| {
806 cursor.paint(scene, origin, cx);
807 })
808 }
809 }
810
811 if let Some(element) = &mut layout.hyperlink_tooltip {
812 element.paint(scene, origin, visible_bounds, view, cx)
813 }
814 });
815 }
816
817 fn metadata(&self) -> Option<&dyn std::any::Any> {
818 None
819 }
820
821 fn debug(
822 &self,
823 _: RectF,
824 _: &Self::LayoutState,
825 _: &Self::PaintState,
826 _: &TerminalView,
827 _: &gpui::ViewContext<TerminalView>,
828 ) -> gpui::serde_json::Value {
829 json!({
830 "type": "TerminalElement",
831 })
832 }
833
834 fn rect_for_text_range(
835 &self,
836 _: Range<usize>,
837 bounds: RectF,
838 _: RectF,
839 layout: &Self::LayoutState,
840 _: &Self::PaintState,
841 _: &TerminalView,
842 _: &gpui::ViewContext<TerminalView>,
843 ) -> Option<RectF> {
844 // Use the same origin that's passed to `Cursor::paint` in the paint
845 // method bove.
846 let mut origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
847
848 // TODO - Why is it necessary to move downward one line to get correct
849 // positioning? I would think that we'd want the same rect that is
850 // painted for the cursor.
851 origin += vec2f(0., layout.size.line_height);
852
853 Some(layout.cursor.as_ref()?.bounding_rect(origin))
854 }
855}
856
857fn is_blank(cell: &IndexedCell) -> bool {
858 if cell.c != ' ' {
859 return false;
860 }
861
862 if cell.bg != AnsiColor::Named(NamedColor::Background) {
863 return false;
864 }
865
866 if cell.hyperlink().is_some() {
867 return false;
868 }
869
870 if cell
871 .flags
872 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
873 {
874 return false;
875 }
876
877 return true;
878}
879
880fn to_highlighted_range_lines(
881 range: &RangeInclusive<Point>,
882 layout: &LayoutState,
883 origin: Vector2F,
884) -> Option<(f32, Vec<HighlightedRangeLine>)> {
885 // Step 1. Normalize the points to be viewport relative.
886 // When display_offset = 1, here's how the grid is arranged:
887 //-2,0 -2,1...
888 //--- Viewport top
889 //-1,0 -1,1...
890 //--------- Terminal Top
891 // 0,0 0,1...
892 // 1,0 1,1...
893 //--- Viewport Bottom
894 // 2,0 2,1...
895 //--------- Terminal Bottom
896
897 // Normalize to viewport relative, from terminal relative.
898 // lines are i32s, which are negative above the top left corner of the terminal
899 // If the user has scrolled, we use the display_offset to tell us which offset
900 // of the grid data we should be looking at. But for the rendering step, we don't
901 // want negatives. We want things relative to the 'viewport' (the area of the grid
902 // which is currently shown according to the display offset)
903 let unclamped_start = Point::new(
904 range.start().line + layout.display_offset,
905 range.start().column,
906 );
907 let unclamped_end = Point::new(range.end().line + layout.display_offset, range.end().column);
908
909 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
910 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.size.num_lines() as i32 {
911 return None;
912 }
913
914 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
915 let clamped_end_line = unclamped_end.line.0.min(layout.size.num_lines() as i32) as usize;
916 //Convert the start of the range to pixels
917 let start_y = origin.y() + clamped_start_line as f32 * layout.size.line_height;
918
919 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
920 // (also convert to pixels)
921 let mut highlighted_range_lines = Vec::new();
922 for line in clamped_start_line..=clamped_end_line {
923 let mut line_start = 0;
924 let mut line_end = layout.size.columns();
925
926 if line == clamped_start_line {
927 line_start = unclamped_start.column.0 as usize;
928 }
929 if line == clamped_end_line {
930 line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
931 }
932
933 highlighted_range_lines.push(HighlightedRangeLine {
934 start_x: origin.x() + line_start as f32 * layout.size.cell_width,
935 end_x: origin.x() + line_end as f32 * layout.size.cell_width,
936 });
937 }
938
939 Some((start_y, highlighted_range_lines))
940}