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