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::<Self>(view_id, view_id, 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 .on_scroll(TerminalElement::generic_button_handler(
432 connection,
433 origin,
434 move |terminal, origin, e, _cx| {
435 terminal.scroll_wheel(e, origin);
436 },
437 ));
438
439 // Mouse mode handlers:
440 // All mouse modes need the extra click handlers
441 if mode.intersects(TermMode::MOUSE_MODE) {
442 region = region
443 .on_down(
444 MouseButton::Right,
445 TerminalElement::generic_button_handler(
446 connection,
447 origin,
448 move |terminal, origin, e, _cx| {
449 terminal.mouse_down(&e, origin);
450 },
451 ),
452 )
453 .on_down(
454 MouseButton::Middle,
455 TerminalElement::generic_button_handler(
456 connection,
457 origin,
458 move |terminal, origin, e, _cx| {
459 terminal.mouse_down(&e, origin);
460 },
461 ),
462 )
463 .on_up(
464 MouseButton::Right,
465 TerminalElement::generic_button_handler(
466 connection,
467 origin,
468 move |terminal, origin, e, _cx| {
469 terminal.mouse_up(&e, origin);
470 },
471 ),
472 )
473 .on_up(
474 MouseButton::Middle,
475 TerminalElement::generic_button_handler(
476 connection,
477 origin,
478 move |terminal, origin, e, _cx| {
479 terminal.mouse_up(&e, origin);
480 },
481 ),
482 )
483 }
484 //Mouse move manages both dragging and motion events
485 if mode.intersects(TermMode::MOUSE_DRAG | TermMode::MOUSE_MOTION) {
486 region = region
487 //TODO: This does not fire on right-mouse-down-move events.
488 .on_move(move |event, cx| {
489 if cx.is_parent_view_focused() {
490 if let Some(conn_handle) = connection.upgrade(cx.app) {
491 conn_handle.update(cx.app, |terminal, cx| {
492 terminal.mouse_move(&event, origin);
493 cx.notify();
494 })
495 }
496 }
497 })
498 }
499
500 cx.scene.push_mouse_region(region);
501 }
502
503 ///Configures a text style from the current settings.
504 pub fn make_text_style(font_cache: &FontCache, settings: &Settings) -> TextStyle {
505 // Pull the font family from settings properly overriding
506 let family_id = settings
507 .terminal_overrides
508 .font_family
509 .as_ref()
510 .or(settings.terminal_defaults.font_family.as_ref())
511 .and_then(|family_name| font_cache.load_family(&[family_name]).log_err())
512 .unwrap_or(settings.buffer_font_family);
513
514 let font_size = settings
515 .terminal_overrides
516 .font_size
517 .or(settings.terminal_defaults.font_size)
518 .unwrap_or(settings.buffer_font_size);
519
520 let font_id = font_cache
521 .select_font(family_id, &Default::default())
522 .unwrap();
523
524 TextStyle {
525 color: settings.theme.editor.text_color,
526 font_family_id: family_id,
527 font_family_name: font_cache.family_name(family_id).unwrap(),
528 font_id,
529 font_size,
530 font_properties: Default::default(),
531 underline: Default::default(),
532 }
533 }
534}
535
536impl Element for TerminalElement {
537 type LayoutState = LayoutState;
538 type PaintState = ();
539
540 fn layout(
541 &mut self,
542 constraint: gpui::SizeConstraint,
543 cx: &mut gpui::LayoutContext,
544 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
545 let settings = cx.global::<Settings>();
546 let font_cache = cx.font_cache();
547
548 //Setup layout information
549 let terminal_theme = settings.theme.terminal.clone(); //TODO: Try to minimize this clone.
550 let text_style = TerminalElement::make_text_style(font_cache, settings);
551 let selection_color = settings.theme.editor.selection.selection;
552 let match_color = settings.theme.search.match_background;
553 let dimensions = {
554 let line_height = font_cache.line_height(text_style.font_size);
555 let cell_width = font_cache.em_advance(text_style.font_id, text_style.font_size);
556 TerminalSize::new(line_height, cell_width, constraint.max)
557 };
558
559 let search_matches = if let Some(terminal_model) = self.terminal.upgrade(cx) {
560 terminal_model.read(cx).matches.clone()
561 } else {
562 Default::default()
563 };
564
565 let background_color = if self.modal {
566 terminal_theme.colors.modal_background
567 } else {
568 terminal_theme.colors.background
569 };
570 let terminal_handle = self.terminal.upgrade(cx).unwrap();
571
572 terminal_handle.update(cx.app, |terminal, cx| {
573 terminal.set_size(dimensions);
574 terminal.try_sync(cx)
575 });
576
577 let TerminalContent {
578 cells,
579 mode,
580 display_offset,
581 cursor_char,
582 selection,
583 cursor,
584 ..
585 } = &terminal_handle.read(cx).last_content;
586
587 // searches, highlights to a single range representations
588 let mut relative_highlighted_ranges = Vec::new();
589 for search_match in search_matches {
590 relative_highlighted_ranges.push((search_match, match_color))
591 }
592 if let Some(selection) = selection {
593 relative_highlighted_ranges.push((selection.start..=selection.end, selection_color));
594 }
595
596 // then have that representation be converted to the appropriate highlight data structure
597
598 let (cells, rects) = TerminalElement::layout_grid(
599 cells,
600 &text_style,
601 &terminal_theme,
602 cx.text_layout_cache,
603 cx.font_cache(),
604 self.modal,
605 );
606
607 //Layout cursor. Rectangle is used for IME, so we should lay it out even
608 //if we don't end up showing it.
609 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
610 None
611 } else {
612 let cursor_point = DisplayCursor::from(cursor.point, *display_offset);
613 let cursor_text = {
614 let str_trxt = cursor_char.to_string();
615
616 let color = if self.focused {
617 terminal_theme.colors.background
618 } else {
619 terminal_theme.colors.foreground
620 };
621
622 cx.text_layout_cache.layout_str(
623 &str_trxt,
624 text_style.font_size,
625 &[(
626 str_trxt.len(),
627 RunStyle {
628 font_id: text_style.font_id,
629 color,
630 underline: Default::default(),
631 },
632 )],
633 )
634 };
635
636 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
637 move |(cursor_position, block_width)| {
638 let shape = match cursor.shape {
639 AlacCursorShape::Block if !self.focused => CursorShape::Hollow,
640 AlacCursorShape::Block => CursorShape::Block,
641 AlacCursorShape::Underline => CursorShape::Underscore,
642 AlacCursorShape::Beam => CursorShape::Bar,
643 AlacCursorShape::HollowBlock => CursorShape::Hollow,
644 //This case is handled in the if wrapping the whole cursor layout
645 AlacCursorShape::Hidden => unreachable!(),
646 };
647
648 Cursor::new(
649 cursor_position,
650 block_width,
651 dimensions.line_height,
652 terminal_theme.colors.cursor,
653 shape,
654 Some(cursor_text),
655 )
656 },
657 )
658 };
659
660 //Done!
661 (
662 constraint.max,
663 LayoutState {
664 cells,
665 cursor,
666 background_color,
667 size: dimensions,
668 rects,
669 relative_highlighted_ranges,
670 mode: *mode,
671 display_offset: *display_offset,
672 },
673 )
674 }
675
676 fn paint(
677 &mut self,
678 bounds: gpui::geometry::rect::RectF,
679 visible_bounds: gpui::geometry::rect::RectF,
680 layout: &mut Self::LayoutState,
681 cx: &mut gpui::PaintContext,
682 ) -> Self::PaintState {
683 //Setup element stuff
684 let clip_bounds = Some(visible_bounds);
685
686 cx.paint_layer(clip_bounds, |cx| {
687 let origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
688
689 //Elements are ephemeral, only at paint time do we know what could be clicked by a mouse
690 self.attach_mouse_handlers(origin, self.view.id(), visible_bounds, layout.mode, cx);
691
692 cx.scene.push_cursor_region(gpui::CursorRegion {
693 bounds,
694 style: gpui::CursorStyle::IBeam,
695 });
696
697 cx.paint_layer(clip_bounds, |cx| {
698 //Start with a background color
699 cx.scene.push_quad(Quad {
700 bounds: RectF::new(bounds.origin(), bounds.size()),
701 background: Some(layout.background_color),
702 border: Default::default(),
703 corner_radius: 0.,
704 });
705
706 for rect in &layout.rects {
707 rect.paint(origin, layout, cx)
708 }
709 });
710
711 //Draw Highlighted Backgrounds
712 cx.paint_layer(clip_bounds, |cx| {
713 for (relative_highlighted_range, color) in layout.relative_highlighted_ranges.iter()
714 {
715 if let Some((start_y, highlighted_range_lines)) =
716 to_highlighted_range_lines(relative_highlighted_range, layout, origin)
717 {
718 let hr = HighlightedRange {
719 start_y, //Need to change this
720 line_height: layout.size.line_height,
721 lines: highlighted_range_lines,
722 color: color.clone(),
723 //Copied from editor. TODO: move to theme or something
724 corner_radius: 0.15 * layout.size.line_height,
725 };
726 hr.paint(bounds, cx.scene);
727 }
728 }
729 });
730
731 //Draw the text cells
732 cx.paint_layer(clip_bounds, |cx| {
733 for cell in &layout.cells {
734 cell.paint(origin, layout, visible_bounds, cx);
735 }
736 });
737
738 //Draw cursor
739 if self.cursor_visible {
740 if let Some(cursor) = &layout.cursor {
741 cx.paint_layer(clip_bounds, |cx| {
742 cursor.paint(origin, cx);
743 })
744 }
745 }
746 });
747 }
748
749 fn dispatch_event(
750 &mut self,
751 event: &gpui::Event,
752 _bounds: gpui::geometry::rect::RectF,
753 _visible_bounds: gpui::geometry::rect::RectF,
754 _layout: &mut Self::LayoutState,
755 _paint: &mut Self::PaintState,
756 cx: &mut gpui::EventContext,
757 ) -> bool {
758 if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = event {
759 if !cx.is_parent_view_focused() {
760 return false;
761 }
762
763 if let Some(view) = self.view.upgrade(cx.app) {
764 view.update(cx.app, |view, cx| {
765 view.clear_bel(cx);
766 view.pause_cursor_blinking(cx);
767 })
768 }
769
770 self.terminal
771 .upgrade(cx.app)
772 .map(|model_handle| {
773 model_handle.update(cx.app, |term, cx| {
774 term.try_keystroke(
775 keystroke,
776 cx.global::<Settings>()
777 .terminal_overrides
778 .option_as_meta
779 .unwrap_or(false),
780 )
781 })
782 })
783 .unwrap_or(false)
784 } else {
785 false
786 }
787 }
788
789 fn metadata(&self) -> Option<&dyn std::any::Any> {
790 None
791 }
792
793 fn debug(
794 &self,
795 _bounds: gpui::geometry::rect::RectF,
796 _layout: &Self::LayoutState,
797 _paint: &Self::PaintState,
798 _cx: &gpui::DebugContext,
799 ) -> gpui::serde_json::Value {
800 json!({
801 "type": "TerminalElement",
802 })
803 }
804
805 fn rect_for_text_range(
806 &self,
807 _: Range<usize>,
808 bounds: RectF,
809 _: RectF,
810 layout: &Self::LayoutState,
811 _: &Self::PaintState,
812 _: &gpui::MeasurementContext,
813 ) -> Option<RectF> {
814 // Use the same origin that's passed to `Cursor::paint` in the paint
815 // method bove.
816 let mut origin = bounds.origin() + vec2f(layout.size.cell_width, 0.);
817
818 // TODO - Why is it necessary to move downward one line to get correct
819 // positioning? I would think that we'd want the same rect that is
820 // painted for the cursor.
821 origin += vec2f(0., layout.size.line_height);
822
823 Some(layout.cursor.as_ref()?.bounding_rect(origin))
824 }
825}
826
827fn to_highlighted_range_lines(
828 range: &RangeInclusive<Point>,
829 layout: &LayoutState,
830 origin: Vector2F,
831) -> Option<(f32, Vec<HighlightedRangeLine>)> {
832 // Step 1. Normalize the points to be viewport relative.
833 // When display_offset = 1, here's how the grid is arranged:
834 //-2,0 -2,1...
835 //--- Viewport top
836 //-1,0 -1,1...
837 //--------- Terminal Top
838 // 0,0 0,1...
839 // 1,0 1,1...
840 //--- Viewport Bottom
841 // 2,0 2,1...
842 //--------- Terminal Bottom
843
844 // Normalize to viewport relative, from terminal relative.
845 // lines are i32s, which are negative above the top left corner of the terminal
846 // If the user has scrolled, we use the display_offset to tell us which offset
847 // of the grid data we should be looking at. But for the rendering step, we don't
848 // want negatives. We want things relative to the 'viewport' (the area of the grid
849 // which is currently shown according to the display offset)
850 let unclamped_start = Point::new(
851 range.start().line + layout.display_offset,
852 range.start().column,
853 );
854 let unclamped_end = Point::new(range.end().line + layout.display_offset, range.end().column);
855
856 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
857 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.size.num_lines() as i32 {
858 return None;
859 }
860
861 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
862 let clamped_end_line = unclamped_end.line.0.min(layout.size.num_lines() as i32) as usize;
863 //Convert the start of the range to pixels
864 let start_y = origin.y() + clamped_start_line as f32 * layout.size.line_height;
865
866 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
867 // (also convert to pixels)
868 let mut highlighted_range_lines = Vec::new();
869 for line in clamped_start_line..=clamped_end_line {
870 let mut line_start = 0;
871 let mut line_end = layout.size.columns();
872
873 if line == clamped_start_line {
874 line_start = unclamped_start.column.0 as usize;
875 }
876 if line == clamped_end_line {
877 line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
878 }
879
880 highlighted_range_lines.push(HighlightedRangeLine {
881 start_x: origin.x() + line_start as f32 * layout.size.cell_width,
882 end_x: origin.x() + line_end as f32 * layout.size.cell_width,
883 });
884 }
885
886 Some((start_y, highlighted_range_lines))
887}