1use editor::{CursorLayout, HighlightedRange, HighlightedRangeLine};
2use gpui::{
3 AnyElement, App, AvailableSpace, Bounds, ContentMask, Context, DispatchPhase, Element,
4 ElementId, Entity, FocusHandle, Font, FontStyle, FontWeight, GlobalElementId, HighlightStyle,
5 Hitbox, Hsla, InputHandler, InteractiveElement, Interactivity, IntoElement, LayoutId,
6 ModifiersChangedEvent, MouseButton, MouseMoveEvent, Pixels, Point, ShapedLine,
7 StatefulInteractiveElement, StrikethroughStyle, Styled, TextRun, TextStyle, UTF16Selection,
8 UnderlineStyle, WeakEntity, WhiteSpace, Window, WindowTextSystem, div, fill, point, px,
9 relative, size,
10};
11use itertools::Itertools;
12use language::CursorShape;
13use settings::Settings;
14use terminal::{
15 IndexedCell, Terminal, TerminalBounds, TerminalContent,
16 alacritty_terminal::{
17 grid::Dimensions,
18 index::Point as AlacPoint,
19 term::{TermMode, cell::Flags},
20 vte::ansi::{
21 Color::{self as AnsiColor, Named},
22 CursorShape as AlacCursorShape, NamedColor,
23 },
24 },
25 terminal_settings::TerminalSettings,
26};
27use theme::{ActiveTheme, Theme, ThemeSettings};
28use ui::{ParentElement, Tooltip};
29use workspace::Workspace;
30
31use std::mem;
32use std::{fmt::Debug, ops::RangeInclusive, rc::Rc};
33
34use crate::{BlockContext, BlockProperties, TerminalView};
35
36/// The information generated during layout that is necessary for painting.
37pub struct LayoutState {
38 hitbox: Hitbox,
39 cells: Vec<LayoutCell>,
40 rects: Vec<LayoutRect>,
41 relative_highlighted_ranges: Vec<(RangeInclusive<AlacPoint>, Hsla)>,
42 cursor: Option<CursorLayout>,
43 background_color: Hsla,
44 dimensions: TerminalBounds,
45 mode: TermMode,
46 display_offset: usize,
47 hyperlink_tooltip: Option<AnyElement>,
48 gutter: Pixels,
49 block_below_cursor_element: Option<AnyElement>,
50}
51
52/// Helper struct for converting data between Alacritty's cursor points, and displayed cursor points.
53struct DisplayCursor {
54 line: i32,
55 col: usize,
56}
57
58impl DisplayCursor {
59 fn from(cursor_point: AlacPoint, display_offset: usize) -> Self {
60 Self {
61 line: cursor_point.line.0 + display_offset as i32,
62 col: cursor_point.column.0,
63 }
64 }
65
66 pub fn line(&self) -> i32 {
67 self.line
68 }
69
70 pub fn col(&self) -> usize {
71 self.col
72 }
73}
74
75#[derive(Debug, Default)]
76pub struct LayoutCell {
77 pub point: AlacPoint<i32, i32>,
78 text: gpui::ShapedLine,
79}
80
81impl LayoutCell {
82 fn new(point: AlacPoint<i32, i32>, text: gpui::ShapedLine) -> LayoutCell {
83 LayoutCell { point, text }
84 }
85
86 pub fn paint(
87 &self,
88 origin: Point<Pixels>,
89 dimensions: &TerminalBounds,
90 _visible_bounds: Bounds<Pixels>,
91 window: &mut Window,
92 cx: &mut App,
93 ) {
94 let pos = {
95 let point = self.point;
96
97 Point::new(
98 (origin.x + point.column as f32 * dimensions.cell_width).floor(),
99 origin.y + point.line as f32 * dimensions.line_height,
100 )
101 };
102
103 self.text
104 .paint(pos, dimensions.line_height, window, cx)
105 .ok();
106 }
107}
108
109#[derive(Clone, Debug, Default)]
110pub struct LayoutRect {
111 point: AlacPoint<i32, i32>,
112 num_of_cells: usize,
113 color: Hsla,
114}
115
116impl LayoutRect {
117 fn new(point: AlacPoint<i32, i32>, num_of_cells: usize, color: Hsla) -> LayoutRect {
118 LayoutRect {
119 point,
120 num_of_cells,
121 color,
122 }
123 }
124
125 fn extend(&self) -> Self {
126 LayoutRect {
127 point: self.point,
128 num_of_cells: self.num_of_cells + 1,
129 color: self.color,
130 }
131 }
132
133 pub fn paint(&self, origin: Point<Pixels>, dimensions: &TerminalBounds, window: &mut Window) {
134 let position = {
135 let alac_point = self.point;
136 point(
137 (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
138 origin.y + alac_point.line as f32 * dimensions.line_height,
139 )
140 };
141 let size = point(
142 (dimensions.cell_width * self.num_of_cells as f32).ceil(),
143 dimensions.line_height,
144 )
145 .into();
146
147 window.paint_quad(fill(Bounds::new(position, size), self.color));
148 }
149}
150
151/// The GPUI element that paints the terminal.
152/// We need to keep a reference to the model for mouse events, do we need it for any other terminal stuff, or can we move that to connection?
153pub struct TerminalElement {
154 terminal: Entity<Terminal>,
155 terminal_view: Entity<TerminalView>,
156 workspace: WeakEntity<Workspace>,
157 focus: FocusHandle,
158 focused: bool,
159 cursor_visible: bool,
160 interactivity: Interactivity,
161 block_below_cursor: Option<Rc<BlockProperties>>,
162}
163
164impl InteractiveElement for TerminalElement {
165 fn interactivity(&mut self) -> &mut Interactivity {
166 &mut self.interactivity
167 }
168}
169
170impl StatefulInteractiveElement for TerminalElement {}
171
172impl TerminalElement {
173 pub fn new(
174 terminal: Entity<Terminal>,
175 terminal_view: Entity<TerminalView>,
176 workspace: WeakEntity<Workspace>,
177 focus: FocusHandle,
178 focused: bool,
179 cursor_visible: 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 block_below_cursor,
190 interactivity: Default::default(),
191 }
192 .track_focus(&focus)
193 .element
194 }
195
196 //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
197
198 pub fn layout_grid(
199 grid: impl Iterator<Item = IndexedCell>,
200 text_style: &TextStyle,
201 // terminal_theme: &TerminalStyle,
202 text_system: &WindowTextSystem,
203 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
204 window: &Window,
205 cx: &App,
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(window.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: TerminalBounds,
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: Entity<Terminal>,
412 focus_handle: FocusHandle,
413 f: impl Fn(&mut Terminal, &E, &mut Context<Terminal>),
414 ) -> impl Fn(&E, &mut Window, &mut App) {
415 move |event, window, cx| {
416 window.focus(&focus_handle);
417 connection.update(cx, |terminal, cx| {
418 f(terminal, event, cx);
419
420 cx.notify();
421 })
422 }
423 }
424
425 fn register_mouse_listeners(&mut self, mode: TermMode, hitbox: &Hitbox, window: &mut Window) {
426 let focus = self.focus.clone();
427 let terminal = self.terminal.clone();
428 let terminal_view = self.terminal_view.clone();
429
430 self.interactivity.on_mouse_down(MouseButton::Left, {
431 let terminal = terminal.clone();
432 let focus = focus.clone();
433 let terminal_view = terminal_view.clone();
434
435 move |e, window, cx| {
436 window.focus(&focus);
437
438 let scroll_top = terminal_view.read(cx).scroll_top;
439 terminal.update(cx, |terminal, cx| {
440 let mut adjusted_event = e.clone();
441 if scroll_top > Pixels::ZERO {
442 adjusted_event.position.y += scroll_top;
443 }
444 terminal.mouse_down(&adjusted_event, cx);
445 cx.notify();
446 })
447 }
448 });
449
450 window.on_mouse_event({
451 let terminal = self.terminal.clone();
452 let hitbox = hitbox.clone();
453 let focus = focus.clone();
454 let terminal_view = terminal_view.clone();
455 move |e: &MouseMoveEvent, phase, window, cx| {
456 if phase != DispatchPhase::Bubble {
457 return;
458 }
459
460 if e.pressed_button.is_some() && !cx.has_active_drag() && focus.is_focused(window) {
461 let hovered = hitbox.is_hovered(window);
462
463 let scroll_top = terminal_view.read(cx).scroll_top;
464 terminal.update(cx, |terminal, cx| {
465 if terminal.selection_started() || hovered {
466 let mut adjusted_event = e.clone();
467 if scroll_top > Pixels::ZERO {
468 adjusted_event.position.y += scroll_top;
469 }
470 terminal.mouse_drag(&adjusted_event, hitbox.bounds, cx);
471 cx.notify();
472 }
473 })
474 }
475
476 if hitbox.is_hovered(window) {
477 terminal.update(cx, |terminal, cx| {
478 terminal.mouse_move(e, cx);
479 })
480 }
481 }
482 });
483
484 self.interactivity.on_mouse_up(
485 MouseButton::Left,
486 TerminalElement::generic_button_handler(
487 terminal.clone(),
488 focus.clone(),
489 move |terminal, e, cx| {
490 terminal.mouse_up(e, cx);
491 },
492 ),
493 );
494 self.interactivity.on_mouse_down(
495 MouseButton::Middle,
496 TerminalElement::generic_button_handler(
497 terminal.clone(),
498 focus.clone(),
499 move |terminal, e, cx| {
500 terminal.mouse_down(e, cx);
501 },
502 ),
503 );
504 self.interactivity.on_scroll_wheel({
505 let terminal_view = self.terminal_view.downgrade();
506 move |e, _, cx| {
507 terminal_view
508 .update(cx, |terminal_view, cx| {
509 terminal_view.scroll_wheel(e, cx);
510 cx.notify();
511 })
512 .ok();
513 }
514 });
515
516 // Mouse mode handlers:
517 // All mouse modes need the extra click handlers
518 if mode.intersects(TermMode::MOUSE_MODE) {
519 self.interactivity.on_mouse_down(
520 MouseButton::Right,
521 TerminalElement::generic_button_handler(
522 terminal.clone(),
523 focus.clone(),
524 move |terminal, e, cx| {
525 terminal.mouse_down(e, cx);
526 },
527 ),
528 );
529 self.interactivity.on_mouse_up(
530 MouseButton::Right,
531 TerminalElement::generic_button_handler(
532 terminal.clone(),
533 focus.clone(),
534 move |terminal, e, cx| {
535 terminal.mouse_up(e, cx);
536 },
537 ),
538 );
539 self.interactivity.on_mouse_up(
540 MouseButton::Middle,
541 TerminalElement::generic_button_handler(terminal, focus, move |terminal, e, cx| {
542 terminal.mouse_up(e, cx);
543 }),
544 );
545 }
546 }
547
548 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
549 let settings = ThemeSettings::get_global(cx).clone();
550 let buffer_font_size = settings.buffer_font_size(cx);
551 let rem_size_scale = {
552 // Our default UI font size is 14px on a 16px base scale.
553 // This means the default UI font size is 0.875rems.
554 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
555
556 // We then determine the delta between a single rem and the default font
557 // size scale.
558 let default_font_size_delta = 1. - default_font_size_scale;
559
560 // Finally, we add this delta to 1rem to get the scale factor that
561 // should be used to scale up the UI.
562 1. + default_font_size_delta
563 };
564
565 Some(buffer_font_size * rem_size_scale)
566 }
567}
568
569impl Element for TerminalElement {
570 type RequestLayoutState = ();
571 type PrepaintState = LayoutState;
572
573 fn id(&self) -> Option<ElementId> {
574 self.interactivity.element_id.clone()
575 }
576
577 fn request_layout(
578 &mut self,
579 global_id: Option<&GlobalElementId>,
580 window: &mut Window,
581 cx: &mut App,
582 ) -> (LayoutId, Self::RequestLayoutState) {
583 let layout_id =
584 self.interactivity
585 .request_layout(global_id, window, cx, |mut style, window, cx| {
586 style.size.width = relative(1.).into();
587 style.size.height = relative(1.).into();
588 // style.overflow = point(Overflow::Hidden, Overflow::Hidden);
589
590 window.request_layout(style, None, cx)
591 });
592 (layout_id, ())
593 }
594
595 fn prepaint(
596 &mut self,
597 global_id: Option<&GlobalElementId>,
598 bounds: Bounds<Pixels>,
599 _: &mut Self::RequestLayoutState,
600 window: &mut Window,
601 cx: &mut App,
602 ) -> Self::PrepaintState {
603 let rem_size = self.rem_size(cx);
604 self.interactivity.prepaint(
605 global_id,
606 bounds,
607 bounds.size,
608 window,
609 cx,
610 |_, _, hitbox, window, 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 .cloned();
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_ansi_background),
669 white_space: WhiteSpace::Normal,
670 // These are going to be overridden per-cell
671 color: theme.colors().terminal_foreground,
672 ..Default::default()
673 };
674
675 let text_system = cx.text_system();
676 let player_color = theme.players().local();
677 let match_color = theme.colors().search_match_background;
678 let gutter;
679 let dimensions = {
680 let rem_size = window.rem_size();
681 let font_pixels = text_style.font_size.to_pixels(rem_size);
682 // TODO: line_height should be an f32 not an AbsoluteLength.
683 let line_height = font_pixels * line_height.to_pixels(rem_size).0;
684 let font_id = cx.text_system().resolve_font(&text_style.font());
685
686 let cell_width = text_system
687 .advance(font_id, font_pixels, 'm')
688 .unwrap()
689 .width;
690 gutter = cell_width;
691
692 let mut size = bounds.size;
693 size.width -= gutter;
694
695 // https://github.com/zed-industries/zed/issues/2750
696 // if the terminal is one column wide, rendering 🦀
697 // causes alacritty to misbehave.
698 if size.width < cell_width * 2.0 {
699 size.width = cell_width * 2.0;
700 }
701
702 let mut origin = bounds.origin;
703 origin.x += gutter;
704
705 TerminalBounds::new(line_height, cell_width, Bounds { origin, size })
706 };
707
708 let search_matches = self.terminal.read(cx).matches.clone();
709
710 let background_color = theme.colors().terminal_background;
711
712 let (last_hovered_word, hover_target) = self.terminal.update(cx, |terminal, cx| {
713 terminal.set_size(dimensions);
714 terminal.sync(window, cx);
715
716 if window.modifiers().secondary()
717 && bounds.contains(&window.mouse_position())
718 && self.terminal_view.read(cx).hover_target_tooltip.is_some()
719 {
720 let hover_target = self.terminal_view.read(cx).hover_target_tooltip.clone();
721 let last_hovered_word = terminal.last_content.last_hovered_word.clone();
722 (last_hovered_word, hover_target)
723 } else {
724 (None, None)
725 }
726 });
727
728 let scroll_top = self.terminal_view.read(cx).scroll_top;
729 let hyperlink_tooltip = hover_target.as_ref().map(|hover_target| {
730 let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
731 let mut element = div()
732 .size_full()
733 .id("terminal-element")
734 .tooltip(Tooltip::text(hover_target.clone()))
735 .into_any_element();
736 element.prepaint_as_root(offset, bounds.size.into(), window, cx);
737 element
738 });
739
740 let TerminalContent {
741 cells,
742 mode,
743 display_offset,
744 cursor_char,
745 selection,
746 cursor,
747 ..
748 } = &self.terminal.read(cx).last_content;
749 let mode = *mode;
750 let display_offset = *display_offset;
751
752 // searches, highlights to a single range representations
753 let mut relative_highlighted_ranges = Vec::new();
754 for search_match in search_matches {
755 relative_highlighted_ranges.push((search_match, match_color))
756 }
757 if let Some(selection) = selection {
758 relative_highlighted_ranges
759 .push((selection.start..=selection.end, player_color.selection));
760 }
761
762 // then have that representation be converted to the appropriate highlight data structure
763
764 let (cells, rects) = TerminalElement::layout_grid(
765 cells.iter().cloned(),
766 &text_style,
767 window.text_system(),
768 last_hovered_word
769 .as_ref()
770 .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
771 window,
772 cx,
773 );
774
775 // Layout cursor. Rectangle is used for IME, so we should lay it out even
776 // if we don't end up showing it.
777 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
778 None
779 } else {
780 let cursor_point = DisplayCursor::from(cursor.point, display_offset);
781 let cursor_text = {
782 let str_trxt = cursor_char.to_string();
783 let len = str_trxt.len();
784 window
785 .text_system()
786 .shape_line(
787 str_trxt.into(),
788 text_style.font_size.to_pixels(window.rem_size()),
789 &[TextRun {
790 len,
791 font: text_style.font(),
792 color: theme.colors().terminal_ansi_background,
793 background_color: None,
794 underline: Default::default(),
795 strikethrough: None,
796 }],
797 )
798 .unwrap()
799 };
800
801 let focused = self.focused;
802 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
803 move |(cursor_position, block_width)| {
804 let (shape, text) = match cursor.shape {
805 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
806 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
807 AlacCursorShape::Underline => (CursorShape::Underline, None),
808 AlacCursorShape::Beam => (CursorShape::Bar, None),
809 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
810 //This case is handled in the if wrapping the whole cursor layout
811 AlacCursorShape::Hidden => unreachable!(),
812 };
813
814 CursorLayout::new(
815 cursor_position,
816 block_width,
817 dimensions.line_height,
818 theme.players().local().cursor,
819 shape,
820 text,
821 )
822 },
823 )
824 };
825
826 let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
827 let terminal = self.terminal.read(cx);
828 if terminal.last_content.display_offset == 0 {
829 let target_line = terminal.last_content.cursor.point.line.0 + 1;
830 let render = &block.render;
831 let mut block_cx = BlockContext {
832 window,
833 context: cx,
834 dimensions,
835 };
836 let element = render(&mut block_cx);
837 let mut element = div().occlude().child(element).into_any_element();
838 let available_space = size(
839 AvailableSpace::Definite(dimensions.width() + gutter),
840 AvailableSpace::Definite(
841 block.height as f32 * dimensions.line_height(),
842 ),
843 );
844 let origin = bounds.origin
845 + point(px(0.), target_line as f32 * dimensions.line_height())
846 - point(px(0.), scroll_top);
847 window.with_rem_size(rem_size, |window| {
848 element.prepaint_as_root(origin, available_space, window, cx);
849 });
850 Some(element)
851 } else {
852 None
853 }
854 } else {
855 None
856 };
857
858 LayoutState {
859 hitbox,
860 cells,
861 cursor,
862 background_color,
863 dimensions,
864 rects,
865 relative_highlighted_ranges,
866 mode,
867 display_offset,
868 hyperlink_tooltip,
869 gutter,
870 block_below_cursor_element,
871 }
872 },
873 )
874 }
875
876 fn paint(
877 &mut self,
878 global_id: Option<&GlobalElementId>,
879 bounds: Bounds<Pixels>,
880 _: &mut Self::RequestLayoutState,
881 layout: &mut Self::PrepaintState,
882 window: &mut Window,
883 cx: &mut App,
884 ) {
885 window.with_content_mask(Some(ContentMask { bounds }), |window| {
886 let scroll_top = self.terminal_view.read(cx).scroll_top;
887
888 window.paint_quad(fill(bounds, layout.background_color));
889 let origin =
890 bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
891
892 let terminal_input_handler = TerminalInputHandler {
893 terminal: self.terminal.clone(),
894 cursor_bounds: layout
895 .cursor
896 .as_ref()
897 .map(|cursor| cursor.bounding_rect(origin)),
898 workspace: self.workspace.clone(),
899 };
900
901 self.register_mouse_listeners(layout.mode, &layout.hitbox, window);
902 if window.modifiers().secondary()
903 && bounds.contains(&window.mouse_position())
904 && self.terminal_view.read(cx).hover_target_tooltip.is_some()
905 {
906 window.set_cursor_style(gpui::CursorStyle::PointingHand, Some(&layout.hitbox));
907 } else {
908 window.set_cursor_style(gpui::CursorStyle::IBeam, Some(&layout.hitbox));
909 }
910
911 let cursor = layout.cursor.take();
912 let hyperlink_tooltip = layout.hyperlink_tooltip.take();
913 let block_below_cursor_element = layout.block_below_cursor_element.take();
914 self.interactivity.paint(
915 global_id,
916 bounds,
917 Some(&layout.hitbox),
918 window,
919 cx,
920 |_, window, cx| {
921 window.handle_input(&self.focus, terminal_input_handler, cx);
922
923 window.on_key_event({
924 let this = self.terminal.clone();
925 move |event: &ModifiersChangedEvent, phase, window, cx| {
926 if phase != DispatchPhase::Bubble {
927 return;
928 }
929
930 this.update(cx, |term, cx| {
931 term.try_modifiers_change(&event.modifiers, window, cx)
932 });
933 }
934 });
935
936 for rect in &layout.rects {
937 rect.paint(origin, &layout.dimensions, window);
938 }
939
940 for (relative_highlighted_range, color) in
941 layout.relative_highlighted_ranges.iter()
942 {
943 if let Some((start_y, highlighted_range_lines)) =
944 to_highlighted_range_lines(relative_highlighted_range, layout, origin)
945 {
946 let hr = HighlightedRange {
947 start_y,
948 line_height: layout.dimensions.line_height,
949 lines: highlighted_range_lines,
950 color: *color,
951 corner_radius: 0.15 * layout.dimensions.line_height,
952 };
953 hr.paint(bounds, window);
954 }
955 }
956
957 for cell in &layout.cells {
958 cell.paint(origin, &layout.dimensions, bounds, window, cx);
959 }
960
961 if self.cursor_visible {
962 if let Some(mut cursor) = cursor {
963 cursor.paint(origin, window, cx);
964 }
965 }
966
967 if let Some(mut element) = block_below_cursor_element {
968 element.paint(window, cx);
969 }
970
971 if let Some(mut element) = hyperlink_tooltip {
972 element.paint(window, cx);
973 }
974 },
975 );
976 });
977 }
978}
979
980impl IntoElement for TerminalElement {
981 type Element = Self;
982
983 fn into_element(self) -> Self::Element {
984 self
985 }
986}
987
988struct TerminalInputHandler {
989 terminal: Entity<Terminal>,
990 workspace: WeakEntity<Workspace>,
991 cursor_bounds: Option<Bounds<Pixels>>,
992}
993
994impl InputHandler for TerminalInputHandler {
995 fn selected_text_range(
996 &mut self,
997 _ignore_disabled_input: bool,
998 _: &mut Window,
999 cx: &mut App,
1000 ) -> Option<UTF16Selection> {
1001 if self
1002 .terminal
1003 .read(cx)
1004 .last_content
1005 .mode
1006 .contains(TermMode::ALT_SCREEN)
1007 {
1008 None
1009 } else {
1010 Some(UTF16Selection {
1011 range: 0..0,
1012 reversed: false,
1013 })
1014 }
1015 }
1016
1017 fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<std::ops::Range<usize>> {
1018 None
1019 }
1020
1021 fn text_for_range(
1022 &mut self,
1023 _: std::ops::Range<usize>,
1024 _: &mut Option<std::ops::Range<usize>>,
1025 _: &mut Window,
1026 _: &mut App,
1027 ) -> Option<String> {
1028 None
1029 }
1030
1031 fn replace_text_in_range(
1032 &mut self,
1033 _replacement_range: Option<std::ops::Range<usize>>,
1034 text: &str,
1035 window: &mut Window,
1036 cx: &mut App,
1037 ) {
1038 self.terminal.update(cx, |terminal, _| {
1039 terminal.input(text);
1040 });
1041
1042 self.workspace
1043 .update(cx, |this, cx| {
1044 window.invalidate_character_coordinates();
1045 let project = this.project().read(cx);
1046 let telemetry = project.client().telemetry().clone();
1047 telemetry.log_edit_event("terminal", project.is_via_ssh());
1048 })
1049 .ok();
1050 }
1051
1052 fn replace_and_mark_text_in_range(
1053 &mut self,
1054 _range_utf16: Option<std::ops::Range<usize>>,
1055 _new_text: &str,
1056 _new_selected_range: Option<std::ops::Range<usize>>,
1057 _window: &mut Window,
1058 _cx: &mut App,
1059 ) {
1060 }
1061
1062 fn unmark_text(&mut self, _window: &mut Window, _cx: &mut App) {}
1063
1064 fn bounds_for_range(
1065 &mut self,
1066 _range_utf16: std::ops::Range<usize>,
1067 _window: &mut Window,
1068 _cx: &mut App,
1069 ) -> Option<Bounds<Pixels>> {
1070 self.cursor_bounds
1071 }
1072
1073 fn apple_press_and_hold_enabled(&mut self) -> bool {
1074 false
1075 }
1076
1077 fn character_index_for_point(
1078 &mut self,
1079 _point: Point<Pixels>,
1080 _window: &mut Window,
1081 _cx: &mut App,
1082 ) -> Option<usize> {
1083 None
1084 }
1085}
1086
1087pub fn is_blank(cell: &IndexedCell) -> bool {
1088 if cell.c != ' ' {
1089 return false;
1090 }
1091
1092 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1093 return false;
1094 }
1095
1096 if cell.hyperlink().is_some() {
1097 return false;
1098 }
1099
1100 if cell
1101 .flags
1102 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1103 {
1104 return false;
1105 }
1106
1107 true
1108}
1109
1110fn to_highlighted_range_lines(
1111 range: &RangeInclusive<AlacPoint>,
1112 layout: &LayoutState,
1113 origin: Point<Pixels>,
1114) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1115 // Step 1. Normalize the points to be viewport relative.
1116 // When display_offset = 1, here's how the grid is arranged:
1117 //-2,0 -2,1...
1118 //--- Viewport top
1119 //-1,0 -1,1...
1120 //--------- Terminal Top
1121 // 0,0 0,1...
1122 // 1,0 1,1...
1123 //--- Viewport Bottom
1124 // 2,0 2,1...
1125 //--------- Terminal Bottom
1126
1127 // Normalize to viewport relative, from terminal relative.
1128 // lines are i32s, which are negative above the top left corner of the terminal
1129 // If the user has scrolled, we use the display_offset to tell us which offset
1130 // of the grid data we should be looking at. But for the rendering step, we don't
1131 // want negatives. We want things relative to the 'viewport' (the area of the grid
1132 // which is currently shown according to the display offset)
1133 let unclamped_start = AlacPoint::new(
1134 range.start().line + layout.display_offset,
1135 range.start().column,
1136 );
1137 let unclamped_end =
1138 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1139
1140 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1141 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1142 return None;
1143 }
1144
1145 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1146 let clamped_end_line = unclamped_end
1147 .line
1148 .0
1149 .min(layout.dimensions.num_lines() as i32) as usize;
1150 //Convert the start of the range to pixels
1151 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1152
1153 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1154 // (also convert to pixels)
1155 let mut highlighted_range_lines = Vec::new();
1156 for line in clamped_start_line..=clamped_end_line {
1157 let mut line_start = 0;
1158 let mut line_end = layout.dimensions.columns();
1159
1160 if line == clamped_start_line {
1161 line_start = unclamped_start.column.0;
1162 }
1163 if line == clamped_end_line {
1164 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1165 }
1166
1167 highlighted_range_lines.push(HighlightedRangeLine {
1168 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1169 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1170 });
1171 }
1172
1173 Some((start_y, highlighted_range_lines))
1174}
1175
1176/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1177pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1178 let colors = theme.colors();
1179 match fg {
1180 // Named and theme defined colors
1181 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1182 NamedColor::Black => colors.terminal_ansi_black,
1183 NamedColor::Red => colors.terminal_ansi_red,
1184 NamedColor::Green => colors.terminal_ansi_green,
1185 NamedColor::Yellow => colors.terminal_ansi_yellow,
1186 NamedColor::Blue => colors.terminal_ansi_blue,
1187 NamedColor::Magenta => colors.terminal_ansi_magenta,
1188 NamedColor::Cyan => colors.terminal_ansi_cyan,
1189 NamedColor::White => colors.terminal_ansi_white,
1190 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1191 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1192 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1193 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1194 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1195 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1196 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1197 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1198 NamedColor::Foreground => colors.terminal_foreground,
1199 NamedColor::Background => colors.terminal_ansi_background,
1200 NamedColor::Cursor => theme.players().local().cursor,
1201 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1202 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1203 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1204 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1205 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1206 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1207 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1208 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1209 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1210 NamedColor::DimForeground => colors.terminal_dim_foreground,
1211 },
1212 // 'True' colors
1213 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1214 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1215 }
1216 // 8 bit, indexed colors
1217 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1218 terminal::get_color_at_index(*i as usize, theme)
1219 }
1220 }
1221}