1use editor::{CursorLayout, EditorSettings, HighlightedRange, HighlightedRangeLine};
2use gpui::{
3 AbsoluteLength, AnyElement, App, AvailableSpace, Bounds, ContentMask, Context, DispatchPhase,
4 Element, ElementId, Entity, FocusHandle, Font, FontFeatures, FontStyle, FontWeight,
5 GlobalElementId, HighlightStyle, Hitbox, Hsla, InputHandler, InteractiveElement, Interactivity,
6 IntoElement, LayoutId, Length, ModifiersChangedEvent, MouseButton, MouseMoveEvent, Pixels,
7 Point, ShapedLine, StatefulInteractiveElement, StrikethroughStyle, Styled, TextRun, TextStyle,
8 UTF16Selection, UnderlineStyle, WeakEntity, WhiteSpace, Window, div, fill, point, px, relative,
9 size,
10};
11use itertools::Itertools;
12use language::CursorShape;
13use settings::Settings;
14use std::time::Instant;
15use terminal::{
16 IndexedCell, Terminal, TerminalBounds, TerminalContent,
17 alacritty_terminal::{
18 grid::Dimensions,
19 index::Point as AlacPoint,
20 term::{TermMode, cell::Flags},
21 vte::ansi::{
22 Color::{self as AnsiColor, Named},
23 CursorShape as AlacCursorShape, NamedColor,
24 },
25 },
26 terminal_settings::TerminalSettings,
27};
28use theme::{ActiveTheme, Theme, ThemeSettings};
29use ui::utils::ensure_minimum_contrast;
30use ui::{ParentElement, Tooltip};
31use util::ResultExt;
32use workspace::Workspace;
33
34use std::mem;
35use std::{fmt::Debug, ops::RangeInclusive, rc::Rc};
36
37use crate::{BlockContext, BlockProperties, ContentMode, TerminalMode, TerminalView};
38
39/// The information generated during layout that is necessary for painting.
40pub struct LayoutState {
41 hitbox: Hitbox,
42 batched_text_runs: Vec<BatchedTextRun>,
43 rects: Vec<LayoutRect>,
44 relative_highlighted_ranges: Vec<(RangeInclusive<AlacPoint>, Hsla)>,
45 cursor: Option<CursorLayout>,
46 background_color: Hsla,
47 dimensions: TerminalBounds,
48 mode: TermMode,
49 display_offset: usize,
50 hyperlink_tooltip: Option<AnyElement>,
51 gutter: Pixels,
52 block_below_cursor_element: Option<AnyElement>,
53 base_text_style: TextStyle,
54 content_mode: ContentMode,
55}
56
57/// Helper struct for converting data between Alacritty's cursor points, and displayed cursor points.
58struct DisplayCursor {
59 line: i32,
60 col: usize,
61}
62
63impl DisplayCursor {
64 fn from(cursor_point: AlacPoint, display_offset: usize) -> Self {
65 Self {
66 line: cursor_point.line.0 + display_offset as i32,
67 col: cursor_point.column.0,
68 }
69 }
70
71 pub fn line(&self) -> i32 {
72 self.line
73 }
74
75 pub fn col(&self) -> usize {
76 self.col
77 }
78}
79
80/// A batched text run that combines multiple adjacent cells with the same style
81#[derive(Debug)]
82pub struct BatchedTextRun {
83 pub start_point: AlacPoint<i32, i32>,
84 pub text: String,
85 pub cell_count: usize,
86 pub style: TextRun,
87 pub font_size: AbsoluteLength,
88}
89
90impl BatchedTextRun {
91 fn new_from_char(
92 start_point: AlacPoint<i32, i32>,
93 c: char,
94 style: TextRun,
95 font_size: AbsoluteLength,
96 ) -> Self {
97 let mut text = String::with_capacity(100); // Pre-allocate for typical line length
98 text.push(c);
99 BatchedTextRun {
100 start_point,
101 text,
102 cell_count: 1,
103 style,
104 font_size,
105 }
106 }
107
108 fn can_append(&self, other_style: &TextRun) -> bool {
109 self.style.font == other_style.font
110 && self.style.color == other_style.color
111 && self.style.background_color == other_style.background_color
112 && self.style.underline == other_style.underline
113 && self.style.strikethrough == other_style.strikethrough
114 }
115
116 fn append_char(&mut self, c: char) {
117 self.append_char_internal(c, true);
118 }
119
120 fn append_zero_width_chars(&mut self, chars: &[char]) {
121 for &c in chars {
122 self.append_char_internal(c, false);
123 }
124 }
125
126 fn append_char_internal(&mut self, c: char, counts_cell: bool) {
127 self.text.push(c);
128 if counts_cell {
129 self.cell_count += 1;
130 }
131 self.style.len += c.len_utf8();
132 }
133
134 pub fn paint(
135 &self,
136 origin: Point<Pixels>,
137 dimensions: &TerminalBounds,
138 window: &mut Window,
139 cx: &mut App,
140 ) {
141 let pos = Point::new(
142 origin.x + self.start_point.column as f32 * dimensions.cell_width,
143 origin.y + self.start_point.line as f32 * dimensions.line_height,
144 );
145
146 let _ = window
147 .text_system()
148 .shape_line(
149 self.text.clone().into(),
150 self.font_size.to_pixels(window.rem_size()),
151 std::slice::from_ref(&self.style),
152 Some(dimensions.cell_width),
153 )
154 .paint(pos, dimensions.line_height, window, cx);
155 }
156}
157
158#[derive(Clone, Debug, Default)]
159pub struct LayoutRect {
160 point: AlacPoint<i32, i32>,
161 num_of_cells: usize,
162 color: Hsla,
163}
164
165impl LayoutRect {
166 fn new(point: AlacPoint<i32, i32>, num_of_cells: usize, color: Hsla) -> LayoutRect {
167 LayoutRect {
168 point,
169 num_of_cells,
170 color,
171 }
172 }
173
174 pub fn paint(&self, origin: Point<Pixels>, dimensions: &TerminalBounds, window: &mut Window) {
175 let position = {
176 let alac_point = self.point;
177 point(
178 (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
179 origin.y + alac_point.line as f32 * dimensions.line_height,
180 )
181 };
182 let size = point(
183 (dimensions.cell_width * self.num_of_cells as f32).ceil(),
184 dimensions.line_height,
185 )
186 .into();
187
188 window.paint_quad(fill(Bounds::new(position, size), self.color));
189 }
190}
191
192/// Represents a rectangular region with a specific background color
193#[derive(Debug, Clone)]
194struct BackgroundRegion {
195 start_line: i32,
196 start_col: i32,
197 end_line: i32,
198 end_col: i32,
199 color: Hsla,
200}
201
202impl BackgroundRegion {
203 fn new(line: i32, col: i32, color: Hsla) -> Self {
204 BackgroundRegion {
205 start_line: line,
206 start_col: col,
207 end_line: line,
208 end_col: col,
209 color,
210 }
211 }
212
213 /// Check if this region can be merged with another region
214 fn can_merge_with(&self, other: &BackgroundRegion) -> bool {
215 if self.color != other.color {
216 return false;
217 }
218
219 // Check if regions are adjacent horizontally
220 if self.start_line == other.start_line && self.end_line == other.end_line {
221 return self.end_col + 1 == other.start_col || other.end_col + 1 == self.start_col;
222 }
223
224 // Check if regions are adjacent vertically with same column span
225 if self.start_col == other.start_col && self.end_col == other.end_col {
226 return self.end_line + 1 == other.start_line || other.end_line + 1 == self.start_line;
227 }
228
229 false
230 }
231
232 /// Merge this region with another region
233 fn merge_with(&mut self, other: &BackgroundRegion) {
234 self.start_line = self.start_line.min(other.start_line);
235 self.start_col = self.start_col.min(other.start_col);
236 self.end_line = self.end_line.max(other.end_line);
237 self.end_col = self.end_col.max(other.end_col);
238 }
239}
240
241/// Merge background regions to minimize the number of rectangles
242fn merge_background_regions(regions: Vec<BackgroundRegion>) -> Vec<BackgroundRegion> {
243 if regions.is_empty() {
244 return regions;
245 }
246
247 let mut merged = regions;
248 let mut changed = true;
249
250 // Keep merging until no more merges are possible
251 while changed {
252 changed = false;
253 let mut i = 0;
254
255 while i < merged.len() {
256 let mut j = i + 1;
257 while j < merged.len() {
258 if merged[i].can_merge_with(&merged[j]) {
259 let other = merged.remove(j);
260 merged[i].merge_with(&other);
261 changed = true;
262 } else {
263 j += 1;
264 }
265 }
266 i += 1;
267 }
268 }
269
270 merged
271}
272
273/// The GPUI element that paints the terminal.
274/// 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?
275pub struct TerminalElement {
276 terminal: Entity<Terminal>,
277 terminal_view: Entity<TerminalView>,
278 workspace: WeakEntity<Workspace>,
279 focus: FocusHandle,
280 focused: bool,
281 cursor_visible: bool,
282 interactivity: Interactivity,
283 mode: TerminalMode,
284 block_below_cursor: Option<Rc<BlockProperties>>,
285}
286
287impl InteractiveElement for TerminalElement {
288 fn interactivity(&mut self) -> &mut Interactivity {
289 &mut self.interactivity
290 }
291}
292
293impl StatefulInteractiveElement for TerminalElement {}
294
295impl TerminalElement {
296 pub fn new(
297 terminal: Entity<Terminal>,
298 terminal_view: Entity<TerminalView>,
299 workspace: WeakEntity<Workspace>,
300 focus: FocusHandle,
301 focused: bool,
302 cursor_visible: bool,
303 block_below_cursor: Option<Rc<BlockProperties>>,
304 mode: TerminalMode,
305 ) -> TerminalElement {
306 TerminalElement {
307 terminal,
308 terminal_view,
309 workspace,
310 focused,
311 focus: focus.clone(),
312 cursor_visible,
313 block_below_cursor,
314 mode,
315 interactivity: Default::default(),
316 }
317 .track_focus(&focus)
318 }
319
320 //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
321
322 pub fn layout_grid(
323 grid: impl Iterator<Item = IndexedCell>,
324 start_line_offset: i32,
325 text_style: &TextStyle,
326 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
327 minimum_contrast: f32,
328 cx: &App,
329 ) -> (Vec<LayoutRect>, Vec<BatchedTextRun>) {
330 let start_time = Instant::now();
331 let theme = cx.theme();
332
333 // Pre-allocate with estimated capacity to reduce reallocations
334 let estimated_cells = grid.size_hint().0;
335 let estimated_runs = estimated_cells / 10; // Estimate ~10 cells per run
336 let estimated_regions = estimated_cells / 20; // Estimate ~20 cells per background region
337
338 let mut batched_runs = Vec::with_capacity(estimated_runs);
339 let mut cell_count = 0;
340
341 // Collect background regions for efficient merging
342 let mut background_regions: Vec<BackgroundRegion> = Vec::with_capacity(estimated_regions);
343 let mut current_batch: Option<BatchedTextRun> = None;
344
345 // First pass: collect all cells and their backgrounds
346 let linegroups = grid.into_iter().chunk_by(|i| i.point.line);
347 for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
348 let alac_line = start_line_offset + line_index as i32;
349
350 // Flush any existing batch at line boundaries
351 if let Some(batch) = current_batch.take() {
352 batched_runs.push(batch);
353 }
354
355 let mut previous_cell_had_extras = false;
356
357 for cell in line {
358 let mut fg = cell.fg;
359 let mut bg = cell.bg;
360 if cell.flags.contains(Flags::INVERSE) {
361 mem::swap(&mut fg, &mut bg);
362 }
363
364 // Collect background regions (skip default background)
365 if !matches!(bg, Named(NamedColor::Background)) {
366 let color = convert_color(&bg, theme);
367 let col = cell.point.column.0 as i32;
368
369 // Try to extend the last region if it's on the same line with the same color
370 if let Some(last_region) = background_regions.last_mut() {
371 if last_region.color == color
372 && last_region.start_line == alac_line
373 && last_region.end_line == alac_line
374 && last_region.end_col + 1 == col
375 {
376 last_region.end_col = col;
377 } else {
378 background_regions.push(BackgroundRegion::new(alac_line, col, color));
379 }
380 } else {
381 background_regions.push(BackgroundRegion::new(alac_line, col, color));
382 }
383 }
384 // Skip wide character spacers - they're just placeholders for the second cell of wide characters
385 if cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
386 continue;
387 }
388
389 // Skip spaces that follow cells with extras (emoji variation sequences)
390 if cell.c == ' ' && previous_cell_had_extras {
391 previous_cell_had_extras = false;
392 continue;
393 }
394 // Update tracking for next iteration
395 previous_cell_had_extras =
396 matches!(cell.zerowidth(), Some(chars) if !chars.is_empty());
397
398 //Layout current cell text
399 {
400 if !is_blank(&cell) {
401 cell_count += 1;
402 let cell_style = TerminalElement::cell_style(
403 &cell,
404 fg,
405 bg,
406 theme,
407 text_style,
408 hyperlink,
409 minimum_contrast,
410 );
411
412 let cell_point = AlacPoint::new(alac_line, cell.point.column.0 as i32);
413 let zero_width_chars = cell.zerowidth();
414
415 // Try to batch with existing run
416 if let Some(ref mut batch) = current_batch {
417 if batch.can_append(&cell_style)
418 && batch.start_point.line == cell_point.line
419 && batch.start_point.column + batch.cell_count as i32
420 == cell_point.column
421 {
422 batch.append_char(cell.c);
423 if let Some(chars) = zero_width_chars {
424 batch.append_zero_width_chars(chars);
425 }
426 } else {
427 // Flush current batch and start new one
428 let old_batch = current_batch.take().unwrap();
429 batched_runs.push(old_batch);
430 let mut new_batch = BatchedTextRun::new_from_char(
431 cell_point,
432 cell.c,
433 cell_style,
434 text_style.font_size,
435 );
436 if let Some(chars) = zero_width_chars {
437 new_batch.append_zero_width_chars(chars);
438 }
439 current_batch = Some(new_batch);
440 }
441 } else {
442 // Start new batch
443 let mut new_batch = BatchedTextRun::new_from_char(
444 cell_point,
445 cell.c,
446 cell_style,
447 text_style.font_size,
448 );
449 if let Some(chars) = zero_width_chars {
450 new_batch.append_zero_width_chars(chars);
451 }
452 current_batch = Some(new_batch);
453 }
454 };
455 }
456 }
457 }
458
459 // Flush any remaining batch
460 if let Some(batch) = current_batch {
461 batched_runs.push(batch);
462 }
463
464 // Second pass: merge background regions and convert to layout rects
465 let region_count = background_regions.len();
466 let merged_regions = merge_background_regions(background_regions);
467 let mut rects = Vec::with_capacity(merged_regions.len() * 2); // Estimate 2 rects per merged region
468
469 // Convert merged regions to layout rects
470 // Since LayoutRect only supports single-line rectangles, we need to split multi-line regions
471 for region in merged_regions {
472 for line in region.start_line..=region.end_line {
473 rects.push(LayoutRect::new(
474 AlacPoint::new(line, region.start_col),
475 (region.end_col - region.start_col + 1) as usize,
476 region.color,
477 ));
478 }
479 }
480
481 let layout_time = start_time.elapsed();
482 log::debug!(
483 "Terminal layout_grid: {} cells processed, {} batched runs created, {} rects (from {} merged regions), layout took {:?}",
484 cell_count,
485 batched_runs.len(),
486 rects.len(),
487 region_count,
488 layout_time
489 );
490
491 (rects, batched_runs)
492 }
493
494 /// Computes the cursor position and expected block width, may return a zero width if x_for_index returns
495 /// the same position for sequential indexes. Use em_width instead
496 fn shape_cursor(
497 cursor_point: DisplayCursor,
498 size: TerminalBounds,
499 text_fragment: &ShapedLine,
500 ) -> Option<(Point<Pixels>, Pixels)> {
501 if cursor_point.line() < size.total_lines() as i32 {
502 let cursor_width = if text_fragment.width == Pixels::ZERO {
503 size.cell_width()
504 } else {
505 text_fragment.width
506 };
507
508 // Cursor should always surround as much of the text as possible,
509 // hence when on pixel boundaries round the origin down and the width up
510 Some((
511 point(
512 (cursor_point.col() as f32 * size.cell_width()).floor(),
513 (cursor_point.line() as f32 * size.line_height()).floor(),
514 ),
515 cursor_width.ceil(),
516 ))
517 } else {
518 None
519 }
520 }
521
522 /// Checks if a character is a decorative block/box-like character that should
523 /// preserve its exact colors without contrast adjustment.
524 ///
525 /// This specifically targets characters used as visual connectors, separators,
526 /// and borders where color matching with adjacent backgrounds is critical.
527 /// Regular icons (git, folders, etc.) are excluded as they need to remain readable.
528 ///
529 /// Fixes https://github.com/zed-industries/zed/issues/34234
530 fn is_decorative_character(ch: char) -> bool {
531 matches!(
532 ch as u32,
533 // Unicode Box Drawing and Block Elements
534 0x2500..=0x257F // Box Drawing (â â â â etc.)
535 | 0x2580..=0x259F // Block Elements (â â â â â â etc.)
536 | 0x25A0..=0x25FF // Geometric Shapes (â âś â etc. - includes triangular/circular separators)
537
538 // Private Use Area - Powerline separator symbols only
539 | 0xE0B0..=0xE0B7 // Powerline separators: triangles (E0B0-E0B3) and half circles (E0B4-E0B7)
540 | 0xE0B8..=0xE0BF // Additional Powerline separators: angles, flames, etc.
541 | 0xE0C0..=0xE0C8 // Powerline separators: pixelated triangles, curves
542 | 0xE0CC..=0xE0D4 // Powerline separators: rounded triangles, ice/lego style
543 )
544 }
545
546 /// Converts the Alacritty cell styles to GPUI text styles and background color.
547 fn cell_style(
548 indexed: &IndexedCell,
549 fg: terminal::alacritty_terminal::vte::ansi::Color,
550 bg: terminal::alacritty_terminal::vte::ansi::Color,
551 colors: &Theme,
552 text_style: &TextStyle,
553 hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
554 minimum_contrast: f32,
555 ) -> TextRun {
556 let flags = indexed.cell.flags;
557 let mut fg = convert_color(&fg, colors);
558 let bg = convert_color(&bg, colors);
559
560 // Only apply contrast adjustment to non-decorative characters
561 if !Self::is_decorative_character(indexed.c) {
562 fg = ensure_minimum_contrast(fg, bg, minimum_contrast);
563 }
564
565 // Ghostty uses (175/255) as the multiplier (~0.69), Alacritty uses 0.66, Kitty
566 // uses 0.75. We're using 0.7 because it's pretty well in the middle of that.
567 if flags.intersects(Flags::DIM) {
568 fg.a *= 0.7;
569 }
570
571 let underline = (flags.intersects(Flags::ALL_UNDERLINES)
572 || indexed.cell.hyperlink().is_some())
573 .then(|| UnderlineStyle {
574 color: Some(fg),
575 thickness: Pixels::from(1.0),
576 wavy: flags.contains(Flags::UNDERCURL),
577 });
578
579 let strikethrough = flags
580 .intersects(Flags::STRIKEOUT)
581 .then(|| StrikethroughStyle {
582 color: Some(fg),
583 thickness: Pixels::from(1.0),
584 });
585
586 let weight = if flags.intersects(Flags::BOLD) {
587 FontWeight::BOLD
588 } else {
589 text_style.font_weight
590 };
591
592 let style = if flags.intersects(Flags::ITALIC) {
593 FontStyle::Italic
594 } else {
595 FontStyle::Normal
596 };
597
598 let mut result = TextRun {
599 len: indexed.c.len_utf8(),
600 color: fg,
601 background_color: None,
602 font: Font {
603 weight,
604 style,
605 ..text_style.font()
606 },
607 underline,
608 strikethrough,
609 };
610
611 if let Some((style, range)) = hyperlink
612 && range.contains(&indexed.point)
613 {
614 if let Some(underline) = style.underline {
615 result.underline = Some(underline);
616 }
617
618 if let Some(color) = style.color {
619 result.color = color;
620 }
621 }
622
623 result
624 }
625
626 fn generic_button_handler<E>(
627 connection: Entity<Terminal>,
628 focus_handle: FocusHandle,
629 steal_focus: bool,
630 f: impl Fn(&mut Terminal, &E, &mut Context<Terminal>),
631 ) -> impl Fn(&E, &mut Window, &mut App) {
632 move |event, window, cx| {
633 if steal_focus {
634 window.focus(&focus_handle);
635 } else if !focus_handle.is_focused(window) {
636 return;
637 }
638 connection.update(cx, |terminal, cx| {
639 f(terminal, event, cx);
640
641 cx.notify();
642 })
643 }
644 }
645
646 fn register_mouse_listeners(
647 &mut self,
648 mode: TermMode,
649 hitbox: &Hitbox,
650 content_mode: &ContentMode,
651 window: &mut Window,
652 ) {
653 let focus = self.focus.clone();
654 let terminal = self.terminal.clone();
655 let terminal_view = self.terminal_view.clone();
656
657 self.interactivity.on_mouse_down(MouseButton::Left, {
658 let terminal = terminal.clone();
659 let focus = focus.clone();
660 let terminal_view = terminal_view.clone();
661
662 move |e, window, cx| {
663 window.focus(&focus);
664
665 let scroll_top = terminal_view.read(cx).scroll_top;
666 terminal.update(cx, |terminal, cx| {
667 let mut adjusted_event = e.clone();
668 if scroll_top > Pixels::ZERO {
669 adjusted_event.position.y += scroll_top;
670 }
671 terminal.mouse_down(&adjusted_event, cx);
672 cx.notify();
673 })
674 }
675 });
676
677 window.on_mouse_event({
678 let terminal = self.terminal.clone();
679 let hitbox = hitbox.clone();
680 let focus = focus.clone();
681 let terminal_view = terminal_view;
682 move |e: &MouseMoveEvent, phase, window, cx| {
683 if phase != DispatchPhase::Bubble {
684 return;
685 }
686
687 if e.pressed_button.is_some() && !cx.has_active_drag() && focus.is_focused(window) {
688 let hovered = hitbox.is_hovered(window);
689
690 let scroll_top = terminal_view.read(cx).scroll_top;
691 terminal.update(cx, |terminal, cx| {
692 if terminal.selection_started() || hovered {
693 let mut adjusted_event = e.clone();
694 if scroll_top > Pixels::ZERO {
695 adjusted_event.position.y += scroll_top;
696 }
697 terminal.mouse_drag(&adjusted_event, hitbox.bounds, cx);
698 cx.notify();
699 }
700 })
701 }
702
703 if hitbox.is_hovered(window) {
704 terminal.update(cx, |terminal, cx| {
705 terminal.mouse_move(e, cx);
706 })
707 }
708 }
709 });
710
711 self.interactivity.on_mouse_up(
712 MouseButton::Left,
713 TerminalElement::generic_button_handler(
714 terminal.clone(),
715 focus.clone(),
716 false,
717 move |terminal, e, cx| {
718 terminal.mouse_up(e, cx);
719 },
720 ),
721 );
722 self.interactivity.on_mouse_down(
723 MouseButton::Middle,
724 TerminalElement::generic_button_handler(
725 terminal.clone(),
726 focus.clone(),
727 true,
728 move |terminal, e, cx| {
729 terminal.mouse_down(e, cx);
730 },
731 ),
732 );
733
734 if content_mode.is_scrollable() {
735 self.interactivity.on_scroll_wheel({
736 let terminal_view = self.terminal_view.downgrade();
737 move |e, window, cx| {
738 terminal_view
739 .update(cx, |terminal_view, cx| {
740 if matches!(terminal_view.mode, TerminalMode::Standalone)
741 || terminal_view.focus_handle.is_focused(window)
742 {
743 terminal_view.scroll_wheel(e, cx);
744 cx.notify();
745 }
746 })
747 .ok();
748 }
749 });
750 }
751
752 // Mouse mode handlers:
753 // All mouse modes need the extra click handlers
754 if mode.intersects(TermMode::MOUSE_MODE) {
755 self.interactivity.on_mouse_down(
756 MouseButton::Right,
757 TerminalElement::generic_button_handler(
758 terminal.clone(),
759 focus.clone(),
760 true,
761 move |terminal, e, cx| {
762 terminal.mouse_down(e, cx);
763 },
764 ),
765 );
766 self.interactivity.on_mouse_up(
767 MouseButton::Right,
768 TerminalElement::generic_button_handler(
769 terminal.clone(),
770 focus.clone(),
771 false,
772 move |terminal, e, cx| {
773 terminal.mouse_up(e, cx);
774 },
775 ),
776 );
777 self.interactivity.on_mouse_up(
778 MouseButton::Middle,
779 TerminalElement::generic_button_handler(
780 terminal,
781 focus,
782 false,
783 move |terminal, e, cx| {
784 terminal.mouse_up(e, cx);
785 },
786 ),
787 );
788 }
789 }
790
791 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
792 let settings = ThemeSettings::get_global(cx).clone();
793 let buffer_font_size = settings.buffer_font_size(cx);
794 let rem_size_scale = {
795 // Our default UI font size is 14px on a 16px base scale.
796 // This means the default UI font size is 0.875rems.
797 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
798
799 // We then determine the delta between a single rem and the default font
800 // size scale.
801 let default_font_size_delta = 1. - default_font_size_scale;
802
803 // Finally, we add this delta to 1rem to get the scale factor that
804 // should be used to scale up the UI.
805 1. + default_font_size_delta
806 };
807
808 Some(buffer_font_size * rem_size_scale)
809 }
810}
811
812impl Element for TerminalElement {
813 type RequestLayoutState = ();
814 type PrepaintState = LayoutState;
815
816 fn id(&self) -> Option<ElementId> {
817 self.interactivity.element_id.clone()
818 }
819
820 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
821 None
822 }
823
824 fn request_layout(
825 &mut self,
826 global_id: Option<&GlobalElementId>,
827 inspector_id: Option<&gpui::InspectorElementId>,
828 window: &mut Window,
829 cx: &mut App,
830 ) -> (LayoutId, Self::RequestLayoutState) {
831 let height: Length = match self.terminal_view.read(cx).content_mode(window, cx) {
832 ContentMode::Inline {
833 displayed_lines,
834 total_lines: _,
835 } => {
836 let rem_size = window.rem_size();
837 let line_height = f32::from(window.text_style().font_size.to_pixels(rem_size))
838 * TerminalSettings::get_global(cx)
839 .line_height
840 .value()
841 .to_pixels(rem_size);
842 (displayed_lines * line_height).into()
843 }
844 ContentMode::Scrollable => {
845 if let TerminalMode::Embedded { .. } = &self.mode {
846 let term = self.terminal.read(cx);
847 if !term.scrolled_to_top() && !term.scrolled_to_bottom() && self.focused {
848 self.interactivity.occlude_mouse();
849 }
850 }
851
852 relative(1.).into()
853 }
854 };
855
856 let layout_id = self.interactivity.request_layout(
857 global_id,
858 inspector_id,
859 window,
860 cx,
861 |mut style, window, cx| {
862 style.size.width = relative(1.).into();
863 style.size.height = height;
864
865 window.request_layout(style, None, cx)
866 },
867 );
868 (layout_id, ())
869 }
870
871 fn prepaint(
872 &mut self,
873 global_id: Option<&GlobalElementId>,
874 inspector_id: Option<&gpui::InspectorElementId>,
875 bounds: Bounds<Pixels>,
876 _: &mut Self::RequestLayoutState,
877 window: &mut Window,
878 cx: &mut App,
879 ) -> Self::PrepaintState {
880 let rem_size = self.rem_size(cx);
881 self.interactivity.prepaint(
882 global_id,
883 inspector_id,
884 bounds,
885 bounds.size,
886 window,
887 cx,
888 |_, _, hitbox, window, cx| {
889 let hitbox = hitbox.unwrap();
890 let settings = ThemeSettings::get_global(cx).clone();
891
892 let buffer_font_size = settings.buffer_font_size(cx);
893
894 let terminal_settings = TerminalSettings::get_global(cx);
895 let minimum_contrast = terminal_settings.minimum_contrast;
896
897 let font_family = terminal_settings.font_family.as_ref().map_or_else(
898 || settings.buffer_font.family.clone(),
899 |font_family| font_family.0.clone().into(),
900 );
901
902 let font_fallbacks = terminal_settings
903 .font_fallbacks
904 .as_ref()
905 .or(settings.buffer_font.fallbacks.as_ref())
906 .cloned();
907
908 let font_features = terminal_settings
909 .font_features
910 .as_ref()
911 .unwrap_or(&FontFeatures::disable_ligatures())
912 .clone();
913
914 let font_weight = terminal_settings.font_weight.unwrap_or_default();
915
916 let line_height = terminal_settings.line_height.value();
917
918 let font_size = match &self.mode {
919 TerminalMode::Embedded { .. } => {
920 window.text_style().font_size.to_pixels(window.rem_size())
921 }
922 TerminalMode::Standalone => terminal_settings
923 .font_size
924 .map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx)),
925 };
926
927 let theme = cx.theme().clone();
928
929 let link_style = HighlightStyle {
930 color: Some(theme.colors().link_text_hover),
931 font_weight: Some(font_weight),
932 font_style: None,
933 background_color: None,
934 underline: Some(UnderlineStyle {
935 thickness: px(1.0),
936 color: Some(theme.colors().link_text_hover),
937 wavy: false,
938 }),
939 strikethrough: None,
940 fade_out: None,
941 };
942
943 let text_style = TextStyle {
944 font_family,
945 font_features,
946 font_weight,
947 font_fallbacks,
948 font_size: font_size.into(),
949 font_style: FontStyle::Normal,
950 line_height: line_height.into(),
951 background_color: Some(theme.colors().terminal_ansi_background),
952 white_space: WhiteSpace::Normal,
953 // These are going to be overridden per-cell
954 color: theme.colors().terminal_foreground,
955 ..Default::default()
956 };
957
958 let text_system = cx.text_system();
959 let player_color = theme.players().local();
960 let match_color = theme.colors().search_match_background;
961 let gutter;
962 let (dimensions, line_height_px) = {
963 let rem_size = window.rem_size();
964 let font_pixels = text_style.font_size.to_pixels(rem_size);
965 // TODO: line_height should be an f32 not an AbsoluteLength.
966 let line_height = f32::from(font_pixels) * line_height.to_pixels(rem_size);
967 let font_id = cx.text_system().resolve_font(&text_style.font());
968
969 let cell_width = text_system
970 .advance(font_id, font_pixels, 'm')
971 .unwrap()
972 .width;
973 gutter = cell_width;
974
975 let mut size = bounds.size;
976 size.width -= gutter;
977
978 // https://github.com/zed-industries/zed/issues/2750
979 // if the terminal is one column wide, rendering đŚ
980 // causes alacritty to misbehave.
981 if size.width < cell_width * 2.0 {
982 size.width = cell_width * 2.0;
983 }
984
985 let mut origin = bounds.origin;
986 origin.x += gutter;
987
988 (
989 TerminalBounds::new(line_height, cell_width, Bounds { origin, size }),
990 line_height,
991 )
992 };
993
994 let search_matches = self.terminal.read(cx).matches.clone();
995
996 let background_color = theme.colors().terminal_background;
997
998 let (last_hovered_word, hover_tooltip) =
999 self.terminal.update(cx, |terminal, cx| {
1000 terminal.set_size(dimensions);
1001 terminal.sync(window, cx);
1002
1003 if window.modifiers().secondary()
1004 && bounds.contains(&window.mouse_position())
1005 && self.terminal_view.read(cx).hover.is_some()
1006 {
1007 let registered_hover = self.terminal_view.read(cx).hover.as_ref();
1008 if terminal.last_content.last_hovered_word.as_ref()
1009 == registered_hover.map(|hover| &hover.hovered_word)
1010 {
1011 (
1012 terminal.last_content.last_hovered_word.clone(),
1013 registered_hover.map(|hover| hover.tooltip.clone()),
1014 )
1015 } else {
1016 (None, None)
1017 }
1018 } else {
1019 (None, None)
1020 }
1021 });
1022
1023 let scroll_top = self.terminal_view.read(cx).scroll_top;
1024 let hyperlink_tooltip = hover_tooltip.map(|hover_tooltip| {
1025 let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
1026 let mut element = div()
1027 .size_full()
1028 .id("terminal-element")
1029 .tooltip(Tooltip::text(hover_tooltip))
1030 .into_any_element();
1031 element.prepaint_as_root(offset, bounds.size.into(), window, cx);
1032 element
1033 });
1034
1035 let TerminalContent {
1036 cells,
1037 mode,
1038 display_offset,
1039 cursor_char,
1040 selection,
1041 cursor,
1042 ..
1043 } = &self.terminal.read(cx).last_content;
1044 let mode = *mode;
1045 let display_offset = *display_offset;
1046
1047 // searches, highlights to a single range representations
1048 let mut relative_highlighted_ranges = Vec::new();
1049 for search_match in search_matches {
1050 relative_highlighted_ranges.push((search_match, match_color))
1051 }
1052 if let Some(selection) = selection {
1053 relative_highlighted_ranges
1054 .push((selection.start..=selection.end, player_color.selection));
1055 }
1056
1057 // then have that representation be converted to the appropriate highlight data structure
1058
1059 let content_mode = self.terminal_view.read(cx).content_mode(window, cx);
1060 let (rects, batched_text_runs) = match content_mode {
1061 ContentMode::Scrollable => {
1062 // In scrollable mode, the terminal already provides cells
1063 // that are correctly positioned for the current viewport
1064 // based on its display_offset. We don't need additional filtering.
1065 TerminalElement::layout_grid(
1066 cells.iter().cloned(),
1067 0,
1068 &text_style,
1069 last_hovered_word.as_ref().map(|last_hovered_word| {
1070 (link_style, &last_hovered_word.word_match)
1071 }),
1072 minimum_contrast,
1073 cx,
1074 )
1075 }
1076 ContentMode::Inline { .. } => {
1077 let intersection = window.content_mask().bounds.intersect(&bounds);
1078 let start_row = (intersection.top() - bounds.top()) / line_height_px;
1079 let end_row = start_row + intersection.size.height / line_height_px;
1080 let line_range = (start_row as i32)..=(end_row as i32);
1081
1082 TerminalElement::layout_grid(
1083 cells
1084 .iter()
1085 .skip_while(|i| &i.point.line < line_range.start())
1086 .take_while(|i| &i.point.line <= line_range.end())
1087 .cloned(),
1088 *line_range.start(),
1089 &text_style,
1090 last_hovered_word.as_ref().map(|last_hovered_word| {
1091 (link_style, &last_hovered_word.word_match)
1092 }),
1093 minimum_contrast,
1094 cx,
1095 )
1096 }
1097 };
1098
1099 // Layout cursor. Rectangle is used for IME, so we should lay it out even
1100 // if we don't end up showing it.
1101 let cursor = if let AlacCursorShape::Hidden = cursor.shape {
1102 None
1103 } else {
1104 let cursor_point = DisplayCursor::from(cursor.point, display_offset);
1105 let cursor_text = {
1106 let str_trxt = cursor_char.to_string();
1107 let len = str_trxt.len();
1108 window.text_system().shape_line(
1109 str_trxt.into(),
1110 text_style.font_size.to_pixels(window.rem_size()),
1111 &[TextRun {
1112 len,
1113 font: text_style.font(),
1114 color: theme.colors().terminal_ansi_background,
1115 ..Default::default()
1116 }],
1117 None,
1118 )
1119 };
1120
1121 let focused = self.focused;
1122 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
1123 move |(cursor_position, block_width)| {
1124 let (shape, text) = match cursor.shape {
1125 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
1126 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
1127 AlacCursorShape::Underline => (CursorShape::Underline, None),
1128 AlacCursorShape::Beam => (CursorShape::Bar, None),
1129 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
1130 //This case is handled in the if wrapping the whole cursor layout
1131 AlacCursorShape::Hidden => unreachable!(),
1132 };
1133
1134 CursorLayout::new(
1135 cursor_position,
1136 block_width,
1137 dimensions.line_height,
1138 theme.players().local().cursor,
1139 shape,
1140 text,
1141 )
1142 },
1143 )
1144 };
1145
1146 let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
1147 let terminal = self.terminal.read(cx);
1148 if terminal.last_content.display_offset == 0 {
1149 let target_line = terminal.last_content.cursor.point.line.0 + 1;
1150 let render = &block.render;
1151 let mut block_cx = BlockContext {
1152 window,
1153 context: cx,
1154 dimensions,
1155 };
1156 let element = render(&mut block_cx);
1157 let mut element = div().occlude().child(element).into_any_element();
1158 let available_space = size(
1159 AvailableSpace::Definite(dimensions.width() + gutter),
1160 AvailableSpace::Definite(
1161 block.height as f32 * dimensions.line_height(),
1162 ),
1163 );
1164 let origin = bounds.origin
1165 + point(px(0.), target_line as f32 * dimensions.line_height())
1166 - point(px(0.), scroll_top);
1167 window.with_rem_size(rem_size, |window| {
1168 element.prepaint_as_root(origin, available_space, window, cx);
1169 });
1170 Some(element)
1171 } else {
1172 None
1173 }
1174 } else {
1175 None
1176 };
1177
1178 LayoutState {
1179 hitbox,
1180 batched_text_runs,
1181 cursor,
1182 background_color,
1183 dimensions,
1184 rects,
1185 relative_highlighted_ranges,
1186 mode,
1187 display_offset,
1188 hyperlink_tooltip,
1189 gutter,
1190 block_below_cursor_element,
1191 base_text_style: text_style,
1192 content_mode,
1193 }
1194 },
1195 )
1196 }
1197
1198 fn paint(
1199 &mut self,
1200 global_id: Option<&GlobalElementId>,
1201 inspector_id: Option<&gpui::InspectorElementId>,
1202 bounds: Bounds<Pixels>,
1203 _: &mut Self::RequestLayoutState,
1204 layout: &mut Self::PrepaintState,
1205 window: &mut Window,
1206 cx: &mut App,
1207 ) {
1208 let paint_start = Instant::now();
1209 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1210 let scroll_top = self.terminal_view.read(cx).scroll_top;
1211
1212 window.paint_quad(fill(bounds, layout.background_color));
1213 let origin =
1214 bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
1215
1216 let marked_text_cloned: Option<String> = {
1217 let ime_state = &self.terminal_view.read(cx).ime_state;
1218 ime_state.as_ref().map(|state| state.marked_text.clone())
1219 };
1220
1221 let terminal_input_handler = TerminalInputHandler {
1222 terminal: self.terminal.clone(),
1223 terminal_view: self.terminal_view.clone(),
1224 cursor_bounds: layout
1225 .cursor
1226 .as_ref()
1227 .map(|cursor| cursor.bounding_rect(origin)),
1228 workspace: self.workspace.clone(),
1229 };
1230
1231 self.register_mouse_listeners(
1232 layout.mode,
1233 &layout.hitbox,
1234 &layout.content_mode,
1235 window,
1236 );
1237 if window.modifiers().secondary()
1238 && bounds.contains(&window.mouse_position())
1239 && self.terminal_view.read(cx).hover.is_some()
1240 {
1241 window.set_cursor_style(gpui::CursorStyle::PointingHand, &layout.hitbox);
1242 } else {
1243 window.set_cursor_style(gpui::CursorStyle::IBeam, &layout.hitbox);
1244 }
1245
1246 let original_cursor = layout.cursor.take();
1247 let hyperlink_tooltip = layout.hyperlink_tooltip.take();
1248 let block_below_cursor_element = layout.block_below_cursor_element.take();
1249 self.interactivity.paint(
1250 global_id,
1251 inspector_id,
1252 bounds,
1253 Some(&layout.hitbox),
1254 window,
1255 cx,
1256 |_, window, cx| {
1257 window.handle_input(&self.focus, terminal_input_handler, cx);
1258
1259 window.on_key_event({
1260 let this = self.terminal.clone();
1261 move |event: &ModifiersChangedEvent, phase, window, cx| {
1262 if phase != DispatchPhase::Bubble {
1263 return;
1264 }
1265
1266 this.update(cx, |term, cx| {
1267 term.try_modifiers_change(&event.modifiers, window, cx)
1268 });
1269 }
1270 });
1271
1272 for rect in &layout.rects {
1273 rect.paint(origin, &layout.dimensions, window);
1274 }
1275
1276 for (relative_highlighted_range, color) in
1277 layout.relative_highlighted_ranges.iter()
1278 {
1279 if let Some((start_y, highlighted_range_lines)) =
1280 to_highlighted_range_lines(relative_highlighted_range, layout, origin)
1281 {
1282 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
1283 0.15 * layout.dimensions.line_height
1284 } else {
1285 Pixels::ZERO
1286 };
1287 let hr = HighlightedRange {
1288 start_y,
1289 line_height: layout.dimensions.line_height,
1290 lines: highlighted_range_lines,
1291 color: *color,
1292 corner_radius: corner_radius,
1293 };
1294 hr.paint(true, bounds, window);
1295 }
1296 }
1297
1298 // Paint batched text runs instead of individual cells
1299 let text_paint_start = Instant::now();
1300 for batch in &layout.batched_text_runs {
1301 batch.paint(origin, &layout.dimensions, window, cx);
1302 }
1303 let text_paint_time = text_paint_start.elapsed();
1304
1305 if let Some(text_to_mark) = &marked_text_cloned
1306 && !text_to_mark.is_empty()
1307 && let Some(cursor_layout) = &original_cursor {
1308 let ime_position = cursor_layout.bounding_rect(origin).origin;
1309 let mut ime_style = layout.base_text_style.clone();
1310 ime_style.underline = Some(UnderlineStyle {
1311 color: Some(ime_style.color),
1312 thickness: px(1.0),
1313 wavy: false,
1314 });
1315
1316 let shaped_line = window.text_system().shape_line(
1317 text_to_mark.clone().into(),
1318 ime_style.font_size.to_pixels(window.rem_size()),
1319 &[TextRun {
1320 len: text_to_mark.len(),
1321 font: ime_style.font(),
1322 color: ime_style.color,
1323 underline: ime_style.underline,
1324 ..Default::default()
1325 }],
1326 None
1327 );
1328 shaped_line
1329 .paint(ime_position, layout.dimensions.line_height, window, cx)
1330 .log_err();
1331 }
1332
1333 if self.cursor_visible && marked_text_cloned.is_none()
1334 && let Some(mut cursor) = original_cursor {
1335 cursor.paint(origin, window, cx);
1336 }
1337
1338 if let Some(mut element) = block_below_cursor_element {
1339 element.paint(window, cx);
1340 }
1341
1342 if let Some(mut element) = hyperlink_tooltip {
1343 element.paint(window, cx);
1344 }
1345 let total_paint_time = paint_start.elapsed();
1346 log::debug!(
1347 "Terminal paint: {} text runs, {} rects, text paint took {:?}, total paint took {:?}",
1348 layout.batched_text_runs.len(),
1349 layout.rects.len(),
1350 text_paint_time,
1351 total_paint_time
1352 );
1353 },
1354 );
1355 });
1356 }
1357}
1358
1359impl IntoElement for TerminalElement {
1360 type Element = Self;
1361
1362 fn into_element(self) -> Self::Element {
1363 self
1364 }
1365}
1366
1367struct TerminalInputHandler {
1368 terminal: Entity<Terminal>,
1369 terminal_view: Entity<TerminalView>,
1370 workspace: WeakEntity<Workspace>,
1371 cursor_bounds: Option<Bounds<Pixels>>,
1372}
1373
1374impl InputHandler for TerminalInputHandler {
1375 fn selected_text_range(
1376 &mut self,
1377 _ignore_disabled_input: bool,
1378 _: &mut Window,
1379 cx: &mut App,
1380 ) -> Option<UTF16Selection> {
1381 if self
1382 .terminal
1383 .read(cx)
1384 .last_content
1385 .mode
1386 .contains(TermMode::ALT_SCREEN)
1387 {
1388 None
1389 } else {
1390 Some(UTF16Selection {
1391 range: 0..0,
1392 reversed: false,
1393 })
1394 }
1395 }
1396
1397 fn marked_text_range(
1398 &mut self,
1399 _window: &mut Window,
1400 cx: &mut App,
1401 ) -> Option<std::ops::Range<usize>> {
1402 self.terminal_view.read(cx).marked_text_range()
1403 }
1404
1405 fn text_for_range(
1406 &mut self,
1407 _: std::ops::Range<usize>,
1408 _: &mut Option<std::ops::Range<usize>>,
1409 _: &mut Window,
1410 _: &mut App,
1411 ) -> Option<String> {
1412 None
1413 }
1414
1415 fn replace_text_in_range(
1416 &mut self,
1417 _replacement_range: Option<std::ops::Range<usize>>,
1418 text: &str,
1419 window: &mut Window,
1420 cx: &mut App,
1421 ) {
1422 self.terminal_view.update(cx, |view, view_cx| {
1423 view.clear_marked_text(view_cx);
1424 view.commit_text(text, view_cx);
1425 });
1426
1427 self.workspace
1428 .update(cx, |this, cx| {
1429 window.invalidate_character_coordinates();
1430 let project = this.project().read(cx);
1431 let telemetry = project.client().telemetry().clone();
1432 telemetry.log_edit_event("terminal", project.is_via_remote_server());
1433 })
1434 .ok();
1435 }
1436
1437 fn replace_and_mark_text_in_range(
1438 &mut self,
1439 _range_utf16: Option<std::ops::Range<usize>>,
1440 new_text: &str,
1441 new_marked_range: Option<std::ops::Range<usize>>,
1442 _window: &mut Window,
1443 cx: &mut App,
1444 ) {
1445 self.terminal_view.update(cx, |view, view_cx| {
1446 view.set_marked_text(new_text.to_string(), new_marked_range, view_cx);
1447 });
1448 }
1449
1450 fn unmark_text(&mut self, _window: &mut Window, cx: &mut App) {
1451 self.terminal_view.update(cx, |view, view_cx| {
1452 view.clear_marked_text(view_cx);
1453 });
1454 }
1455
1456 fn bounds_for_range(
1457 &mut self,
1458 range_utf16: std::ops::Range<usize>,
1459 _window: &mut Window,
1460 cx: &mut App,
1461 ) -> Option<Bounds<Pixels>> {
1462 let term_bounds = self.terminal_view.read(cx).terminal_bounds(cx);
1463
1464 let mut bounds = self.cursor_bounds?;
1465 let offset_x = term_bounds.cell_width * range_utf16.start as f32;
1466 bounds.origin.x += offset_x;
1467
1468 Some(bounds)
1469 }
1470
1471 fn apple_press_and_hold_enabled(&mut self) -> bool {
1472 false
1473 }
1474
1475 fn character_index_for_point(
1476 &mut self,
1477 _point: Point<Pixels>,
1478 _window: &mut Window,
1479 _cx: &mut App,
1480 ) -> Option<usize> {
1481 None
1482 }
1483}
1484
1485pub fn is_blank(cell: &IndexedCell) -> bool {
1486 if cell.c != ' ' {
1487 return false;
1488 }
1489
1490 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1491 return false;
1492 }
1493
1494 if cell.hyperlink().is_some() {
1495 return false;
1496 }
1497
1498 if cell
1499 .flags
1500 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1501 {
1502 return false;
1503 }
1504
1505 true
1506}
1507
1508fn to_highlighted_range_lines(
1509 range: &RangeInclusive<AlacPoint>,
1510 layout: &LayoutState,
1511 origin: Point<Pixels>,
1512) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1513 // Step 1. Normalize the points to be viewport relative.
1514 // When display_offset = 1, here's how the grid is arranged:
1515 //-2,0 -2,1...
1516 //--- Viewport top
1517 //-1,0 -1,1...
1518 //--------- Terminal Top
1519 // 0,0 0,1...
1520 // 1,0 1,1...
1521 //--- Viewport Bottom
1522 // 2,0 2,1...
1523 //--------- Terminal Bottom
1524
1525 // Normalize to viewport relative, from terminal relative.
1526 // lines are i32s, which are negative above the top left corner of the terminal
1527 // If the user has scrolled, we use the display_offset to tell us which offset
1528 // of the grid data we should be looking at. But for the rendering step, we don't
1529 // want negatives. We want things relative to the 'viewport' (the area of the grid
1530 // which is currently shown according to the display offset)
1531 let unclamped_start = AlacPoint::new(
1532 range.start().line + layout.display_offset,
1533 range.start().column,
1534 );
1535 let unclamped_end =
1536 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1537
1538 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1539 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1540 return None;
1541 }
1542
1543 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1544 let clamped_end_line = unclamped_end
1545 .line
1546 .0
1547 .min(layout.dimensions.num_lines() as i32) as usize;
1548 //Convert the start of the range to pixels
1549 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1550
1551 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1552 // (also convert to pixels)
1553 let mut highlighted_range_lines = Vec::new();
1554 for line in clamped_start_line..=clamped_end_line {
1555 let mut line_start = 0;
1556 let mut line_end = layout.dimensions.columns();
1557
1558 if line == clamped_start_line {
1559 line_start = unclamped_start.column.0;
1560 }
1561 if line == clamped_end_line {
1562 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1563 }
1564
1565 highlighted_range_lines.push(HighlightedRangeLine {
1566 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1567 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1568 });
1569 }
1570
1571 Some((start_y, highlighted_range_lines))
1572}
1573
1574/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1575pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1576 let colors = theme.colors();
1577 match fg {
1578 // Named and theme defined colors
1579 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1580 NamedColor::Black => colors.terminal_ansi_black,
1581 NamedColor::Red => colors.terminal_ansi_red,
1582 NamedColor::Green => colors.terminal_ansi_green,
1583 NamedColor::Yellow => colors.terminal_ansi_yellow,
1584 NamedColor::Blue => colors.terminal_ansi_blue,
1585 NamedColor::Magenta => colors.terminal_ansi_magenta,
1586 NamedColor::Cyan => colors.terminal_ansi_cyan,
1587 NamedColor::White => colors.terminal_ansi_white,
1588 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1589 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1590 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1591 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1592 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1593 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1594 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1595 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1596 NamedColor::Foreground => colors.terminal_foreground,
1597 NamedColor::Background => colors.terminal_ansi_background,
1598 NamedColor::Cursor => theme.players().local().cursor,
1599 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1600 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1601 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1602 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1603 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1604 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1605 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1606 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1607 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1608 NamedColor::DimForeground => colors.terminal_dim_foreground,
1609 },
1610 // 'True' colors
1611 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1612 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1613 }
1614 // 8 bit, indexed colors
1615 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1616 terminal::get_color_at_index(*i as usize, theme)
1617 }
1618 }
1619}
1620
1621#[cfg(test)]
1622mod tests {
1623 use super::*;
1624 use gpui::{AbsoluteLength, Hsla, font};
1625 use ui::utils::apca_contrast;
1626
1627 #[test]
1628 fn test_is_decorative_character() {
1629 // Box Drawing characters (U+2500 to U+257F)
1630 assert!(TerminalElement::is_decorative_character('â')); // U+2500
1631 assert!(TerminalElement::is_decorative_character('â')); // U+2502
1632 assert!(TerminalElement::is_decorative_character('â')); // U+250C
1633 assert!(TerminalElement::is_decorative_character('â')); // U+2510
1634 assert!(TerminalElement::is_decorative_character('â')); // U+2514
1635 assert!(TerminalElement::is_decorative_character('â')); // U+2518
1636 assert!(TerminalElement::is_decorative_character('âź')); // U+253C
1637
1638 // Block Elements (U+2580 to U+259F)
1639 assert!(TerminalElement::is_decorative_character('â')); // U+2580
1640 assert!(TerminalElement::is_decorative_character('â')); // U+2584
1641 assert!(TerminalElement::is_decorative_character('â')); // U+2588
1642 assert!(TerminalElement::is_decorative_character('â')); // U+2591
1643 assert!(TerminalElement::is_decorative_character('â')); // U+2592
1644 assert!(TerminalElement::is_decorative_character('â')); // U+2593
1645
1646 // Geometric Shapes - block/box-like subset (U+25A0 to U+25D7)
1647 assert!(TerminalElement::is_decorative_character('â ')); // U+25A0
1648 assert!(TerminalElement::is_decorative_character('âĄ')); // U+25A1
1649 assert!(TerminalElement::is_decorative_character('â˛')); // U+25B2
1650 assert!(TerminalElement::is_decorative_character('âź')); // U+25BC
1651 assert!(TerminalElement::is_decorative_character('â')); // U+25C6
1652 assert!(TerminalElement::is_decorative_character('â')); // U+25CF
1653
1654 // The specific character from the issue
1655 assert!(TerminalElement::is_decorative_character('â')); // U+25D7
1656 assert!(TerminalElement::is_decorative_character('â')); // U+25D8 (now included in Geometric Shapes)
1657 assert!(TerminalElement::is_decorative_character('â')); // U+25D9 (now included in Geometric Shapes)
1658
1659 // Powerline symbols (Private Use Area)
1660 assert!(TerminalElement::is_decorative_character('\u{E0B0}')); // Powerline right triangle
1661 assert!(TerminalElement::is_decorative_character('\u{E0B2}')); // Powerline left triangle
1662 assert!(TerminalElement::is_decorative_character('\u{E0B4}')); // Powerline right half circle (the actual issue!)
1663 assert!(TerminalElement::is_decorative_character('\u{E0B6}')); // Powerline left half circle
1664
1665 // Characters that should NOT be considered decorative
1666 assert!(!TerminalElement::is_decorative_character('A')); // Regular letter
1667 assert!(!TerminalElement::is_decorative_character('$')); // Symbol
1668 assert!(!TerminalElement::is_decorative_character(' ')); // Space
1669 assert!(!TerminalElement::is_decorative_character('â')); // U+2190 (Arrow, not in our ranges)
1670 assert!(!TerminalElement::is_decorative_character('â')); // U+2192 (Arrow, not in our ranges)
1671 assert!(!TerminalElement::is_decorative_character('\u{F00C}')); // Font Awesome check (icon, needs contrast)
1672 assert!(!TerminalElement::is_decorative_character('\u{E711}')); // Devicons (icon, needs contrast)
1673 assert!(!TerminalElement::is_decorative_character('\u{EA71}')); // Codicons folder (icon, needs contrast)
1674 assert!(!TerminalElement::is_decorative_character('\u{F401}')); // Octicons (icon, needs contrast)
1675 assert!(!TerminalElement::is_decorative_character('\u{1F600}')); // Emoji (not in our ranges)
1676 }
1677
1678 #[test]
1679 fn test_decorative_character_boundary_cases() {
1680 // Test exact boundaries of our ranges
1681 // Box Drawing range boundaries
1682 assert!(TerminalElement::is_decorative_character('\u{2500}')); // First char
1683 assert!(TerminalElement::is_decorative_character('\u{257F}')); // Last char
1684 assert!(!TerminalElement::is_decorative_character('\u{24FF}')); // Just before
1685
1686 // Block Elements range boundaries
1687 assert!(TerminalElement::is_decorative_character('\u{2580}')); // First char
1688 assert!(TerminalElement::is_decorative_character('\u{259F}')); // Last char
1689
1690 // Geometric Shapes subset boundaries
1691 assert!(TerminalElement::is_decorative_character('\u{25A0}')); // First char
1692 assert!(TerminalElement::is_decorative_character('\u{25FF}')); // Last char
1693 assert!(!TerminalElement::is_decorative_character('\u{2600}')); // Just after
1694 }
1695
1696 #[test]
1697 fn test_decorative_characters_bypass_contrast_adjustment() {
1698 // Decorative characters should not be affected by contrast adjustment
1699
1700 // The specific character from issue #34234
1701 let problematic_char = 'â'; // U+25D7
1702 assert!(
1703 TerminalElement::is_decorative_character(problematic_char),
1704 "Character â (U+25D7) should be recognized as decorative"
1705 );
1706
1707 // Verify some other commonly used decorative characters
1708 assert!(TerminalElement::is_decorative_character('â')); // Vertical line
1709 assert!(TerminalElement::is_decorative_character('â')); // Horizontal line
1710 assert!(TerminalElement::is_decorative_character('â')); // Full block
1711 assert!(TerminalElement::is_decorative_character('â')); // Dark shade
1712 assert!(TerminalElement::is_decorative_character('â ')); // Black square
1713 assert!(TerminalElement::is_decorative_character('â')); // Black circle
1714
1715 // Verify normal text characters are NOT decorative
1716 assert!(!TerminalElement::is_decorative_character('A'));
1717 assert!(!TerminalElement::is_decorative_character('1'));
1718 assert!(!TerminalElement::is_decorative_character('$'));
1719 assert!(!TerminalElement::is_decorative_character(' '));
1720 }
1721
1722 #[test]
1723 fn test_contrast_adjustment_logic() {
1724 // Test the core contrast adjustment logic without needing full app context
1725
1726 // Test case 1: Light colors (poor contrast)
1727 let white_fg = gpui::Hsla {
1728 h: 0.0,
1729 s: 0.0,
1730 l: 1.0,
1731 a: 1.0,
1732 };
1733 let light_gray_bg = gpui::Hsla {
1734 h: 0.0,
1735 s: 0.0,
1736 l: 0.95,
1737 a: 1.0,
1738 };
1739
1740 // Should have poor contrast
1741 let actual_contrast = apca_contrast(white_fg, light_gray_bg).abs();
1742 assert!(
1743 actual_contrast < 30.0,
1744 "White on light gray should have poor APCA contrast: {}",
1745 actual_contrast
1746 );
1747
1748 // After adjustment with minimum APCA contrast of 45, should be darker
1749 let adjusted = ensure_minimum_contrast(white_fg, light_gray_bg, 45.0);
1750 assert!(
1751 adjusted.l < white_fg.l,
1752 "Adjusted color should be darker than original"
1753 );
1754 let adjusted_contrast = apca_contrast(adjusted, light_gray_bg).abs();
1755 assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1756
1757 // Test case 2: Dark colors (poor contrast)
1758 let black_fg = gpui::Hsla {
1759 h: 0.0,
1760 s: 0.0,
1761 l: 0.0,
1762 a: 1.0,
1763 };
1764 let dark_gray_bg = gpui::Hsla {
1765 h: 0.0,
1766 s: 0.0,
1767 l: 0.05,
1768 a: 1.0,
1769 };
1770
1771 // Should have poor contrast
1772 let actual_contrast = apca_contrast(black_fg, dark_gray_bg).abs();
1773 assert!(
1774 actual_contrast < 30.0,
1775 "Black on dark gray should have poor APCA contrast: {}",
1776 actual_contrast
1777 );
1778
1779 // After adjustment with minimum APCA contrast of 45, should be lighter
1780 let adjusted = ensure_minimum_contrast(black_fg, dark_gray_bg, 45.0);
1781 assert!(
1782 adjusted.l > black_fg.l,
1783 "Adjusted color should be lighter than original"
1784 );
1785 let adjusted_contrast = apca_contrast(adjusted, dark_gray_bg).abs();
1786 assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1787
1788 // Test case 3: Already good contrast
1789 let good_contrast = ensure_minimum_contrast(black_fg, white_fg, 45.0);
1790 assert_eq!(
1791 good_contrast, black_fg,
1792 "Good contrast should not be adjusted"
1793 );
1794 }
1795
1796 #[test]
1797 fn test_white_on_white_contrast_issue() {
1798 // This test reproduces the exact issue from the bug report
1799 // where white ANSI text on white background should be adjusted
1800
1801 // Simulate One Light theme colors
1802 let white_fg = gpui::Hsla {
1803 h: 0.0,
1804 s: 0.0,
1805 l: 0.98, // #fafafaff is approximately 98% lightness
1806 a: 1.0,
1807 };
1808 let white_bg = gpui::Hsla {
1809 h: 0.0,
1810 s: 0.0,
1811 l: 0.98, // Same as foreground - this is the problem!
1812 a: 1.0,
1813 };
1814
1815 // With minimum contrast of 0.0, no adjustment should happen
1816 let no_adjust = ensure_minimum_contrast(white_fg, white_bg, 0.0);
1817 assert_eq!(no_adjust, white_fg, "No adjustment with min_contrast 0.0");
1818
1819 // With minimum APCA contrast of 15, it should adjust to a darker color
1820 let adjusted = ensure_minimum_contrast(white_fg, white_bg, 15.0);
1821 assert!(
1822 adjusted.l < white_fg.l,
1823 "White on white should become darker, got l={}",
1824 adjusted.l
1825 );
1826
1827 // Verify the contrast is now acceptable
1828 let new_contrast = apca_contrast(adjusted, white_bg).abs();
1829 assert!(
1830 new_contrast >= 15.0,
1831 "Adjusted APCA contrast {} should be >= 15.0",
1832 new_contrast
1833 );
1834 }
1835
1836 #[test]
1837 fn test_batched_text_run_can_append() {
1838 let style1 = TextRun {
1839 len: 1,
1840 font: font("Helvetica"),
1841 color: Hsla::red(),
1842 ..Default::default()
1843 };
1844
1845 let style2 = TextRun {
1846 len: 1,
1847 font: font("Helvetica"),
1848 color: Hsla::red(),
1849 ..Default::default()
1850 };
1851
1852 let style3 = TextRun {
1853 len: 1,
1854 font: font("Helvetica"),
1855 color: Hsla::blue(), // Different color
1856 ..Default::default()
1857 };
1858
1859 let font_size = AbsoluteLength::Pixels(px(12.0));
1860 let batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style1, font_size);
1861
1862 // Should be able to append same style
1863 assert!(batch.can_append(&style2));
1864
1865 // Should not be able to append different style
1866 assert!(!batch.can_append(&style3));
1867 }
1868
1869 #[test]
1870 fn test_batched_text_run_append() {
1871 let style = TextRun {
1872 len: 1,
1873 font: font("Helvetica"),
1874 color: Hsla::red(),
1875 ..Default::default()
1876 };
1877
1878 let font_size = AbsoluteLength::Pixels(px(12.0));
1879 let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style, font_size);
1880
1881 assert_eq!(batch.text, "a");
1882 assert_eq!(batch.cell_count, 1);
1883 assert_eq!(batch.style.len, 1);
1884
1885 batch.append_char('b');
1886
1887 assert_eq!(batch.text, "ab");
1888 assert_eq!(batch.cell_count, 2);
1889 assert_eq!(batch.style.len, 2);
1890
1891 batch.append_char('c');
1892
1893 assert_eq!(batch.text, "abc");
1894 assert_eq!(batch.cell_count, 3);
1895 assert_eq!(batch.style.len, 3);
1896 }
1897
1898 #[test]
1899 fn test_batched_text_run_append_char() {
1900 let style = TextRun {
1901 len: 1,
1902 font: font("Helvetica"),
1903 color: Hsla::red(),
1904 ..Default::default()
1905 };
1906
1907 let font_size = AbsoluteLength::Pixels(px(12.0));
1908 let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'x', style, font_size);
1909
1910 assert_eq!(batch.text, "x");
1911 assert_eq!(batch.cell_count, 1);
1912 assert_eq!(batch.style.len, 1);
1913
1914 batch.append_char('y');
1915
1916 assert_eq!(batch.text, "xy");
1917 assert_eq!(batch.cell_count, 2);
1918 assert_eq!(batch.style.len, 2);
1919
1920 // Test with multi-byte character
1921 batch.append_char('đ');
1922
1923 assert_eq!(batch.text, "xyđ");
1924 assert_eq!(batch.cell_count, 3);
1925 assert_eq!(batch.style.len, 6); // 1 + 1 + 4 bytes for emoji
1926 }
1927
1928 #[test]
1929 fn test_batched_text_run_append_zero_width_char() {
1930 let style = TextRun {
1931 len: 1,
1932 font: font("Helvetica"),
1933 color: Hsla::red(),
1934 ..Default::default()
1935 };
1936
1937 let font_size = AbsoluteLength::Pixels(px(12.0));
1938 let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'x', style, font_size);
1939
1940 let combining = '\u{0301}';
1941 batch.append_zero_width_chars(&[combining]);
1942
1943 assert_eq!(batch.text, format!("x{}", combining));
1944 assert_eq!(batch.cell_count, 1);
1945 assert_eq!(batch.style.len, 1 + combining.len_utf8());
1946 }
1947
1948 #[test]
1949 fn test_background_region_can_merge() {
1950 let color1 = Hsla::red();
1951 let color2 = Hsla::blue();
1952
1953 // Test horizontal merging
1954 let mut region1 = BackgroundRegion::new(0, 0, color1);
1955 region1.end_col = 5;
1956 let region2 = BackgroundRegion::new(0, 6, color1);
1957 assert!(region1.can_merge_with(®ion2));
1958
1959 // Test vertical merging with same column span
1960 let mut region3 = BackgroundRegion::new(0, 0, color1);
1961 region3.end_col = 5;
1962 let mut region4 = BackgroundRegion::new(1, 0, color1);
1963 region4.end_col = 5;
1964 assert!(region3.can_merge_with(®ion4));
1965
1966 // Test cannot merge different colors
1967 let region5 = BackgroundRegion::new(0, 0, color1);
1968 let region6 = BackgroundRegion::new(0, 1, color2);
1969 assert!(!region5.can_merge_with(®ion6));
1970
1971 // Test cannot merge non-adjacent regions
1972 let region7 = BackgroundRegion::new(0, 0, color1);
1973 let region8 = BackgroundRegion::new(0, 2, color1);
1974 assert!(!region7.can_merge_with(®ion8));
1975
1976 // Test cannot merge vertical regions with different column spans
1977 let mut region9 = BackgroundRegion::new(0, 0, color1);
1978 region9.end_col = 5;
1979 let mut region10 = BackgroundRegion::new(1, 0, color1);
1980 region10.end_col = 6;
1981 assert!(!region9.can_merge_with(®ion10));
1982 }
1983
1984 #[test]
1985 fn test_background_region_merge() {
1986 let color = Hsla::red();
1987
1988 // Test horizontal merge
1989 let mut region1 = BackgroundRegion::new(0, 0, color);
1990 region1.end_col = 5;
1991 let mut region2 = BackgroundRegion::new(0, 6, color);
1992 region2.end_col = 10;
1993 region1.merge_with(®ion2);
1994 assert_eq!(region1.start_col, 0);
1995 assert_eq!(region1.end_col, 10);
1996 assert_eq!(region1.start_line, 0);
1997 assert_eq!(region1.end_line, 0);
1998
1999 // Test vertical merge
2000 let mut region3 = BackgroundRegion::new(0, 0, color);
2001 region3.end_col = 5;
2002 let mut region4 = BackgroundRegion::new(1, 0, color);
2003 region4.end_col = 5;
2004 region3.merge_with(®ion4);
2005 assert_eq!(region3.start_col, 0);
2006 assert_eq!(region3.end_col, 5);
2007 assert_eq!(region3.start_line, 0);
2008 assert_eq!(region3.end_line, 1);
2009 }
2010
2011 #[test]
2012 fn test_merge_background_regions() {
2013 let color = Hsla::red();
2014
2015 // Test merging multiple adjacent regions
2016 let regions = vec![
2017 BackgroundRegion::new(0, 0, color),
2018 BackgroundRegion::new(0, 1, color),
2019 BackgroundRegion::new(0, 2, color),
2020 BackgroundRegion::new(1, 0, color),
2021 BackgroundRegion::new(1, 1, color),
2022 BackgroundRegion::new(1, 2, color),
2023 ];
2024
2025 let merged = merge_background_regions(regions);
2026 assert_eq!(merged.len(), 1);
2027 assert_eq!(merged[0].start_line, 0);
2028 assert_eq!(merged[0].end_line, 1);
2029 assert_eq!(merged[0].start_col, 0);
2030 assert_eq!(merged[0].end_col, 2);
2031
2032 // Test with non-mergeable regions
2033 let color2 = Hsla::blue();
2034 let regions2 = vec![
2035 BackgroundRegion::new(0, 0, color),
2036 BackgroundRegion::new(0, 2, color), // Gap at column 1
2037 BackgroundRegion::new(1, 0, color2), // Different color
2038 ];
2039
2040 let merged2 = merge_background_regions(regions2);
2041 assert_eq!(merged2.len(), 3);
2042 }
2043}