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