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