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