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