1use editor::{Cursor, HighlightedRange, HighlightedRangeLine};
2use gpui::{
3 div, fill, point, px, relative, AnyElement, AvailableSpace, Bounds, DispatchPhase, Element,
4 ElementContext, ElementId, FocusHandle, Font, FontStyle, FontWeight, HighlightStyle, Hsla,
5 InputHandler, InteractiveBounds, InteractiveElement, InteractiveElementState, Interactivity,
6 IntoElement, LayoutId, Model, ModelContext, ModifiersChangedEvent, MouseButton, MouseMoveEvent,
7 Pixels, Point, ShapedLine, StatefulInteractiveElement, Styled, TextRun, TextStyle, TextSystem,
8 UnderlineStyle, WeakView, WhiteSpace, WindowContext,
9};
10use itertools::Itertools;
11use language::CursorShape;
12use settings::Settings;
13use terminal::{
14 alacritty_terminal::{
15 grid::Dimensions,
16 index::Point as AlacPoint,
17 term::{cell::Flags, TermMode},
18 vte::ansi::{Color as AnsiColor, Color::Named, CursorShape as AlacCursorShape, NamedColor},
19 },
20 terminal_settings::TerminalSettings,
21 IndexedCell, Terminal, TerminalContent, TerminalSize,
22};
23use theme::{ActiveTheme, Theme, ThemeSettings};
24use ui::Tooltip;
25use workspace::Workspace;
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 dimensions: 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 ElementContext,
84 ) {
85 let pos = {
86 let point = self.point;
87
88 Point::new(
89 (origin.x + point.column as f32 * layout.dimensions.cell_width).floor(),
90 origin.y + point.line as f32 * layout.dimensions.line_height,
91 )
92 };
93
94 self.text.paint(pos, layout.dimensions.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 ElementContext) {
123 let position = {
124 let alac_point = self.point;
125 point(
126 (origin.x + alac_point.column as f32 * layout.dimensions.cell_width).floor(),
127 origin.y + alac_point.line as f32 * layout.dimensions.line_height,
128 )
129 };
130 let size = point(
131 (layout.dimensions.cell_width * self.num_of_cells as f32).ceil(),
132 layout.dimensions.line_height,
133 )
134 .into();
135
136 cx.paint_quad(fill(Bounds::new(position, size), self.color));
137 }
138}
139
140/// The GPUI element that paints the terminal.
141/// 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?
142pub struct TerminalElement {
143 terminal: Model<Terminal>,
144 workspace: WeakView<Workspace>,
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 workspace: WeakView<Workspace>,
164 focus: FocusHandle,
165 focused: bool,
166 cursor_visible: bool,
167 can_navigate_to_selected_word: bool,
168 ) -> TerminalElement {
169 TerminalElement {
170 terminal,
171 workspace,
172 focused,
173 focus: focus.clone(),
174 cursor_visible,
175 can_navigate_to_selected_word,
176 interactivity: Default::default(),
177 }
178 .track_focus(&focus)
179 .element
180 }
181
182 //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
183
184 fn layout_grid(
185 grid: &Vec<IndexedCell>,
186 text_style: &TextStyle,
187 // terminal_theme: &TerminalStyle,
188 text_system: &TextSystem,
189 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
190 cx: &WindowContext<'_>,
191 ) -> (Vec<LayoutCell>, Vec<LayoutRect>) {
192 let theme = cx.theme();
193 let mut cells = vec![];
194 let mut rects = vec![];
195
196 let mut cur_rect: Option<LayoutRect> = None;
197 let mut cur_alac_color = None;
198
199 let linegroups = grid.into_iter().group_by(|i| i.point.line);
200 for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
201 for cell in line {
202 let mut fg = cell.fg;
203 let mut bg = cell.bg;
204 if cell.flags.contains(Flags::INVERSE) {
205 mem::swap(&mut fg, &mut bg);
206 }
207
208 //Expand background rect range
209 {
210 if matches!(bg, Named(NamedColor::Background)) {
211 //Continue to next cell, resetting variables if necessary
212 cur_alac_color = None;
213 if let Some(rect) = cur_rect {
214 rects.push(rect);
215 cur_rect = None
216 }
217 } else {
218 match cur_alac_color {
219 Some(cur_color) => {
220 if bg == cur_color {
221 cur_rect = cur_rect.take().map(|rect| rect.extend());
222 } else {
223 cur_alac_color = Some(bg);
224 if cur_rect.is_some() {
225 rects.push(cur_rect.take().unwrap());
226 }
227 cur_rect = Some(LayoutRect::new(
228 AlacPoint::new(
229 line_index as i32,
230 cell.point.column.0 as i32,
231 ),
232 1,
233 convert_color(&bg, theme),
234 ));
235 }
236 }
237 None => {
238 cur_alac_color = Some(bg);
239 cur_rect = Some(LayoutRect::new(
240 AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
241 1,
242 convert_color(&bg, &theme),
243 ));
244 }
245 }
246 }
247 }
248
249 //Layout current cell text
250 {
251 if !is_blank(&cell) {
252 let cell_text = cell.c.to_string();
253 let cell_style =
254 TerminalElement::cell_style(&cell, fg, theme, text_style, hyperlink);
255
256 let layout_cell = text_system
257 .shape_line(
258 cell_text.into(),
259 text_style.font_size.to_pixels(cx.rem_size()),
260 &[cell_style],
261 )
262 .unwrap();
263
264 cells.push(LayoutCell::new(
265 AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
266 layout_cell,
267 ))
268 };
269 }
270 }
271
272 if cur_rect.is_some() {
273 rects.push(cur_rect.take().unwrap());
274 }
275 }
276 (cells, rects)
277 }
278
279 /// Computes the cursor position and expected block width, may return a zero width if x_for_index returns
280 /// the same position for sequential indexes. Use em_width instead
281 fn shape_cursor(
282 cursor_point: DisplayCursor,
283 size: TerminalSize,
284 text_fragment: &ShapedLine,
285 ) -> Option<(Point<Pixels>, Pixels)> {
286 if cursor_point.line() < size.total_lines() as i32 {
287 let cursor_width = if text_fragment.width == Pixels::ZERO {
288 size.cell_width()
289 } else {
290 text_fragment.width
291 };
292
293 // Cursor should always surround as much of the text as possible,
294 // hence when on pixel boundaries round the origin down and the width up
295 Some((
296 point(
297 (cursor_point.col() as f32 * size.cell_width()).floor(),
298 (cursor_point.line() as f32 * size.line_height()).floor(),
299 ),
300 cursor_width.ceil(),
301 ))
302 } else {
303 None
304 }
305 }
306
307 /// Converts the Alacritty cell styles to GPUI text styles and background color.
308 fn cell_style(
309 indexed: &IndexedCell,
310 fg: terminal::alacritty_terminal::vte::ansi::Color,
311 // bg: terminal::alacritty_terminal::ansi::Color,
312 colors: &Theme,
313 text_style: &TextStyle,
314 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
315 ) -> TextRun {
316 let flags = indexed.cell.flags;
317 let fg = convert_color(&fg, &colors);
318 // let bg = convert_color(&bg, &colors);
319
320 let underline = (flags.intersects(Flags::ALL_UNDERLINES)
321 || indexed.cell.hyperlink().is_some())
322 .then(|| UnderlineStyle {
323 color: Some(fg),
324 thickness: Pixels::from(1.0),
325 wavy: flags.contains(Flags::UNDERCURL),
326 });
327
328 let weight = if flags.intersects(Flags::BOLD | Flags::DIM_BOLD) {
329 FontWeight::BOLD
330 } else {
331 FontWeight::NORMAL
332 };
333
334 let style = if flags.intersects(Flags::ITALIC) {
335 FontStyle::Italic
336 } else {
337 FontStyle::Normal
338 };
339
340 let mut result = TextRun {
341 len: indexed.c.len_utf8() as usize,
342 color: fg,
343 background_color: None,
344 font: Font {
345 weight,
346 style,
347 ..text_style.font()
348 },
349 underline,
350 };
351
352 if let Some((style, range)) = hyperlink {
353 if range.contains(&indexed.point) {
354 if let Some(underline) = style.underline {
355 result.underline = Some(underline);
356 }
357
358 if let Some(color) = style.color {
359 result.color = color;
360 }
361 }
362 }
363
364 result
365 }
366
367 fn compute_layout(&self, bounds: Bounds<gpui::Pixels>, cx: &mut ElementContext) -> LayoutState {
368 let settings = ThemeSettings::get_global(cx).clone();
369
370 let buffer_font_size = settings.buffer_font_size(cx);
371
372 let terminal_settings = TerminalSettings::get_global(cx);
373 let font_family = terminal_settings
374 .font_family
375 .as_ref()
376 .map(|string| string.clone().into())
377 .unwrap_or(settings.buffer_font.family);
378
379 let font_features = terminal_settings
380 .font_features
381 .clone()
382 .unwrap_or(settings.buffer_font.features.clone());
383
384 let line_height = terminal_settings.line_height.value();
385 let font_size = terminal_settings.font_size.clone();
386
387 let font_size =
388 font_size.map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx));
389
390 let theme = cx.theme().clone();
391
392 let link_style = HighlightStyle {
393 color: Some(theme.colors().link_text_hover),
394 font_weight: None,
395 font_style: None,
396 background_color: None,
397 underline: Some(UnderlineStyle {
398 thickness: px(1.0),
399 color: Some(theme.colors().link_text_hover),
400 wavy: false,
401 }),
402 fade_out: None,
403 };
404
405 let text_style = TextStyle {
406 font_family,
407 font_features,
408 font_size: font_size.into(),
409 font_style: FontStyle::Normal,
410 line_height: line_height.into(),
411 background_color: None,
412 white_space: WhiteSpace::Normal,
413 // These are going to be overridden per-cell
414 underline: None,
415 color: theme.colors().text,
416 font_weight: FontWeight::NORMAL,
417 };
418
419 let text_system = cx.text_system();
420 let selection_color = theme.players().local();
421 let match_color = theme.colors().search_match_background;
422 let gutter;
423 let dimensions = {
424 let rem_size = cx.rem_size();
425 let font_pixels = text_style.font_size.to_pixels(rem_size);
426 let line_height = font_pixels * line_height.to_pixels(rem_size);
427 let font_id = cx.text_system().resolve_font(&text_style.font());
428
429 let cell_width = text_system
430 .advance(font_id, font_pixels, 'm')
431 .unwrap()
432 .width;
433 gutter = cell_width;
434
435 let mut size = bounds.size.clone();
436 size.width -= gutter;
437
438 TerminalSize::new(line_height, cell_width, size)
439 };
440
441 let search_matches = self.terminal.read(cx).matches.clone();
442
443 let background_color = theme.colors().terminal_background;
444
445 let last_hovered_word = self.terminal.update(cx, |terminal, cx| {
446 terminal.set_size(dimensions);
447 terminal.sync(cx);
448 if self.can_navigate_to_selected_word && terminal.can_navigate_to_selected_word() {
449 terminal.last_content.last_hovered_word.clone()
450 } else {
451 None
452 }
453 });
454
455 let interactive_text_bounds = InteractiveBounds {
456 bounds,
457 stacking_order: cx.stacking_order().clone(),
458 };
459 if interactive_text_bounds.visibly_contains(&cx.mouse_position(), cx) {
460 if self.can_navigate_to_selected_word && last_hovered_word.is_some() {
461 cx.set_cursor_style(gpui::CursorStyle::PointingHand)
462 } else {
463 cx.set_cursor_style(gpui::CursorStyle::IBeam)
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 let len = str_trxt.len();
516 cx.text_system()
517 .shape_line(
518 str_trxt.into(),
519 text_style.font_size.to_pixels(cx.rem_size()),
520 &[TextRun {
521 len,
522 font: text_style.font(),
523 color: theme.colors().terminal_background,
524 background_color: None,
525 underline: Default::default(),
526 }],
527 )
528 .unwrap()
529 };
530
531 let focused = self.focused;
532 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
533 move |(cursor_position, block_width)| {
534 let (shape, text) = match cursor.shape {
535 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
536 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
537 AlacCursorShape::Underline => (CursorShape::Underscore, None),
538 AlacCursorShape::Beam => (CursorShape::Bar, None),
539 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
540 //This case is handled in the if wrapping the whole cursor layout
541 AlacCursorShape::Hidden => unreachable!(),
542 };
543
544 Cursor::new(
545 cursor_position,
546 block_width,
547 dimensions.line_height,
548 theme.players().local().cursor,
549 shape,
550 text,
551 None,
552 )
553 },
554 )
555 };
556
557 LayoutState {
558 cells,
559 cursor,
560 background_color,
561 dimensions,
562 rects,
563 relative_highlighted_ranges,
564 mode: *mode,
565 display_offset: *display_offset,
566 hyperlink_tooltip,
567 gutter,
568 }
569 }
570
571 fn generic_button_handler<E>(
572 connection: Model<Terminal>,
573 origin: Point<Pixels>,
574 focus_handle: FocusHandle,
575 f: impl Fn(&mut Terminal, Point<Pixels>, &E, &mut ModelContext<Terminal>),
576 ) -> impl Fn(&E, &mut WindowContext) {
577 move |event, cx| {
578 cx.focus(&focus_handle);
579 connection.update(cx, |terminal, cx| {
580 f(terminal, origin, event, cx);
581
582 cx.notify();
583 })
584 }
585 }
586
587 fn register_mouse_listeners(
588 &mut self,
589 origin: Point<Pixels>,
590 mode: TermMode,
591 bounds: Bounds<Pixels>,
592 cx: &mut ElementContext,
593 ) {
594 let focus = self.focus.clone();
595 let terminal = self.terminal.clone();
596 let interactive_bounds = InteractiveBounds {
597 bounds: bounds.intersect(&cx.content_mask().bounds),
598 stacking_order: cx.stacking_order().clone(),
599 };
600
601 self.interactivity.on_mouse_down(MouseButton::Left, {
602 let terminal = terminal.clone();
603 let focus = focus.clone();
604 move |e, cx| {
605 cx.focus(&focus);
606 terminal.update(cx, |terminal, cx| {
607 terminal.mouse_down(&e, origin);
608 cx.notify();
609 })
610 }
611 });
612
613 cx.on_mouse_event({
614 let bounds = bounds.clone();
615 let focus = self.focus.clone();
616 let terminal = self.terminal.clone();
617 move |e: &MouseMoveEvent, phase, cx| {
618 if phase != DispatchPhase::Bubble || !focus.is_focused(cx) {
619 return;
620 }
621
622 if e.pressed_button.is_some() && !cx.has_active_drag() {
623 let visibly_contains = interactive_bounds.visibly_contains(&e.position, cx);
624 terminal.update(cx, |terminal, cx| {
625 if !terminal.selection_started() {
626 if visibly_contains {
627 terminal.mouse_drag(e, origin, bounds);
628 cx.notify();
629 }
630 } else {
631 terminal.mouse_drag(e, origin, bounds);
632 cx.notify();
633 }
634 })
635 }
636
637 if interactive_bounds.visibly_contains(&e.position, cx) {
638 terminal.update(cx, |terminal, cx| {
639 terminal.mouse_move(&e, origin);
640 cx.notify();
641 })
642 }
643 }
644 });
645
646 self.interactivity.on_mouse_up(
647 MouseButton::Left,
648 TerminalElement::generic_button_handler(
649 terminal.clone(),
650 origin,
651 focus.clone(),
652 move |terminal, origin, e, cx| {
653 terminal.mouse_up(&e, origin, cx);
654 },
655 ),
656 );
657 self.interactivity.on_scroll_wheel({
658 let terminal = terminal.clone();
659 move |e, cx| {
660 terminal.update(cx, |terminal, cx| {
661 terminal.scroll_wheel(e, origin);
662 cx.notify();
663 })
664 }
665 });
666
667 // Mouse mode handlers:
668 // All mouse modes need the extra click handlers
669 if mode.intersects(TermMode::MOUSE_MODE) {
670 self.interactivity.on_mouse_down(
671 MouseButton::Right,
672 TerminalElement::generic_button_handler(
673 terminal.clone(),
674 origin,
675 focus.clone(),
676 move |terminal, origin, e, _cx| {
677 terminal.mouse_down(&e, origin);
678 },
679 ),
680 );
681 self.interactivity.on_mouse_down(
682 MouseButton::Middle,
683 TerminalElement::generic_button_handler(
684 terminal.clone(),
685 origin,
686 focus.clone(),
687 move |terminal, origin, e, _cx| {
688 terminal.mouse_down(&e, origin);
689 },
690 ),
691 );
692 self.interactivity.on_mouse_up(
693 MouseButton::Right,
694 TerminalElement::generic_button_handler(
695 terminal.clone(),
696 origin,
697 focus.clone(),
698 move |terminal, origin, e, cx| {
699 terminal.mouse_up(&e, origin, cx);
700 },
701 ),
702 );
703 self.interactivity.on_mouse_up(
704 MouseButton::Middle,
705 TerminalElement::generic_button_handler(
706 terminal,
707 origin,
708 focus,
709 move |terminal, origin, e, cx| {
710 terminal.mouse_up(&e, origin, cx);
711 },
712 ),
713 );
714 }
715 }
716}
717
718impl Element for TerminalElement {
719 type State = InteractiveElementState;
720
721 fn request_layout(
722 &mut self,
723 element_state: Option<Self::State>,
724 cx: &mut ElementContext<'_>,
725 ) -> (LayoutId, Self::State) {
726 let (layout_id, interactive_state) =
727 self.interactivity
728 .layout(element_state, cx, |mut style, cx| {
729 style.size.width = relative(1.).into();
730 style.size.height = relative(1.).into();
731 let layout_id = cx.request_layout(&style, None);
732
733 layout_id
734 });
735
736 (layout_id, interactive_state)
737 }
738
739 fn paint(
740 &mut self,
741 bounds: Bounds<Pixels>,
742 state: &mut Self::State,
743 cx: &mut ElementContext<'_>,
744 ) {
745 let mut layout = self.compute_layout(bounds, cx);
746
747 cx.paint_quad(fill(bounds, layout.background_color));
748 let origin = bounds.origin + Point::new(layout.gutter, px(0.));
749
750 let terminal_input_handler = TerminalInputHandler {
751 terminal: self.terminal.clone(),
752 cursor_bounds: layout
753 .cursor
754 .as_ref()
755 .map(|cursor| cursor.bounding_rect(origin)),
756 workspace: self.workspace.clone(),
757 };
758
759 self.register_mouse_listeners(origin, layout.mode, bounds, cx);
760
761 self.interactivity
762 .paint(bounds, bounds.size, state, cx, |_, _, cx| {
763 cx.handle_input(&self.focus, terminal_input_handler);
764 cx.keymatch_mode_immediate();
765
766 cx.on_key_event({
767 let this = self.terminal.clone();
768 move |event: &ModifiersChangedEvent, phase, cx| {
769 if phase != DispatchPhase::Bubble {
770 return;
771 }
772
773 let handled =
774 this.update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
775
776 if handled {
777 cx.refresh();
778 }
779 }
780 });
781
782 for rect in &layout.rects {
783 rect.paint(origin, &layout, cx);
784 }
785
786 cx.with_z_index(1, |cx| {
787 for (relative_highlighted_range, color) in
788 layout.relative_highlighted_ranges.iter()
789 {
790 if let Some((start_y, highlighted_range_lines)) =
791 to_highlighted_range_lines(relative_highlighted_range, &layout, origin)
792 {
793 let hr = HighlightedRange {
794 start_y, //Need to change this
795 line_height: layout.dimensions.line_height,
796 lines: highlighted_range_lines,
797 color: color.clone(),
798 //Copied from editor. TODO: move to theme or something
799 corner_radius: 0.15 * layout.dimensions.line_height,
800 };
801 hr.paint(bounds, cx);
802 }
803 }
804 });
805
806 cx.with_z_index(2, |cx| {
807 for cell in &layout.cells {
808 cell.paint(origin, &layout, bounds, cx);
809 }
810 });
811
812 if self.cursor_visible {
813 cx.with_z_index(3, |cx| {
814 if let Some(cursor) = &layout.cursor {
815 cursor.paint(origin, cx);
816 }
817 });
818 }
819
820 if let Some(mut element) = layout.hyperlink_tooltip.take() {
821 element.draw(origin, bounds.size.map(AvailableSpace::Definite), cx)
822 }
823 });
824 }
825}
826
827impl IntoElement for TerminalElement {
828 type Element = Self;
829
830 fn element_id(&self) -> Option<ElementId> {
831 Some("terminal".into())
832 }
833
834 fn into_element(self) -> Self::Element {
835 self
836 }
837}
838
839struct TerminalInputHandler {
840 terminal: Model<Terminal>,
841 workspace: WeakView<Workspace>,
842 cursor_bounds: Option<Bounds<Pixels>>,
843}
844
845impl InputHandler for TerminalInputHandler {
846 fn selected_text_range(&mut self, cx: &mut WindowContext) -> Option<std::ops::Range<usize>> {
847 if self
848 .terminal
849 .read(cx)
850 .last_content
851 .mode
852 .contains(TermMode::ALT_SCREEN)
853 {
854 None
855 } else {
856 Some(0..0)
857 }
858 }
859
860 fn marked_text_range(&mut self, _: &mut WindowContext) -> Option<std::ops::Range<usize>> {
861 None
862 }
863
864 fn text_for_range(
865 &mut self,
866 _: std::ops::Range<usize>,
867 _: &mut WindowContext,
868 ) -> Option<String> {
869 None
870 }
871
872 fn replace_text_in_range(
873 &mut self,
874 _replacement_range: Option<std::ops::Range<usize>>,
875 text: &str,
876 cx: &mut WindowContext,
877 ) {
878 self.terminal.update(cx, |terminal, _| {
879 terminal.input(text.into());
880 });
881
882 self.workspace
883 .update(cx, |this, cx| {
884 let telemetry = this.project().read(cx).client().telemetry().clone();
885 telemetry.log_edit_event("terminal");
886 })
887 .ok();
888 }
889
890 fn replace_and_mark_text_in_range(
891 &mut self,
892 _range_utf16: Option<std::ops::Range<usize>>,
893 _new_text: &str,
894 _new_selected_range: Option<std::ops::Range<usize>>,
895 _: &mut WindowContext,
896 ) {
897 }
898
899 fn unmark_text(&mut self, _: &mut WindowContext) {}
900
901 fn bounds_for_range(
902 &mut self,
903 _range_utf16: std::ops::Range<usize>,
904 _: &mut WindowContext,
905 ) -> Option<Bounds<Pixels>> {
906 self.cursor_bounds
907 }
908}
909
910fn is_blank(cell: &IndexedCell) -> bool {
911 if cell.c != ' ' {
912 return false;
913 }
914
915 if cell.bg != AnsiColor::Named(NamedColor::Background) {
916 return false;
917 }
918
919 if cell.hyperlink().is_some() {
920 return false;
921 }
922
923 if cell
924 .flags
925 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
926 {
927 return false;
928 }
929
930 return true;
931}
932
933fn to_highlighted_range_lines(
934 range: &RangeInclusive<AlacPoint>,
935 layout: &LayoutState,
936 origin: Point<Pixels>,
937) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
938 // Step 1. Normalize the points to be viewport relative.
939 // When display_offset = 1, here's how the grid is arranged:
940 //-2,0 -2,1...
941 //--- Viewport top
942 //-1,0 -1,1...
943 //--------- Terminal Top
944 // 0,0 0,1...
945 // 1,0 1,1...
946 //--- Viewport Bottom
947 // 2,0 2,1...
948 //--------- Terminal Bottom
949
950 // Normalize to viewport relative, from terminal relative.
951 // lines are i32s, which are negative above the top left corner of the terminal
952 // If the user has scrolled, we use the display_offset to tell us which offset
953 // of the grid data we should be looking at. But for the rendering step, we don't
954 // want negatives. We want things relative to the 'viewport' (the area of the grid
955 // which is currently shown according to the display offset)
956 let unclamped_start = AlacPoint::new(
957 range.start().line + layout.display_offset,
958 range.start().column,
959 );
960 let unclamped_end =
961 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
962
963 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
964 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
965 return None;
966 }
967
968 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
969 let clamped_end_line = unclamped_end
970 .line
971 .0
972 .min(layout.dimensions.num_lines() as i32) as usize;
973 //Convert the start of the range to pixels
974 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
975
976 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
977 // (also convert to pixels)
978 let mut highlighted_range_lines = Vec::new();
979 for line in clamped_start_line..=clamped_end_line {
980 let mut line_start = 0;
981 let mut line_end = layout.dimensions.columns();
982
983 if line == clamped_start_line {
984 line_start = unclamped_start.column.0 as usize;
985 }
986 if line == clamped_end_line {
987 line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
988 }
989
990 highlighted_range_lines.push(HighlightedRangeLine {
991 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
992 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
993 });
994 }
995
996 Some((start_y, highlighted_range_lines))
997}
998
999/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1000fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1001 let colors = theme.colors();
1002 match fg {
1003 // Named and theme defined colors
1004 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1005 NamedColor::Black => colors.terminal_ansi_black,
1006 NamedColor::Red => colors.terminal_ansi_red,
1007 NamedColor::Green => colors.terminal_ansi_green,
1008 NamedColor::Yellow => colors.terminal_ansi_yellow,
1009 NamedColor::Blue => colors.terminal_ansi_blue,
1010 NamedColor::Magenta => colors.terminal_ansi_magenta,
1011 NamedColor::Cyan => colors.terminal_ansi_cyan,
1012 NamedColor::White => colors.terminal_ansi_white,
1013 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1014 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1015 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1016 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1017 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1018 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1019 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1020 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1021 NamedColor::Foreground => colors.text,
1022 NamedColor::Background => colors.background,
1023 NamedColor::Cursor => theme.players().local().cursor,
1024 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1025 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1026 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1027 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1028 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1029 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1030 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1031 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1032 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1033 NamedColor::DimForeground => colors.terminal_dim_foreground,
1034 },
1035 // 'True' colors
1036 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1037 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1038 }
1039 // 8 bit, indexed colors
1040 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1041 terminal::get_color_at_index(*i as usize, theme)
1042 }
1043 }
1044}