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