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