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