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