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
685 .font_family
686 .as_ref()
687 .unwrap_or(&settings.buffer_font.family)
688 .clone();
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}