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