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 background_color: None,
1116 underline: Default::default(),
1117 strikethrough: None,
1118 }],
1119 None,
1120 )
1121 };
1122
1123 let focused = self.focused;
1124 TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
1125 move |(cursor_position, block_width)| {
1126 let (shape, text) = match cursor.shape {
1127 AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
1128 AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
1129 AlacCursorShape::Underline => (CursorShape::Underline, None),
1130 AlacCursorShape::Beam => (CursorShape::Bar, None),
1131 AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
1132 //This case is handled in the if wrapping the whole cursor layout
1133 AlacCursorShape::Hidden => unreachable!(),
1134 };
1135
1136 CursorLayout::new(
1137 cursor_position,
1138 block_width,
1139 dimensions.line_height,
1140 theme.players().local().cursor,
1141 shape,
1142 text,
1143 )
1144 },
1145 )
1146 };
1147
1148 let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
1149 let terminal = self.terminal.read(cx);
1150 if terminal.last_content.display_offset == 0 {
1151 let target_line = terminal.last_content.cursor.point.line.0 + 1;
1152 let render = &block.render;
1153 let mut block_cx = BlockContext {
1154 window,
1155 context: cx,
1156 dimensions,
1157 };
1158 let element = render(&mut block_cx);
1159 let mut element = div().occlude().child(element).into_any_element();
1160 let available_space = size(
1161 AvailableSpace::Definite(dimensions.width() + gutter),
1162 AvailableSpace::Definite(
1163 block.height as f32 * dimensions.line_height(),
1164 ),
1165 );
1166 let origin = bounds.origin
1167 + point(px(0.), target_line as f32 * dimensions.line_height())
1168 - point(px(0.), scroll_top);
1169 window.with_rem_size(rem_size, |window| {
1170 element.prepaint_as_root(origin, available_space, window, cx);
1171 });
1172 Some(element)
1173 } else {
1174 None
1175 }
1176 } else {
1177 None
1178 };
1179
1180 LayoutState {
1181 hitbox,
1182 batched_text_runs,
1183 cursor,
1184 background_color,
1185 dimensions,
1186 rects,
1187 relative_highlighted_ranges,
1188 mode,
1189 display_offset,
1190 hyperlink_tooltip,
1191 gutter,
1192 block_below_cursor_element,
1193 base_text_style: text_style,
1194 content_mode,
1195 }
1196 },
1197 )
1198 }
1199
1200 fn paint(
1201 &mut self,
1202 global_id: Option<&GlobalElementId>,
1203 inspector_id: Option<&gpui::InspectorElementId>,
1204 bounds: Bounds<Pixels>,
1205 _: &mut Self::RequestLayoutState,
1206 layout: &mut Self::PrepaintState,
1207 window: &mut Window,
1208 cx: &mut App,
1209 ) {
1210 let paint_start = Instant::now();
1211 window.with_content_mask(Some(ContentMask { bounds }), |window| {
1212 let scroll_top = self.terminal_view.read(cx).scroll_top;
1213
1214 window.paint_quad(fill(bounds, layout.background_color));
1215 let origin =
1216 bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
1217
1218 let marked_text_cloned: Option<String> = {
1219 let ime_state = &self.terminal_view.read(cx).ime_state;
1220 ime_state.as_ref().map(|state| state.marked_text.clone())
1221 };
1222
1223 let terminal_input_handler = TerminalInputHandler {
1224 terminal: self.terminal.clone(),
1225 terminal_view: self.terminal_view.clone(),
1226 cursor_bounds: layout
1227 .cursor
1228 .as_ref()
1229 .map(|cursor| cursor.bounding_rect(origin)),
1230 workspace: self.workspace.clone(),
1231 };
1232
1233 self.register_mouse_listeners(
1234 layout.mode,
1235 &layout.hitbox,
1236 &layout.content_mode,
1237 window,
1238 );
1239 if window.modifiers().secondary()
1240 && bounds.contains(&window.mouse_position())
1241 && self.terminal_view.read(cx).hover.is_some()
1242 {
1243 window.set_cursor_style(gpui::CursorStyle::PointingHand, &layout.hitbox);
1244 } else {
1245 window.set_cursor_style(gpui::CursorStyle::IBeam, &layout.hitbox);
1246 }
1247
1248 let original_cursor = layout.cursor.take();
1249 let hyperlink_tooltip = layout.hyperlink_tooltip.take();
1250 let block_below_cursor_element = layout.block_below_cursor_element.take();
1251 self.interactivity.paint(
1252 global_id,
1253 inspector_id,
1254 bounds,
1255 Some(&layout.hitbox),
1256 window,
1257 cx,
1258 |_, window, cx| {
1259 window.handle_input(&self.focus, terminal_input_handler, cx);
1260
1261 window.on_key_event({
1262 let this = self.terminal.clone();
1263 move |event: &ModifiersChangedEvent, phase, window, cx| {
1264 if phase != DispatchPhase::Bubble {
1265 return;
1266 }
1267
1268 this.update(cx, |term, cx| {
1269 term.try_modifiers_change(&event.modifiers, window, cx)
1270 });
1271 }
1272 });
1273
1274 for rect in &layout.rects {
1275 rect.paint(origin, &layout.dimensions, window);
1276 }
1277
1278 for (relative_highlighted_range, color) in
1279 layout.relative_highlighted_ranges.iter()
1280 {
1281 if let Some((start_y, highlighted_range_lines)) =
1282 to_highlighted_range_lines(relative_highlighted_range, layout, origin)
1283 {
1284 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
1285 0.15 * layout.dimensions.line_height
1286 } else {
1287 Pixels::ZERO
1288 };
1289 let hr = HighlightedRange {
1290 start_y,
1291 line_height: layout.dimensions.line_height,
1292 lines: highlighted_range_lines,
1293 color: *color,
1294 corner_radius: corner_radius,
1295 };
1296 hr.paint(true, bounds, window);
1297 }
1298 }
1299
1300 // Paint batched text runs instead of individual cells
1301 let text_paint_start = Instant::now();
1302 for batch in &layout.batched_text_runs {
1303 batch.paint(origin, &layout.dimensions, window, cx);
1304 }
1305 let text_paint_time = text_paint_start.elapsed();
1306
1307 if let Some(text_to_mark) = &marked_text_cloned
1308 && !text_to_mark.is_empty()
1309 && let Some(cursor_layout) = &original_cursor {
1310 let ime_position = cursor_layout.bounding_rect(origin).origin;
1311 let mut ime_style = layout.base_text_style.clone();
1312 ime_style.underline = Some(UnderlineStyle {
1313 color: Some(ime_style.color),
1314 thickness: px(1.0),
1315 wavy: false,
1316 });
1317
1318 let shaped_line = window.text_system().shape_line(
1319 text_to_mark.clone().into(),
1320 ime_style.font_size.to_pixels(window.rem_size()),
1321 &[TextRun {
1322 len: text_to_mark.len(),
1323 font: ime_style.font(),
1324 color: ime_style.color,
1325 background_color: None,
1326 underline: ime_style.underline,
1327 strikethrough: None,
1328 }],
1329 None
1330 );
1331 shaped_line
1332 .paint(ime_position, layout.dimensions.line_height, window, cx)
1333 .log_err();
1334 }
1335
1336 if self.cursor_visible && marked_text_cloned.is_none()
1337 && let Some(mut cursor) = original_cursor {
1338 cursor.paint(origin, window, cx);
1339 }
1340
1341 if let Some(mut element) = block_below_cursor_element {
1342 element.paint(window, cx);
1343 }
1344
1345 if let Some(mut element) = hyperlink_tooltip {
1346 element.paint(window, cx);
1347 }
1348 let total_paint_time = paint_start.elapsed();
1349 log::debug!(
1350 "Terminal paint: {} text runs, {} rects, text paint took {:?}, total paint took {:?}",
1351 layout.batched_text_runs.len(),
1352 layout.rects.len(),
1353 text_paint_time,
1354 total_paint_time
1355 );
1356 },
1357 );
1358 });
1359 }
1360}
1361
1362impl IntoElement for TerminalElement {
1363 type Element = Self;
1364
1365 fn into_element(self) -> Self::Element {
1366 self
1367 }
1368}
1369
1370struct TerminalInputHandler {
1371 terminal: Entity<Terminal>,
1372 terminal_view: Entity<TerminalView>,
1373 workspace: WeakEntity<Workspace>,
1374 cursor_bounds: Option<Bounds<Pixels>>,
1375}
1376
1377impl InputHandler for TerminalInputHandler {
1378 fn selected_text_range(
1379 &mut self,
1380 _ignore_disabled_input: bool,
1381 _: &mut Window,
1382 cx: &mut App,
1383 ) -> Option<UTF16Selection> {
1384 if self
1385 .terminal
1386 .read(cx)
1387 .last_content
1388 .mode
1389 .contains(TermMode::ALT_SCREEN)
1390 {
1391 None
1392 } else {
1393 Some(UTF16Selection {
1394 range: 0..0,
1395 reversed: false,
1396 })
1397 }
1398 }
1399
1400 fn marked_text_range(
1401 &mut self,
1402 _window: &mut Window,
1403 cx: &mut App,
1404 ) -> Option<std::ops::Range<usize>> {
1405 self.terminal_view.read(cx).marked_text_range()
1406 }
1407
1408 fn text_for_range(
1409 &mut self,
1410 _: std::ops::Range<usize>,
1411 _: &mut Option<std::ops::Range<usize>>,
1412 _: &mut Window,
1413 _: &mut App,
1414 ) -> Option<String> {
1415 None
1416 }
1417
1418 fn replace_text_in_range(
1419 &mut self,
1420 _replacement_range: Option<std::ops::Range<usize>>,
1421 text: &str,
1422 window: &mut Window,
1423 cx: &mut App,
1424 ) {
1425 self.terminal_view.update(cx, |view, view_cx| {
1426 view.clear_marked_text(view_cx);
1427 view.commit_text(text, view_cx);
1428 });
1429
1430 self.workspace
1431 .update(cx, |this, cx| {
1432 window.invalidate_character_coordinates();
1433 let project = this.project().read(cx);
1434 let telemetry = project.client().telemetry().clone();
1435 telemetry.log_edit_event("terminal", project.is_via_remote_server());
1436 })
1437 .ok();
1438 }
1439
1440 fn replace_and_mark_text_in_range(
1441 &mut self,
1442 _range_utf16: Option<std::ops::Range<usize>>,
1443 new_text: &str,
1444 new_marked_range: Option<std::ops::Range<usize>>,
1445 _window: &mut Window,
1446 cx: &mut App,
1447 ) {
1448 self.terminal_view.update(cx, |view, view_cx| {
1449 view.set_marked_text(new_text.to_string(), new_marked_range, view_cx);
1450 });
1451 }
1452
1453 fn unmark_text(&mut self, _window: &mut Window, cx: &mut App) {
1454 self.terminal_view.update(cx, |view, view_cx| {
1455 view.clear_marked_text(view_cx);
1456 });
1457 }
1458
1459 fn bounds_for_range(
1460 &mut self,
1461 range_utf16: std::ops::Range<usize>,
1462 _window: &mut Window,
1463 cx: &mut App,
1464 ) -> Option<Bounds<Pixels>> {
1465 let term_bounds = self.terminal_view.read(cx).terminal_bounds(cx);
1466
1467 let mut bounds = self.cursor_bounds?;
1468 let offset_x = term_bounds.cell_width * range_utf16.start as f32;
1469 bounds.origin.x += offset_x;
1470
1471 Some(bounds)
1472 }
1473
1474 fn apple_press_and_hold_enabled(&mut self) -> bool {
1475 false
1476 }
1477
1478 fn character_index_for_point(
1479 &mut self,
1480 _point: Point<Pixels>,
1481 _window: &mut Window,
1482 _cx: &mut App,
1483 ) -> Option<usize> {
1484 None
1485 }
1486}
1487
1488pub fn is_blank(cell: &IndexedCell) -> bool {
1489 if cell.c != ' ' {
1490 return false;
1491 }
1492
1493 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1494 return false;
1495 }
1496
1497 if cell.hyperlink().is_some() {
1498 return false;
1499 }
1500
1501 if cell
1502 .flags
1503 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1504 {
1505 return false;
1506 }
1507
1508 true
1509}
1510
1511fn to_highlighted_range_lines(
1512 range: &RangeInclusive<AlacPoint>,
1513 layout: &LayoutState,
1514 origin: Point<Pixels>,
1515) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1516 // Step 1. Normalize the points to be viewport relative.
1517 // When display_offset = 1, here's how the grid is arranged:
1518 //-2,0 -2,1...
1519 //--- Viewport top
1520 //-1,0 -1,1...
1521 //--------- Terminal Top
1522 // 0,0 0,1...
1523 // 1,0 1,1...
1524 //--- Viewport Bottom
1525 // 2,0 2,1...
1526 //--------- Terminal Bottom
1527
1528 // Normalize to viewport relative, from terminal relative.
1529 // lines are i32s, which are negative above the top left corner of the terminal
1530 // If the user has scrolled, we use the display_offset to tell us which offset
1531 // of the grid data we should be looking at. But for the rendering step, we don't
1532 // want negatives. We want things relative to the 'viewport' (the area of the grid
1533 // which is currently shown according to the display offset)
1534 let unclamped_start = AlacPoint::new(
1535 range.start().line + layout.display_offset,
1536 range.start().column,
1537 );
1538 let unclamped_end =
1539 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1540
1541 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1542 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1543 return None;
1544 }
1545
1546 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1547 let clamped_end_line = unclamped_end
1548 .line
1549 .0
1550 .min(layout.dimensions.num_lines() as i32) as usize;
1551 //Convert the start of the range to pixels
1552 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1553
1554 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1555 // (also convert to pixels)
1556 let mut highlighted_range_lines = Vec::new();
1557 for line in clamped_start_line..=clamped_end_line {
1558 let mut line_start = 0;
1559 let mut line_end = layout.dimensions.columns();
1560
1561 if line == clamped_start_line {
1562 line_start = unclamped_start.column.0;
1563 }
1564 if line == clamped_end_line {
1565 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1566 }
1567
1568 highlighted_range_lines.push(HighlightedRangeLine {
1569 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1570 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1571 });
1572 }
1573
1574 Some((start_y, highlighted_range_lines))
1575}
1576
1577/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1578pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1579 let colors = theme.colors();
1580 match fg {
1581 // Named and theme defined colors
1582 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1583 NamedColor::Black => colors.terminal_ansi_black,
1584 NamedColor::Red => colors.terminal_ansi_red,
1585 NamedColor::Green => colors.terminal_ansi_green,
1586 NamedColor::Yellow => colors.terminal_ansi_yellow,
1587 NamedColor::Blue => colors.terminal_ansi_blue,
1588 NamedColor::Magenta => colors.terminal_ansi_magenta,
1589 NamedColor::Cyan => colors.terminal_ansi_cyan,
1590 NamedColor::White => colors.terminal_ansi_white,
1591 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1592 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1593 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1594 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1595 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1596 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1597 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1598 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1599 NamedColor::Foreground => colors.terminal_foreground,
1600 NamedColor::Background => colors.terminal_ansi_background,
1601 NamedColor::Cursor => theme.players().local().cursor,
1602 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1603 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1604 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1605 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1606 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1607 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1608 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1609 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1610 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1611 NamedColor::DimForeground => colors.terminal_dim_foreground,
1612 },
1613 // 'True' colors
1614 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1615 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1616 }
1617 // 8 bit, indexed colors
1618 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1619 terminal::get_color_at_index(*i as usize, theme)
1620 }
1621 }
1622}
1623
1624#[cfg(test)]
1625mod tests {
1626 use super::*;
1627 use gpui::{AbsoluteLength, Hsla, font};
1628 use ui::utils::apca_contrast;
1629
1630 #[test]
1631 fn test_is_decorative_character() {
1632 // Box Drawing characters (U+2500 to U+257F)
1633 assert!(TerminalElement::is_decorative_character('â')); // U+2500
1634 assert!(TerminalElement::is_decorative_character('â')); // U+2502
1635 assert!(TerminalElement::is_decorative_character('â')); // U+250C
1636 assert!(TerminalElement::is_decorative_character('â')); // U+2510
1637 assert!(TerminalElement::is_decorative_character('â')); // U+2514
1638 assert!(TerminalElement::is_decorative_character('â')); // U+2518
1639 assert!(TerminalElement::is_decorative_character('âź')); // U+253C
1640
1641 // Block Elements (U+2580 to U+259F)
1642 assert!(TerminalElement::is_decorative_character('â')); // U+2580
1643 assert!(TerminalElement::is_decorative_character('â')); // U+2584
1644 assert!(TerminalElement::is_decorative_character('â')); // U+2588
1645 assert!(TerminalElement::is_decorative_character('â')); // U+2591
1646 assert!(TerminalElement::is_decorative_character('â')); // U+2592
1647 assert!(TerminalElement::is_decorative_character('â')); // U+2593
1648
1649 // Geometric Shapes - block/box-like subset (U+25A0 to U+25D7)
1650 assert!(TerminalElement::is_decorative_character('â ')); // U+25A0
1651 assert!(TerminalElement::is_decorative_character('âĄ')); // U+25A1
1652 assert!(TerminalElement::is_decorative_character('â˛')); // U+25B2
1653 assert!(TerminalElement::is_decorative_character('âź')); // U+25BC
1654 assert!(TerminalElement::is_decorative_character('â')); // U+25C6
1655 assert!(TerminalElement::is_decorative_character('â')); // U+25CF
1656
1657 // The specific character from the issue
1658 assert!(TerminalElement::is_decorative_character('â')); // U+25D7
1659 assert!(TerminalElement::is_decorative_character('â')); // U+25D8 (now included in Geometric Shapes)
1660 assert!(TerminalElement::is_decorative_character('â')); // U+25D9 (now included in Geometric Shapes)
1661
1662 // Powerline symbols (Private Use Area)
1663 assert!(TerminalElement::is_decorative_character('\u{E0B0}')); // Powerline right triangle
1664 assert!(TerminalElement::is_decorative_character('\u{E0B2}')); // Powerline left triangle
1665 assert!(TerminalElement::is_decorative_character('\u{E0B4}')); // Powerline right half circle (the actual issue!)
1666 assert!(TerminalElement::is_decorative_character('\u{E0B6}')); // Powerline left half circle
1667
1668 // Characters that should NOT be considered decorative
1669 assert!(!TerminalElement::is_decorative_character('A')); // Regular letter
1670 assert!(!TerminalElement::is_decorative_character('$')); // Symbol
1671 assert!(!TerminalElement::is_decorative_character(' ')); // Space
1672 assert!(!TerminalElement::is_decorative_character('â')); // U+2190 (Arrow, not in our ranges)
1673 assert!(!TerminalElement::is_decorative_character('â')); // U+2192 (Arrow, not in our ranges)
1674 assert!(!TerminalElement::is_decorative_character('\u{F00C}')); // Font Awesome check (icon, needs contrast)
1675 assert!(!TerminalElement::is_decorative_character('\u{E711}')); // Devicons (icon, needs contrast)
1676 assert!(!TerminalElement::is_decorative_character('\u{EA71}')); // Codicons folder (icon, needs contrast)
1677 assert!(!TerminalElement::is_decorative_character('\u{F401}')); // Octicons (icon, needs contrast)
1678 assert!(!TerminalElement::is_decorative_character('\u{1F600}')); // Emoji (not in our ranges)
1679 }
1680
1681 #[test]
1682 fn test_decorative_character_boundary_cases() {
1683 // Test exact boundaries of our ranges
1684 // Box Drawing range boundaries
1685 assert!(TerminalElement::is_decorative_character('\u{2500}')); // First char
1686 assert!(TerminalElement::is_decorative_character('\u{257F}')); // Last char
1687 assert!(!TerminalElement::is_decorative_character('\u{24FF}')); // Just before
1688
1689 // Block Elements range boundaries
1690 assert!(TerminalElement::is_decorative_character('\u{2580}')); // First char
1691 assert!(TerminalElement::is_decorative_character('\u{259F}')); // Last char
1692
1693 // Geometric Shapes subset boundaries
1694 assert!(TerminalElement::is_decorative_character('\u{25A0}')); // First char
1695 assert!(TerminalElement::is_decorative_character('\u{25FF}')); // Last char
1696 assert!(!TerminalElement::is_decorative_character('\u{2600}')); // Just after
1697 }
1698
1699 #[test]
1700 fn test_decorative_characters_bypass_contrast_adjustment() {
1701 // Decorative characters should not be affected by contrast adjustment
1702
1703 // The specific character from issue #34234
1704 let problematic_char = 'â'; // U+25D7
1705 assert!(
1706 TerminalElement::is_decorative_character(problematic_char),
1707 "Character â (U+25D7) should be recognized as decorative"
1708 );
1709
1710 // Verify some other commonly used decorative characters
1711 assert!(TerminalElement::is_decorative_character('â')); // Vertical line
1712 assert!(TerminalElement::is_decorative_character('â')); // Horizontal line
1713 assert!(TerminalElement::is_decorative_character('â')); // Full block
1714 assert!(TerminalElement::is_decorative_character('â')); // Dark shade
1715 assert!(TerminalElement::is_decorative_character('â ')); // Black square
1716 assert!(TerminalElement::is_decorative_character('â')); // Black circle
1717
1718 // Verify normal text characters are NOT decorative
1719 assert!(!TerminalElement::is_decorative_character('A'));
1720 assert!(!TerminalElement::is_decorative_character('1'));
1721 assert!(!TerminalElement::is_decorative_character('$'));
1722 assert!(!TerminalElement::is_decorative_character(' '));
1723 }
1724
1725 #[test]
1726 fn test_contrast_adjustment_logic() {
1727 // Test the core contrast adjustment logic without needing full app context
1728
1729 // Test case 1: Light colors (poor contrast)
1730 let white_fg = gpui::Hsla {
1731 h: 0.0,
1732 s: 0.0,
1733 l: 1.0,
1734 a: 1.0,
1735 };
1736 let light_gray_bg = gpui::Hsla {
1737 h: 0.0,
1738 s: 0.0,
1739 l: 0.95,
1740 a: 1.0,
1741 };
1742
1743 // Should have poor contrast
1744 let actual_contrast = apca_contrast(white_fg, light_gray_bg).abs();
1745 assert!(
1746 actual_contrast < 30.0,
1747 "White on light gray should have poor APCA contrast: {}",
1748 actual_contrast
1749 );
1750
1751 // After adjustment with minimum APCA contrast of 45, should be darker
1752 let adjusted = ensure_minimum_contrast(white_fg, light_gray_bg, 45.0);
1753 assert!(
1754 adjusted.l < white_fg.l,
1755 "Adjusted color should be darker than original"
1756 );
1757 let adjusted_contrast = apca_contrast(adjusted, light_gray_bg).abs();
1758 assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1759
1760 // Test case 2: Dark colors (poor contrast)
1761 let black_fg = gpui::Hsla {
1762 h: 0.0,
1763 s: 0.0,
1764 l: 0.0,
1765 a: 1.0,
1766 };
1767 let dark_gray_bg = gpui::Hsla {
1768 h: 0.0,
1769 s: 0.0,
1770 l: 0.05,
1771 a: 1.0,
1772 };
1773
1774 // Should have poor contrast
1775 let actual_contrast = apca_contrast(black_fg, dark_gray_bg).abs();
1776 assert!(
1777 actual_contrast < 30.0,
1778 "Black on dark gray should have poor APCA contrast: {}",
1779 actual_contrast
1780 );
1781
1782 // After adjustment with minimum APCA contrast of 45, should be lighter
1783 let adjusted = ensure_minimum_contrast(black_fg, dark_gray_bg, 45.0);
1784 assert!(
1785 adjusted.l > black_fg.l,
1786 "Adjusted color should be lighter than original"
1787 );
1788 let adjusted_contrast = apca_contrast(adjusted, dark_gray_bg).abs();
1789 assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1790
1791 // Test case 3: Already good contrast
1792 let good_contrast = ensure_minimum_contrast(black_fg, white_fg, 45.0);
1793 assert_eq!(
1794 good_contrast, black_fg,
1795 "Good contrast should not be adjusted"
1796 );
1797 }
1798
1799 #[test]
1800 fn test_white_on_white_contrast_issue() {
1801 // This test reproduces the exact issue from the bug report
1802 // where white ANSI text on white background should be adjusted
1803
1804 // Simulate One Light theme colors
1805 let white_fg = gpui::Hsla {
1806 h: 0.0,
1807 s: 0.0,
1808 l: 0.98, // #fafafaff is approximately 98% lightness
1809 a: 1.0,
1810 };
1811 let white_bg = gpui::Hsla {
1812 h: 0.0,
1813 s: 0.0,
1814 l: 0.98, // Same as foreground - this is the problem!
1815 a: 1.0,
1816 };
1817
1818 // With minimum contrast of 0.0, no adjustment should happen
1819 let no_adjust = ensure_minimum_contrast(white_fg, white_bg, 0.0);
1820 assert_eq!(no_adjust, white_fg, "No adjustment with min_contrast 0.0");
1821
1822 // With minimum APCA contrast of 15, it should adjust to a darker color
1823 let adjusted = ensure_minimum_contrast(white_fg, white_bg, 15.0);
1824 assert!(
1825 adjusted.l < white_fg.l,
1826 "White on white should become darker, got l={}",
1827 adjusted.l
1828 );
1829
1830 // Verify the contrast is now acceptable
1831 let new_contrast = apca_contrast(adjusted, white_bg).abs();
1832 assert!(
1833 new_contrast >= 15.0,
1834 "Adjusted APCA contrast {} should be >= 15.0",
1835 new_contrast
1836 );
1837 }
1838
1839 #[test]
1840 fn test_batched_text_run_can_append() {
1841 let style1 = TextRun {
1842 len: 1,
1843 font: font("Helvetica"),
1844 color: Hsla::red(),
1845 background_color: None,
1846 underline: None,
1847 strikethrough: None,
1848 };
1849
1850 let style2 = TextRun {
1851 len: 1,
1852 font: font("Helvetica"),
1853 color: Hsla::red(),
1854 background_color: None,
1855 underline: None,
1856 strikethrough: None,
1857 };
1858
1859 let style3 = TextRun {
1860 len: 1,
1861 font: font("Helvetica"),
1862 color: Hsla::blue(), // Different color
1863 background_color: None,
1864 underline: None,
1865 strikethrough: None,
1866 };
1867
1868 let font_size = AbsoluteLength::Pixels(px(12.0));
1869 let batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style1, font_size);
1870
1871 // Should be able to append same style
1872 assert!(batch.can_append(&style2));
1873
1874 // Should not be able to append different style
1875 assert!(!batch.can_append(&style3));
1876 }
1877
1878 #[test]
1879 fn test_batched_text_run_append() {
1880 let style = TextRun {
1881 len: 1,
1882 font: font("Helvetica"),
1883 color: Hsla::red(),
1884 background_color: None,
1885 underline: None,
1886 strikethrough: None,
1887 };
1888
1889 let font_size = AbsoluteLength::Pixels(px(12.0));
1890 let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style, font_size);
1891
1892 assert_eq!(batch.text, "a");
1893 assert_eq!(batch.cell_count, 1);
1894 assert_eq!(batch.style.len, 1);
1895
1896 batch.append_char('b');
1897
1898 assert_eq!(batch.text, "ab");
1899 assert_eq!(batch.cell_count, 2);
1900 assert_eq!(batch.style.len, 2);
1901
1902 batch.append_char('c');
1903
1904 assert_eq!(batch.text, "abc");
1905 assert_eq!(batch.cell_count, 3);
1906 assert_eq!(batch.style.len, 3);
1907 }
1908
1909 #[test]
1910 fn test_batched_text_run_append_char() {
1911 let style = TextRun {
1912 len: 1,
1913 font: font("Helvetica"),
1914 color: Hsla::red(),
1915 background_color: None,
1916 underline: None,
1917 strikethrough: None,
1918 };
1919
1920 let font_size = AbsoluteLength::Pixels(px(12.0));
1921 let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'x', style, font_size);
1922
1923 assert_eq!(batch.text, "x");
1924 assert_eq!(batch.cell_count, 1);
1925 assert_eq!(batch.style.len, 1);
1926
1927 batch.append_char('y');
1928
1929 assert_eq!(batch.text, "xy");
1930 assert_eq!(batch.cell_count, 2);
1931 assert_eq!(batch.style.len, 2);
1932
1933 // Test with multi-byte character
1934 batch.append_char('đ');
1935
1936 assert_eq!(batch.text, "xyđ");
1937 assert_eq!(batch.cell_count, 3);
1938 assert_eq!(batch.style.len, 6); // 1 + 1 + 4 bytes for emoji
1939 }
1940
1941 #[test]
1942 fn test_batched_text_run_append_zero_width_char() {
1943 let style = TextRun {
1944 len: 1,
1945 font: font("Helvetica"),
1946 color: Hsla::red(),
1947 background_color: None,
1948 underline: None,
1949 strikethrough: None,
1950 };
1951
1952 let font_size = AbsoluteLength::Pixels(px(12.0));
1953 let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'x', style, font_size);
1954
1955 let combining = '\u{0301}';
1956 batch.append_zero_width_chars(&[combining]);
1957
1958 assert_eq!(batch.text, format!("x{}", combining));
1959 assert_eq!(batch.cell_count, 1);
1960 assert_eq!(batch.style.len, 1 + combining.len_utf8());
1961 }
1962
1963 #[test]
1964 fn test_background_region_can_merge() {
1965 let color1 = Hsla::red();
1966 let color2 = Hsla::blue();
1967
1968 // Test horizontal merging
1969 let mut region1 = BackgroundRegion::new(0, 0, color1);
1970 region1.end_col = 5;
1971 let region2 = BackgroundRegion::new(0, 6, color1);
1972 assert!(region1.can_merge_with(®ion2));
1973
1974 // Test vertical merging with same column span
1975 let mut region3 = BackgroundRegion::new(0, 0, color1);
1976 region3.end_col = 5;
1977 let mut region4 = BackgroundRegion::new(1, 0, color1);
1978 region4.end_col = 5;
1979 assert!(region3.can_merge_with(®ion4));
1980
1981 // Test cannot merge different colors
1982 let region5 = BackgroundRegion::new(0, 0, color1);
1983 let region6 = BackgroundRegion::new(0, 1, color2);
1984 assert!(!region5.can_merge_with(®ion6));
1985
1986 // Test cannot merge non-adjacent regions
1987 let region7 = BackgroundRegion::new(0, 0, color1);
1988 let region8 = BackgroundRegion::new(0, 2, color1);
1989 assert!(!region7.can_merge_with(®ion8));
1990
1991 // Test cannot merge vertical regions with different column spans
1992 let mut region9 = BackgroundRegion::new(0, 0, color1);
1993 region9.end_col = 5;
1994 let mut region10 = BackgroundRegion::new(1, 0, color1);
1995 region10.end_col = 6;
1996 assert!(!region9.can_merge_with(®ion10));
1997 }
1998
1999 #[test]
2000 fn test_background_region_merge() {
2001 let color = Hsla::red();
2002
2003 // Test horizontal merge
2004 let mut region1 = BackgroundRegion::new(0, 0, color);
2005 region1.end_col = 5;
2006 let mut region2 = BackgroundRegion::new(0, 6, color);
2007 region2.end_col = 10;
2008 region1.merge_with(®ion2);
2009 assert_eq!(region1.start_col, 0);
2010 assert_eq!(region1.end_col, 10);
2011 assert_eq!(region1.start_line, 0);
2012 assert_eq!(region1.end_line, 0);
2013
2014 // Test vertical merge
2015 let mut region3 = BackgroundRegion::new(0, 0, color);
2016 region3.end_col = 5;
2017 let mut region4 = BackgroundRegion::new(1, 0, color);
2018 region4.end_col = 5;
2019 region3.merge_with(®ion4);
2020 assert_eq!(region3.start_col, 0);
2021 assert_eq!(region3.end_col, 5);
2022 assert_eq!(region3.start_line, 0);
2023 assert_eq!(region3.end_line, 1);
2024 }
2025
2026 #[test]
2027 fn test_merge_background_regions() {
2028 let color = Hsla::red();
2029
2030 // Test merging multiple adjacent regions
2031 let regions = vec![
2032 BackgroundRegion::new(0, 0, color),
2033 BackgroundRegion::new(0, 1, color),
2034 BackgroundRegion::new(0, 2, color),
2035 BackgroundRegion::new(1, 0, color),
2036 BackgroundRegion::new(1, 1, color),
2037 BackgroundRegion::new(1, 2, color),
2038 ];
2039
2040 let merged = merge_background_regions(regions);
2041 assert_eq!(merged.len(), 1);
2042 assert_eq!(merged[0].start_line, 0);
2043 assert_eq!(merged[0].end_line, 1);
2044 assert_eq!(merged[0].start_col, 0);
2045 assert_eq!(merged[0].end_col, 2);
2046
2047 // Test with non-mergeable regions
2048 let color2 = Hsla::blue();
2049 let regions2 = vec![
2050 BackgroundRegion::new(0, 0, color),
2051 BackgroundRegion::new(0, 2, color), // Gap at column 1
2052 BackgroundRegion::new(1, 0, color2), // Different color
2053 ];
2054
2055 let merged2 = merge_background_regions(regions2);
2056 assert_eq!(merged2.len(), 3);
2057 }
2058}