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