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