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 source_location(&self) -> Option<&'static core::panic::Location<'static>> {
585 None
586 }
587
588 fn request_layout(
589 &mut self,
590 global_id: Option<&GlobalElementId>,
591 inspector_id: Option<&gpui::InspectorElementId>,
592 window: &mut Window,
593 cx: &mut App,
594 ) -> (LayoutId, Self::RequestLayoutState) {
595 if self.embedded {
596 let scrollable = {
597 let term = self.terminal.read(cx);
598 !term.scrolled_to_top() && !term.scrolled_to_bottom() && self.focused
599 };
600 if scrollable {
601 self.interactivity.occlude_mouse();
602 }
603 }
604
605 let layout_id = self.interactivity.request_layout(
606 global_id,
607 inspector_id,
608 window,
609 cx,
610 |mut style, window, cx| {
611 style.size.width = relative(1.).into();
612 style.size.height = relative(1.).into();
613 // style.overflow = point(Overflow::Hidden, Overflow::Hidden);
614
615 window.request_layout(style, None, cx)
616 },
617 );
618 (layout_id, ())
619 }
620
621 fn prepaint(
622 &mut self,
623 global_id: Option<&GlobalElementId>,
624 inspector_id: Option<&gpui::InspectorElementId>,
625 bounds: Bounds<Pixels>,
626 _: &mut Self::RequestLayoutState,
627 window: &mut Window,
628 cx: &mut App,
629 ) -> Self::PrepaintState {
630 let rem_size = self.rem_size(cx);
631 self.interactivity.prepaint(
632 global_id,
633 inspector_id,
634 bounds,
635 bounds.size,
636 window,
637 cx,
638 |_, _, hitbox, window, cx| {
639 let hitbox = hitbox.unwrap();
640 let settings = ThemeSettings::get_global(cx).clone();
641
642 let buffer_font_size = settings.buffer_font_size(cx);
643
644 let terminal_settings = TerminalSettings::get_global(cx);
645
646 let font_family = terminal_settings
647 .font_family
648 .as_ref()
649 .unwrap_or(&settings.buffer_font.family)
650 .clone();
651
652 let font_fallbacks = terminal_settings
653 .font_fallbacks
654 .as_ref()
655 .or(settings.buffer_font.fallbacks.as_ref())
656 .cloned();
657
658 let font_features = terminal_settings
659 .font_features
660 .as_ref()
661 .unwrap_or(&settings.buffer_font.features)
662 .clone();
663
664 let font_weight = terminal_settings.font_weight.unwrap_or_default();
665
666 let line_height = terminal_settings.line_height.value();
667
668 let font_size = if self.embedded {
669 window.text_style().font_size.to_pixels(window.rem_size())
670 } else {
671 terminal_settings
672 .font_size
673 .map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx))
674 };
675
676 let theme = cx.theme().clone();
677
678 let link_style = HighlightStyle {
679 color: Some(theme.colors().link_text_hover),
680 font_weight: Some(font_weight),
681 font_style: None,
682 background_color: None,
683 underline: Some(UnderlineStyle {
684 thickness: px(1.0),
685 color: Some(theme.colors().link_text_hover),
686 wavy: false,
687 }),
688 strikethrough: None,
689 fade_out: None,
690 };
691
692 let text_style = TextStyle {
693 font_family,
694 font_features,
695 font_weight,
696 font_fallbacks,
697 font_size: font_size.into(),
698 font_style: FontStyle::Normal,
699 line_height: line_height.into(),
700 background_color: Some(theme.colors().terminal_ansi_background),
701 white_space: WhiteSpace::Normal,
702 // These are going to be overridden per-cell
703 color: theme.colors().terminal_foreground,
704 ..Default::default()
705 };
706
707 let text_system = cx.text_system();
708 let player_color = theme.players().local();
709 let match_color = theme.colors().search_match_background;
710 let gutter;
711 let dimensions = {
712 let rem_size = window.rem_size();
713 let font_pixels = text_style.font_size.to_pixels(rem_size);
714 // TODO: line_height should be an f32 not an AbsoluteLength.
715 let line_height = font_pixels * line_height.to_pixels(rem_size).0;
716 let font_id = cx.text_system().resolve_font(&text_style.font());
717
718 let cell_width = text_system
719 .advance(font_id, font_pixels, 'm')
720 .unwrap()
721 .width;
722 gutter = cell_width;
723
724 let mut size = bounds.size;
725 size.width -= gutter;
726
727 // https://github.com/zed-industries/zed/issues/2750
728 // if the terminal is one column wide, rendering 🦀
729 // causes alacritty to misbehave.
730 if size.width < cell_width * 2.0 {
731 size.width = cell_width * 2.0;
732 }
733
734 let mut origin = bounds.origin;
735 origin.x += gutter;
736
737 TerminalBounds::new(line_height, cell_width, Bounds { origin, size })
738 };
739
740 let search_matches = self.terminal.read(cx).matches.clone();
741
742 let background_color = theme.colors().terminal_background;
743
744 let (last_hovered_word, hover_tooltip) =
745 self.terminal.update(cx, |terminal, cx| {
746 terminal.set_size(dimensions);
747 terminal.sync(window, cx);
748
749 if window.modifiers().secondary()
750 && bounds.contains(&window.mouse_position())
751 && self.terminal_view.read(cx).hover.is_some()
752 {
753 let registered_hover = self.terminal_view.read(cx).hover.as_ref();
754 if terminal.last_content.last_hovered_word.as_ref()
755 == registered_hover.map(|hover| &hover.hovered_word)
756 {
757 (
758 terminal.last_content.last_hovered_word.clone(),
759 registered_hover.map(|hover| hover.tooltip.clone()),
760 )
761 } else {
762 (None, None)
763 }
764 } else {
765 (None, None)
766 }
767 });
768
769 let scroll_top = self.terminal_view.read(cx).scroll_top;
770 let hyperlink_tooltip = hover_tooltip.map(|hover_tooltip| {
771 let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
772 let mut element = div()
773 .size_full()
774 .id("terminal-element")
775 .tooltip(Tooltip::text(hover_tooltip))
776 .into_any_element();
777 element.prepaint_as_root(offset, bounds.size.into(), window, cx);
778 element
779 });
780
781 let TerminalContent {
782 cells,
783 mode,
784 display_offset,
785 cursor_char,
786 selection,
787 cursor,
788 ..
789 } = &self.terminal.read(cx).last_content;
790 let mode = *mode;
791 let display_offset = *display_offset;
792
793 // searches, highlights to a single range representations
794 let mut relative_highlighted_ranges = Vec::new();
795 for search_match in search_matches {
796 relative_highlighted_ranges.push((search_match, match_color))
797 }
798 if let Some(selection) = selection {
799 relative_highlighted_ranges
800 .push((selection.start..=selection.end, player_color.selection));
801 }
802
803 // then have that representation be converted to the appropriate highlight data structure
804
805 let (cells, rects) = TerminalElement::layout_grid(
806 cells.iter().cloned(),
807 &text_style,
808 window.text_system(),
809 last_hovered_word
810 .as_ref()
811 .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
812 window,
813 cx,
814 );
815
816 // Layout cursor. Rectangle is used for IME, so we should lay it out even
817 // if we don't end up showing it.
818 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
819 None
820 } else {
821 let cursor_point = DisplayCursor::from(cursor.point, display_offset);
822 let cursor_text = {
823 let str_trxt = cursor_char.to_string();
824 let len = str_trxt.len();
825 window.text_system().shape_line(
826 str_trxt.into(),
827 text_style.font_size.to_pixels(window.rem_size()),
828 &[TextRun {
829 len,
830 font: text_style.font(),
831 color: theme.colors().terminal_ansi_background,
832 background_color: None,
833 underline: Default::default(),
834 strikethrough: None,
835 }],
836 )
837 };
838
839 let focused = self.focused;
840 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
841 move |(cursor_position, block_width)| {
842 let (shape, text) = match cursor.shape {
843 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
844 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
845 AlacCursorShape::Underline => (CursorShape::Underline, None),
846 AlacCursorShape::Beam => (CursorShape::Bar, None),
847 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
848 //This case is handled in the if wrapping the whole cursor layout
849 AlacCursorShape::Hidden => unreachable!(),
850 };
851
852 CursorLayout::new(
853 cursor_position,
854 block_width,
855 dimensions.line_height,
856 theme.players().local().cursor,
857 shape,
858 text,
859 )
860 },
861 )
862 };
863
864 let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
865 let terminal = self.terminal.read(cx);
866 if terminal.last_content.display_offset == 0 {
867 let target_line = terminal.last_content.cursor.point.line.0 + 1;
868 let render = &block.render;
869 let mut block_cx = BlockContext {
870 window,
871 context: cx,
872 dimensions,
873 };
874 let element = render(&mut block_cx);
875 let mut element = div().occlude().child(element).into_any_element();
876 let available_space = size(
877 AvailableSpace::Definite(dimensions.width() + gutter),
878 AvailableSpace::Definite(
879 block.height as f32 * dimensions.line_height(),
880 ),
881 );
882 let origin = bounds.origin
883 + point(px(0.), target_line as f32 * dimensions.line_height())
884 - point(px(0.), scroll_top);
885 window.with_rem_size(rem_size, |window| {
886 element.prepaint_as_root(origin, available_space, window, cx);
887 });
888 Some(element)
889 } else {
890 None
891 }
892 } else {
893 None
894 };
895
896 LayoutState {
897 hitbox,
898 cells,
899 cursor,
900 background_color,
901 dimensions,
902 rects,
903 relative_highlighted_ranges,
904 mode,
905 display_offset,
906 hyperlink_tooltip,
907 gutter,
908 block_below_cursor_element,
909 base_text_style: text_style,
910 }
911 },
912 )
913 }
914
915 fn paint(
916 &mut self,
917 global_id: Option<&GlobalElementId>,
918 inspector_id: Option<&gpui::InspectorElementId>,
919 bounds: Bounds<Pixels>,
920 _: &mut Self::RequestLayoutState,
921 layout: &mut Self::PrepaintState,
922 window: &mut Window,
923 cx: &mut App,
924 ) {
925 window.with_content_mask(Some(ContentMask { bounds }), |window| {
926 let scroll_top = self.terminal_view.read(cx).scroll_top;
927
928 window.paint_quad(fill(bounds, layout.background_color));
929 let origin =
930 bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
931
932 let marked_text_cloned: Option<String> = {
933 let ime_state = self.terminal_view.read(cx);
934 ime_state.marked_text.clone()
935 };
936
937 let terminal_input_handler = TerminalInputHandler {
938 terminal: self.terminal.clone(),
939 terminal_view: self.terminal_view.clone(),
940 cursor_bounds: layout
941 .cursor
942 .as_ref()
943 .map(|cursor| cursor.bounding_rect(origin)),
944 workspace: self.workspace.clone(),
945 };
946
947 self.register_mouse_listeners(layout.mode, &layout.hitbox, window);
948 if window.modifiers().secondary()
949 && bounds.contains(&window.mouse_position())
950 && self.terminal_view.read(cx).hover.is_some()
951 {
952 window.set_cursor_style(gpui::CursorStyle::PointingHand, Some(&layout.hitbox));
953 } else {
954 window.set_cursor_style(gpui::CursorStyle::IBeam, Some(&layout.hitbox));
955 }
956
957 let original_cursor = layout.cursor.take();
958 let hyperlink_tooltip = layout.hyperlink_tooltip.take();
959 let block_below_cursor_element = layout.block_below_cursor_element.take();
960 self.interactivity.paint(
961 global_id,
962 inspector_id,
963 bounds,
964 Some(&layout.hitbox),
965 window,
966 cx,
967 |_, window, cx| {
968 window.handle_input(&self.focus, terminal_input_handler, cx);
969
970 window.on_key_event({
971 let this = self.terminal.clone();
972 move |event: &ModifiersChangedEvent, phase, window, cx| {
973 if phase != DispatchPhase::Bubble {
974 return;
975 }
976
977 this.update(cx, |term, cx| {
978 term.try_modifiers_change(&event.modifiers, window, cx)
979 });
980 }
981 });
982
983 for rect in &layout.rects {
984 rect.paint(origin, &layout.dimensions, window);
985 }
986
987 for (relative_highlighted_range, color) in
988 layout.relative_highlighted_ranges.iter()
989 {
990 if let Some((start_y, highlighted_range_lines)) =
991 to_highlighted_range_lines(relative_highlighted_range, layout, origin)
992 {
993 let hr = HighlightedRange {
994 start_y,
995 line_height: layout.dimensions.line_height,
996 lines: highlighted_range_lines,
997 color: *color,
998 corner_radius: 0.15 * layout.dimensions.line_height,
999 };
1000 hr.paint(bounds, window);
1001 }
1002 }
1003
1004 for cell in &layout.cells {
1005 cell.paint(origin, &layout.dimensions, bounds, window, cx);
1006 }
1007
1008 if let Some(text_to_mark) = &marked_text_cloned {
1009 if !text_to_mark.is_empty() {
1010 if let Some(cursor_layout) = &original_cursor {
1011 let ime_position = cursor_layout.bounding_rect(origin).origin;
1012 let mut ime_style = layout.base_text_style.clone();
1013 ime_style.underline = Some(UnderlineStyle {
1014 color: Some(ime_style.color),
1015 thickness: px(1.0),
1016 wavy: false,
1017 });
1018
1019 let shaped_line = window.text_system().shape_line(
1020 text_to_mark.clone().into(),
1021 ime_style.font_size.to_pixels(window.rem_size()),
1022 &[TextRun {
1023 len: text_to_mark.len(),
1024 font: ime_style.font(),
1025 color: ime_style.color,
1026 background_color: None,
1027 underline: ime_style.underline,
1028 strikethrough: None,
1029 }],
1030 );
1031 shaped_line
1032 .paint(ime_position, layout.dimensions.line_height, window, cx)
1033 .log_err();
1034 }
1035 }
1036 }
1037
1038 if self.cursor_visible && marked_text_cloned.is_none() {
1039 if let Some(mut cursor) = original_cursor {
1040 cursor.paint(origin, window, cx);
1041 }
1042 }
1043
1044 if let Some(mut element) = block_below_cursor_element {
1045 element.paint(window, cx);
1046 }
1047
1048 if let Some(mut element) = hyperlink_tooltip {
1049 element.paint(window, cx);
1050 }
1051 },
1052 );
1053 });
1054 }
1055}
1056
1057impl IntoElement for TerminalElement {
1058 type Element = Self;
1059
1060 fn into_element(self) -> Self::Element {
1061 self
1062 }
1063}
1064
1065struct TerminalInputHandler {
1066 terminal: Entity<Terminal>,
1067 terminal_view: Entity<TerminalView>,
1068 workspace: WeakEntity<Workspace>,
1069 cursor_bounds: Option<Bounds<Pixels>>,
1070}
1071
1072impl InputHandler for TerminalInputHandler {
1073 fn selected_text_range(
1074 &mut self,
1075 _ignore_disabled_input: bool,
1076 _: &mut Window,
1077 cx: &mut App,
1078 ) -> Option<UTF16Selection> {
1079 if self
1080 .terminal
1081 .read(cx)
1082 .last_content
1083 .mode
1084 .contains(TermMode::ALT_SCREEN)
1085 {
1086 None
1087 } else {
1088 Some(UTF16Selection {
1089 range: 0..0,
1090 reversed: false,
1091 })
1092 }
1093 }
1094
1095 fn marked_text_range(
1096 &mut self,
1097 _window: &mut Window,
1098 cx: &mut App,
1099 ) -> Option<std::ops::Range<usize>> {
1100 self.terminal_view.read(cx).marked_text_range()
1101 }
1102
1103 fn text_for_range(
1104 &mut self,
1105 _: std::ops::Range<usize>,
1106 _: &mut Option<std::ops::Range<usize>>,
1107 _: &mut Window,
1108 _: &mut App,
1109 ) -> Option<String> {
1110 None
1111 }
1112
1113 fn replace_text_in_range(
1114 &mut self,
1115 _replacement_range: Option<std::ops::Range<usize>>,
1116 text: &str,
1117 window: &mut Window,
1118 cx: &mut App,
1119 ) {
1120 self.terminal_view.update(cx, |view, view_cx| {
1121 view.clear_marked_text(view_cx);
1122 view.commit_text(text, view_cx);
1123 });
1124
1125 self.workspace
1126 .update(cx, |this, cx| {
1127 window.invalidate_character_coordinates();
1128 let project = this.project().read(cx);
1129 let telemetry = project.client().telemetry().clone();
1130 telemetry.log_edit_event("terminal", project.is_via_ssh());
1131 })
1132 .ok();
1133 }
1134
1135 fn replace_and_mark_text_in_range(
1136 &mut self,
1137 _range_utf16: Option<std::ops::Range<usize>>,
1138 new_text: &str,
1139 new_marked_range: Option<std::ops::Range<usize>>,
1140 _window: &mut Window,
1141 cx: &mut App,
1142 ) {
1143 if let Some(range) = new_marked_range {
1144 self.terminal_view.update(cx, |view, view_cx| {
1145 view.set_marked_text(new_text.to_string(), range, view_cx);
1146 });
1147 }
1148 }
1149
1150 fn unmark_text(&mut self, _window: &mut Window, cx: &mut App) {
1151 self.terminal_view.update(cx, |view, view_cx| {
1152 view.clear_marked_text(view_cx);
1153 });
1154 }
1155
1156 fn bounds_for_range(
1157 &mut self,
1158 range_utf16: std::ops::Range<usize>,
1159 _window: &mut Window,
1160 cx: &mut App,
1161 ) -> Option<Bounds<Pixels>> {
1162 let term_bounds = self.terminal_view.read(cx).terminal_bounds(cx);
1163
1164 let mut bounds = self.cursor_bounds?;
1165 let offset_x = term_bounds.cell_width * range_utf16.start as f32;
1166 bounds.origin.x += offset_x;
1167
1168 Some(bounds)
1169 }
1170
1171 fn apple_press_and_hold_enabled(&mut self) -> bool {
1172 false
1173 }
1174
1175 fn character_index_for_point(
1176 &mut self,
1177 _point: Point<Pixels>,
1178 _window: &mut Window,
1179 _cx: &mut App,
1180 ) -> Option<usize> {
1181 None
1182 }
1183}
1184
1185pub fn is_blank(cell: &IndexedCell) -> bool {
1186 if cell.c != ' ' {
1187 return false;
1188 }
1189
1190 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1191 return false;
1192 }
1193
1194 if cell.hyperlink().is_some() {
1195 return false;
1196 }
1197
1198 if cell
1199 .flags
1200 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1201 {
1202 return false;
1203 }
1204
1205 true
1206}
1207
1208fn to_highlighted_range_lines(
1209 range: &RangeInclusive<AlacPoint>,
1210 layout: &LayoutState,
1211 origin: Point<Pixels>,
1212) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1213 // Step 1. Normalize the points to be viewport relative.
1214 // When display_offset = 1, here's how the grid is arranged:
1215 //-2,0 -2,1...
1216 //--- Viewport top
1217 //-1,0 -1,1...
1218 //--------- Terminal Top
1219 // 0,0 0,1...
1220 // 1,0 1,1...
1221 //--- Viewport Bottom
1222 // 2,0 2,1...
1223 //--------- Terminal Bottom
1224
1225 // Normalize to viewport relative, from terminal relative.
1226 // lines are i32s, which are negative above the top left corner of the terminal
1227 // If the user has scrolled, we use the display_offset to tell us which offset
1228 // of the grid data we should be looking at. But for the rendering step, we don't
1229 // want negatives. We want things relative to the 'viewport' (the area of the grid
1230 // which is currently shown according to the display offset)
1231 let unclamped_start = AlacPoint::new(
1232 range.start().line + layout.display_offset,
1233 range.start().column,
1234 );
1235 let unclamped_end =
1236 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1237
1238 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1239 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1240 return None;
1241 }
1242
1243 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1244 let clamped_end_line = unclamped_end
1245 .line
1246 .0
1247 .min(layout.dimensions.num_lines() as i32) as usize;
1248 //Convert the start of the range to pixels
1249 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1250
1251 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1252 // (also convert to pixels)
1253 let mut highlighted_range_lines = Vec::new();
1254 for line in clamped_start_line..=clamped_end_line {
1255 let mut line_start = 0;
1256 let mut line_end = layout.dimensions.columns();
1257
1258 if line == clamped_start_line {
1259 line_start = unclamped_start.column.0;
1260 }
1261 if line == clamped_end_line {
1262 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1263 }
1264
1265 highlighted_range_lines.push(HighlightedRangeLine {
1266 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1267 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1268 });
1269 }
1270
1271 Some((start_y, highlighted_range_lines))
1272}
1273
1274/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1275pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1276 let colors = theme.colors();
1277 match fg {
1278 // Named and theme defined colors
1279 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1280 NamedColor::Black => colors.terminal_ansi_black,
1281 NamedColor::Red => colors.terminal_ansi_red,
1282 NamedColor::Green => colors.terminal_ansi_green,
1283 NamedColor::Yellow => colors.terminal_ansi_yellow,
1284 NamedColor::Blue => colors.terminal_ansi_blue,
1285 NamedColor::Magenta => colors.terminal_ansi_magenta,
1286 NamedColor::Cyan => colors.terminal_ansi_cyan,
1287 NamedColor::White => colors.terminal_ansi_white,
1288 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1289 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1290 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1291 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1292 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1293 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1294 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1295 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1296 NamedColor::Foreground => colors.terminal_foreground,
1297 NamedColor::Background => colors.terminal_ansi_background,
1298 NamedColor::Cursor => theme.players().local().cursor,
1299 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1300 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1301 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1302 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1303 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1304 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1305 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1306 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1307 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1308 NamedColor::DimForeground => colors.terminal_dim_foreground,
1309 },
1310 // 'True' colors
1311 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1312 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1313 }
1314 // 8 bit, indexed colors
1315 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1316 terminal::get_color_at_index(*i as usize, theme)
1317 }
1318 }
1319}