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