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