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