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 util::ResultExt;
30use workspace::Workspace;
31
32use std::mem;
33use std::{fmt::Debug, ops::RangeInclusive, rc::Rc};
34
35use crate::{BlockContext, BlockProperties, TerminalView};
36
37/// The information generated during layout that is necessary for painting.
38pub struct LayoutState {
39 hitbox: Hitbox,
40 cells: Vec<LayoutCell>,
41 rects: Vec<LayoutRect>,
42 relative_highlighted_ranges: Vec<(RangeInclusive<AlacPoint>, Hsla)>,
43 cursor: Option<CursorLayout>,
44 background_color: Hsla,
45 dimensions: TerminalBounds,
46 mode: TermMode,
47 display_offset: usize,
48 hyperlink_tooltip: Option<AnyElement>,
49 gutter: Pixels,
50 block_below_cursor_element: Option<AnyElement>,
51 base_text_style: TextStyle,
52}
53
54/// Helper struct for converting data between Alacritty's cursor points, and displayed cursor points.
55struct DisplayCursor {
56 line: i32,
57 col: usize,
58}
59
60impl DisplayCursor {
61 fn from(cursor_point: AlacPoint, display_offset: usize) -> Self {
62 Self {
63 line: cursor_point.line.0 + display_offset as i32,
64 col: cursor_point.column.0,
65 }
66 }
67
68 pub fn line(&self) -> i32 {
69 self.line
70 }
71
72 pub fn col(&self) -> usize {
73 self.col
74 }
75}
76
77#[derive(Debug, Default)]
78pub struct LayoutCell {
79 pub point: AlacPoint<i32, i32>,
80 text: gpui::ShapedLine,
81}
82
83impl LayoutCell {
84 fn new(point: AlacPoint<i32, i32>, text: gpui::ShapedLine) -> LayoutCell {
85 LayoutCell { point, text }
86 }
87
88 pub fn paint(
89 &self,
90 origin: Point<Pixels>,
91 dimensions: &TerminalBounds,
92 _visible_bounds: Bounds<Pixels>,
93 window: &mut Window,
94 cx: &mut App,
95 ) {
96 let pos = {
97 let point = self.point;
98
99 Point::new(
100 (origin.x + point.column as f32 * dimensions.cell_width).floor(),
101 origin.y + point.line as f32 * dimensions.line_height,
102 )
103 };
104
105 self.text
106 .paint(pos, dimensions.line_height, window, cx)
107 .ok();
108 }
109}
110
111#[derive(Clone, Debug, Default)]
112pub struct LayoutRect {
113 point: AlacPoint<i32, i32>,
114 num_of_cells: usize,
115 color: Hsla,
116}
117
118impl LayoutRect {
119 fn new(point: AlacPoint<i32, i32>, num_of_cells: usize, color: Hsla) -> LayoutRect {
120 LayoutRect {
121 point,
122 num_of_cells,
123 color,
124 }
125 }
126
127 fn extend(&self) -> Self {
128 LayoutRect {
129 point: self.point,
130 num_of_cells: self.num_of_cells + 1,
131 color: self.color,
132 }
133 }
134
135 pub fn paint(&self, origin: Point<Pixels>, dimensions: &TerminalBounds, window: &mut Window) {
136 let position = {
137 let alac_point = self.point;
138 point(
139 (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
140 origin.y + alac_point.line as f32 * dimensions.line_height,
141 )
142 };
143 let size = point(
144 (dimensions.cell_width * self.num_of_cells as f32).ceil(),
145 dimensions.line_height,
146 )
147 .into();
148
149 window.paint_quad(fill(Bounds::new(position, size), self.color));
150 }
151}
152
153/// The GPUI element that paints the terminal.
154/// 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?
155pub struct TerminalElement {
156 terminal: Entity<Terminal>,
157 terminal_view: Entity<TerminalView>,
158 workspace: WeakEntity<Workspace>,
159 focus: FocusHandle,
160 focused: bool,
161 cursor_visible: bool,
162 interactivity: Interactivity,
163 embedded: bool,
164 block_below_cursor: Option<Rc<BlockProperties>>,
165}
166
167impl InteractiveElement for TerminalElement {
168 fn interactivity(&mut self) -> &mut Interactivity {
169 &mut self.interactivity
170 }
171}
172
173impl StatefulInteractiveElement for TerminalElement {}
174
175impl TerminalElement {
176 pub fn new(
177 terminal: Entity<Terminal>,
178 terminal_view: Entity<TerminalView>,
179 workspace: WeakEntity<Workspace>,
180 focus: FocusHandle,
181 focused: bool,
182 cursor_visible: bool,
183 block_below_cursor: Option<Rc<BlockProperties>>,
184 embedded: bool,
185 ) -> TerminalElement {
186 TerminalElement {
187 terminal,
188 terminal_view,
189 workspace,
190 focused,
191 focus: focus.clone(),
192 cursor_visible,
193 block_below_cursor,
194 embedded,
195 interactivity: Default::default(),
196 }
197 .track_focus(&focus)
198 .element
199 }
200
201 //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
202
203 pub fn layout_grid(
204 grid: impl Iterator<Item = IndexedCell>,
205 text_style: &TextStyle,
206 // terminal_theme: &TerminalStyle,
207 text_system: &WindowTextSystem,
208 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
209 window: &Window,
210 cx: &App,
211 ) -> (Vec<LayoutCell>, Vec<LayoutRect>) {
212 let theme = cx.theme();
213 let mut cells = vec![];
214 let mut rects = vec![];
215
216 let mut cur_rect: Option<LayoutRect> = None;
217 let mut cur_alac_color = None;
218
219 let linegroups = grid.into_iter().chunk_by(|i| i.point.line);
220 for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
221 for cell in line {
222 let mut fg = cell.fg;
223 let mut bg = cell.bg;
224 if cell.flags.contains(Flags::INVERSE) {
225 mem::swap(&mut fg, &mut bg);
226 }
227
228 //Expand background rect range
229 {
230 if matches!(bg, Named(NamedColor::Background)) {
231 //Continue to next cell, resetting variables if necessary
232 cur_alac_color = None;
233 if let Some(rect) = cur_rect {
234 rects.push(rect);
235 cur_rect = None
236 }
237 } else {
238 match cur_alac_color {
239 Some(cur_color) => {
240 if bg == cur_color {
241 // `cur_rect` can be None if it was moved to the `rects` vec after wrapping around
242 // from one line to the next. The variables are all set correctly but there is no current
243 // rect, so we create one if necessary.
244 cur_rect = cur_rect.map_or_else(
245 || {
246 Some(LayoutRect::new(
247 AlacPoint::new(
248 line_index as i32,
249 cell.point.column.0 as i32,
250 ),
251 1,
252 convert_color(&bg, theme),
253 ))
254 },
255 |rect| Some(rect.extend()),
256 );
257 } else {
258 cur_alac_color = Some(bg);
259 if cur_rect.is_some() {
260 rects.push(cur_rect.take().unwrap());
261 }
262 cur_rect = Some(LayoutRect::new(
263 AlacPoint::new(
264 line_index as i32,
265 cell.point.column.0 as i32,
266 ),
267 1,
268 convert_color(&bg, theme),
269 ));
270 }
271 }
272 None => {
273 cur_alac_color = Some(bg);
274 cur_rect = Some(LayoutRect::new(
275 AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
276 1,
277 convert_color(&bg, theme),
278 ));
279 }
280 }
281 }
282 }
283
284 //Layout current cell text
285 {
286 if !is_blank(&cell) {
287 let cell_text = cell.c.to_string();
288 let cell_style =
289 TerminalElement::cell_style(&cell, fg, theme, text_style, hyperlink);
290
291 let layout_cell = text_system.shape_line(
292 cell_text.into(),
293 text_style.font_size.to_pixels(window.rem_size()),
294 &[cell_style],
295 );
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_tooltip) =
734 self.terminal.update(cx, |terminal, cx| {
735 terminal.set_size(dimensions);
736 terminal.sync(window, cx);
737
738 if window.modifiers().secondary()
739 && bounds.contains(&window.mouse_position())
740 && self.terminal_view.read(cx).hover.is_some()
741 {
742 let registered_hover = self.terminal_view.read(cx).hover.as_ref();
743 if terminal.last_content.last_hovered_word.as_ref()
744 == registered_hover.map(|hover| &hover.hovered_word)
745 {
746 (
747 terminal.last_content.last_hovered_word.clone(),
748 registered_hover.map(|hover| hover.tooltip.clone()),
749 )
750 } else {
751 (None, None)
752 }
753 } else {
754 (None, None)
755 }
756 });
757
758 let scroll_top = self.terminal_view.read(cx).scroll_top;
759 let hyperlink_tooltip = hover_tooltip.map(|hover_tooltip| {
760 let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
761 let mut element = div()
762 .size_full()
763 .id("terminal-element")
764 .tooltip(Tooltip::text(hover_tooltip))
765 .into_any_element();
766 element.prepaint_as_root(offset, bounds.size.into(), window, cx);
767 element
768 });
769
770 let TerminalContent {
771 cells,
772 mode,
773 display_offset,
774 cursor_char,
775 selection,
776 cursor,
777 ..
778 } = &self.terminal.read(cx).last_content;
779 let mode = *mode;
780 let display_offset = *display_offset;
781
782 // searches, highlights to a single range representations
783 let mut relative_highlighted_ranges = Vec::new();
784 for search_match in search_matches {
785 relative_highlighted_ranges.push((search_match, match_color))
786 }
787 if let Some(selection) = selection {
788 relative_highlighted_ranges
789 .push((selection.start..=selection.end, player_color.selection));
790 }
791
792 // then have that representation be converted to the appropriate highlight data structure
793
794 let (cells, rects) = TerminalElement::layout_grid(
795 cells.iter().cloned(),
796 &text_style,
797 window.text_system(),
798 last_hovered_word
799 .as_ref()
800 .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
801 window,
802 cx,
803 );
804
805 // Layout cursor. Rectangle is used for IME, so we should lay it out even
806 // if we don't end up showing it.
807 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
808 None
809 } else {
810 let cursor_point = DisplayCursor::from(cursor.point, display_offset);
811 let cursor_text = {
812 let str_trxt = cursor_char.to_string();
813 let len = str_trxt.len();
814 window.text_system().shape_line(
815 str_trxt.into(),
816 text_style.font_size.to_pixels(window.rem_size()),
817 &[TextRun {
818 len,
819 font: text_style.font(),
820 color: theme.colors().terminal_ansi_background,
821 background_color: None,
822 underline: Default::default(),
823 strikethrough: None,
824 }],
825 )
826 };
827
828 let focused = self.focused;
829 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
830 move |(cursor_position, block_width)| {
831 let (shape, text) = match cursor.shape {
832 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
833 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
834 AlacCursorShape::Underline => (CursorShape::Underline, None),
835 AlacCursorShape::Beam => (CursorShape::Bar, None),
836 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
837 //This case is handled in the if wrapping the whole cursor layout
838 AlacCursorShape::Hidden => unreachable!(),
839 };
840
841 CursorLayout::new(
842 cursor_position,
843 block_width,
844 dimensions.line_height,
845 theme.players().local().cursor,
846 shape,
847 text,
848 )
849 },
850 )
851 };
852
853 let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
854 let terminal = self.terminal.read(cx);
855 if terminal.last_content.display_offset == 0 {
856 let target_line = terminal.last_content.cursor.point.line.0 + 1;
857 let render = &block.render;
858 let mut block_cx = BlockContext {
859 window,
860 context: cx,
861 dimensions,
862 };
863 let element = render(&mut block_cx);
864 let mut element = div().occlude().child(element).into_any_element();
865 let available_space = size(
866 AvailableSpace::Definite(dimensions.width() + gutter),
867 AvailableSpace::Definite(
868 block.height as f32 * dimensions.line_height(),
869 ),
870 );
871 let origin = bounds.origin
872 + point(px(0.), target_line as f32 * dimensions.line_height())
873 - point(px(0.), scroll_top);
874 window.with_rem_size(rem_size, |window| {
875 element.prepaint_as_root(origin, available_space, window, cx);
876 });
877 Some(element)
878 } else {
879 None
880 }
881 } else {
882 None
883 };
884
885 LayoutState {
886 hitbox,
887 cells,
888 cursor,
889 background_color,
890 dimensions,
891 rects,
892 relative_highlighted_ranges,
893 mode,
894 display_offset,
895 hyperlink_tooltip,
896 gutter,
897 block_below_cursor_element,
898 base_text_style: text_style,
899 }
900 },
901 )
902 }
903
904 fn paint(
905 &mut self,
906 global_id: Option<&GlobalElementId>,
907 bounds: Bounds<Pixels>,
908 _: &mut Self::RequestLayoutState,
909 layout: &mut Self::PrepaintState,
910 window: &mut Window,
911 cx: &mut App,
912 ) {
913 window.with_content_mask(Some(ContentMask { bounds }), |window| {
914 let scroll_top = self.terminal_view.read(cx).scroll_top;
915
916 window.paint_quad(fill(bounds, layout.background_color));
917 let origin =
918 bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
919
920 let marked_text_cloned: Option<String> = {
921 let ime_state = self.terminal_view.read(cx);
922 ime_state.marked_text.clone()
923 };
924
925 let terminal_input_handler = TerminalInputHandler {
926 terminal: self.terminal.clone(),
927 terminal_view: self.terminal_view.clone(),
928 cursor_bounds: layout
929 .cursor
930 .as_ref()
931 .map(|cursor| cursor.bounding_rect(origin)),
932 workspace: self.workspace.clone(),
933 };
934
935 self.register_mouse_listeners(layout.mode, &layout.hitbox, window);
936 if window.modifiers().secondary()
937 && bounds.contains(&window.mouse_position())
938 && self.terminal_view.read(cx).hover.is_some()
939 {
940 window.set_cursor_style(gpui::CursorStyle::PointingHand, Some(&layout.hitbox));
941 } else {
942 window.set_cursor_style(gpui::CursorStyle::IBeam, Some(&layout.hitbox));
943 }
944
945 let original_cursor = layout.cursor.take();
946 let hyperlink_tooltip = layout.hyperlink_tooltip.take();
947 let block_below_cursor_element = layout.block_below_cursor_element.take();
948 self.interactivity.paint(
949 global_id,
950 bounds,
951 Some(&layout.hitbox),
952 window,
953 cx,
954 |_, window, cx| {
955 window.handle_input(&self.focus, terminal_input_handler, cx);
956
957 window.on_key_event({
958 let this = self.terminal.clone();
959 move |event: &ModifiersChangedEvent, phase, window, cx| {
960 if phase != DispatchPhase::Bubble {
961 return;
962 }
963
964 this.update(cx, |term, cx| {
965 term.try_modifiers_change(&event.modifiers, window, cx)
966 });
967 }
968 });
969
970 for rect in &layout.rects {
971 rect.paint(origin, &layout.dimensions, window);
972 }
973
974 for (relative_highlighted_range, color) in
975 layout.relative_highlighted_ranges.iter()
976 {
977 if let Some((start_y, highlighted_range_lines)) =
978 to_highlighted_range_lines(relative_highlighted_range, layout, origin)
979 {
980 let hr = HighlightedRange {
981 start_y,
982 line_height: layout.dimensions.line_height,
983 lines: highlighted_range_lines,
984 color: *color,
985 corner_radius: 0.15 * layout.dimensions.line_height,
986 };
987 hr.paint(bounds, window);
988 }
989 }
990
991 for cell in &layout.cells {
992 cell.paint(origin, &layout.dimensions, bounds, window, cx);
993 }
994
995 if let Some(text_to_mark) = &marked_text_cloned {
996 if !text_to_mark.is_empty() {
997 if let Some(cursor_layout) = &original_cursor {
998 let ime_position = cursor_layout.bounding_rect(origin).origin;
999 let mut ime_style = layout.base_text_style.clone();
1000 ime_style.underline = Some(UnderlineStyle {
1001 color: Some(ime_style.color),
1002 thickness: px(1.0),
1003 wavy: false,
1004 });
1005
1006 let shaped_line = window.text_system().shape_line(
1007 text_to_mark.clone().into(),
1008 ime_style.font_size.to_pixels(window.rem_size()),
1009 &[TextRun {
1010 len: text_to_mark.len(),
1011 font: ime_style.font(),
1012 color: ime_style.color,
1013 background_color: None,
1014 underline: ime_style.underline,
1015 strikethrough: None,
1016 }],
1017 );
1018 shaped_line
1019 .paint(ime_position, layout.dimensions.line_height, window, cx)
1020 .log_err();
1021 }
1022 }
1023 }
1024
1025 if self.cursor_visible && marked_text_cloned.is_none() {
1026 if let Some(mut cursor) = original_cursor {
1027 cursor.paint(origin, window, cx);
1028 }
1029 }
1030
1031 if let Some(mut element) = block_below_cursor_element {
1032 element.paint(window, cx);
1033 }
1034
1035 if let Some(mut element) = hyperlink_tooltip {
1036 element.paint(window, cx);
1037 }
1038 },
1039 );
1040 });
1041 }
1042}
1043
1044impl IntoElement for TerminalElement {
1045 type Element = Self;
1046
1047 fn into_element(self) -> Self::Element {
1048 self
1049 }
1050}
1051
1052struct TerminalInputHandler {
1053 terminal: Entity<Terminal>,
1054 terminal_view: Entity<TerminalView>,
1055 workspace: WeakEntity<Workspace>,
1056 cursor_bounds: Option<Bounds<Pixels>>,
1057}
1058
1059impl InputHandler for TerminalInputHandler {
1060 fn selected_text_range(
1061 &mut self,
1062 _ignore_disabled_input: bool,
1063 _: &mut Window,
1064 cx: &mut App,
1065 ) -> Option<UTF16Selection> {
1066 if self
1067 .terminal
1068 .read(cx)
1069 .last_content
1070 .mode
1071 .contains(TermMode::ALT_SCREEN)
1072 {
1073 None
1074 } else {
1075 Some(UTF16Selection {
1076 range: 0..0,
1077 reversed: false,
1078 })
1079 }
1080 }
1081
1082 fn marked_text_range(
1083 &mut self,
1084 _window: &mut Window,
1085 cx: &mut App,
1086 ) -> Option<std::ops::Range<usize>> {
1087 self.terminal_view.read(cx).marked_text_range()
1088 }
1089
1090 fn text_for_range(
1091 &mut self,
1092 _: std::ops::Range<usize>,
1093 _: &mut Option<std::ops::Range<usize>>,
1094 _: &mut Window,
1095 _: &mut App,
1096 ) -> Option<String> {
1097 None
1098 }
1099
1100 fn replace_text_in_range(
1101 &mut self,
1102 _replacement_range: Option<std::ops::Range<usize>>,
1103 text: &str,
1104 window: &mut Window,
1105 cx: &mut App,
1106 ) {
1107 self.terminal_view.update(cx, |view, view_cx| {
1108 view.clear_marked_text(view_cx);
1109 view.commit_text(text, view_cx);
1110 });
1111
1112 self.workspace
1113 .update(cx, |this, cx| {
1114 window.invalidate_character_coordinates();
1115 let project = this.project().read(cx);
1116 let telemetry = project.client().telemetry().clone();
1117 telemetry.log_edit_event("terminal", project.is_via_ssh());
1118 })
1119 .ok();
1120 }
1121
1122 fn replace_and_mark_text_in_range(
1123 &mut self,
1124 _range_utf16: Option<std::ops::Range<usize>>,
1125 new_text: &str,
1126 new_marked_range: Option<std::ops::Range<usize>>,
1127 _window: &mut Window,
1128 cx: &mut App,
1129 ) {
1130 if let Some(range) = new_marked_range {
1131 self.terminal_view.update(cx, |view, view_cx| {
1132 view.set_marked_text(new_text.to_string(), range, view_cx);
1133 });
1134 }
1135 }
1136
1137 fn unmark_text(&mut self, _window: &mut Window, cx: &mut App) {
1138 self.terminal_view.update(cx, |view, view_cx| {
1139 view.clear_marked_text(view_cx);
1140 });
1141 }
1142
1143 fn bounds_for_range(
1144 &mut self,
1145 range_utf16: std::ops::Range<usize>,
1146 _window: &mut Window,
1147 cx: &mut App,
1148 ) -> Option<Bounds<Pixels>> {
1149 let term_bounds = self.terminal_view.read(cx).terminal_bounds(cx);
1150
1151 let mut bounds = self.cursor_bounds?;
1152 let offset_x = term_bounds.cell_width * range_utf16.start as f32;
1153 bounds.origin.x += offset_x;
1154
1155 Some(bounds)
1156 }
1157
1158 fn apple_press_and_hold_enabled(&mut self) -> bool {
1159 false
1160 }
1161
1162 fn character_index_for_point(
1163 &mut self,
1164 _point: Point<Pixels>,
1165 _window: &mut Window,
1166 _cx: &mut App,
1167 ) -> Option<usize> {
1168 None
1169 }
1170}
1171
1172pub fn is_blank(cell: &IndexedCell) -> bool {
1173 if cell.c != ' ' {
1174 return false;
1175 }
1176
1177 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1178 return false;
1179 }
1180
1181 if cell.hyperlink().is_some() {
1182 return false;
1183 }
1184
1185 if cell
1186 .flags
1187 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1188 {
1189 return false;
1190 }
1191
1192 true
1193}
1194
1195fn to_highlighted_range_lines(
1196 range: &RangeInclusive<AlacPoint>,
1197 layout: &LayoutState,
1198 origin: Point<Pixels>,
1199) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1200 // Step 1. Normalize the points to be viewport relative.
1201 // When display_offset = 1, here's how the grid is arranged:
1202 //-2,0 -2,1...
1203 //--- Viewport top
1204 //-1,0 -1,1...
1205 //--------- Terminal Top
1206 // 0,0 0,1...
1207 // 1,0 1,1...
1208 //--- Viewport Bottom
1209 // 2,0 2,1...
1210 //--------- Terminal Bottom
1211
1212 // Normalize to viewport relative, from terminal relative.
1213 // lines are i32s, which are negative above the top left corner of the terminal
1214 // If the user has scrolled, we use the display_offset to tell us which offset
1215 // of the grid data we should be looking at. But for the rendering step, we don't
1216 // want negatives. We want things relative to the 'viewport' (the area of the grid
1217 // which is currently shown according to the display offset)
1218 let unclamped_start = AlacPoint::new(
1219 range.start().line + layout.display_offset,
1220 range.start().column,
1221 );
1222 let unclamped_end =
1223 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1224
1225 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1226 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1227 return None;
1228 }
1229
1230 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1231 let clamped_end_line = unclamped_end
1232 .line
1233 .0
1234 .min(layout.dimensions.num_lines() as i32) as usize;
1235 //Convert the start of the range to pixels
1236 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1237
1238 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1239 // (also convert to pixels)
1240 let mut highlighted_range_lines = Vec::new();
1241 for line in clamped_start_line..=clamped_end_line {
1242 let mut line_start = 0;
1243 let mut line_end = layout.dimensions.columns();
1244
1245 if line == clamped_start_line {
1246 line_start = unclamped_start.column.0;
1247 }
1248 if line == clamped_end_line {
1249 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1250 }
1251
1252 highlighted_range_lines.push(HighlightedRangeLine {
1253 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1254 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1255 });
1256 }
1257
1258 Some((start_y, highlighted_range_lines))
1259}
1260
1261/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1262pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1263 let colors = theme.colors();
1264 match fg {
1265 // Named and theme defined colors
1266 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1267 NamedColor::Black => colors.terminal_ansi_black,
1268 NamedColor::Red => colors.terminal_ansi_red,
1269 NamedColor::Green => colors.terminal_ansi_green,
1270 NamedColor::Yellow => colors.terminal_ansi_yellow,
1271 NamedColor::Blue => colors.terminal_ansi_blue,
1272 NamedColor::Magenta => colors.terminal_ansi_magenta,
1273 NamedColor::Cyan => colors.terminal_ansi_cyan,
1274 NamedColor::White => colors.terminal_ansi_white,
1275 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1276 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1277 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1278 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1279 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1280 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1281 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1282 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1283 NamedColor::Foreground => colors.terminal_foreground,
1284 NamedColor::Background => colors.terminal_ansi_background,
1285 NamedColor::Cursor => theme.players().local().cursor,
1286 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1287 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1288 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1289 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1290 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1291 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1292 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1293 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1294 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1295 NamedColor::DimForeground => colors.terminal_dim_foreground,
1296 },
1297 // 'True' colors
1298 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1299 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1300 }
1301 // 8 bit, indexed colors
1302 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1303 terminal::get_color_at_index(*i as usize, theme)
1304 }
1305 }
1306}