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