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