1use crate::color_contrast;
2use editor::{CursorLayout, HighlightedRange, HighlightedRangeLine};
3use gpui::{
4 AbsoluteLength, AnyElement, App, AvailableSpace, Bounds, ContentMask, Context, DispatchPhase,
5 Element, ElementId, Entity, FocusHandle, Font, FontFeatures, FontStyle, FontWeight,
6 GlobalElementId, HighlightStyle, Hitbox, Hsla, InputHandler, InteractiveElement, Interactivity,
7 IntoElement, LayoutId, Length, ModifiersChangedEvent, MouseButton, MouseMoveEvent, Pixels,
8 Point, ShapedLine, StatefulInteractiveElement, StrikethroughStyle, Styled, TextRun, TextStyle,
9 UTF16Selection, UnderlineStyle, WeakEntity, WhiteSpace, Window, div, fill, point, px, relative,
10 size,
11};
12use itertools::Itertools;
13use language::CursorShape;
14use settings::Settings;
15use std::time::Instant;
16use terminal::{
17 IndexedCell, Terminal, TerminalBounds, TerminalContent,
18 alacritty_terminal::{
19 grid::Dimensions,
20 index::Point as AlacPoint,
21 term::{TermMode, cell::Flags},
22 vte::ansi::{
23 Color::{self as AnsiColor, Named},
24 CursorShape as AlacCursorShape, NamedColor,
25 },
26 },
27 terminal_settings::TerminalSettings,
28};
29use theme::{ActiveTheme, Theme, ThemeSettings};
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 = color_contrast::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 if let Some(underline) = style.underline {
589 result.underline = Some(underline);
590 }
591
592 if let Some(color) = style.color {
593 result.color = color;
594 }
595 }
596
597 result
598 }
599
600 fn generic_button_handler<E>(
601 connection: Entity<Terminal>,
602 focus_handle: FocusHandle,
603 steal_focus: bool,
604 f: impl Fn(&mut Terminal, &E, &mut Context<Terminal>),
605 ) -> impl Fn(&E, &mut Window, &mut App) {
606 move |event, window, cx| {
607 if steal_focus {
608 window.focus(&focus_handle);
609 } else if !focus_handle.is_focused(window) {
610 return;
611 }
612 connection.update(cx, |terminal, cx| {
613 f(terminal, event, cx);
614
615 cx.notify();
616 })
617 }
618 }
619
620 fn register_mouse_listeners(
621 &mut self,
622 mode: TermMode,
623 hitbox: &Hitbox,
624 content_mode: &ContentMode,
625 window: &mut Window,
626 ) {
627 let focus = self.focus.clone();
628 let terminal = self.terminal.clone();
629 let terminal_view = self.terminal_view.clone();
630
631 self.interactivity.on_mouse_down(MouseButton::Left, {
632 let terminal = terminal.clone();
633 let focus = focus.clone();
634 let terminal_view = terminal_view.clone();
635
636 move |e, window, cx| {
637 window.focus(&focus);
638
639 let scroll_top = terminal_view.read(cx).scroll_top;
640 terminal.update(cx, |terminal, cx| {
641 let mut adjusted_event = e.clone();
642 if scroll_top > Pixels::ZERO {
643 adjusted_event.position.y += scroll_top;
644 }
645 terminal.mouse_down(&adjusted_event, cx);
646 cx.notify();
647 })
648 }
649 });
650
651 window.on_mouse_event({
652 let terminal = self.terminal.clone();
653 let hitbox = hitbox.clone();
654 let focus = focus.clone();
655 let terminal_view = terminal_view.clone();
656 move |e: &MouseMoveEvent, phase, window, cx| {
657 if phase != DispatchPhase::Bubble {
658 return;
659 }
660
661 if e.pressed_button.is_some() && !cx.has_active_drag() && focus.is_focused(window) {
662 let hovered = hitbox.is_hovered(window);
663
664 let scroll_top = terminal_view.read(cx).scroll_top;
665 terminal.update(cx, |terminal, cx| {
666 if terminal.selection_started() || hovered {
667 let mut adjusted_event = e.clone();
668 if scroll_top > Pixels::ZERO {
669 adjusted_event.position.y += scroll_top;
670 }
671 terminal.mouse_drag(&adjusted_event, hitbox.bounds, cx);
672 cx.notify();
673 }
674 })
675 }
676
677 if hitbox.is_hovered(window) {
678 terminal.update(cx, |terminal, cx| {
679 terminal.mouse_move(e, cx);
680 })
681 }
682 }
683 });
684
685 self.interactivity.on_mouse_up(
686 MouseButton::Left,
687 TerminalElement::generic_button_handler(
688 terminal.clone(),
689 focus.clone(),
690 false,
691 move |terminal, e, cx| {
692 terminal.mouse_up(e, cx);
693 },
694 ),
695 );
696 self.interactivity.on_mouse_down(
697 MouseButton::Middle,
698 TerminalElement::generic_button_handler(
699 terminal.clone(),
700 focus.clone(),
701 true,
702 move |terminal, e, cx| {
703 terminal.mouse_down(e, cx);
704 },
705 ),
706 );
707
708 if content_mode.is_scrollable() {
709 self.interactivity.on_scroll_wheel({
710 let terminal_view = self.terminal_view.downgrade();
711 move |e, window, cx| {
712 terminal_view
713 .update(cx, |terminal_view, cx| {
714 if matches!(terminal_view.mode, TerminalMode::Standalone)
715 || terminal_view.focus_handle.is_focused(window)
716 {
717 terminal_view.scroll_wheel(e, cx);
718 cx.notify();
719 }
720 })
721 .ok();
722 }
723 });
724 }
725
726 // Mouse mode handlers:
727 // All mouse modes need the extra click handlers
728 if mode.intersects(TermMode::MOUSE_MODE) {
729 self.interactivity.on_mouse_down(
730 MouseButton::Right,
731 TerminalElement::generic_button_handler(
732 terminal.clone(),
733 focus.clone(),
734 true,
735 move |terminal, e, cx| {
736 terminal.mouse_down(e, cx);
737 },
738 ),
739 );
740 self.interactivity.on_mouse_up(
741 MouseButton::Right,
742 TerminalElement::generic_button_handler(
743 terminal.clone(),
744 focus.clone(),
745 false,
746 move |terminal, e, cx| {
747 terminal.mouse_up(e, cx);
748 },
749 ),
750 );
751 self.interactivity.on_mouse_up(
752 MouseButton::Middle,
753 TerminalElement::generic_button_handler(
754 terminal,
755 focus,
756 false,
757 move |terminal, e, cx| {
758 terminal.mouse_up(e, cx);
759 },
760 ),
761 );
762 }
763 }
764
765 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
766 let settings = ThemeSettings::get_global(cx).clone();
767 let buffer_font_size = settings.buffer_font_size(cx);
768 let rem_size_scale = {
769 // Our default UI font size is 14px on a 16px base scale.
770 // This means the default UI font size is 0.875rems.
771 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
772
773 // We then determine the delta between a single rem and the default font
774 // size scale.
775 let default_font_size_delta = 1. - default_font_size_scale;
776
777 // Finally, we add this delta to 1rem to get the scale factor that
778 // should be used to scale up the UI.
779 1. + default_font_size_delta
780 };
781
782 Some(buffer_font_size * rem_size_scale)
783 }
784}
785
786impl Element for TerminalElement {
787 type RequestLayoutState = ();
788 type PrepaintState = LayoutState;
789
790 fn id(&self) -> Option<ElementId> {
791 self.interactivity.element_id.clone()
792 }
793
794 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
795 None
796 }
797
798 fn request_layout(
799 &mut self,
800 global_id: Option<&GlobalElementId>,
801 inspector_id: Option<&gpui::InspectorElementId>,
802 window: &mut Window,
803 cx: &mut App,
804 ) -> (LayoutId, Self::RequestLayoutState) {
805 let height: Length = match self.terminal_view.read(cx).content_mode(window, cx) {
806 ContentMode::Inline {
807 displayed_lines,
808 total_lines: _,
809 } => {
810 let rem_size = window.rem_size();
811 let line_height = window.text_style().font_size.to_pixels(rem_size)
812 * TerminalSettings::get_global(cx)
813 .line_height
814 .value()
815 .to_pixels(rem_size)
816 .0;
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 = font_pixels * line_height.to_pixels(rem_size).0;
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);
1195 ime_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 hr = HighlightedRange {
1260 start_y,
1261 line_height: layout.dimensions.line_height,
1262 lines: highlighted_range_lines,
1263 color: *color,
1264 corner_radius: 0.15 * layout.dimensions.line_height,
1265 };
1266 hr.paint(true, bounds, window);
1267 }
1268 }
1269
1270 // Paint batched text runs instead of individual cells
1271 let text_paint_start = Instant::now();
1272 for batch in &layout.batched_text_runs {
1273 batch.paint(origin, &layout.dimensions, window, cx);
1274 }
1275 let text_paint_time = text_paint_start.elapsed();
1276
1277 if let Some(text_to_mark) = &marked_text_cloned
1278 && !text_to_mark.is_empty()
1279 && let Some(cursor_layout) = &original_cursor {
1280 let ime_position = cursor_layout.bounding_rect(origin).origin;
1281 let mut ime_style = layout.base_text_style.clone();
1282 ime_style.underline = Some(UnderlineStyle {
1283 color: Some(ime_style.color),
1284 thickness: px(1.0),
1285 wavy: false,
1286 });
1287
1288 let shaped_line = window.text_system().shape_line(
1289 text_to_mark.clone().into(),
1290 ime_style.font_size.to_pixels(window.rem_size()),
1291 &[TextRun {
1292 len: text_to_mark.len(),
1293 font: ime_style.font(),
1294 color: ime_style.color,
1295 background_color: None,
1296 underline: ime_style.underline,
1297 strikethrough: None,
1298 }],
1299 None
1300 );
1301 shaped_line
1302 .paint(ime_position, layout.dimensions.line_height, window, cx)
1303 .log_err();
1304 }
1305
1306 if self.cursor_visible && marked_text_cloned.is_none()
1307 && let Some(mut cursor) = original_cursor {
1308 cursor.paint(origin, window, cx);
1309 }
1310
1311 if let Some(mut element) = block_below_cursor_element {
1312 element.paint(window, cx);
1313 }
1314
1315 if let Some(mut element) = hyperlink_tooltip {
1316 element.paint(window, cx);
1317 }
1318 let total_paint_time = paint_start.elapsed();
1319 log::debug!(
1320 "Terminal paint: {} text runs, {} rects, text paint took {:?}, total paint took {:?}",
1321 layout.batched_text_runs.len(),
1322 layout.rects.len(),
1323 text_paint_time,
1324 total_paint_time
1325 );
1326 },
1327 );
1328 });
1329 }
1330}
1331
1332impl IntoElement for TerminalElement {
1333 type Element = Self;
1334
1335 fn into_element(self) -> Self::Element {
1336 self
1337 }
1338}
1339
1340struct TerminalInputHandler {
1341 terminal: Entity<Terminal>,
1342 terminal_view: Entity<TerminalView>,
1343 workspace: WeakEntity<Workspace>,
1344 cursor_bounds: Option<Bounds<Pixels>>,
1345}
1346
1347impl InputHandler for TerminalInputHandler {
1348 fn selected_text_range(
1349 &mut self,
1350 _ignore_disabled_input: bool,
1351 _: &mut Window,
1352 cx: &mut App,
1353 ) -> Option<UTF16Selection> {
1354 if self
1355 .terminal
1356 .read(cx)
1357 .last_content
1358 .mode
1359 .contains(TermMode::ALT_SCREEN)
1360 {
1361 None
1362 } else {
1363 Some(UTF16Selection {
1364 range: 0..0,
1365 reversed: false,
1366 })
1367 }
1368 }
1369
1370 fn marked_text_range(
1371 &mut self,
1372 _window: &mut Window,
1373 cx: &mut App,
1374 ) -> Option<std::ops::Range<usize>> {
1375 self.terminal_view.read(cx).marked_text_range()
1376 }
1377
1378 fn text_for_range(
1379 &mut self,
1380 _: std::ops::Range<usize>,
1381 _: &mut Option<std::ops::Range<usize>>,
1382 _: &mut Window,
1383 _: &mut App,
1384 ) -> Option<String> {
1385 None
1386 }
1387
1388 fn replace_text_in_range(
1389 &mut self,
1390 _replacement_range: Option<std::ops::Range<usize>>,
1391 text: &str,
1392 window: &mut Window,
1393 cx: &mut App,
1394 ) {
1395 self.terminal_view.update(cx, |view, view_cx| {
1396 view.clear_marked_text(view_cx);
1397 view.commit_text(text, view_cx);
1398 });
1399
1400 self.workspace
1401 .update(cx, |this, cx| {
1402 window.invalidate_character_coordinates();
1403 let project = this.project().read(cx);
1404 let telemetry = project.client().telemetry().clone();
1405 telemetry.log_edit_event("terminal", project.is_via_ssh());
1406 })
1407 .ok();
1408 }
1409
1410 fn replace_and_mark_text_in_range(
1411 &mut self,
1412 _range_utf16: Option<std::ops::Range<usize>>,
1413 new_text: &str,
1414 new_marked_range: Option<std::ops::Range<usize>>,
1415 _window: &mut Window,
1416 cx: &mut App,
1417 ) {
1418 if let Some(range) = new_marked_range {
1419 self.terminal_view.update(cx, |view, view_cx| {
1420 view.set_marked_text(new_text.to_string(), range, view_cx);
1421 });
1422 }
1423 }
1424
1425 fn unmark_text(&mut self, _window: &mut Window, cx: &mut App) {
1426 self.terminal_view.update(cx, |view, view_cx| {
1427 view.clear_marked_text(view_cx);
1428 });
1429 }
1430
1431 fn bounds_for_range(
1432 &mut self,
1433 range_utf16: std::ops::Range<usize>,
1434 _window: &mut Window,
1435 cx: &mut App,
1436 ) -> Option<Bounds<Pixels>> {
1437 let term_bounds = self.terminal_view.read(cx).terminal_bounds(cx);
1438
1439 let mut bounds = self.cursor_bounds?;
1440 let offset_x = term_bounds.cell_width * range_utf16.start as f32;
1441 bounds.origin.x += offset_x;
1442
1443 Some(bounds)
1444 }
1445
1446 fn apple_press_and_hold_enabled(&mut self) -> bool {
1447 false
1448 }
1449
1450 fn character_index_for_point(
1451 &mut self,
1452 _point: Point<Pixels>,
1453 _window: &mut Window,
1454 _cx: &mut App,
1455 ) -> Option<usize> {
1456 None
1457 }
1458}
1459
1460pub fn is_blank(cell: &IndexedCell) -> bool {
1461 if cell.c != ' ' {
1462 return false;
1463 }
1464
1465 if cell.bg != AnsiColor::Named(NamedColor::Background) {
1466 return false;
1467 }
1468
1469 if cell.hyperlink().is_some() {
1470 return false;
1471 }
1472
1473 if cell
1474 .flags
1475 .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1476 {
1477 return false;
1478 }
1479
1480 return true;
1481}
1482
1483fn to_highlighted_range_lines(
1484 range: &RangeInclusive<AlacPoint>,
1485 layout: &LayoutState,
1486 origin: Point<Pixels>,
1487) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1488 // Step 1. Normalize the points to be viewport relative.
1489 // When display_offset = 1, here's how the grid is arranged:
1490 //-2,0 -2,1...
1491 //--- Viewport top
1492 //-1,0 -1,1...
1493 //--------- Terminal Top
1494 // 0,0 0,1...
1495 // 1,0 1,1...
1496 //--- Viewport Bottom
1497 // 2,0 2,1...
1498 //--------- Terminal Bottom
1499
1500 // Normalize to viewport relative, from terminal relative.
1501 // lines are i32s, which are negative above the top left corner of the terminal
1502 // If the user has scrolled, we use the display_offset to tell us which offset
1503 // of the grid data we should be looking at. But for the rendering step, we don't
1504 // want negatives. We want things relative to the 'viewport' (the area of the grid
1505 // which is currently shown according to the display offset)
1506 let unclamped_start = AlacPoint::new(
1507 range.start().line + layout.display_offset,
1508 range.start().column,
1509 );
1510 let unclamped_end =
1511 AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1512
1513 // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1514 if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1515 return None;
1516 }
1517
1518 let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1519 let clamped_end_line = unclamped_end
1520 .line
1521 .0
1522 .min(layout.dimensions.num_lines() as i32) as usize;
1523 //Convert the start of the range to pixels
1524 let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1525
1526 // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1527 // (also convert to pixels)
1528 let mut highlighted_range_lines = Vec::new();
1529 for line in clamped_start_line..=clamped_end_line {
1530 let mut line_start = 0;
1531 let mut line_end = layout.dimensions.columns();
1532
1533 if line == clamped_start_line {
1534 line_start = unclamped_start.column.0;
1535 }
1536 if line == clamped_end_line {
1537 line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1538 }
1539
1540 highlighted_range_lines.push(HighlightedRangeLine {
1541 start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1542 end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1543 });
1544 }
1545
1546 Some((start_y, highlighted_range_lines))
1547}
1548
1549/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1550pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1551 let colors = theme.colors();
1552 match fg {
1553 // Named and theme defined colors
1554 terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1555 NamedColor::Black => colors.terminal_ansi_black,
1556 NamedColor::Red => colors.terminal_ansi_red,
1557 NamedColor::Green => colors.terminal_ansi_green,
1558 NamedColor::Yellow => colors.terminal_ansi_yellow,
1559 NamedColor::Blue => colors.terminal_ansi_blue,
1560 NamedColor::Magenta => colors.terminal_ansi_magenta,
1561 NamedColor::Cyan => colors.terminal_ansi_cyan,
1562 NamedColor::White => colors.terminal_ansi_white,
1563 NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1564 NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1565 NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1566 NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1567 NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1568 NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1569 NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1570 NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1571 NamedColor::Foreground => colors.terminal_foreground,
1572 NamedColor::Background => colors.terminal_ansi_background,
1573 NamedColor::Cursor => theme.players().local().cursor,
1574 NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1575 NamedColor::DimRed => colors.terminal_ansi_dim_red,
1576 NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1577 NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1578 NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1579 NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1580 NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1581 NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1582 NamedColor::BrightForeground => colors.terminal_bright_foreground,
1583 NamedColor::DimForeground => colors.terminal_dim_foreground,
1584 },
1585 // 'True' colors
1586 terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1587 terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1588 }
1589 // 8 bit, indexed colors
1590 terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1591 terminal::get_color_at_index(*i as usize, theme)
1592 }
1593 }
1594}
1595
1596#[cfg(test)]
1597mod tests {
1598 use super::*;
1599 use gpui::{AbsoluteLength, Hsla, font};
1600
1601 #[test]
1602 fn test_is_decorative_character() {
1603 // Box Drawing characters (U+2500 to U+257F)
1604 assert!(TerminalElement::is_decorative_character('â')); // U+2500
1605 assert!(TerminalElement::is_decorative_character('â')); // U+2502
1606 assert!(TerminalElement::is_decorative_character('â')); // U+250C
1607 assert!(TerminalElement::is_decorative_character('â')); // U+2510
1608 assert!(TerminalElement::is_decorative_character('â')); // U+2514
1609 assert!(TerminalElement::is_decorative_character('â')); // U+2518
1610 assert!(TerminalElement::is_decorative_character('âź')); // U+253C
1611
1612 // Block Elements (U+2580 to U+259F)
1613 assert!(TerminalElement::is_decorative_character('â')); // U+2580
1614 assert!(TerminalElement::is_decorative_character('â')); // U+2584
1615 assert!(TerminalElement::is_decorative_character('â')); // U+2588
1616 assert!(TerminalElement::is_decorative_character('â')); // U+2591
1617 assert!(TerminalElement::is_decorative_character('â')); // U+2592
1618 assert!(TerminalElement::is_decorative_character('â')); // U+2593
1619
1620 // Geometric Shapes - block/box-like subset (U+25A0 to U+25D7)
1621 assert!(TerminalElement::is_decorative_character('â ')); // U+25A0
1622 assert!(TerminalElement::is_decorative_character('âĄ')); // U+25A1
1623 assert!(TerminalElement::is_decorative_character('â˛')); // U+25B2
1624 assert!(TerminalElement::is_decorative_character('âź')); // U+25BC
1625 assert!(TerminalElement::is_decorative_character('â')); // U+25C6
1626 assert!(TerminalElement::is_decorative_character('â')); // U+25CF
1627
1628 // The specific character from the issue
1629 assert!(TerminalElement::is_decorative_character('â')); // U+25D7
1630 assert!(TerminalElement::is_decorative_character('â')); // U+25D8 (now included in Geometric Shapes)
1631 assert!(TerminalElement::is_decorative_character('â')); // U+25D9 (now included in Geometric Shapes)
1632
1633 // Powerline symbols (Private Use Area)
1634 assert!(TerminalElement::is_decorative_character('\u{E0B0}')); // Powerline right triangle
1635 assert!(TerminalElement::is_decorative_character('\u{E0B2}')); // Powerline left triangle
1636 assert!(TerminalElement::is_decorative_character('\u{E0B4}')); // Powerline right half circle (the actual issue!)
1637 assert!(TerminalElement::is_decorative_character('\u{E0B6}')); // Powerline left half circle
1638
1639 // Characters that should NOT be considered decorative
1640 assert!(!TerminalElement::is_decorative_character('A')); // Regular letter
1641 assert!(!TerminalElement::is_decorative_character('$')); // Symbol
1642 assert!(!TerminalElement::is_decorative_character(' ')); // Space
1643 assert!(!TerminalElement::is_decorative_character('â')); // U+2190 (Arrow, not in our ranges)
1644 assert!(!TerminalElement::is_decorative_character('â')); // U+2192 (Arrow, not in our ranges)
1645 assert!(!TerminalElement::is_decorative_character('\u{F00C}')); // Font Awesome check (icon, needs contrast)
1646 assert!(!TerminalElement::is_decorative_character('\u{E711}')); // Devicons (icon, needs contrast)
1647 assert!(!TerminalElement::is_decorative_character('\u{EA71}')); // Codicons folder (icon, needs contrast)
1648 assert!(!TerminalElement::is_decorative_character('\u{F401}')); // Octicons (icon, needs contrast)
1649 assert!(!TerminalElement::is_decorative_character('\u{1F600}')); // Emoji (not in our ranges)
1650 }
1651
1652 #[test]
1653 fn test_decorative_character_boundary_cases() {
1654 // Test exact boundaries of our ranges
1655 // Box Drawing range boundaries
1656 assert!(TerminalElement::is_decorative_character('\u{2500}')); // First char
1657 assert!(TerminalElement::is_decorative_character('\u{257F}')); // Last char
1658 assert!(!TerminalElement::is_decorative_character('\u{24FF}')); // Just before
1659
1660 // Block Elements range boundaries
1661 assert!(TerminalElement::is_decorative_character('\u{2580}')); // First char
1662 assert!(TerminalElement::is_decorative_character('\u{259F}')); // Last char
1663
1664 // Geometric Shapes subset boundaries
1665 assert!(TerminalElement::is_decorative_character('\u{25A0}')); // First char
1666 assert!(TerminalElement::is_decorative_character('\u{25FF}')); // Last char
1667 assert!(!TerminalElement::is_decorative_character('\u{2600}')); // Just after
1668 }
1669
1670 #[test]
1671 fn test_decorative_characters_bypass_contrast_adjustment() {
1672 // Decorative characters should not be affected by contrast adjustment
1673
1674 // The specific character from issue #34234
1675 let problematic_char = 'â'; // U+25D7
1676 assert!(
1677 TerminalElement::is_decorative_character(problematic_char),
1678 "Character â (U+25D7) should be recognized as decorative"
1679 );
1680
1681 // Verify some other commonly used decorative characters
1682 assert!(TerminalElement::is_decorative_character('â')); // Vertical line
1683 assert!(TerminalElement::is_decorative_character('â')); // Horizontal line
1684 assert!(TerminalElement::is_decorative_character('â')); // Full block
1685 assert!(TerminalElement::is_decorative_character('â')); // Dark shade
1686 assert!(TerminalElement::is_decorative_character('â ')); // Black square
1687 assert!(TerminalElement::is_decorative_character('â')); // Black circle
1688
1689 // Verify normal text characters are NOT decorative
1690 assert!(!TerminalElement::is_decorative_character('A'));
1691 assert!(!TerminalElement::is_decorative_character('1'));
1692 assert!(!TerminalElement::is_decorative_character('$'));
1693 assert!(!TerminalElement::is_decorative_character(' '));
1694 }
1695
1696 #[test]
1697 fn test_contrast_adjustment_logic() {
1698 // Test the core contrast adjustment logic without needing full app context
1699
1700 // Test case 1: Light colors (poor contrast)
1701 let white_fg = gpui::Hsla {
1702 h: 0.0,
1703 s: 0.0,
1704 l: 1.0,
1705 a: 1.0,
1706 };
1707 let light_gray_bg = gpui::Hsla {
1708 h: 0.0,
1709 s: 0.0,
1710 l: 0.95,
1711 a: 1.0,
1712 };
1713
1714 // Should have poor contrast
1715 let actual_contrast = color_contrast::apca_contrast(white_fg, light_gray_bg).abs();
1716 assert!(
1717 actual_contrast < 30.0,
1718 "White on light gray should have poor APCA contrast: {}",
1719 actual_contrast
1720 );
1721
1722 // After adjustment with minimum APCA contrast of 45, should be darker
1723 let adjusted = color_contrast::ensure_minimum_contrast(white_fg, light_gray_bg, 45.0);
1724 assert!(
1725 adjusted.l < white_fg.l,
1726 "Adjusted color should be darker than original"
1727 );
1728 let adjusted_contrast = color_contrast::apca_contrast(adjusted, light_gray_bg).abs();
1729 assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1730
1731 // Test case 2: Dark colors (poor contrast)
1732 let black_fg = gpui::Hsla {
1733 h: 0.0,
1734 s: 0.0,
1735 l: 0.0,
1736 a: 1.0,
1737 };
1738 let dark_gray_bg = gpui::Hsla {
1739 h: 0.0,
1740 s: 0.0,
1741 l: 0.05,
1742 a: 1.0,
1743 };
1744
1745 // Should have poor contrast
1746 let actual_contrast = color_contrast::apca_contrast(black_fg, dark_gray_bg).abs();
1747 assert!(
1748 actual_contrast < 30.0,
1749 "Black on dark gray should have poor APCA contrast: {}",
1750 actual_contrast
1751 );
1752
1753 // After adjustment with minimum APCA contrast of 45, should be lighter
1754 let adjusted = color_contrast::ensure_minimum_contrast(black_fg, dark_gray_bg, 45.0);
1755 assert!(
1756 adjusted.l > black_fg.l,
1757 "Adjusted color should be lighter than original"
1758 );
1759 let adjusted_contrast = color_contrast::apca_contrast(adjusted, dark_gray_bg).abs();
1760 assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1761
1762 // Test case 3: Already good contrast
1763 let good_contrast = color_contrast::ensure_minimum_contrast(black_fg, white_fg, 45.0);
1764 assert_eq!(
1765 good_contrast, black_fg,
1766 "Good contrast should not be adjusted"
1767 );
1768 }
1769
1770 #[test]
1771 fn test_white_on_white_contrast_issue() {
1772 // This test reproduces the exact issue from the bug report
1773 // where white ANSI text on white background should be adjusted
1774
1775 // Simulate One Light theme colors
1776 let white_fg = gpui::Hsla {
1777 h: 0.0,
1778 s: 0.0,
1779 l: 0.98, // #fafafaff is approximately 98% lightness
1780 a: 1.0,
1781 };
1782 let white_bg = gpui::Hsla {
1783 h: 0.0,
1784 s: 0.0,
1785 l: 0.98, // Same as foreground - this is the problem!
1786 a: 1.0,
1787 };
1788
1789 // With minimum contrast of 0.0, no adjustment should happen
1790 let no_adjust = color_contrast::ensure_minimum_contrast(white_fg, white_bg, 0.0);
1791 assert_eq!(no_adjust, white_fg, "No adjustment with min_contrast 0.0");
1792
1793 // With minimum APCA contrast of 15, it should adjust to a darker color
1794 let adjusted = color_contrast::ensure_minimum_contrast(white_fg, white_bg, 15.0);
1795 assert!(
1796 adjusted.l < white_fg.l,
1797 "White on white should become darker, got l={}",
1798 adjusted.l
1799 );
1800
1801 // Verify the contrast is now acceptable
1802 let new_contrast = color_contrast::apca_contrast(adjusted, white_bg).abs();
1803 assert!(
1804 new_contrast >= 15.0,
1805 "Adjusted APCA contrast {} should be >= 15.0",
1806 new_contrast
1807 );
1808 }
1809
1810 #[test]
1811 fn test_batched_text_run_can_append() {
1812 let style1 = TextRun {
1813 len: 1,
1814 font: font("Helvetica"),
1815 color: Hsla::red(),
1816 background_color: None,
1817 underline: None,
1818 strikethrough: None,
1819 };
1820
1821 let style2 = TextRun {
1822 len: 1,
1823 font: font("Helvetica"),
1824 color: Hsla::red(),
1825 background_color: None,
1826 underline: None,
1827 strikethrough: None,
1828 };
1829
1830 let style3 = TextRun {
1831 len: 1,
1832 font: font("Helvetica"),
1833 color: Hsla::blue(), // Different color
1834 background_color: None,
1835 underline: None,
1836 strikethrough: None,
1837 };
1838
1839 let font_size = AbsoluteLength::Pixels(px(12.0));
1840 let batch =
1841 BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style1.clone(), font_size);
1842
1843 // Should be able to append same style
1844 assert!(batch.can_append(&style2));
1845
1846 // Should not be able to append different style
1847 assert!(!batch.can_append(&style3));
1848 }
1849
1850 #[test]
1851 fn test_batched_text_run_append() {
1852 let style = TextRun {
1853 len: 1,
1854 font: font("Helvetica"),
1855 color: Hsla::red(),
1856 background_color: None,
1857 underline: None,
1858 strikethrough: None,
1859 };
1860
1861 let font_size = AbsoluteLength::Pixels(px(12.0));
1862 let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style, font_size);
1863
1864 assert_eq!(batch.text, "a");
1865 assert_eq!(batch.cell_count, 1);
1866 assert_eq!(batch.style.len, 1);
1867
1868 batch.append_char('b');
1869
1870 assert_eq!(batch.text, "ab");
1871 assert_eq!(batch.cell_count, 2);
1872 assert_eq!(batch.style.len, 2);
1873
1874 batch.append_char('c');
1875
1876 assert_eq!(batch.text, "abc");
1877 assert_eq!(batch.cell_count, 3);
1878 assert_eq!(batch.style.len, 3);
1879 }
1880
1881 #[test]
1882 fn test_batched_text_run_append_char() {
1883 let style = TextRun {
1884 len: 1,
1885 font: font("Helvetica"),
1886 color: Hsla::red(),
1887 background_color: None,
1888 underline: None,
1889 strikethrough: None,
1890 };
1891
1892 let font_size = AbsoluteLength::Pixels(px(12.0));
1893 let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'x', style, font_size);
1894
1895 assert_eq!(batch.text, "x");
1896 assert_eq!(batch.cell_count, 1);
1897 assert_eq!(batch.style.len, 1);
1898
1899 batch.append_char('y');
1900
1901 assert_eq!(batch.text, "xy");
1902 assert_eq!(batch.cell_count, 2);
1903 assert_eq!(batch.style.len, 2);
1904
1905 // Test with multi-byte character
1906 batch.append_char('đ');
1907
1908 assert_eq!(batch.text, "xyđ");
1909 assert_eq!(batch.cell_count, 3);
1910 assert_eq!(batch.style.len, 6); // 1 + 1 + 4 bytes for emoji
1911 }
1912
1913 #[test]
1914 fn test_background_region_can_merge() {
1915 let color1 = Hsla::red();
1916 let color2 = Hsla::blue();
1917
1918 // Test horizontal merging
1919 let mut region1 = BackgroundRegion::new(0, 0, color1);
1920 region1.end_col = 5;
1921 let region2 = BackgroundRegion::new(0, 6, color1);
1922 assert!(region1.can_merge_with(®ion2));
1923
1924 // Test vertical merging with same column span
1925 let mut region3 = BackgroundRegion::new(0, 0, color1);
1926 region3.end_col = 5;
1927 let mut region4 = BackgroundRegion::new(1, 0, color1);
1928 region4.end_col = 5;
1929 assert!(region3.can_merge_with(®ion4));
1930
1931 // Test cannot merge different colors
1932 let region5 = BackgroundRegion::new(0, 0, color1);
1933 let region6 = BackgroundRegion::new(0, 1, color2);
1934 assert!(!region5.can_merge_with(®ion6));
1935
1936 // Test cannot merge non-adjacent regions
1937 let region7 = BackgroundRegion::new(0, 0, color1);
1938 let region8 = BackgroundRegion::new(0, 2, color1);
1939 assert!(!region7.can_merge_with(®ion8));
1940
1941 // Test cannot merge vertical regions with different column spans
1942 let mut region9 = BackgroundRegion::new(0, 0, color1);
1943 region9.end_col = 5;
1944 let mut region10 = BackgroundRegion::new(1, 0, color1);
1945 region10.end_col = 6;
1946 assert!(!region9.can_merge_with(®ion10));
1947 }
1948
1949 #[test]
1950 fn test_background_region_merge() {
1951 let color = Hsla::red();
1952
1953 // Test horizontal merge
1954 let mut region1 = BackgroundRegion::new(0, 0, color);
1955 region1.end_col = 5;
1956 let mut region2 = BackgroundRegion::new(0, 6, color);
1957 region2.end_col = 10;
1958 region1.merge_with(®ion2);
1959 assert_eq!(region1.start_col, 0);
1960 assert_eq!(region1.end_col, 10);
1961 assert_eq!(region1.start_line, 0);
1962 assert_eq!(region1.end_line, 0);
1963
1964 // Test vertical merge
1965 let mut region3 = BackgroundRegion::new(0, 0, color);
1966 region3.end_col = 5;
1967 let mut region4 = BackgroundRegion::new(1, 0, color);
1968 region4.end_col = 5;
1969 region3.merge_with(®ion4);
1970 assert_eq!(region3.start_col, 0);
1971 assert_eq!(region3.end_col, 5);
1972 assert_eq!(region3.start_line, 0);
1973 assert_eq!(region3.end_line, 1);
1974 }
1975
1976 #[test]
1977 fn test_merge_background_regions() {
1978 let color = Hsla::red();
1979
1980 // Test merging multiple adjacent regions
1981 let regions = vec![
1982 BackgroundRegion::new(0, 0, color),
1983 BackgroundRegion::new(0, 1, color),
1984 BackgroundRegion::new(0, 2, color),
1985 BackgroundRegion::new(1, 0, color),
1986 BackgroundRegion::new(1, 1, color),
1987 BackgroundRegion::new(1, 2, color),
1988 ];
1989
1990 let merged = merge_background_regions(regions);
1991 assert_eq!(merged.len(), 1);
1992 assert_eq!(merged[0].start_line, 0);
1993 assert_eq!(merged[0].end_line, 1);
1994 assert_eq!(merged[0].start_col, 0);
1995 assert_eq!(merged[0].end_col, 2);
1996
1997 // Test with non-mergeable regions
1998 let color2 = Hsla::blue();
1999 let regions2 = vec![
2000 BackgroundRegion::new(0, 0, color),
2001 BackgroundRegion::new(0, 2, color), // Gap at column 1
2002 BackgroundRegion::new(1, 0, color2), // Different color
2003 ];
2004
2005 let merged2 = merge_background_regions(regions2);
2006 assert_eq!(merged2.len(), 3);
2007 }
2008}