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 if hovered {
464 terminal.mouse_drag(e, origin, hitbox.bounds);
465 cx.notify();
466 }
467 })
468 }
469
470 if hitbox.is_hovered(cx) {
471 terminal.update(cx, |terminal, cx| {
472 terminal.mouse_move(e, origin);
473 cx.notify();
474 })
475 }
476 }
477 });
478
479 self.interactivity.on_mouse_up(
480 MouseButton::Left,
481 TerminalElement::generic_button_handler(
482 terminal.clone(),
483 origin,
484 focus.clone(),
485 move |terminal, origin, e, cx| {
486 terminal.mouse_up(e, origin, cx);
487 },
488 ),
489 );
490 self.interactivity.on_mouse_down(
491 MouseButton::Middle,
492 TerminalElement::generic_button_handler(
493 terminal.clone(),
494 origin,
495 focus.clone(),
496 move |terminal, origin, e, cx| {
497 terminal.mouse_down(e, origin, cx);
498 },
499 ),
500 );
501 self.interactivity.on_scroll_wheel({
502 let terminal_view = self.terminal_view.downgrade();
503 move |e, cx| {
504 terminal_view
505 .update(cx, |terminal_view, cx| {
506 terminal_view.scroll_wheel(e, origin, cx);
507 cx.notify();
508 })
509 .ok();
510 }
511 });
512
513 // Mouse mode handlers:
514 // All mouse modes need the extra click handlers
515 if mode.intersects(TermMode::MOUSE_MODE) {
516 self.interactivity.on_mouse_down(
517 MouseButton::Right,
518 TerminalElement::generic_button_handler(
519 terminal.clone(),
520 origin,
521 focus.clone(),
522 move |terminal, origin, e, cx| {
523 terminal.mouse_down(e, origin, cx);
524 },
525 ),
526 );
527 self.interactivity.on_mouse_up(
528 MouseButton::Right,
529 TerminalElement::generic_button_handler(
530 terminal.clone(),
531 origin,
532 focus.clone(),
533 move |terminal, origin, e, cx| {
534 terminal.mouse_up(e, origin, cx);
535 },
536 ),
537 );
538 self.interactivity.on_mouse_up(
539 MouseButton::Middle,
540 TerminalElement::generic_button_handler(
541 terminal,
542 origin,
543 focus,
544 move |terminal, origin, e, cx| {
545 terminal.mouse_up(e, origin, cx);
546 },
547 ),
548 );
549 }
550 }
551
552 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
553 let settings = ThemeSettings::get_global(cx).clone();
554 let buffer_font_size = settings.buffer_font_size(cx);
555 let rem_size_scale = {
556 // Our default UI font size is 14px on a 16px base scale.
557 // This means the default UI font size is 0.875rems.
558 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
559
560 // We then determine the delta between a single rem and the default font
561 // size scale.
562 let default_font_size_delta = 1. - default_font_size_scale;
563
564 // Finally, we add this delta to 1rem to get the scale factor that
565 // should be used to scale up the UI.
566 1. + default_font_size_delta
567 };
568
569 Some(buffer_font_size * rem_size_scale)
570 }
571}
572
573impl Element for TerminalElement {
574 type RequestLayoutState = ();
575 type PrepaintState = LayoutState;
576
577 fn id(&self) -> Option<ElementId> {
578 self.interactivity.element_id.clone()
579 }
580
581 fn request_layout(
582 &mut self,
583 global_id: Option<&GlobalElementId>,
584 cx: &mut WindowContext,
585 ) -> (LayoutId, Self::RequestLayoutState) {
586 let layout_id = self
587 .interactivity
588 .request_layout(global_id, cx, |mut style, cx| {
589 style.size.width = relative(1.).into();
590 style.size.height = relative(1.).into();
591 // style.overflow = point(Overflow::Hidden, Overflow::Hidden);
592
593 cx.request_layout(style, None)
594 });
595 (layout_id, ())
596 }
597
598 fn prepaint(
599 &mut self,
600 global_id: Option<&GlobalElementId>,
601 bounds: Bounds<Pixels>,
602 _: &mut Self::RequestLayoutState,
603 cx: &mut WindowContext,
604 ) -> Self::PrepaintState {
605 let rem_size = self.rem_size(cx);
606 self.interactivity
607 .prepaint(global_id, bounds, bounds.size, cx, |_, _, hitbox, cx| {
608 let hitbox = hitbox.unwrap();
609 let settings = ThemeSettings::get_global(cx).clone();
610
611 let buffer_font_size = settings.buffer_font_size(cx);
612
613 let terminal_settings = TerminalSettings::get_global(cx);
614
615 let font_family = terminal_settings
616 .font_family
617 .as_ref()
618 .unwrap_or(&settings.buffer_font.family)
619 .clone();
620
621 let font_fallbacks = terminal_settings
622 .font_fallbacks
623 .as_ref()
624 .or(settings.buffer_font.fallbacks.as_ref())
625 .cloned();
626
627 let font_features = terminal_settings
628 .font_features
629 .as_ref()
630 .unwrap_or(&settings.buffer_font.features)
631 .clone();
632
633 let font_weight = terminal_settings.font_weight.unwrap_or_default();
634
635 let line_height = terminal_settings.line_height.value();
636 let font_size = terminal_settings.font_size;
637
638 let font_size =
639 font_size.map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx));
640
641 let theme = cx.theme().clone();
642
643 let link_style = HighlightStyle {
644 color: Some(theme.colors().link_text_hover),
645 font_weight: Some(font_weight),
646 font_style: None,
647 background_color: None,
648 underline: Some(UnderlineStyle {
649 thickness: px(1.0),
650 color: Some(theme.colors().link_text_hover),
651 wavy: false,
652 }),
653 strikethrough: None,
654 fade_out: None,
655 };
656
657 let text_style = TextStyle {
658 font_family,
659 font_features,
660 font_weight,
661 font_fallbacks,
662 font_size: font_size.into(),
663 font_style: FontStyle::Normal,
664 line_height: line_height.into(),
665 background_color: Some(theme.colors().terminal_ansi_background),
666 white_space: WhiteSpace::Normal,
667 truncate: None,
668 // These are going to be overridden per-cell
669 underline: None,
670 strikethrough: None,
671 color: theme.colors().terminal_foreground,
672 };
673
674 let text_system = cx.text_system();
675 let player_color = theme.players().local();
676 let match_color = theme.colors().search_match_background;
677 let gutter;
678 let dimensions = {
679 let rem_size = cx.rem_size();
680 let font_pixels = text_style.font_size.to_pixels(rem_size);
681 let line_height = font_pixels * line_height.to_pixels(rem_size);
682 let font_id = cx.text_system().resolve_font(&text_style.font());
683
684 let cell_width = text_system
685 .advance(font_id, font_pixels, 'm')
686 .unwrap()
687 .width;
688 gutter = cell_width;
689
690 let mut size = bounds.size;
691 size.width -= gutter;
692
693 // https://github.com/zed-industries/zed/issues/2750
694 // if the terminal is one column wide, rendering 🦀
695 // causes alacritty to misbehave.
696 if size.width < cell_width * 2.0 {
697 size.width = cell_width * 2.0;
698 }
699
700 TerminalSize::new(line_height, cell_width, size)
701 };
702
703 let search_matches = self.terminal.read(cx).matches.clone();
704
705 let background_color = theme.colors().terminal_background;
706
707 let last_hovered_word = self.terminal.update(cx, |terminal, cx| {
708 terminal.set_size(dimensions);
709 terminal.sync(cx);
710 if self.can_navigate_to_selected_word
711 && terminal.can_navigate_to_selected_word()
712 {
713 terminal.last_content.last_hovered_word.clone()
714 } else {
715 None
716 }
717 });
718
719 let scroll_top = self.terminal_view.read(cx).scroll_top;
720 let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
721 let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
722 let mut element = div()
723 .size_full()
724 .id("terminal-element")
725 .tooltip(move |cx| Tooltip::text(hovered_word.word.clone(), cx))
726 .into_any_element();
727 element.prepaint_as_root(offset, bounds.size.into(), cx);
728 element
729 });
730
731 let TerminalContent {
732 cells,
733 mode,
734 display_offset,
735 cursor_char,
736 selection,
737 cursor,
738 ..
739 } = &self.terminal.read(cx).last_content;
740 let mode = *mode;
741 let display_offset = *display_offset;
742
743 // searches, highlights to a single range representations
744 let mut relative_highlighted_ranges = Vec::new();
745 for search_match in search_matches {
746 relative_highlighted_ranges.push((search_match, match_color))
747 }
748 if let Some(selection) = selection {
749 relative_highlighted_ranges
750 .push((selection.start..=selection.end, player_color.selection));
751 }
752
753 // then have that representation be converted to the appropriate highlight data structure
754
755 let (cells, rects) = TerminalElement::layout_grid(
756 cells.iter().cloned(),
757 &text_style,
758 cx.text_system(),
759 last_hovered_word
760 .as_ref()
761 .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
762 cx,
763 );
764
765 // Layout cursor. Rectangle is used for IME, so we should lay it out even
766 // if we don't end up showing it.
767 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
768 None
769 } else {
770 let cursor_point = DisplayCursor::from(cursor.point, display_offset);
771 let cursor_text = {
772 let str_trxt = cursor_char.to_string();
773 let len = str_trxt.len();
774 cx.text_system()
775 .shape_line(
776 str_trxt.into(),
777 text_style.font_size.to_pixels(cx.rem_size()),
778 &[TextRun {
779 len,
780 font: text_style.font(),
781 color: theme.colors().terminal_ansi_background,
782 background_color: None,
783 underline: Default::default(),
784 strikethrough: None,
785 }],
786 )
787 .unwrap()
788 };
789
790 let focused = self.focused;
791 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
792 move |(cursor_position, block_width)| {
793 let (shape, text) = match cursor.shape {
794 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
795 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
796 AlacCursorShape::Underline => (CursorShape::Underline, None),
797 AlacCursorShape::Beam => (CursorShape::Bar, None),
798 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
799 //This case is handled in the if wrapping the whole cursor layout
800 AlacCursorShape::Hidden => unreachable!(),
801 };
802
803 CursorLayout::new(
804 cursor_position,
805 block_width,
806 dimensions.line_height,
807 theme.players().local().cursor,
808 shape,
809 text,
810 )
811 },
812 )
813 };
814
815 let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
816 let terminal = self.terminal.read(cx);
817 if terminal.last_content.display_offset == 0 {
818 let target_line = terminal.last_content.cursor.point.line.0 + 1;
819 let render = &block.render;
820 let mut block_cx = BlockContext {
821 context: cx,
822 dimensions,
823 };
824 let element = render(&mut block_cx);
825 let mut element = div().occlude().child(element).into_any_element();
826 let available_space = size(
827 AvailableSpace::Definite(dimensions.width() + gutter),
828 AvailableSpace::Definite(
829 block.height as f32 * dimensions.line_height(),
830 ),
831 );
832 let origin = bounds.origin
833 + point(px(0.), target_line as f32 * dimensions.line_height())
834 - point(px(0.), scroll_top);
835 cx.with_rem_size(rem_size, |cx| {
836 element.prepaint_as_root(origin, available_space, cx);
837 });
838 Some(element)
839 } else {
840 None
841 }
842 } else {
843 None
844 };
845
846 LayoutState {
847 hitbox,
848 cells,
849 cursor,
850 background_color,
851 dimensions,
852 rects,
853 relative_highlighted_ranges,
854 mode,
855 display_offset,
856 hyperlink_tooltip,
857 gutter,
858 last_hovered_word,
859 block_below_cursor_element,
860 }
861 })
862 }
863
864 fn paint(
865 &mut self,
866 global_id: Option<&GlobalElementId>,
867 bounds: Bounds<Pixels>,
868 _: &mut Self::RequestLayoutState,
869 layout: &mut Self::PrepaintState,
870 cx: &mut WindowContext<'_>,
871 ) {
872 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
873 let scroll_top = self.terminal_view.read(cx).scroll_top;
874
875 cx.paint_quad(fill(bounds, layout.background_color));
876 let origin =
877 bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
878
879 let terminal_input_handler = TerminalInputHandler {
880 terminal: self.terminal.clone(),
881 cursor_bounds: layout
882 .cursor
883 .as_ref()
884 .map(|cursor| cursor.bounding_rect(origin)),
885 workspace: self.workspace.clone(),
886 };
887
888 self.register_mouse_listeners(origin, layout.mode, &layout.hitbox, cx);
889 if self.can_navigate_to_selected_word && layout.last_hovered_word.is_some() {
890 cx.set_cursor_style(gpui::CursorStyle::PointingHand, &layout.hitbox);
891 } else {
892 cx.set_cursor_style(gpui::CursorStyle::IBeam, &layout.hitbox);
893 }
894
895 let cursor = layout.cursor.take();
896 let hyperlink_tooltip = layout.hyperlink_tooltip.take();
897 let block_below_cursor_element = layout.block_below_cursor_element.take();
898 self.interactivity
899 .paint(global_id, bounds, Some(&layout.hitbox), cx, |_, cx| {
900 cx.handle_input(&self.focus, terminal_input_handler);
901
902 cx.on_key_event({
903 let this = self.terminal.clone();
904 move |event: &ModifiersChangedEvent, phase, cx| {
905 if phase != DispatchPhase::Bubble {
906 return;
907 }
908
909 let handled = this
910 .update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
911
912 if handled {
913 cx.refresh();
914 }
915 }
916 });
917
918 for rect in &layout.rects {
919 rect.paint(origin, &layout.dimensions, cx);
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, cx);
936 }
937 }
938
939 for cell in &layout.cells {
940 cell.paint(origin, &layout.dimensions, bounds, cx);
941 }
942
943 if self.cursor_visible {
944 if let Some(mut cursor) = cursor {
945 cursor.paint(origin, cx);
946 }
947 }
948
949 if let Some(mut element) = block_below_cursor_element {
950 element.paint(cx);
951 }
952
953 if let Some(mut element) = hyperlink_tooltip {
954 element.paint(cx);
955 }
956 });
957 });
958 }
959}
960
961impl IntoElement for TerminalElement {
962 type Element = Self;
963
964 fn into_element(self) -> Self::Element {
965 self
966 }
967}
968
969struct TerminalInputHandler {
970 terminal: Model<Terminal>,
971 workspace: WeakView<Workspace>,
972 cursor_bounds: Option<Bounds<Pixels>>,
973}
974
975impl InputHandler for TerminalInputHandler {
976 fn selected_text_range(
977 &mut self,
978 _ignore_disabled_input: bool,
979 cx: &mut WindowContext,
980 ) -> Option<UTF16Selection> {
981 if self
982 .terminal
983 .read(cx)
984 .last_content
985 .mode
986 .contains(TermMode::ALT_SCREEN)
987 {
988 None
989 } else {
990 Some(UTF16Selection {
991 range: 0..0,
992 reversed: false,
993 })
994 }
995 }
996
997 fn marked_text_range(&mut self, _: &mut WindowContext) -> Option<std::ops::Range<usize>> {
998 None
999 }
1000
1001 fn text_for_range(
1002 &mut self,
1003 _: std::ops::Range<usize>,
1004 _: &mut WindowContext,
1005 ) -> Option<String> {
1006 None
1007 }
1008
1009 fn replace_text_in_range(
1010 &mut self,
1011 _replacement_range: Option<std::ops::Range<usize>>,
1012 text: &str,
1013 cx: &mut WindowContext,
1014 ) {
1015 self.terminal.update(cx, |terminal, _| {
1016 terminal.input(text.into());
1017 });
1018
1019 self.workspace
1020 .update(cx, |this, cx| {
1021 cx.invalidate_character_coordinates();
1022 let project = this.project().read(cx);
1023 let telemetry = project.client().telemetry().clone();
1024 telemetry.log_edit_event("terminal", project.is_via_ssh());
1025 })
1026 .ok();
1027 }
1028
1029 fn replace_and_mark_text_in_range(
1030 &mut self,
1031 _range_utf16: Option<std::ops::Range<usize>>,
1032 _new_text: &str,
1033 _new_selected_range: Option<std::ops::Range<usize>>,
1034 _: &mut WindowContext,
1035 ) {
1036 }
1037
1038 fn unmark_text(&mut self, _: &mut WindowContext) {}
1039
1040 fn bounds_for_range(
1041 &mut self,
1042 _range_utf16: std::ops::Range<usize>,
1043 _: &mut WindowContext,
1044 ) -> Option<Bounds<Pixels>> {
1045 self.cursor_bounds
1046 }
1047
1048 fn apple_press_and_hold_enabled(&mut self) -> bool {
1049 false
1050 }
1051}
1052
1053pub fn is_blank(cell: &IndexedCell) -> bool {
1054 if cell.c != ' ' {
1055 return false;
1056 }
1057
1058 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1059 return false;
1060 }
1061
1062 if cell.hyperlink().is_some() {
1063 return false;
1064 }
1065
1066 if cell
1067 .flags
1068 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1069 {
1070 return false;
1071 }
1072
1073 true
1074}
1075
1076fn to_highlighted_range_lines(
1077 range: &RangeInclusive<AlacPoint>,
1078 layout: &LayoutState,
1079 origin: Point<Pixels>,
1080) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1081 // Step 1. Normalize the points to be viewport relative.
1082 // When display_offset = 1, here's how the grid is arranged:
1083 //-2,0 -2,1...
1084 //--- Viewport top
1085 //-1,0 -1,1...
1086 //--------- Terminal Top
1087 // 0,0 0,1...
1088 // 1,0 1,1...
1089 //--- Viewport Bottom
1090 // 2,0 2,1...
1091 //--------- Terminal Bottom
1092
1093 // Normalize to viewport relative, from terminal relative.
1094 // lines are i32s, which are negative above the top left corner of the terminal
1095 // If the user has scrolled, we use the display_offset to tell us which offset
1096 // of the grid data we should be looking at. But for the rendering step, we don't
1097 // want negatives. We want things relative to the 'viewport' (the area of the grid
1098 // which is currently shown according to the display offset)
1099 let unclamped_start = AlacPoint::new(
1100 range.start().line + layout.display_offset,
1101 range.start().column,
1102 );
1103 let unclamped_end =
1104 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1105
1106 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1107 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1108 return None;
1109 }
1110
1111 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1112 let clamped_end_line = unclamped_end
1113 .line
1114 .0
1115 .min(layout.dimensions.num_lines() as i32) as usize;
1116 //Convert the start of the range to pixels
1117 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1118
1119 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1120 // (also convert to pixels)
1121 let mut highlighted_range_lines = Vec::new();
1122 for line in clamped_start_line..=clamped_end_line {
1123 let mut line_start = 0;
1124 let mut line_end = layout.dimensions.columns();
1125
1126 if line == clamped_start_line {
1127 line_start = unclamped_start.column.0;
1128 }
1129 if line == clamped_end_line {
1130 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1131 }
1132
1133 highlighted_range_lines.push(HighlightedRangeLine {
1134 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1135 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1136 });
1137 }
1138
1139 Some((start_y, highlighted_range_lines))
1140}
1141
1142/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1143pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1144 let colors = theme.colors();
1145 match fg {
1146 // Named and theme defined colors
1147 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1148 NamedColor::Black => colors.terminal_ansi_black,
1149 NamedColor::Red => colors.terminal_ansi_red,
1150 NamedColor::Green => colors.terminal_ansi_green,
1151 NamedColor::Yellow => colors.terminal_ansi_yellow,
1152 NamedColor::Blue => colors.terminal_ansi_blue,
1153 NamedColor::Magenta => colors.terminal_ansi_magenta,
1154 NamedColor::Cyan => colors.terminal_ansi_cyan,
1155 NamedColor::White => colors.terminal_ansi_white,
1156 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1157 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1158 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1159 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1160 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1161 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1162 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1163 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1164 NamedColor::Foreground => colors.terminal_foreground,
1165 NamedColor::Background => colors.terminal_ansi_background,
1166 NamedColor::Cursor => theme.players().local().cursor,
1167 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1168 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1169 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1170 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1171 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1172 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1173 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1174 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1175 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1176 NamedColor::DimForeground => colors.terminal_dim_foreground,
1177 },
1178 // 'True' colors
1179 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1180 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1181 }
1182 // 8 bit, indexed colors
1183 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1184 terminal::get_color_at_index(*i as usize, theme)
1185 }
1186 }
1187}