terminal_element.rs

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