1use editor::{Cursor, HighlightedRange, HighlightedRangeLine};
2use gpui::{
3 black, div, point, px, red, relative, transparent_black, AnyElement, AsyncWindowContext,
4 AvailableSpace, Bounds, DispatchPhase, Element, ElementId, FocusHandle, Font, FontStyle,
5 FontWeight, HighlightStyle, Hsla, InteractiveElement, InteractiveElementState, IntoElement,
6 LayoutId, Model, ModelContext, ModifiersChangedEvent, MouseButton, Pixels,
7 PlatformInputHandler, Point, Rgba, ShapedLine, Size, StatefulInteractiveElement, Styled,
8 TextRun, TextStyle, TextSystem, UnderlineStyle, View, WhiteSpace, WindowContext,
9};
10use itertools::Itertools;
11use language::CursorShape;
12use settings::Settings;
13use terminal::{
14 alacritty_terminal::ansi::NamedColor,
15 alacritty_terminal::{
16 ansi::{Color as AnsiColor, Color::Named, CursorShape as AlacCursorShape},
17 grid::Dimensions,
18 index::Point as AlacPoint,
19 term::{cell::Flags, TermMode},
20 },
21 terminal_settings::TerminalSettings,
22 IndexedCell, Terminal, TerminalContent, TerminalSize,
23};
24use theme::{ActiveTheme, Theme, ThemeSettings};
25use ui::Tooltip;
26
27use std::mem;
28use std::{fmt::Debug, ops::RangeInclusive};
29
30use crate::TerminalView;
31
32///The information generated during layout that is necessary for painting
33pub struct LayoutState {
34 cells: Vec<LayoutCell>,
35 rects: Vec<LayoutRect>,
36 relative_highlighted_ranges: Vec<(RangeInclusive<AlacPoint>, Hsla)>,
37 cursor: Option<Cursor>,
38 background_color: Hsla,
39 size: TerminalSize,
40 mode: TermMode,
41 display_offset: usize,
42 hyperlink_tooltip: Option<AnyElement>,
43 gutter: Pixels,
44}
45
46///Helper struct for converting data between alacritty's cursor points, and displayed cursor points
47struct DisplayCursor {
48 line: i32,
49 col: usize,
50}
51
52impl DisplayCursor {
53 fn from(cursor_point: AlacPoint, display_offset: usize) -> Self {
54 Self {
55 line: cursor_point.line.0 + display_offset as i32,
56 col: cursor_point.column.0,
57 }
58 }
59
60 pub fn line(&self) -> i32 {
61 self.line
62 }
63
64 pub fn col(&self) -> usize {
65 self.col
66 }
67}
68
69#[derive(Debug, Default)]
70struct LayoutCell {
71 point: AlacPoint<i32, i32>,
72 text: gpui::ShapedLine,
73}
74
75impl LayoutCell {
76 fn new(point: AlacPoint<i32, i32>, text: gpui::ShapedLine) -> LayoutCell {
77 LayoutCell { point, text }
78 }
79
80 fn paint(
81 &self,
82 origin: Point<Pixels>,
83 layout: &LayoutState,
84 _visible_bounds: Bounds<Pixels>,
85 cx: &mut WindowContext,
86 ) {
87 let pos = {
88 let point = self.point;
89
90 Point::new(
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.paint(pos, layout.size.line_height, cx).ok();
97 }
98}
99
100#[derive(Clone, Debug, Default)]
101struct LayoutRect {
102 point: AlacPoint<i32, i32>,
103 num_of_cells: usize,
104 color: Hsla,
105}
106
107impl LayoutRect {
108 fn new(point: AlacPoint<i32, i32>, num_of_cells: usize, color: Hsla) -> LayoutRect {
109 LayoutRect {
110 point,
111 num_of_cells,
112 color,
113 }
114 }
115
116 fn extend(&self) -> Self {
117 LayoutRect {
118 point: self.point,
119 num_of_cells: self.num_of_cells + 1,
120 color: self.color,
121 }
122 }
123
124 fn paint(&self, origin: Point<Pixels>, layout: &LayoutState, cx: &mut WindowContext) {
125 let position = {
126 let alac_point = self.point;
127 point(
128 (origin.x + alac_point.column as f32 * layout.size.cell_width).floor(),
129 origin.y + alac_point.line as f32 * layout.size.line_height,
130 )
131 };
132 let size = point(
133 (layout.size.cell_width * self.num_of_cells as f32).ceil(),
134 layout.size.line_height,
135 )
136 .into();
137
138 cx.paint_quad(
139 Bounds::new(position, size),
140 Default::default(),
141 self.color,
142 Default::default(),
143 transparent_black(),
144 );
145 }
146}
147
148///The GPUI element that paints the terminal.
149///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?
150pub struct TerminalElement {
151 terminal: Model<Terminal>,
152 terminal_view: View<TerminalView>,
153 focus: FocusHandle,
154 focused: bool,
155 cursor_visible: bool,
156 can_navigate_to_selected_word: bool,
157 interactivity: gpui::Interactivity,
158}
159
160impl InteractiveElement for TerminalElement {
161 fn interactivity(&mut self) -> &mut gpui::Interactivity {
162 &mut self.interactivity
163 }
164}
165
166impl StatefulInteractiveElement for TerminalElement {}
167
168impl TerminalElement {
169 pub fn new(
170 terminal: Model<Terminal>,
171 terminal_view: View<TerminalView>,
172 focus: FocusHandle,
173 focused: bool,
174 cursor_visible: bool,
175 can_navigate_to_selected_word: bool,
176 ) -> TerminalElement {
177 TerminalElement {
178 terminal,
179 terminal_view,
180 focused,
181 focus: focus.clone(),
182 cursor_visible,
183 can_navigate_to_selected_word,
184 interactivity: Default::default(),
185 }
186 .track_focus(&focus)
187 .element
188 }
189
190 //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
191
192 fn layout_grid(
193 grid: &Vec<IndexedCell>,
194 text_style: &TextStyle,
195 // terminal_theme: &TerminalStyle,
196 text_system: &TextSystem,
197 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
198 cx: &WindowContext<'_>,
199 ) -> (Vec<LayoutCell>, Vec<LayoutRect>) {
200 let theme = cx.theme();
201 let mut cells = vec![];
202 let mut rects = vec![];
203
204 let mut cur_rect: Option<LayoutRect> = None;
205 let mut cur_alac_color = None;
206
207 let linegroups = grid.into_iter().group_by(|i| i.point.line);
208 for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
209 for cell in line {
210 let mut fg = cell.fg;
211 let mut bg = cell.bg;
212 if cell.flags.contains(Flags::INVERSE) {
213 mem::swap(&mut fg, &mut bg);
214 }
215
216 //Expand background rect range
217 {
218 if matches!(bg, Named(NamedColor::Background)) {
219 //Continue to next cell, resetting variables if necessary
220 cur_alac_color = None;
221 if let Some(rect) = cur_rect {
222 rects.push(rect);
223 cur_rect = None
224 }
225 } else {
226 match cur_alac_color {
227 Some(cur_color) => {
228 if bg == cur_color {
229 cur_rect = cur_rect.take().map(|rect| rect.extend());
230 } else {
231 cur_alac_color = Some(bg);
232 if cur_rect.is_some() {
233 rects.push(cur_rect.take().unwrap());
234 }
235 cur_rect = Some(LayoutRect::new(
236 AlacPoint::new(
237 line_index as i32,
238 cell.point.column.0 as i32,
239 ),
240 1,
241 convert_color(&bg, theme),
242 ));
243 }
244 }
245 None => {
246 cur_alac_color = Some(bg);
247 cur_rect = Some(LayoutRect::new(
248 AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
249 1,
250 convert_color(&bg, &theme),
251 ));
252 }
253 }
254 }
255 }
256
257 //Layout current cell text
258 {
259 let cell_text = cell.c.to_string();
260 if !is_blank(&cell) {
261 let cell_style = TerminalElement::cell_style(
262 &cell,
263 fg,
264 theme,
265 text_style,
266 text_system,
267 hyperlink,
268 );
269
270 let layout_cell = text_system
271 .shape_line(
272 cell_text.into(),
273 text_style.font_size.to_pixels(cx.rem_size()),
274 &[cell_style],
275 )
276 .unwrap();
277
278 cells.push(LayoutCell::new(
279 AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
280 layout_cell,
281 ))
282 };
283 }
284 }
285
286 if cur_rect.is_some() {
287 rects.push(cur_rect.take().unwrap());
288 }
289 }
290 (cells, rects)
291 }
292
293 // Compute the cursor position and expected block width, may return a zero width if x_for_index returns
294 // the same position for sequential indexes. Use em_width instead
295 fn shape_cursor(
296 cursor_point: DisplayCursor,
297 size: TerminalSize,
298 text_fragment: &ShapedLine,
299 ) -> Option<(Point<Pixels>, Pixels)> {
300 if cursor_point.line() < size.total_lines() as i32 {
301 let cursor_width = if text_fragment.width == Pixels::ZERO {
302 size.cell_width()
303 } else {
304 text_fragment.width
305 };
306
307 //Cursor should always surround as much of the text as possible,
308 //hence when on pixel boundaries round the origin down and the width up
309 Some((
310 point(
311 (cursor_point.col() as f32 * size.cell_width()).floor(),
312 (cursor_point.line() as f32 * size.line_height()).floor(),
313 ),
314 cursor_width.ceil(),
315 ))
316 } else {
317 None
318 }
319 }
320
321 ///Convert the Alacritty cell styles to GPUI text styles and background color
322 fn cell_style(
323 indexed: &IndexedCell,
324 fg: terminal::alacritty_terminal::ansi::Color,
325 // bg: terminal::alacritty_terminal::ansi::Color,
326 colors: &Theme,
327 text_style: &TextStyle,
328 text_system: &TextSystem,
329 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
330 ) -> TextRun {
331 let flags = indexed.cell.flags;
332 let fg = convert_color(&fg, &colors);
333 // let bg = convert_color(&bg, &colors);
334
335 let underline = (flags.intersects(Flags::ALL_UNDERLINES)
336 || indexed.cell.hyperlink().is_some())
337 .then(|| UnderlineStyle {
338 color: Some(fg),
339 thickness: Pixels::from(1.0),
340 wavy: flags.contains(Flags::UNDERCURL),
341 });
342
343 let weight = if flags.intersects(Flags::BOLD | Flags::DIM_BOLD) {
344 FontWeight::BOLD
345 } else {
346 FontWeight::NORMAL
347 };
348
349 let style = if flags.intersects(Flags::ITALIC) {
350 FontStyle::Italic
351 } else {
352 FontStyle::Normal
353 };
354
355 let mut result = TextRun {
356 len: indexed.c.len_utf8() as usize,
357 color: fg,
358 background_color: None,
359 font: Font {
360 weight,
361 style,
362 ..text_style.font()
363 },
364 underline,
365 };
366
367 if let Some((style, range)) = hyperlink {
368 if range.contains(&indexed.point) {
369 if let Some(underline) = style.underline {
370 result.underline = Some(underline);
371 }
372
373 if let Some(color) = style.color {
374 result.color = color;
375 }
376 }
377 }
378
379 result
380 }
381
382 fn compute_layout(&self, bounds: Bounds<gpui::Pixels>, cx: &mut WindowContext) -> LayoutState {
383 let settings = ThemeSettings::get_global(cx).clone();
384
385 let buffer_font_size = settings.buffer_font_size(cx);
386
387 let terminal_settings = TerminalSettings::get_global(cx);
388 let font_family = terminal_settings
389 .font_family
390 .as_ref()
391 .map(|string| string.clone().into())
392 .unwrap_or(settings.buffer_font.family);
393
394 let font_features = terminal_settings
395 .font_features
396 .clone()
397 .unwrap_or(settings.buffer_font.features.clone());
398
399 let line_height = terminal_settings.line_height.value();
400 let font_size = terminal_settings.font_size.clone();
401
402 let font_size =
403 font_size.map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx));
404
405 let settings = ThemeSettings::get_global(cx);
406 let theme = cx.theme().clone();
407
408 let link_style = HighlightStyle {
409 color: Some(gpui::blue()),
410 font_weight: None,
411 font_style: None,
412 background_color: None,
413 underline: Some(UnderlineStyle {
414 thickness: px(1.0),
415 color: Some(gpui::red()),
416 wavy: false,
417 }),
418 fade_out: None,
419 };
420
421 let text_style = TextStyle {
422 font_family,
423 font_features,
424 font_size: font_size.into(),
425 font_style: FontStyle::Normal,
426 line_height: line_height.into(),
427 background_color: None,
428 white_space: WhiteSpace::Normal,
429 // These are going to be overridden per-cell
430 underline: None,
431 color: theme.colors().text,
432 font_weight: FontWeight::NORMAL,
433 };
434
435 let text_system = cx.text_system();
436 let selection_color = theme.players().local();
437 let match_color = theme.colors().search_match_background;
438 let gutter;
439 let dimensions = {
440 let rem_size = cx.rem_size();
441 let font_pixels = text_style.font_size.to_pixels(rem_size);
442 let line_height = font_pixels * line_height.to_pixels(rem_size);
443 let font_id = cx.text_system().font_id(&text_style.font()).unwrap();
444
445 // todo!(do we need to keep this unwrap?)
446 let cell_width = text_system
447 .advance(font_id, font_pixels, 'm')
448 .unwrap()
449 .width;
450 gutter = cell_width;
451
452 let mut size = bounds.size.clone();
453 size.width -= gutter;
454
455 TerminalSize::new(line_height, cell_width, size)
456 };
457
458 let search_matches = self.terminal.read(cx).matches.clone();
459
460 let background_color = theme.colors().background;
461
462 let last_hovered_word = self.terminal.update(cx, |terminal, cx| {
463 terminal.set_size(dimensions);
464 terminal.try_sync(cx);
465 if self.can_navigate_to_selected_word && terminal.can_navigate_to_selected_word() {
466 terminal.last_content.last_hovered_word.clone()
467 } else {
468 None
469 }
470 });
471
472 let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
473 div()
474 .size_full()
475 .id("terminal-element")
476 .tooltip(move |cx| Tooltip::text(hovered_word.word.clone(), cx))
477 });
478
479 let TerminalContent {
480 cells,
481 mode,
482 display_offset,
483 cursor_char,
484 selection,
485 cursor,
486 ..
487 } = &self.terminal.read(cx).last_content;
488
489 // searches, highlights to a single range representations
490 let mut relative_highlighted_ranges = Vec::new();
491 for search_match in search_matches {
492 relative_highlighted_ranges.push((search_match, match_color))
493 }
494 if let Some(selection) = selection {
495 relative_highlighted_ranges
496 .push((selection.start..=selection.end, selection_color.cursor));
497 }
498
499 // then have that representation be converted to the appropriate highlight data structure
500
501 let (cells, rects) = TerminalElement::layout_grid(
502 cells,
503 &text_style,
504 &cx.text_system(),
505 last_hovered_word
506 .as_ref()
507 .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
508 cx,
509 );
510
511 //Layout cursor. Rectangle is used for IME, so we should lay it out even
512 //if we don't end up showing it.
513 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
514 None
515 } else {
516 let cursor_point = DisplayCursor::from(cursor.point, *display_offset);
517 let cursor_text = {
518 let str_trxt = cursor_char.to_string();
519
520 let color = if self.focused {
521 theme.players().local().background
522 } else {
523 theme.players().local().cursor
524 };
525
526 let len = str_trxt.len();
527 cx.text_system()
528 .shape_line(
529 str_trxt.into(),
530 text_style.font_size.to_pixels(cx.rem_size()),
531 &[TextRun {
532 len,
533 font: text_style.font(),
534 color,
535 background_color: None,
536 underline: Default::default(),
537 }],
538 )
539 //todo!(do we need to keep this unwrap?)
540 .unwrap()
541 };
542
543 let focused = self.focused;
544 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
545 move |(cursor_position, block_width)| {
546 let (shape, text) = match cursor.shape {
547 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
548 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
549 AlacCursorShape::Underline => (CursorShape::Underscore, None),
550 AlacCursorShape::Beam => (CursorShape::Bar, None),
551 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
552 //This case is handled in the if wrapping the whole cursor layout
553 AlacCursorShape::Hidden => unreachable!(),
554 };
555
556 Cursor::new(
557 cursor_position,
558 block_width,
559 dimensions.line_height,
560 theme.players().local().cursor,
561 shape,
562 text,
563 )
564 },
565 )
566 };
567
568 //Done!
569 LayoutState {
570 cells,
571 cursor,
572 background_color,
573 size: dimensions,
574 rects,
575 relative_highlighted_ranges,
576 mode: *mode,
577 display_offset: *display_offset,
578 hyperlink_tooltip: None, // todo!(tooltips)
579 gutter,
580 }
581 }
582
583 fn generic_button_handler<E>(
584 connection: Model<Terminal>,
585 origin: Point<Pixels>,
586 focus_handle: FocusHandle,
587 f: impl Fn(&mut Terminal, Point<Pixels>, &E, &mut ModelContext<Terminal>),
588 ) -> impl Fn(&E, &mut WindowContext) {
589 move |event, cx| {
590 cx.focus(&focus_handle);
591 connection.update(cx, |terminal, cx| {
592 f(terminal, origin, event, cx);
593
594 cx.notify();
595 })
596 }
597 }
598
599 fn register_key_listeners(&self, cx: &mut WindowContext) {
600 cx.on_key_event({
601 let this = self.terminal.clone();
602 move |event: &ModifiersChangedEvent, phase, cx| {
603 if phase != DispatchPhase::Bubble {
604 return;
605 }
606
607 let handled =
608 this.update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
609
610 if handled {
611 cx.notify();
612 }
613 }
614 });
615 }
616
617 fn register_mouse_listeners(
618 self,
619 origin: Point<Pixels>,
620 mode: TermMode,
621 bounds: Bounds<Pixels>,
622 cx: &mut WindowContext,
623 ) -> Self {
624 let focus = self.focus.clone();
625 let connection = self.terminal.clone();
626
627 let mut this = self
628 .on_mouse_down(MouseButton::Left, {
629 let connection = connection.clone();
630 let focus = focus.clone();
631 move |e, cx| {
632 cx.focus(&focus);
633 //todo!(context menu)
634 // v.context_menu.update(cx, |menu, _cx| menu.delay_cancel());
635 connection.update(cx, |terminal, cx| {
636 terminal.mouse_down(&e, origin);
637
638 cx.notify();
639 })
640 }
641 })
642 .on_mouse_move({
643 let connection = connection.clone();
644 let focus = focus.clone();
645 move |e, cx| {
646 if e.pressed_button.is_some() {
647 if focus.is_focused(cx) {
648 connection.update(cx, |terminal, cx| {
649 terminal.mouse_drag(e, origin, bounds);
650 cx.notify();
651 })
652 }
653 }
654 }
655 })
656 .on_mouse_up(
657 MouseButton::Left,
658 TerminalElement::generic_button_handler(
659 connection.clone(),
660 origin,
661 focus.clone(),
662 move |terminal, origin, e, cx| {
663 terminal.mouse_up(&e, origin, cx);
664 },
665 ),
666 )
667 .on_click({
668 let connection = connection.clone();
669 move |e, cx| {
670 if e.down.button == MouseButton::Right {
671 let mouse_mode = connection.update(cx, |terminal, _cx| {
672 terminal.mouse_mode(e.down.modifiers.shift)
673 });
674
675 if !mouse_mode {
676 //todo!(context menu)
677 // view.deploy_context_menu(e.position, cx);
678 }
679 }
680 }
681 })
682 .on_mouse_move({
683 let connection = connection.clone();
684 let focus = focus.clone();
685 move |e, cx| {
686 if focus.is_focused(cx) {
687 connection.update(cx, |terminal, cx| {
688 terminal.mouse_move(&e, origin);
689 cx.notify();
690 })
691 }
692 }
693 })
694 .on_scroll_wheel({
695 let connection = connection.clone();
696 move |e, cx| {
697 connection.update(cx, |terminal, cx| {
698 terminal.scroll_wheel(e, origin);
699 cx.notify();
700 })
701 }
702 });
703
704 // Mouse mode handlers:
705 // All mouse modes need the extra click handlers
706 if mode.intersects(TermMode::MOUSE_MODE) {
707 this = this
708 .on_mouse_down(
709 MouseButton::Right,
710 TerminalElement::generic_button_handler(
711 connection.clone(),
712 origin,
713 focus.clone(),
714 move |terminal, origin, e, _cx| {
715 terminal.mouse_down(&e, origin);
716 },
717 ),
718 )
719 .on_mouse_down(
720 MouseButton::Middle,
721 TerminalElement::generic_button_handler(
722 connection.clone(),
723 origin,
724 focus.clone(),
725 move |terminal, origin, e, _cx| {
726 terminal.mouse_down(&e, origin);
727 },
728 ),
729 )
730 .on_mouse_up(
731 MouseButton::Right,
732 TerminalElement::generic_button_handler(
733 connection.clone(),
734 origin,
735 focus.clone(),
736 move |terminal, origin, e, cx| {
737 terminal.mouse_up(&e, origin, cx);
738 },
739 ),
740 )
741 .on_mouse_up(
742 MouseButton::Middle,
743 TerminalElement::generic_button_handler(
744 connection,
745 origin,
746 focus,
747 move |terminal, origin, e, cx| {
748 terminal.mouse_up(&e, origin, cx);
749 },
750 ),
751 )
752 }
753
754 this
755 }
756}
757
758impl Element for TerminalElement {
759 type State = InteractiveElementState;
760
761 fn layout(
762 &mut self,
763 element_state: Option<Self::State>,
764 cx: &mut WindowContext<'_>,
765 ) -> (LayoutId, Self::State) {
766 let (layout_id, interactive_state) =
767 self.interactivity
768 .layout(element_state, cx, |mut style, cx| {
769 style.size.width = relative(1.).into();
770 style.size.height = relative(1.).into();
771 let layout_id = cx.request_layout(&style, None);
772
773 layout_id
774 });
775
776 (layout_id, interactive_state)
777 }
778
779 fn paint(
780 mut self,
781 bounds: Bounds<Pixels>,
782 state: &mut Self::State,
783 cx: &mut WindowContext<'_>,
784 ) {
785 let mut layout = self.compute_layout(bounds, cx);
786
787 let theme = cx.theme();
788
789 let dispatch_context = self.terminal_view.read(cx).dispatch_context(cx);
790 self.interactivity().key_context = Some(dispatch_context);
791 cx.paint_quad(
792 bounds,
793 Default::default(),
794 layout.background_color,
795 Default::default(),
796 Hsla::default(),
797 );
798 let origin = bounds.origin + Point::new(layout.gutter, px(0.));
799
800 let terminal_input_handler = TerminalInputHandler {
801 cx: cx.to_async(),
802 terminal: self.terminal.clone(),
803 cursor_bounds: layout
804 .cursor
805 .as_ref()
806 .map(|cursor| cursor.bounding_rect(origin)),
807 };
808
809 let mut this = self.register_mouse_listeners(origin, layout.mode, bounds, cx);
810
811 let interactivity = mem::take(&mut this.interactivity);
812
813 interactivity.paint(bounds, bounds.size, state, cx, |_, _, cx| {
814 cx.handle_input(&this.focus, terminal_input_handler);
815
816 this.register_key_listeners(cx);
817
818 for rect in &layout.rects {
819 rect.paint(origin, &layout, cx);
820 }
821
822 cx.with_z_index(1, |cx| {
823 for (relative_highlighted_range, color) in layout.relative_highlighted_ranges.iter()
824 {
825 if let Some((start_y, highlighted_range_lines)) =
826 to_highlighted_range_lines(relative_highlighted_range, &layout, origin)
827 {
828 let hr = HighlightedRange {
829 start_y, //Need to change this
830 line_height: layout.size.line_height,
831 lines: highlighted_range_lines,
832 color: color.clone(),
833 //Copied from editor. TODO: move to theme or something
834 corner_radius: 0.15 * layout.size.line_height,
835 };
836 hr.paint(bounds, cx);
837 }
838 }
839 });
840
841 cx.with_z_index(2, |cx| {
842 for cell in &layout.cells {
843 cell.paint(origin, &layout, bounds, cx);
844 }
845 });
846
847 if this.cursor_visible {
848 cx.with_z_index(3, |cx| {
849 if let Some(cursor) = &layout.cursor {
850 cursor.paint(origin, cx);
851 }
852 });
853 }
854
855 if let Some(element) = layout.hyperlink_tooltip.take() {
856 let width: AvailableSpace = bounds.size.width.into();
857 let height: AvailableSpace = bounds.size.height.into();
858 element.draw(origin, Size { width, height }, cx)
859 }
860 });
861 }
862}
863
864impl IntoElement for TerminalElement {
865 type Element = Self;
866
867 fn element_id(&self) -> Option<ElementId> {
868 Some("terminal".into())
869 }
870
871 fn into_element(self) -> Self::Element {
872 self
873 }
874}
875
876struct TerminalInputHandler {
877 cx: AsyncWindowContext,
878 terminal: Model<Terminal>,
879 cursor_bounds: Option<Bounds<Pixels>>,
880}
881
882impl PlatformInputHandler for TerminalInputHandler {
883 fn selected_text_range(&mut self) -> Option<std::ops::Range<usize>> {
884 self.cx
885 .update(|_, cx| {
886 if self
887 .terminal
888 .read(cx)
889 .last_content
890 .mode
891 .contains(TermMode::ALT_SCREEN)
892 {
893 None
894 } else {
895 Some(0..0)
896 }
897 })
898 .ok()
899 .flatten()
900 }
901
902 fn marked_text_range(&mut self) -> Option<std::ops::Range<usize>> {
903 None
904 }
905
906 fn text_for_range(&mut self, range_utf16: std::ops::Range<usize>) -> Option<String> {
907 None
908 }
909
910 fn replace_text_in_range(
911 &mut self,
912 _replacement_range: Option<std::ops::Range<usize>>,
913 text: &str,
914 ) {
915 self.cx
916 .update(|_, cx| {
917 self.terminal.update(cx, |terminal, _| {
918 terminal.input(text.into());
919 })
920 })
921 .ok();
922 }
923
924 fn replace_and_mark_text_in_range(
925 &mut self,
926 _range_utf16: Option<std::ops::Range<usize>>,
927 _new_text: &str,
928 _new_selected_range: Option<std::ops::Range<usize>>,
929 ) {
930 }
931
932 fn unmark_text(&mut self) {}
933
934 fn bounds_for_range(&mut self, _range_utf16: std::ops::Range<usize>) -> Option<Bounds<Pixels>> {
935 self.cursor_bounds
936 }
937}
938
939fn is_blank(cell: &IndexedCell) -> bool {
940 if cell.c != ' ' {
941 return false;
942 }
943
944 if cell.bg != AnsiColor::Named(NamedColor::Background) {
945 return false;
946 }
947
948 if cell.hyperlink().is_some() {
949 return false;
950 }
951
952 if cell
953 .flags
954 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
955 {
956 return false;
957 }
958
959 return true;
960}
961
962fn to_highlighted_range_lines(
963 range: &RangeInclusive<AlacPoint>,
964 layout: &LayoutState,
965 origin: Point<Pixels>,
966) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
967 // Step 1. Normalize the points to be viewport relative.
968 // When display_offset = 1, here's how the grid is arranged:
969 //-2,0 -2,1...
970 //--- Viewport top
971 //-1,0 -1,1...
972 //--------- Terminal Top
973 // 0,0 0,1...
974 // 1,0 1,1...
975 //--- Viewport Bottom
976 // 2,0 2,1...
977 //--------- Terminal Bottom
978
979 // Normalize to viewport relative, from terminal relative.
980 // lines are i32s, which are negative above the top left corner of the terminal
981 // If the user has scrolled, we use the display_offset to tell us which offset
982 // of the grid data we should be looking at. But for the rendering step, we don't
983 // want negatives. We want things relative to the 'viewport' (the area of the grid
984 // which is currently shown according to the display offset)
985 let unclamped_start = AlacPoint::new(
986 range.start().line + layout.display_offset,
987 range.start().column,
988 );
989 let unclamped_end =
990 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
991
992 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
993 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.size.num_lines() as i32 {
994 return None;
995 }
996
997 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
998 let clamped_end_line = unclamped_end.line.0.min(layout.size.num_lines() as i32) as usize;
999 //Convert the start of the range to pixels
1000 let start_y = origin.y + clamped_start_line as f32 * layout.size.line_height;
1001
1002 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1003 // (also convert to pixels)
1004 let mut highlighted_range_lines = Vec::new();
1005 for line in clamped_start_line..=clamped_end_line {
1006 let mut line_start = 0;
1007 let mut line_end = layout.size.columns();
1008
1009 if line == clamped_start_line {
1010 line_start = unclamped_start.column.0 as usize;
1011 }
1012 if line == clamped_end_line {
1013 line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
1014 }
1015
1016 highlighted_range_lines.push(HighlightedRangeLine {
1017 start_x: origin.x + line_start as f32 * layout.size.cell_width,
1018 end_x: origin.x + line_end as f32 * layout.size.cell_width,
1019 });
1020 }
1021
1022 Some((start_y, highlighted_range_lines))
1023}
1024
1025///Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent
1026fn convert_color(fg: &terminal::alacritty_terminal::ansi::Color, theme: &Theme) -> Hsla {
1027 let colors = theme.colors();
1028 match fg {
1029 //Named and theme defined colors
1030 terminal::alacritty_terminal::ansi::Color::Named(n) => match n {
1031 NamedColor::Black => colors.terminal_ansi_black,
1032 NamedColor::Red => colors.terminal_ansi_red,
1033 NamedColor::Green => colors.terminal_ansi_green,
1034 NamedColor::Yellow => colors.terminal_ansi_yellow,
1035 NamedColor::Blue => colors.terminal_ansi_blue,
1036 NamedColor::Magenta => colors.terminal_ansi_magenta,
1037 NamedColor::Cyan => colors.terminal_ansi_cyan,
1038 NamedColor::White => colors.terminal_ansi_white,
1039 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1040 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1041 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1042 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1043 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1044 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1045 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1046 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1047 NamedColor::Foreground => colors.text,
1048 NamedColor::Background => colors.background,
1049 NamedColor::Cursor => theme.players().local().cursor,
1050
1051 // todo!(more colors)
1052 NamedColor::DimBlack => red(),
1053 NamedColor::DimRed => red(),
1054 NamedColor::DimGreen => red(),
1055 NamedColor::DimYellow => red(),
1056 NamedColor::DimBlue => red(),
1057 NamedColor::DimMagenta => red(),
1058 NamedColor::DimCyan => red(),
1059 NamedColor::DimWhite => red(),
1060 NamedColor::BrightForeground => red(),
1061 NamedColor::DimForeground => red(),
1062 },
1063 //'True' colors
1064 terminal::alacritty_terminal::ansi::Color::Spec(rgb) => rgba_color(rgb.r, rgb.g, rgb.b),
1065 //8 bit, indexed colors
1066 terminal::alacritty_terminal::ansi::Color::Indexed(i) => {
1067 get_color_at_index(&(*i as usize), theme)
1068 }
1069 }
1070}
1071
1072///Converts an 8 bit ANSI color to it's GPUI equivalent.
1073///Accepts usize for compatibility with the alacritty::Colors interface,
1074///Other than that use case, should only be called with values in the [0,255] range
1075pub fn get_color_at_index(index: &usize, theme: &Theme) -> Hsla {
1076 let colors = theme.colors();
1077
1078 match index {
1079 //0-15 are the same as the named colors above
1080 0 => colors.terminal_ansi_black,
1081 1 => colors.terminal_ansi_red,
1082 2 => colors.terminal_ansi_green,
1083 3 => colors.terminal_ansi_yellow,
1084 4 => colors.terminal_ansi_blue,
1085 5 => colors.terminal_ansi_magenta,
1086 6 => colors.terminal_ansi_cyan,
1087 7 => colors.terminal_ansi_white,
1088 8 => colors.terminal_ansi_bright_black,
1089 9 => colors.terminal_ansi_bright_red,
1090 10 => colors.terminal_ansi_bright_green,
1091 11 => colors.terminal_ansi_bright_yellow,
1092 12 => colors.terminal_ansi_bright_blue,
1093 13 => colors.terminal_ansi_bright_magenta,
1094 14 => colors.terminal_ansi_bright_cyan,
1095 15 => colors.terminal_ansi_bright_white,
1096 //16-231 are mapped to their RGB colors on a 0-5 range per channel
1097 16..=231 => {
1098 let (r, g, b) = rgb_for_index(&(*index as u8)); //Split the index into it's ANSI-RGB components
1099 let step = (u8::MAX as f32 / 5.).floor() as u8; //Split the RGB range into 5 chunks, with floor so no overflow
1100 rgba_color(r * step, g * step, b * step) //Map the ANSI-RGB components to an RGB color
1101 }
1102 //232-255 are a 24 step grayscale from black to white
1103 232..=255 => {
1104 let i = *index as u8 - 232; //Align index to 0..24
1105 let step = (u8::MAX as f32 / 24.).floor() as u8; //Split the RGB grayscale values into 24 chunks
1106 rgba_color(i * step, i * step, i * step) //Map the ANSI-grayscale components to the RGB-grayscale
1107 }
1108 //For compatibility with the alacritty::Colors interface
1109 256 => colors.text,
1110 257 => colors.background,
1111 258 => theme.players().local().cursor,
1112
1113 // todo!(more colors)
1114 259 => red(), //style.dim_black,
1115 260 => red(), //style.dim_red,
1116 261 => red(), //style.dim_green,
1117 262 => red(), //style.dim_yellow,
1118 263 => red(), //style.dim_blue,
1119 264 => red(), //style.dim_magenta,
1120 265 => red(), //style.dim_cyan,
1121 266 => red(), //style.dim_white,
1122 267 => red(), //style.bright_foreground,
1123 268 => colors.terminal_ansi_black, //'Dim Background', non-standard color
1124
1125 _ => black(),
1126 }
1127}
1128
1129///Generates the rgb channels in [0, 5] for a given index into the 6x6x6 ANSI color cube
1130///See: [8 bit ansi color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1131///
1132///Wikipedia gives a formula for calculating the index for a given color:
1133///
1134///index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1135///
1136///This function does the reverse, calculating the r, g, and b components from a given index.
1137fn rgb_for_index(i: &u8) -> (u8, u8, u8) {
1138 debug_assert!((&16..=&231).contains(&i));
1139 let i = i - 16;
1140 let r = (i - (i % 36)) / 36;
1141 let g = ((i % 36) - (i % 6)) / 6;
1142 let b = (i % 36) % 6;
1143 (r, g, b)
1144}
1145
1146fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1147 Rgba {
1148 r: (r as f32 / 255.) as f32,
1149 g: (g as f32 / 255.) as f32,
1150 b: (b as f32 / 255.) as f32,
1151 a: 1.,
1152 }
1153 .into()
1154}
1155
1156#[cfg(test)]
1157mod tests {
1158 use crate::terminal_element::rgb_for_index;
1159
1160 #[test]
1161 fn test_rgb_for_index() {
1162 //Test every possible value in the color cube
1163 for i in 16..=231 {
1164 let (r, g, b) = rgb_for_index(&(i as u8));
1165 assert_eq!(i, 16 + 36 * r + 6 * g + b);
1166 }
1167 }
1168}