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