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 UTF16Selection, 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::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: 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)]
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: &TerminalSize,
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 * dimensions.cell_width).floor(),
98 origin.y + point.line as f32 * dimensions.line_height,
99 )
100 };
101
102 self.text.paint(pos, dimensions.line_height, cx).ok();
103 }
104}
105
106#[derive(Clone, Debug, Default)]
107pub struct 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 pub fn paint(&self, origin: Point<Pixels>, dimensions: &TerminalSize, cx: &mut WindowContext) {
131 let position = {
132 let alac_point = self.point;
133 point(
134 (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
135 origin.y + alac_point.line as f32 * dimensions.line_height,
136 )
137 };
138 let size = point(
139 (dimensions.cell_width * self.num_of_cells as f32).ceil(),
140 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<Rc<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<Rc<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 pub fn layout_grid(
200 grid: impl Iterator<Item = 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().chunk_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
618 let font_family = terminal_settings
619 .font_family
620 .as_ref()
621 .unwrap_or(&settings.buffer_font.family)
622 .clone();
623
624 let font_fallbacks = terminal_settings
625 .font_fallbacks
626 .as_ref()
627 .or(settings.buffer_font.fallbacks.as_ref())
628 .map(|fallbacks| fallbacks.clone());
629
630 let font_features = terminal_settings
631 .font_features
632 .as_ref()
633 .unwrap_or(&settings.buffer_font.features)
634 .clone();
635
636 let font_weight = terminal_settings.font_weight.unwrap_or_default();
637
638 let line_height = terminal_settings.line_height.value();
639 let font_size = terminal_settings.font_size;
640
641 let font_size =
642 font_size.map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx));
643
644 let theme = cx.theme().clone();
645
646 let link_style = HighlightStyle {
647 color: Some(theme.colors().link_text_hover),
648 font_weight: Some(font_weight),
649 font_style: None,
650 background_color: None,
651 underline: Some(UnderlineStyle {
652 thickness: px(1.0),
653 color: Some(theme.colors().link_text_hover),
654 wavy: false,
655 }),
656 strikethrough: None,
657 fade_out: None,
658 };
659
660 let text_style = TextStyle {
661 font_family,
662 font_features,
663 font_weight,
664 font_fallbacks,
665 font_size: font_size.into(),
666 font_style: FontStyle::Normal,
667 line_height: line_height.into(),
668 background_color: Some(theme.colors().terminal_background),
669 white_space: WhiteSpace::Normal,
670 truncate: None,
671 // These are going to be overridden per-cell
672 underline: None,
673 strikethrough: None,
674 color: theme.colors().terminal_foreground,
675 };
676
677 let text_system = cx.text_system();
678 let player_color = theme.players().local();
679 let match_color = theme.colors().search_match_background;
680 let gutter;
681 let dimensions = {
682 let rem_size = cx.rem_size();
683 let font_pixels = text_style.font_size.to_pixels(rem_size);
684 let line_height = font_pixels * line_height.to_pixels(rem_size);
685 let font_id = cx.text_system().resolve_font(&text_style.font());
686
687 let cell_width = text_system
688 .advance(font_id, font_pixels, 'm')
689 .unwrap()
690 .width;
691 gutter = cell_width;
692
693 let mut size = bounds.size;
694 size.width -= gutter;
695
696 // https://github.com/zed-industries/zed/issues/2750
697 // if the terminal is one column wide, rendering 🦀
698 // causes alacritty to misbehave.
699 if size.width < cell_width * 2.0 {
700 size.width = cell_width * 2.0;
701 }
702
703 TerminalSize::new(line_height, cell_width, size)
704 };
705
706 let search_matches = self.terminal.read(cx).matches.clone();
707
708 let background_color = theme.colors().terminal_background;
709
710 let last_hovered_word = self.terminal.update(cx, |terminal, cx| {
711 terminal.set_size(dimensions);
712 terminal.sync(cx);
713 if self.can_navigate_to_selected_word
714 && terminal.can_navigate_to_selected_word()
715 {
716 terminal.last_content.last_hovered_word.clone()
717 } else {
718 None
719 }
720 });
721
722 let scroll_top = self.terminal_view.read(cx).scroll_top;
723 let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
724 let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
725 let mut element = div()
726 .size_full()
727 .id("terminal-element")
728 .tooltip(move |cx| Tooltip::text(hovered_word.word.clone(), cx))
729 .into_any_element();
730 element.prepaint_as_root(offset, bounds.size.into(), cx);
731 element
732 });
733
734 let TerminalContent {
735 cells,
736 mode,
737 display_offset,
738 cursor_char,
739 selection,
740 cursor,
741 ..
742 } = &self.terminal.read(cx).last_content;
743 let mode = *mode;
744 let display_offset = *display_offset;
745
746 // searches, highlights to a single range representations
747 let mut relative_highlighted_ranges = Vec::new();
748 for search_match in search_matches {
749 relative_highlighted_ranges.push((search_match, match_color))
750 }
751 if let Some(selection) = selection {
752 relative_highlighted_ranges
753 .push((selection.start..=selection.end, player_color.selection));
754 }
755
756 // then have that representation be converted to the appropriate highlight data structure
757
758 let (cells, rects) = TerminalElement::layout_grid(
759 cells.iter().cloned(),
760 &text_style,
761 &cx.text_system(),
762 last_hovered_word
763 .as_ref()
764 .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
765 cx,
766 );
767
768 // Layout cursor. Rectangle is used for IME, so we should lay it out even
769 // if we don't end up showing it.
770 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
771 None
772 } else {
773 let cursor_point = DisplayCursor::from(cursor.point, display_offset);
774 let cursor_text = {
775 let str_trxt = cursor_char.to_string();
776 let len = str_trxt.len();
777 cx.text_system()
778 .shape_line(
779 str_trxt.into(),
780 text_style.font_size.to_pixels(cx.rem_size()),
781 &[TextRun {
782 len,
783 font: text_style.font(),
784 color: theme.colors().terminal_background,
785 background_color: None,
786 underline: Default::default(),
787 strikethrough: None,
788 }],
789 )
790 .unwrap()
791 };
792
793 let focused = self.focused;
794 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
795 move |(cursor_position, block_width)| {
796 let (shape, text) = match cursor.shape {
797 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
798 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
799 AlacCursorShape::Underline => (CursorShape::Underscore, None),
800 AlacCursorShape::Beam => (CursorShape::Bar, None),
801 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
802 //This case is handled in the if wrapping the whole cursor layout
803 AlacCursorShape::Hidden => unreachable!(),
804 };
805
806 CursorLayout::new(
807 cursor_position,
808 block_width,
809 dimensions.line_height,
810 theme.players().local().cursor,
811 shape,
812 text,
813 )
814 },
815 )
816 };
817
818 let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
819 let terminal = self.terminal.read(cx);
820 if terminal.last_content.display_offset == 0 {
821 let target_line = terminal.last_content.cursor.point.line.0 + 1;
822 let render = &block.render;
823 let mut block_cx = BlockContext {
824 context: cx,
825 dimensions,
826 };
827 let element = render(&mut block_cx);
828 let mut element = div().occlude().child(element).into_any_element();
829 let available_space = size(
830 AvailableSpace::Definite(dimensions.width() + gutter),
831 AvailableSpace::Definite(
832 block.height as f32 * dimensions.line_height(),
833 ),
834 );
835 let origin = bounds.origin
836 + point(px(0.), target_line as f32 * dimensions.line_height())
837 - point(px(0.), scroll_top);
838 cx.with_rem_size(rem_size, |cx| {
839 element.prepaint_as_root(origin, available_space, cx);
840 });
841 Some(element)
842 } else {
843 None
844 }
845 } else {
846 None
847 };
848
849 LayoutState {
850 hitbox,
851 cells,
852 cursor,
853 background_color,
854 dimensions,
855 rects,
856 relative_highlighted_ranges,
857 mode,
858 display_offset,
859 hyperlink_tooltip,
860 gutter,
861 last_hovered_word,
862 block_below_cursor_element,
863 }
864 })
865 }
866
867 fn paint(
868 &mut self,
869 global_id: Option<&GlobalElementId>,
870 bounds: Bounds<Pixels>,
871 _: &mut Self::RequestLayoutState,
872 layout: &mut Self::PrepaintState,
873 cx: &mut WindowContext<'_>,
874 ) {
875 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
876 let scroll_top = self.terminal_view.read(cx).scroll_top;
877
878 cx.paint_quad(fill(bounds, layout.background_color));
879 let origin =
880 bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
881
882 let terminal_input_handler = TerminalInputHandler {
883 terminal: self.terminal.clone(),
884 cursor_bounds: layout
885 .cursor
886 .as_ref()
887 .map(|cursor| cursor.bounding_rect(origin)),
888 workspace: self.workspace.clone(),
889 };
890
891 self.register_mouse_listeners(origin, layout.mode, &layout.hitbox, cx);
892 if self.can_navigate_to_selected_word && layout.last_hovered_word.is_some() {
893 cx.set_cursor_style(gpui::CursorStyle::PointingHand, &layout.hitbox);
894 } else {
895 cx.set_cursor_style(gpui::CursorStyle::IBeam, &layout.hitbox);
896 }
897
898 let cursor = layout.cursor.take();
899 let hyperlink_tooltip = layout.hyperlink_tooltip.take();
900 let block_below_cursor_element = layout.block_below_cursor_element.take();
901 self.interactivity
902 .paint(global_id, bounds, Some(&layout.hitbox), cx, |_, cx| {
903 cx.handle_input(&self.focus, terminal_input_handler);
904
905 cx.on_key_event({
906 let this = self.terminal.clone();
907 move |event: &ModifiersChangedEvent, phase, cx| {
908 if phase != DispatchPhase::Bubble {
909 return;
910 }
911
912 let handled = this
913 .update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
914
915 if handled {
916 cx.refresh();
917 }
918 }
919 });
920
921 for rect in &layout.rects {
922 rect.paint(origin, &layout.dimensions, cx);
923 }
924
925 for (relative_highlighted_range, color) in
926 layout.relative_highlighted_ranges.iter()
927 {
928 if let Some((start_y, highlighted_range_lines)) =
929 to_highlighted_range_lines(relative_highlighted_range, &layout, origin)
930 {
931 let hr = HighlightedRange {
932 start_y,
933 line_height: layout.dimensions.line_height,
934 lines: highlighted_range_lines,
935 color: *color,
936 corner_radius: 0.15 * layout.dimensions.line_height,
937 };
938 hr.paint(bounds, cx);
939 }
940 }
941
942 for cell in &layout.cells {
943 cell.paint(origin, &layout.dimensions, bounds, cx);
944 }
945
946 if self.cursor_visible {
947 if let Some(mut cursor) = cursor {
948 cursor.paint(origin, cx);
949 }
950 }
951
952 if let Some(mut element) = block_below_cursor_element {
953 element.paint(cx);
954 }
955
956 if let Some(mut element) = hyperlink_tooltip {
957 element.paint(cx);
958 }
959 });
960 });
961 }
962}
963
964impl IntoElement for TerminalElement {
965 type Element = Self;
966
967 fn into_element(self) -> Self::Element {
968 self
969 }
970}
971
972struct TerminalInputHandler {
973 terminal: Model<Terminal>,
974 workspace: WeakView<Workspace>,
975 cursor_bounds: Option<Bounds<Pixels>>,
976}
977
978impl InputHandler for TerminalInputHandler {
979 fn selected_text_range(
980 &mut self,
981 _ignore_disabled_input: bool,
982 cx: &mut WindowContext,
983 ) -> Option<UTF16Selection> {
984 if self
985 .terminal
986 .read(cx)
987 .last_content
988 .mode
989 .contains(TermMode::ALT_SCREEN)
990 {
991 None
992 } else {
993 Some(UTF16Selection {
994 range: 0..0,
995 reversed: false,
996 })
997 }
998 }
999
1000 fn marked_text_range(&mut self, _: &mut WindowContext) -> Option<std::ops::Range<usize>> {
1001 None
1002 }
1003
1004 fn text_for_range(
1005 &mut self,
1006 _: std::ops::Range<usize>,
1007 _: &mut WindowContext,
1008 ) -> Option<String> {
1009 None
1010 }
1011
1012 fn replace_text_in_range(
1013 &mut self,
1014 _replacement_range: Option<std::ops::Range<usize>>,
1015 text: &str,
1016 cx: &mut WindowContext,
1017 ) {
1018 self.terminal.update(cx, |terminal, _| {
1019 terminal.input(text.into());
1020 });
1021
1022 self.workspace
1023 .update(cx, |this, cx| {
1024 cx.invalidate_character_coordinates();
1025
1026 let telemetry = this.project().read(cx).client().telemetry().clone();
1027 telemetry.log_edit_event("terminal");
1028 })
1029 .ok();
1030 }
1031
1032 fn replace_and_mark_text_in_range(
1033 &mut self,
1034 _range_utf16: Option<std::ops::Range<usize>>,
1035 _new_text: &str,
1036 _new_selected_range: Option<std::ops::Range<usize>>,
1037 _: &mut WindowContext,
1038 ) {
1039 }
1040
1041 fn unmark_text(&mut self, _: &mut WindowContext) {}
1042
1043 fn bounds_for_range(
1044 &mut self,
1045 _range_utf16: std::ops::Range<usize>,
1046 _: &mut WindowContext,
1047 ) -> Option<Bounds<Pixels>> {
1048 self.cursor_bounds
1049 }
1050}
1051
1052pub fn is_blank(cell: &IndexedCell) -> bool {
1053 if cell.c != ' ' {
1054 return false;
1055 }
1056
1057 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1058 return false;
1059 }
1060
1061 if cell.hyperlink().is_some() {
1062 return false;
1063 }
1064
1065 if cell
1066 .flags
1067 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1068 {
1069 return false;
1070 }
1071
1072 return true;
1073}
1074
1075fn to_highlighted_range_lines(
1076 range: &RangeInclusive<AlacPoint>,
1077 layout: &LayoutState,
1078 origin: Point<Pixels>,
1079) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1080 // Step 1. Normalize the points to be viewport relative.
1081 // When display_offset = 1, here's how the grid is arranged:
1082 //-2,0 -2,1...
1083 //--- Viewport top
1084 //-1,0 -1,1...
1085 //--------- Terminal Top
1086 // 0,0 0,1...
1087 // 1,0 1,1...
1088 //--- Viewport Bottom
1089 // 2,0 2,1...
1090 //--------- Terminal Bottom
1091
1092 // Normalize to viewport relative, from terminal relative.
1093 // lines are i32s, which are negative above the top left corner of the terminal
1094 // If the user has scrolled, we use the display_offset to tell us which offset
1095 // of the grid data we should be looking at. But for the rendering step, we don't
1096 // want negatives. We want things relative to the 'viewport' (the area of the grid
1097 // which is currently shown according to the display offset)
1098 let unclamped_start = AlacPoint::new(
1099 range.start().line + layout.display_offset,
1100 range.start().column,
1101 );
1102 let unclamped_end =
1103 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1104
1105 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1106 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1107 return None;
1108 }
1109
1110 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1111 let clamped_end_line = unclamped_end
1112 .line
1113 .0
1114 .min(layout.dimensions.num_lines() as i32) as usize;
1115 //Convert the start of the range to pixels
1116 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1117
1118 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1119 // (also convert to pixels)
1120 let mut highlighted_range_lines = Vec::new();
1121 for line in clamped_start_line..=clamped_end_line {
1122 let mut line_start = 0;
1123 let mut line_end = layout.dimensions.columns();
1124
1125 if line == clamped_start_line {
1126 line_start = unclamped_start.column.0;
1127 }
1128 if line == clamped_end_line {
1129 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1130 }
1131
1132 highlighted_range_lines.push(HighlightedRangeLine {
1133 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1134 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1135 });
1136 }
1137
1138 Some((start_y, highlighted_range_lines))
1139}
1140
1141/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1142pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1143 let colors = theme.colors();
1144 match fg {
1145 // Named and theme defined colors
1146 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1147 NamedColor::Black => colors.terminal_ansi_black,
1148 NamedColor::Red => colors.terminal_ansi_red,
1149 NamedColor::Green => colors.terminal_ansi_green,
1150 NamedColor::Yellow => colors.terminal_ansi_yellow,
1151 NamedColor::Blue => colors.terminal_ansi_blue,
1152 NamedColor::Magenta => colors.terminal_ansi_magenta,
1153 NamedColor::Cyan => colors.terminal_ansi_cyan,
1154 NamedColor::White => colors.terminal_ansi_white,
1155 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1156 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1157 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1158 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1159 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1160 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1161 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1162 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1163 NamedColor::Foreground => colors.terminal_foreground,
1164 NamedColor::Background => colors.terminal_background,
1165 NamedColor::Cursor => theme.players().local().cursor,
1166 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1167 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1168 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1169 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1170 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1171 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1172 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1173 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1174 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1175 NamedColor::DimForeground => colors.terminal_dim_foreground,
1176 },
1177 // 'True' colors
1178 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1179 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1180 }
1181 // 8 bit, indexed colors
1182 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1183 terminal::get_color_at_index(*i as usize, theme)
1184 }
1185 }
1186}