terminal_element.rs

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