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