1use editor::{Cursor, HighlightedRange, HighlightedRangeLine};
2use gpui::{
3 div, fill, point, px, red, relative, AnyElement, AsyncWindowContext, AvailableSpace,
4 BorrowWindow, Bounds, DispatchPhase, Element, ElementId, FocusHandle, Font, FontStyle,
5 FontWeight, HighlightStyle, Hsla, InteractiveBounds, InteractiveElement,
6 InteractiveElementState, Interactivity, IntoElement, LayoutId, Model, ModelContext,
7 ModifiersChangedEvent, MouseButton, MouseMoveEvent, Pixels, PlatformInputHandler, Point,
8 ShapedLine, StatefulInteractiveElement, Styled, TextRun, TextStyle, TextSystem, UnderlineStyle,
9 WhiteSpace, 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::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 dimensions: 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.dimensions.cell_width).floor(),
91 origin.y + point.line as f32 * layout.dimensions.line_height,
92 )
93 };
94
95 self.text.paint(pos, layout.dimensions.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.dimensions.cell_width).floor(),
128 origin.y + alac_point.line as f32 * layout.dimensions.line_height,
129 )
130 };
131 let size = point(
132 (layout.dimensions.cell_width * self.num_of_cells as f32).ceil(),
133 layout.dimensions.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 =
252 TerminalElement::cell_style(&cell, fg, theme, text_style, hyperlink);
253
254 let layout_cell = text_system
255 .shape_line(
256 cell_text.into(),
257 text_style.font_size.to_pixels(cx.rem_size()),
258 &[cell_style],
259 )
260 .unwrap();
261
262 cells.push(LayoutCell::new(
263 AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
264 layout_cell,
265 ))
266 };
267 }
268 }
269
270 if cur_rect.is_some() {
271 rects.push(cur_rect.take().unwrap());
272 }
273 }
274 (cells, rects)
275 }
276
277 // Compute the cursor position and expected block width, may return a zero width if x_for_index returns
278 // the same position for sequential indexes. Use em_width instead
279 fn shape_cursor(
280 cursor_point: DisplayCursor,
281 size: TerminalSize,
282 text_fragment: &ShapedLine,
283 ) -> Option<(Point<Pixels>, Pixels)> {
284 if cursor_point.line() < size.total_lines() as i32 {
285 let cursor_width = if text_fragment.width == Pixels::ZERO {
286 size.cell_width()
287 } else {
288 text_fragment.width
289 };
290
291 // Cursor should always surround as much of the text as possible,
292 // hence when on pixel boundaries round the origin down and the width up
293 Some((
294 point(
295 (cursor_point.col() as f32 * size.cell_width()).floor(),
296 (cursor_point.line() as f32 * size.line_height()).floor(),
297 ),
298 cursor_width.ceil(),
299 ))
300 } else {
301 None
302 }
303 }
304
305 /// Convert the Alacritty cell styles to GPUI text styles and background color
306 fn cell_style(
307 indexed: &IndexedCell,
308 fg: terminal::alacritty_terminal::ansi::Color,
309 // bg: terminal::alacritty_terminal::ansi::Color,
310 colors: &Theme,
311 text_style: &TextStyle,
312 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
313 ) -> TextRun {
314 let flags = indexed.cell.flags;
315 let fg = convert_color(&fg, &colors);
316 // let bg = convert_color(&bg, &colors);
317
318 let underline = (flags.intersects(Flags::ALL_UNDERLINES)
319 || indexed.cell.hyperlink().is_some())
320 .then(|| UnderlineStyle {
321 color: Some(fg),
322 thickness: Pixels::from(1.0),
323 wavy: flags.contains(Flags::UNDERCURL),
324 });
325
326 let weight = if flags.intersects(Flags::BOLD | Flags::DIM_BOLD) {
327 FontWeight::BOLD
328 } else {
329 FontWeight::NORMAL
330 };
331
332 let style = if flags.intersects(Flags::ITALIC) {
333 FontStyle::Italic
334 } else {
335 FontStyle::Normal
336 };
337
338 let mut result = TextRun {
339 len: indexed.c.len_utf8() as usize,
340 color: fg,
341 background_color: None,
342 font: Font {
343 weight,
344 style,
345 ..text_style.font()
346 },
347 underline,
348 };
349
350 if let Some((style, range)) = hyperlink {
351 if range.contains(&indexed.point) {
352 if let Some(underline) = style.underline {
353 result.underline = Some(underline);
354 }
355
356 if let Some(color) = style.color {
357 result.color = color;
358 }
359 }
360 }
361
362 result
363 }
364
365 fn compute_layout(&self, bounds: Bounds<gpui::Pixels>, cx: &mut WindowContext) -> LayoutState {
366 let settings = ThemeSettings::get_global(cx).clone();
367
368 let buffer_font_size = settings.buffer_font_size(cx);
369
370 let terminal_settings = TerminalSettings::get_global(cx);
371 let font_family = terminal_settings
372 .font_family
373 .as_ref()
374 .map(|string| string.clone().into())
375 .unwrap_or(settings.buffer_font.family);
376
377 let font_features = terminal_settings
378 .font_features
379 .clone()
380 .unwrap_or(settings.buffer_font.features.clone());
381
382 let line_height = terminal_settings.line_height.value();
383 let font_size = terminal_settings.font_size.clone();
384
385 let font_size =
386 font_size.map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx));
387
388 let theme = cx.theme().clone();
389
390 let link_style = HighlightStyle {
391 color: Some(theme.colors().link_text_hover),
392 font_weight: None,
393 font_style: None,
394 background_color: None,
395 underline: Some(UnderlineStyle {
396 thickness: px(1.0),
397 color: Some(theme.colors().link_text_hover),
398 wavy: false,
399 }),
400 fade_out: None,
401 };
402
403 let text_style = TextStyle {
404 font_family,
405 font_features,
406 font_size: font_size.into(),
407 font_style: FontStyle::Normal,
408 line_height: line_height.into(),
409 background_color: None,
410 white_space: WhiteSpace::Normal,
411 // These are going to be overridden per-cell
412 underline: None,
413 color: theme.colors().text,
414 font_weight: FontWeight::NORMAL,
415 };
416
417 let text_system = cx.text_system();
418 let selection_color = theme.players().local();
419 let match_color = theme.colors().search_match_background;
420 let gutter;
421 let dimensions = {
422 let rem_size = cx.rem_size();
423 let font_pixels = text_style.font_size.to_pixels(rem_size);
424 let line_height = font_pixels * line_height.to_pixels(rem_size);
425 let font_id = cx.text_system().resolve_font(&text_style.font());
426
427 // todo!(do we need to keep this unwrap?)
428 let cell_width = text_system
429 .advance(font_id, font_pixels, 'm')
430 .unwrap()
431 .width;
432 gutter = cell_width;
433
434 let mut size = bounds.size.clone();
435 size.width -= gutter;
436
437 TerminalSize::new(line_height, cell_width, size)
438 };
439
440 let search_matches = self.terminal.read(cx).matches.clone();
441
442 let background_color = theme.colors().terminal_background;
443
444 let last_hovered_word = self.terminal.update(cx, |terminal, cx| {
445 terminal.set_size(dimensions);
446 terminal.try_sync(cx);
447 if self.can_navigate_to_selected_word && terminal.can_navigate_to_selected_word() {
448 terminal.last_content.last_hovered_word.clone()
449 } else {
450 None
451 }
452 });
453
454 let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
455 div()
456 .size_full()
457 .id("terminal-element")
458 .tooltip(move |cx| Tooltip::text(hovered_word.word.clone(), cx))
459 .into_any_element()
460 });
461
462 let TerminalContent {
463 cells,
464 mode,
465 display_offset,
466 cursor_char,
467 selection,
468 cursor,
469 ..
470 } = &self.terminal.read(cx).last_content;
471
472 // searches, highlights to a single range representations
473 let mut relative_highlighted_ranges = Vec::new();
474 for search_match in search_matches {
475 relative_highlighted_ranges.push((search_match, match_color))
476 }
477 if let Some(selection) = selection {
478 relative_highlighted_ranges
479 .push((selection.start..=selection.end, selection_color.cursor));
480 }
481
482 // then have that representation be converted to the appropriate highlight data structure
483
484 let (cells, rects) = TerminalElement::layout_grid(
485 cells,
486 &text_style,
487 &cx.text_system(),
488 last_hovered_word
489 .as_ref()
490 .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
491 cx,
492 );
493
494 //Layout cursor. Rectangle is used for IME, so we should lay it out even
495 //if we don't end up showing it.
496 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
497 None
498 } else {
499 let cursor_point = DisplayCursor::from(cursor.point, *display_offset);
500 let cursor_text = {
501 let str_trxt = cursor_char.to_string();
502 let len = str_trxt.len();
503 cx.text_system()
504 .shape_line(
505 str_trxt.into(),
506 text_style.font_size.to_pixels(cx.rem_size()),
507 &[TextRun {
508 len,
509 font: text_style.font(),
510 color: theme.colors().terminal_background,
511 background_color: None,
512 underline: Default::default(),
513 }],
514 )
515 //todo!(do we need to keep this unwrap?)
516 .unwrap()
517 };
518
519 let focused = self.focused;
520 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
521 move |(cursor_position, block_width)| {
522 let (shape, text) = match cursor.shape {
523 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
524 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
525 AlacCursorShape::Underline => (CursorShape::Underscore, None),
526 AlacCursorShape::Beam => (CursorShape::Bar, None),
527 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
528 //This case is handled in the if wrapping the whole cursor layout
529 AlacCursorShape::Hidden => unreachable!(),
530 };
531
532 Cursor::new(
533 cursor_position,
534 block_width,
535 dimensions.line_height,
536 theme.players().local().cursor,
537 shape,
538 text,
539 )
540 },
541 )
542 };
543
544 //Done!
545 LayoutState {
546 cells,
547 cursor,
548 background_color,
549 dimensions,
550 rects,
551 relative_highlighted_ranges,
552 mode: *mode,
553 display_offset: *display_offset,
554 hyperlink_tooltip,
555 gutter,
556 }
557 }
558
559 fn generic_button_handler<E>(
560 connection: Model<Terminal>,
561 origin: Point<Pixels>,
562 focus_handle: FocusHandle,
563 f: impl Fn(&mut Terminal, Point<Pixels>, &E, &mut ModelContext<Terminal>),
564 ) -> impl Fn(&E, &mut WindowContext) {
565 move |event, cx| {
566 cx.focus(&focus_handle);
567 connection.update(cx, |terminal, cx| {
568 f(terminal, origin, event, cx);
569
570 cx.notify();
571 })
572 }
573 }
574
575 fn register_key_listeners(&self, cx: &mut WindowContext) {
576 cx.on_key_event({
577 let this = self.terminal.clone();
578 move |event: &ModifiersChangedEvent, phase, cx| {
579 if phase != DispatchPhase::Bubble {
580 return;
581 }
582
583 let handled =
584 this.update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
585
586 if handled {
587 cx.notify();
588 }
589 }
590 });
591 }
592
593 fn register_mouse_listeners(
594 &mut self,
595 origin: Point<Pixels>,
596 mode: TermMode,
597 bounds: Bounds<Pixels>,
598 cx: &mut WindowContext,
599 ) {
600 let focus = self.focus.clone();
601 let terminal = self.terminal.clone();
602 let interactive_bounds = InteractiveBounds {
603 bounds: bounds.intersect(&cx.content_mask().bounds),
604 stacking_order: cx.stacking_order().clone(),
605 };
606
607 self.interactivity.on_mouse_down(MouseButton::Left, {
608 let terminal = terminal.clone();
609 let focus = focus.clone();
610 move |e, cx| {
611 cx.focus(&focus);
612 terminal.update(cx, |terminal, cx| {
613 terminal.mouse_down(&e, origin);
614 cx.notify();
615 })
616 }
617 });
618
619 cx.on_mouse_event({
620 let bounds = bounds.clone();
621 let focus = self.focus.clone();
622 let terminal = self.terminal.clone();
623 move |e: &MouseMoveEvent, phase, cx| {
624 if phase != DispatchPhase::Bubble || !focus.is_focused(cx) {
625 return;
626 }
627
628 if e.pressed_button.is_some() && !cx.has_active_drag() {
629 terminal.update(cx, |terminal, cx| {
630 terminal.mouse_drag(e, origin, bounds);
631 cx.notify();
632 })
633 }
634
635 if interactive_bounds.visibly_contains(&e.position, cx) {
636 terminal.update(cx, |terminal, cx| {
637 terminal.mouse_move(&e, origin);
638 cx.notify();
639 })
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 self.interactivity.on_scroll_wheel({
671 let terminal = terminal.clone();
672 move |e, cx| {
673 terminal.update(cx, |terminal, cx| {
674 terminal.scroll_wheel(e, origin);
675 cx.notify();
676 })
677 }
678 });
679
680 // Mouse mode handlers:
681 // All mouse modes need the extra click handlers
682 if mode.intersects(TermMode::MOUSE_MODE) {
683 self.interactivity.on_mouse_down(
684 MouseButton::Right,
685 TerminalElement::generic_button_handler(
686 terminal.clone(),
687 origin,
688 focus.clone(),
689 move |terminal, origin, e, _cx| {
690 terminal.mouse_down(&e, origin);
691 },
692 ),
693 );
694 self.interactivity.on_mouse_down(
695 MouseButton::Middle,
696 TerminalElement::generic_button_handler(
697 terminal.clone(),
698 origin,
699 focus.clone(),
700 move |terminal, origin, e, _cx| {
701 terminal.mouse_down(&e, origin);
702 },
703 ),
704 );
705 self.interactivity.on_mouse_up(
706 MouseButton::Right,
707 TerminalElement::generic_button_handler(
708 terminal.clone(),
709 origin,
710 focus.clone(),
711 move |terminal, origin, e, cx| {
712 terminal.mouse_up(&e, origin, cx);
713 },
714 ),
715 );
716 self.interactivity.on_mouse_up(
717 MouseButton::Middle,
718 TerminalElement::generic_button_handler(
719 terminal,
720 origin,
721 focus,
722 move |terminal, origin, e, cx| {
723 terminal.mouse_up(&e, origin, cx);
724 },
725 ),
726 );
727 }
728 }
729}
730
731impl Element for TerminalElement {
732 type State = InteractiveElementState;
733
734 fn request_layout(
735 &mut self,
736 element_state: Option<Self::State>,
737 cx: &mut WindowContext<'_>,
738 ) -> (LayoutId, Self::State) {
739 let (layout_id, interactive_state) =
740 self.interactivity
741 .layout(element_state, cx, |mut style, cx| {
742 style.size.width = relative(1.).into();
743 style.size.height = relative(1.).into();
744 let layout_id = cx.request_layout(&style, None);
745
746 layout_id
747 });
748
749 (layout_id, interactive_state)
750 }
751
752 fn paint(
753 &mut self,
754 bounds: Bounds<Pixels>,
755 state: &mut Self::State,
756 cx: &mut WindowContext<'_>,
757 ) {
758 let mut layout = self.compute_layout(bounds, cx);
759
760 cx.paint_quad(fill(bounds, layout.background_color));
761 let origin = bounds.origin + Point::new(layout.gutter, px(0.));
762
763 let terminal_input_handler = TerminalInputHandler {
764 cx: cx.to_async(),
765 terminal: self.terminal.clone(),
766 cursor_bounds: layout
767 .cursor
768 .as_ref()
769 .map(|cursor| cursor.bounding_rect(origin)),
770 };
771
772 self.register_mouse_listeners(origin, layout.mode, bounds, cx);
773
774 let mut interactivity = mem::take(&mut self.interactivity);
775 interactivity.paint(bounds, bounds.size, state, cx, |_, _, cx| {
776 cx.handle_input(&self.focus, terminal_input_handler);
777
778 self.register_key_listeners(cx);
779
780 for rect in &layout.rects {
781 rect.paint(origin, &layout, cx);
782 }
783
784 cx.with_z_index(1, |cx| {
785 for (relative_highlighted_range, color) in layout.relative_highlighted_ranges.iter()
786 {
787 if let Some((start_y, highlighted_range_lines)) =
788 to_highlighted_range_lines(relative_highlighted_range, &layout, origin)
789 {
790 let hr = HighlightedRange {
791 start_y, //Need to change this
792 line_height: layout.dimensions.line_height,
793 lines: highlighted_range_lines,
794 color: color.clone(),
795 //Copied from editor. TODO: move to theme or something
796 corner_radius: 0.15 * layout.dimensions.line_height,
797 };
798 hr.paint(bounds, cx);
799 }
800 }
801 });
802
803 cx.with_z_index(2, |cx| {
804 for cell in &layout.cells {
805 cell.paint(origin, &layout, bounds, cx);
806 }
807 });
808
809 if self.cursor_visible {
810 cx.with_z_index(3, |cx| {
811 if let Some(cursor) = &layout.cursor {
812 cursor.paint(origin, cx);
813 }
814 });
815 }
816
817 if let Some(mut element) = layout.hyperlink_tooltip.take() {
818 element.draw(origin, bounds.size.map(AvailableSpace::Definite), cx)
819 }
820 });
821 }
822}
823
824impl IntoElement for TerminalElement {
825 type Element = Self;
826
827 fn element_id(&self) -> Option<ElementId> {
828 Some("terminal".into())
829 }
830
831 fn into_element(self) -> Self::Element {
832 self
833 }
834}
835
836struct TerminalInputHandler {
837 cx: AsyncWindowContext,
838 terminal: Model<Terminal>,
839 cursor_bounds: Option<Bounds<Pixels>>,
840}
841
842impl PlatformInputHandler for TerminalInputHandler {
843 fn selected_text_range(&mut self) -> Option<std::ops::Range<usize>> {
844 self.cx
845 .update(|_, cx| {
846 if self
847 .terminal
848 .read(cx)
849 .last_content
850 .mode
851 .contains(TermMode::ALT_SCREEN)
852 {
853 None
854 } else {
855 Some(0..0)
856 }
857 })
858 .ok()
859 .flatten()
860 }
861
862 fn marked_text_range(&mut self) -> Option<std::ops::Range<usize>> {
863 None
864 }
865
866 fn text_for_range(&mut self, _: std::ops::Range<usize>) -> Option<String> {
867 None
868 }
869
870 fn replace_text_in_range(
871 &mut self,
872 _replacement_range: Option<std::ops::Range<usize>>,
873 text: &str,
874 ) {
875 self.cx
876 .update(|_, cx| {
877 self.terminal.update(cx, |terminal, _| {
878 terminal.input(text.into());
879 })
880 })
881 .ok();
882 }
883
884 fn replace_and_mark_text_in_range(
885 &mut self,
886 _range_utf16: Option<std::ops::Range<usize>>,
887 _new_text: &str,
888 _new_selected_range: Option<std::ops::Range<usize>>,
889 ) {
890 }
891
892 fn unmark_text(&mut self) {}
893
894 fn bounds_for_range(&mut self, _range_utf16: std::ops::Range<usize>) -> Option<Bounds<Pixels>> {
895 self.cursor_bounds
896 }
897}
898
899fn is_blank(cell: &IndexedCell) -> bool {
900 if cell.c != ' ' {
901 return false;
902 }
903
904 if cell.bg != AnsiColor::Named(NamedColor::Background) {
905 return false;
906 }
907
908 if cell.hyperlink().is_some() {
909 return false;
910 }
911
912 if cell
913 .flags
914 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
915 {
916 return false;
917 }
918
919 return true;
920}
921
922fn to_highlighted_range_lines(
923 range: &RangeInclusive<AlacPoint>,
924 layout: &LayoutState,
925 origin: Point<Pixels>,
926) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
927 // Step 1. Normalize the points to be viewport relative.
928 // When display_offset = 1, here's how the grid is arranged:
929 //-2,0 -2,1...
930 //--- Viewport top
931 //-1,0 -1,1...
932 //--------- Terminal Top
933 // 0,0 0,1...
934 // 1,0 1,1...
935 //--- Viewport Bottom
936 // 2,0 2,1...
937 //--------- Terminal Bottom
938
939 // Normalize to viewport relative, from terminal relative.
940 // lines are i32s, which are negative above the top left corner of the terminal
941 // If the user has scrolled, we use the display_offset to tell us which offset
942 // of the grid data we should be looking at. But for the rendering step, we don't
943 // want negatives. We want things relative to the 'viewport' (the area of the grid
944 // which is currently shown according to the display offset)
945 let unclamped_start = AlacPoint::new(
946 range.start().line + layout.display_offset,
947 range.start().column,
948 );
949 let unclamped_end =
950 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
951
952 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
953 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
954 return None;
955 }
956
957 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
958 let clamped_end_line = unclamped_end
959 .line
960 .0
961 .min(layout.dimensions.num_lines() as i32) as usize;
962 //Convert the start of the range to pixels
963 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
964
965 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
966 // (also convert to pixels)
967 let mut highlighted_range_lines = Vec::new();
968 for line in clamped_start_line..=clamped_end_line {
969 let mut line_start = 0;
970 let mut line_end = layout.dimensions.columns();
971
972 if line == clamped_start_line {
973 line_start = unclamped_start.column.0 as usize;
974 }
975 if line == clamped_end_line {
976 line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
977 }
978
979 highlighted_range_lines.push(HighlightedRangeLine {
980 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
981 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
982 });
983 }
984
985 Some((start_y, highlighted_range_lines))
986}
987
988///Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent
989fn convert_color(fg: &terminal::alacritty_terminal::ansi::Color, theme: &Theme) -> Hsla {
990 let colors = theme.colors();
991 match fg {
992 //Named and theme defined colors
993 terminal::alacritty_terminal::ansi::Color::Named(n) => match n {
994 NamedColor::Black => colors.terminal_ansi_black,
995 NamedColor::Red => colors.terminal_ansi_red,
996 NamedColor::Green => colors.terminal_ansi_green,
997 NamedColor::Yellow => colors.terminal_ansi_yellow,
998 NamedColor::Blue => colors.terminal_ansi_blue,
999 NamedColor::Magenta => colors.terminal_ansi_magenta,
1000 NamedColor::Cyan => colors.terminal_ansi_cyan,
1001 NamedColor::White => colors.terminal_ansi_white,
1002 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1003 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1004 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1005 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1006 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1007 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1008 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1009 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1010 NamedColor::Foreground => colors.text,
1011 NamedColor::Background => colors.background,
1012 NamedColor::Cursor => theme.players().local().cursor,
1013
1014 // todo!(more colors)
1015 NamedColor::DimBlack => red(),
1016 NamedColor::DimRed => red(),
1017 NamedColor::DimGreen => red(),
1018 NamedColor::DimYellow => red(),
1019 NamedColor::DimBlue => red(),
1020 NamedColor::DimMagenta => red(),
1021 NamedColor::DimCyan => red(),
1022 NamedColor::DimWhite => red(),
1023 NamedColor::BrightForeground => red(),
1024 NamedColor::DimForeground => red(),
1025 },
1026 //'True' colors
1027 terminal::alacritty_terminal::ansi::Color::Spec(rgb) => {
1028 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1029 }
1030 //8 bit, indexed colors
1031 terminal::alacritty_terminal::ansi::Color::Indexed(i) => {
1032 terminal::get_color_at_index(*i as usize, theme)
1033 }
1034 }
1035}