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