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