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, TerminalBounds, TerminalContent,
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: TerminalBounds,
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: &TerminalBounds,
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: &TerminalBounds, 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: TerminalBounds,
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 focus_handle: FocusHandle,
417 f: impl Fn(&mut Terminal, &E, &mut Context<Terminal>),
418 ) -> impl Fn(&E, &mut Window, &mut App) {
419 move |event, window, cx| {
420 window.focus(&focus_handle);
421 connection.update(cx, |terminal, cx| {
422 f(terminal, event, cx);
423
424 cx.notify();
425 })
426 }
427 }
428
429 fn register_mouse_listeners(&mut self, mode: TermMode, hitbox: &Hitbox, window: &mut Window) {
430 let focus = self.focus.clone();
431 let terminal = self.terminal.clone();
432
433 self.interactivity.on_mouse_down(MouseButton::Left, {
434 let terminal = terminal.clone();
435 let focus = focus.clone();
436 move |e, window, cx| {
437 window.focus(&focus);
438 terminal.update(cx, |terminal, cx| {
439 terminal.mouse_down(e, cx);
440 cx.notify();
441 })
442 }
443 });
444
445 window.on_mouse_event({
446 let terminal = self.terminal.clone();
447 let hitbox = hitbox.clone();
448 let focus = focus.clone();
449 move |e: &MouseMoveEvent, phase, window, cx| {
450 if phase != DispatchPhase::Bubble {
451 return;
452 }
453
454 if e.pressed_button.is_some() && !cx.has_active_drag() && focus.is_focused(window) {
455 let hovered = hitbox.is_hovered(window);
456 terminal.update(cx, |terminal, cx| {
457 if terminal.selection_started() || hovered {
458 terminal.mouse_drag(e, hitbox.bounds, cx);
459 cx.notify();
460 }
461 })
462 }
463
464 if hitbox.is_hovered(window) {
465 terminal.update(cx, |terminal, cx| {
466 terminal.mouse_move(e, cx);
467 })
468 }
469 }
470 });
471
472 self.interactivity.on_mouse_up(
473 MouseButton::Left,
474 TerminalElement::generic_button_handler(
475 terminal.clone(),
476 focus.clone(),
477 move |terminal, e, cx| {
478 terminal.mouse_up(e, cx);
479 },
480 ),
481 );
482 self.interactivity.on_mouse_down(
483 MouseButton::Middle,
484 TerminalElement::generic_button_handler(
485 terminal.clone(),
486 focus.clone(),
487 move |terminal, e, cx| {
488 terminal.mouse_down(e, cx);
489 },
490 ),
491 );
492 self.interactivity.on_scroll_wheel({
493 let terminal_view = self.terminal_view.downgrade();
494 move |e, _, cx| {
495 terminal_view
496 .update(cx, |terminal_view, cx| {
497 terminal_view.scroll_wheel(e, cx);
498 cx.notify();
499 })
500 .ok();
501 }
502 });
503
504 // Mouse mode handlers:
505 // All mouse modes need the extra click handlers
506 if mode.intersects(TermMode::MOUSE_MODE) {
507 self.interactivity.on_mouse_down(
508 MouseButton::Right,
509 TerminalElement::generic_button_handler(
510 terminal.clone(),
511 focus.clone(),
512 move |terminal, e, cx| {
513 terminal.mouse_down(e, cx);
514 },
515 ),
516 );
517 self.interactivity.on_mouse_up(
518 MouseButton::Right,
519 TerminalElement::generic_button_handler(
520 terminal.clone(),
521 focus.clone(),
522 move |terminal, e, cx| {
523 terminal.mouse_up(e, cx);
524 },
525 ),
526 );
527 self.interactivity.on_mouse_up(
528 MouseButton::Middle,
529 TerminalElement::generic_button_handler(terminal, focus, move |terminal, e, cx| {
530 terminal.mouse_up(e, cx);
531 }),
532 );
533 }
534 }
535
536 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
537 let settings = ThemeSettings::get_global(cx).clone();
538 let buffer_font_size = settings.buffer_font_size(cx);
539 let rem_size_scale = {
540 // Our default UI font size is 14px on a 16px base scale.
541 // This means the default UI font size is 0.875rems.
542 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
543
544 // We then determine the delta between a single rem and the default font
545 // size scale.
546 let default_font_size_delta = 1. - default_font_size_scale;
547
548 // Finally, we add this delta to 1rem to get the scale factor that
549 // should be used to scale up the UI.
550 1. + default_font_size_delta
551 };
552
553 Some(buffer_font_size * rem_size_scale)
554 }
555}
556
557impl Element for TerminalElement {
558 type RequestLayoutState = ();
559 type PrepaintState = LayoutState;
560
561 fn id(&self) -> Option<ElementId> {
562 self.interactivity.element_id.clone()
563 }
564
565 fn request_layout(
566 &mut self,
567 global_id: Option<&GlobalElementId>,
568 window: &mut Window,
569 cx: &mut App,
570 ) -> (LayoutId, Self::RequestLayoutState) {
571 let layout_id =
572 self.interactivity
573 .request_layout(global_id, window, cx, |mut style, window, cx| {
574 style.size.width = relative(1.).into();
575 style.size.height = relative(1.).into();
576 // style.overflow = point(Overflow::Hidden, Overflow::Hidden);
577
578 window.request_layout(style, None, cx)
579 });
580 (layout_id, ())
581 }
582
583 fn prepaint(
584 &mut self,
585 global_id: Option<&GlobalElementId>,
586 bounds: Bounds<Pixels>,
587 _: &mut Self::RequestLayoutState,
588 window: &mut Window,
589 cx: &mut App,
590 ) -> Self::PrepaintState {
591 let rem_size = self.rem_size(cx);
592 self.interactivity.prepaint(
593 global_id,
594 bounds,
595 bounds.size,
596 window,
597 cx,
598 |_, _, hitbox, window, cx| {
599 let hitbox = hitbox.unwrap();
600 let settings = ThemeSettings::get_global(cx).clone();
601
602 let buffer_font_size = settings.buffer_font_size(cx);
603
604 let terminal_settings = TerminalSettings::get_global(cx);
605
606 let font_family = terminal_settings
607 .font_family
608 .as_ref()
609 .unwrap_or(&settings.buffer_font.family)
610 .clone();
611
612 let font_fallbacks = terminal_settings
613 .font_fallbacks
614 .as_ref()
615 .or(settings.buffer_font.fallbacks.as_ref())
616 .cloned();
617
618 let font_features = terminal_settings
619 .font_features
620 .as_ref()
621 .unwrap_or(&settings.buffer_font.features)
622 .clone();
623
624 let font_weight = terminal_settings.font_weight.unwrap_or_default();
625
626 let line_height = terminal_settings.line_height.value();
627 let font_size = terminal_settings.font_size;
628
629 let font_size =
630 font_size.map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx));
631
632 let theme = cx.theme().clone();
633
634 let link_style = HighlightStyle {
635 color: Some(theme.colors().link_text_hover),
636 font_weight: Some(font_weight),
637 font_style: None,
638 background_color: None,
639 underline: Some(UnderlineStyle {
640 thickness: px(1.0),
641 color: Some(theme.colors().link_text_hover),
642 wavy: false,
643 }),
644 strikethrough: None,
645 fade_out: None,
646 };
647
648 let text_style = TextStyle {
649 font_family,
650 font_features,
651 font_weight,
652 font_fallbacks,
653 font_size: font_size.into(),
654 font_style: FontStyle::Normal,
655 line_height: line_height.into(),
656 background_color: Some(theme.colors().terminal_ansi_background),
657 white_space: WhiteSpace::Normal,
658 // These are going to be overridden per-cell
659 color: theme.colors().terminal_foreground,
660 ..Default::default()
661 };
662
663 let text_system = cx.text_system();
664 let player_color = theme.players().local();
665 let match_color = theme.colors().search_match_background;
666 let gutter;
667 let dimensions = {
668 let rem_size = window.rem_size();
669 let font_pixels = text_style.font_size.to_pixels(rem_size);
670 let line_height = font_pixels * line_height.to_pixels(rem_size);
671 let font_id = cx.text_system().resolve_font(&text_style.font());
672
673 let cell_width = text_system
674 .advance(font_id, font_pixels, 'm')
675 .unwrap()
676 .width;
677 gutter = cell_width;
678
679 let mut size = bounds.size;
680 size.width -= gutter;
681
682 // https://github.com/zed-industries/zed/issues/2750
683 // if the terminal is one column wide, rendering 🦀
684 // causes alacritty to misbehave.
685 if size.width < cell_width * 2.0 {
686 size.width = cell_width * 2.0;
687 }
688
689 let mut origin = bounds.origin;
690 origin.x += gutter;
691
692 TerminalBounds::new(line_height, cell_width, Bounds { origin, size })
693 };
694
695 let search_matches = self.terminal.read(cx).matches.clone();
696
697 let background_color = theme.colors().terminal_background;
698
699 let last_hovered_word = self.terminal.update(cx, |terminal, cx| {
700 terminal.set_size(dimensions);
701 terminal.sync(window, cx);
702
703 if self.can_navigate_to_selected_word
704 && window.modifiers().secondary()
705 && bounds.contains(&window.mouse_position())
706 {
707 terminal.last_content.last_hovered_word.clone()
708 } else {
709 None
710 }
711 });
712
713 let scroll_top = self.terminal_view.read(cx).scroll_top;
714 let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
715 let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
716 let mut element = div()
717 .size_full()
718 .id("terminal-element")
719 .tooltip(Tooltip::text(hovered_word.word.clone()))
720 .into_any_element();
721 element.prepaint_as_root(offset, bounds.size.into(), window, cx);
722 element
723 });
724
725 let TerminalContent {
726 cells,
727 mode,
728 display_offset,
729 cursor_char,
730 selection,
731 cursor,
732 ..
733 } = &self.terminal.read(cx).last_content;
734 let mode = *mode;
735 let display_offset = *display_offset;
736
737 // searches, highlights to a single range representations
738 let mut relative_highlighted_ranges = Vec::new();
739 for search_match in search_matches {
740 relative_highlighted_ranges.push((search_match, match_color))
741 }
742 if let Some(selection) = selection {
743 relative_highlighted_ranges
744 .push((selection.start..=selection.end, player_color.selection));
745 }
746
747 // then have that representation be converted to the appropriate highlight data structure
748
749 let (cells, rects) = TerminalElement::layout_grid(
750 cells.iter().cloned(),
751 &text_style,
752 window.text_system(),
753 last_hovered_word
754 .as_ref()
755 .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
756 window,
757 cx,
758 );
759
760 // Layout cursor. Rectangle is used for IME, so we should lay it out even
761 // if we don't end up showing it.
762 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
763 None
764 } else {
765 let cursor_point = DisplayCursor::from(cursor.point, display_offset);
766 let cursor_text = {
767 let str_trxt = cursor_char.to_string();
768 let len = str_trxt.len();
769 window
770 .text_system()
771 .shape_line(
772 str_trxt.into(),
773 text_style.font_size.to_pixels(window.rem_size()),
774 &[TextRun {
775 len,
776 font: text_style.font(),
777 color: theme.colors().terminal_ansi_background,
778 background_color: None,
779 underline: Default::default(),
780 strikethrough: None,
781 }],
782 )
783 .unwrap()
784 };
785
786 let focused = self.focused;
787 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
788 move |(cursor_position, block_width)| {
789 let (shape, text) = match cursor.shape {
790 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
791 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
792 AlacCursorShape::Underline => (CursorShape::Underline, None),
793 AlacCursorShape::Beam => (CursorShape::Bar, None),
794 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
795 //This case is handled in the if wrapping the whole cursor layout
796 AlacCursorShape::Hidden => unreachable!(),
797 };
798
799 CursorLayout::new(
800 cursor_position,
801 block_width,
802 dimensions.line_height,
803 theme.players().local().cursor,
804 shape,
805 text,
806 )
807 },
808 )
809 };
810
811 let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
812 let terminal = self.terminal.read(cx);
813 if terminal.last_content.display_offset == 0 {
814 let target_line = terminal.last_content.cursor.point.line.0 + 1;
815 let render = &block.render;
816 let mut block_cx = BlockContext {
817 window,
818 context: cx,
819 dimensions,
820 };
821 let element = render(&mut block_cx);
822 let mut element = div().occlude().child(element).into_any_element();
823 let available_space = size(
824 AvailableSpace::Definite(dimensions.width() + gutter),
825 AvailableSpace::Definite(
826 block.height as f32 * dimensions.line_height(),
827 ),
828 );
829 let origin = bounds.origin
830 + point(px(0.), target_line as f32 * dimensions.line_height())
831 - point(px(0.), scroll_top);
832 window.with_rem_size(rem_size, |window| {
833 element.prepaint_as_root(origin, available_space, window, cx);
834 });
835 Some(element)
836 } else {
837 None
838 }
839 } else {
840 None
841 };
842
843 LayoutState {
844 hitbox,
845 cells,
846 cursor,
847 background_color,
848 dimensions,
849 rects,
850 relative_highlighted_ranges,
851 mode,
852 display_offset,
853 hyperlink_tooltip,
854 gutter,
855 last_hovered_word,
856 block_below_cursor_element,
857 }
858 },
859 )
860 }
861
862 fn paint(
863 &mut self,
864 global_id: Option<&GlobalElementId>,
865 bounds: Bounds<Pixels>,
866 _: &mut Self::RequestLayoutState,
867 layout: &mut Self::PrepaintState,
868 window: &mut Window,
869 cx: &mut App,
870 ) {
871 window.with_content_mask(Some(ContentMask { bounds }), |window| {
872 let scroll_top = self.terminal_view.read(cx).scroll_top;
873
874 window.paint_quad(fill(bounds, layout.background_color));
875 let origin =
876 bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
877
878 let terminal_input_handler = TerminalInputHandler {
879 terminal: self.terminal.clone(),
880 cursor_bounds: layout
881 .cursor
882 .as_ref()
883 .map(|cursor| cursor.bounding_rect(origin)),
884 workspace: self.workspace.clone(),
885 };
886
887 self.register_mouse_listeners(layout.mode, &layout.hitbox, window);
888 if self.can_navigate_to_selected_word && layout.last_hovered_word.is_some() {
889 window.set_cursor_style(gpui::CursorStyle::PointingHand, &layout.hitbox);
890 } else {
891 window.set_cursor_style(gpui::CursorStyle::IBeam, &layout.hitbox);
892 }
893
894 let cursor = layout.cursor.take();
895 let hyperlink_tooltip = layout.hyperlink_tooltip.take();
896 let block_below_cursor_element = layout.block_below_cursor_element.take();
897 self.interactivity.paint(
898 global_id,
899 bounds,
900 Some(&layout.hitbox),
901 window,
902 cx,
903 |_, window, cx| {
904 window.handle_input(&self.focus, terminal_input_handler, cx);
905
906 window.on_key_event({
907 let this = self.terminal.clone();
908 move |event: &ModifiersChangedEvent, phase, window, cx| {
909 if phase != DispatchPhase::Bubble {
910 return;
911 }
912
913 this.update(cx, |term, cx| {
914 term.try_modifiers_change(&event.modifiers, window, cx)
915 });
916 }
917 });
918
919 for rect in &layout.rects {
920 rect.paint(origin, &layout.dimensions, window);
921 }
922
923 for (relative_highlighted_range, color) in
924 layout.relative_highlighted_ranges.iter()
925 {
926 if let Some((start_y, highlighted_range_lines)) =
927 to_highlighted_range_lines(relative_highlighted_range, layout, origin)
928 {
929 let hr = HighlightedRange {
930 start_y,
931 line_height: layout.dimensions.line_height,
932 lines: highlighted_range_lines,
933 color: *color,
934 corner_radius: 0.15 * layout.dimensions.line_height,
935 };
936 hr.paint(bounds, window);
937 }
938 }
939
940 for cell in &layout.cells {
941 cell.paint(origin, &layout.dimensions, bounds, window, cx);
942 }
943
944 if self.cursor_visible {
945 if let Some(mut cursor) = cursor {
946 cursor.paint(origin, window, cx);
947 }
948 }
949
950 if let Some(mut element) = block_below_cursor_element {
951 element.paint(window, cx);
952 }
953
954 if let Some(mut element) = hyperlink_tooltip {
955 element.paint(window, cx);
956 }
957 },
958 );
959 });
960 }
961}
962
963impl IntoElement for TerminalElement {
964 type Element = Self;
965
966 fn into_element(self) -> Self::Element {
967 self
968 }
969}
970
971struct TerminalInputHandler {
972 terminal: Entity<Terminal>,
973 workspace: WeakEntity<Workspace>,
974 cursor_bounds: Option<Bounds<Pixels>>,
975}
976
977impl InputHandler for TerminalInputHandler {
978 fn selected_text_range(
979 &mut self,
980 _ignore_disabled_input: bool,
981 _: &mut Window,
982 cx: &mut App,
983 ) -> Option<UTF16Selection> {
984 if self
985 .terminal
986 .read(cx)
987 .last_content
988 .mode
989 .contains(TermMode::ALT_SCREEN)
990 {
991 None
992 } else {
993 Some(UTF16Selection {
994 range: 0..0,
995 reversed: false,
996 })
997 }
998 }
999
1000 fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<std::ops::Range<usize>> {
1001 None
1002 }
1003
1004 fn text_for_range(
1005 &mut self,
1006 _: std::ops::Range<usize>,
1007 _: &mut Option<std::ops::Range<usize>>,
1008 _: &mut Window,
1009 _: &mut App,
1010 ) -> Option<String> {
1011 None
1012 }
1013
1014 fn replace_text_in_range(
1015 &mut self,
1016 _replacement_range: Option<std::ops::Range<usize>>,
1017 text: &str,
1018 window: &mut Window,
1019 cx: &mut App,
1020 ) {
1021 self.terminal.update(cx, |terminal, _| {
1022 terminal.input(text.into());
1023 });
1024
1025 self.workspace
1026 .update(cx, |this, cx| {
1027 window.invalidate_character_coordinates();
1028 let project = this.project().read(cx);
1029 let telemetry = project.client().telemetry().clone();
1030 telemetry.log_edit_event("terminal", project.is_via_ssh());
1031 })
1032 .ok();
1033 }
1034
1035 fn replace_and_mark_text_in_range(
1036 &mut self,
1037 _range_utf16: Option<std::ops::Range<usize>>,
1038 _new_text: &str,
1039 _new_selected_range: Option<std::ops::Range<usize>>,
1040 _window: &mut Window,
1041 _cx: &mut App,
1042 ) {
1043 }
1044
1045 fn unmark_text(&mut self, _window: &mut Window, _cx: &mut App) {}
1046
1047 fn bounds_for_range(
1048 &mut self,
1049 _range_utf16: std::ops::Range<usize>,
1050 _window: &mut Window,
1051 _cx: &mut App,
1052 ) -> Option<Bounds<Pixels>> {
1053 self.cursor_bounds
1054 }
1055
1056 fn apple_press_and_hold_enabled(&mut self) -> bool {
1057 false
1058 }
1059
1060 fn character_index_for_point(
1061 &mut self,
1062 _point: Point<Pixels>,
1063 _window: &mut Window,
1064 _cx: &mut App,
1065 ) -> Option<usize> {
1066 None
1067 }
1068}
1069
1070pub fn is_blank(cell: &IndexedCell) -> bool {
1071 if cell.c != ' ' {
1072 return false;
1073 }
1074
1075 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1076 return false;
1077 }
1078
1079 if cell.hyperlink().is_some() {
1080 return false;
1081 }
1082
1083 if cell
1084 .flags
1085 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1086 {
1087 return false;
1088 }
1089
1090 true
1091}
1092
1093fn to_highlighted_range_lines(
1094 range: &RangeInclusive<AlacPoint>,
1095 layout: &LayoutState,
1096 origin: Point<Pixels>,
1097) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1098 // Step 1. Normalize the points to be viewport relative.
1099 // When display_offset = 1, here's how the grid is arranged:
1100 //-2,0 -2,1...
1101 //--- Viewport top
1102 //-1,0 -1,1...
1103 //--------- Terminal Top
1104 // 0,0 0,1...
1105 // 1,0 1,1...
1106 //--- Viewport Bottom
1107 // 2,0 2,1...
1108 //--------- Terminal Bottom
1109
1110 // Normalize to viewport relative, from terminal relative.
1111 // lines are i32s, which are negative above the top left corner of the terminal
1112 // If the user has scrolled, we use the display_offset to tell us which offset
1113 // of the grid data we should be looking at. But for the rendering step, we don't
1114 // want negatives. We want things relative to the 'viewport' (the area of the grid
1115 // which is currently shown according to the display offset)
1116 let unclamped_start = AlacPoint::new(
1117 range.start().line + layout.display_offset,
1118 range.start().column,
1119 );
1120 let unclamped_end =
1121 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1122
1123 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1124 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1125 return None;
1126 }
1127
1128 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1129 let clamped_end_line = unclamped_end
1130 .line
1131 .0
1132 .min(layout.dimensions.num_lines() as i32) as usize;
1133 //Convert the start of the range to pixels
1134 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1135
1136 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1137 // (also convert to pixels)
1138 let mut highlighted_range_lines = Vec::new();
1139 for line in clamped_start_line..=clamped_end_line {
1140 let mut line_start = 0;
1141 let mut line_end = layout.dimensions.columns();
1142
1143 if line == clamped_start_line {
1144 line_start = unclamped_start.column.0;
1145 }
1146 if line == clamped_end_line {
1147 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1148 }
1149
1150 highlighted_range_lines.push(HighlightedRangeLine {
1151 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1152 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1153 });
1154 }
1155
1156 Some((start_y, highlighted_range_lines))
1157}
1158
1159/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1160pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1161 let colors = theme.colors();
1162 match fg {
1163 // Named and theme defined colors
1164 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1165 NamedColor::Black => colors.terminal_ansi_black,
1166 NamedColor::Red => colors.terminal_ansi_red,
1167 NamedColor::Green => colors.terminal_ansi_green,
1168 NamedColor::Yellow => colors.terminal_ansi_yellow,
1169 NamedColor::Blue => colors.terminal_ansi_blue,
1170 NamedColor::Magenta => colors.terminal_ansi_magenta,
1171 NamedColor::Cyan => colors.terminal_ansi_cyan,
1172 NamedColor::White => colors.terminal_ansi_white,
1173 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1174 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1175 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1176 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1177 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1178 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1179 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1180 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1181 NamedColor::Foreground => colors.terminal_foreground,
1182 NamedColor::Background => colors.terminal_ansi_background,
1183 NamedColor::Cursor => theme.players().local().cursor,
1184 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1185 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1186 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1187 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1188 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1189 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1190 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1191 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1192 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1193 NamedColor::DimForeground => colors.terminal_dim_foreground,
1194 },
1195 // 'True' colors
1196 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1197 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1198 }
1199 // 8 bit, indexed colors
1200 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1201 terminal::get_color_at_index(*i as usize, theme)
1202 }
1203 }
1204}