terminal_element.rs

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