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