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