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        log::debug!(
 488            "Terminal layout_grid: {} cells processed, {} batched runs created, {} rects (from {} merged regions), layout took {:?}",
 489            cell_count,
 490            batched_runs.len(),
 491            rects.len(),
 492            region_count,
 493            layout_time
 494        );
 495
 496        (rects, batched_runs)
 497    }
 498
 499    /// Computes the cursor position and expected block width, may return a zero width if x_for_index returns
 500    /// the same position for sequential indexes. Use em_width instead
 501    fn shape_cursor(
 502        cursor_point: DisplayCursor,
 503        size: TerminalBounds,
 504        text_fragment: &ShapedLine,
 505    ) -> Option<(Point<Pixels>, Pixels)> {
 506        if cursor_point.line() < size.total_lines() as i32 {
 507            let cursor_width = if text_fragment.width == Pixels::ZERO {
 508                size.cell_width()
 509            } else {
 510                text_fragment.width
 511            };
 512
 513            // Cursor should always surround as much of the text as possible,
 514            // hence when on pixel boundaries round the origin down and the width up
 515            Some((
 516                point(
 517                    (cursor_point.col() as f32 * size.cell_width()).floor(),
 518                    (cursor_point.line() as f32 * size.line_height()).floor(),
 519                ),
 520                cursor_width.ceil(),
 521            ))
 522        } else {
 523            None
 524        }
 525    }
 526
 527    /// Checks if a character is a decorative block/box-like character that should
 528    /// preserve its exact colors without contrast adjustment.
 529    ///
 530    /// This specifically targets characters used as visual connectors, separators,
 531    /// and borders where color matching with adjacent backgrounds is critical.
 532    /// Regular icons (git, folders, etc.) are excluded as they need to remain readable.
 533    ///
 534    /// Fixes https://github.com/zed-industries/zed/issues/34234
 535    fn is_decorative_character(ch: char) -> bool {
 536        matches!(
 537            ch as u32,
 538            // Unicode Box Drawing and Block Elements
 539            0x2500..=0x257F // Box Drawing (└ ┐ ─ │ etc.)
 540            | 0x2580..=0x259F // Block Elements (▀ ▄ █ ░ ▒ ▓ etc.)
 541            | 0x25A0..=0x25FF // Geometric Shapes (■ ▶ ● etc. - includes triangular/circular separators)
 542
 543            // Private Use Area - Powerline separator symbols only
 544            | 0xE0B0..=0xE0B7 // Powerline separators: triangles (E0B0-E0B3) and half circles (E0B4-E0B7)
 545            | 0xE0B8..=0xE0BF // Powerline separators: corner triangles
 546            | 0xE0C0..=0xE0CA // Powerline separators: flames (E0C0-E0C3), pixelated (E0C4-E0C7), and ice (E0C8 & E0CA)
 547            | 0xE0CC..=0xE0D1 // Powerline separators: honeycombs (E0CC-E0CD) and lego (E0CE-E0D1)
 548            | 0xE0D2..=0xE0D7 // Powerline separators: trapezoid (E0D2 & E0D4) and inverted triangles (E0D6-E0D7)
 549        )
 550    }
 551
 552    /// Converts the Alacritty cell styles to GPUI text styles and background color.
 553    fn cell_style(
 554        indexed: &IndexedCell,
 555        fg: terminal::alacritty_terminal::vte::ansi::Color,
 556        bg: terminal::alacritty_terminal::vte::ansi::Color,
 557        colors: &Theme,
 558        text_style: &TextStyle,
 559        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 560        minimum_contrast: f32,
 561    ) -> TextRun {
 562        let flags = indexed.cell.flags;
 563        let mut fg = convert_color(&fg, colors);
 564        let bg = convert_color(&bg, colors);
 565
 566        // Only apply contrast adjustment to non-decorative characters
 567        if !Self::is_decorative_character(indexed.c) {
 568            fg = ensure_minimum_contrast(fg, bg, minimum_contrast);
 569        }
 570
 571        // Ghostty uses (175/255) as the multiplier (~0.69), Alacritty uses 0.66, Kitty
 572        // uses 0.75. We're using 0.7 because it's pretty well in the middle of that.
 573        if flags.intersects(Flags::DIM) {
 574            fg.a *= 0.7;
 575        }
 576
 577        let underline = (flags.intersects(Flags::ALL_UNDERLINES)
 578            || indexed.cell.hyperlink().is_some())
 579        .then(|| UnderlineStyle {
 580            color: Some(fg),
 581            thickness: Pixels::from(1.0),
 582            wavy: flags.contains(Flags::UNDERCURL),
 583        });
 584
 585        let strikethrough = flags
 586            .intersects(Flags::STRIKEOUT)
 587            .then(|| StrikethroughStyle {
 588                color: Some(fg),
 589                thickness: Pixels::from(1.0),
 590            });
 591
 592        let weight = if flags.intersects(Flags::BOLD) {
 593            FontWeight::BOLD
 594        } else {
 595            text_style.font_weight
 596        };
 597
 598        let style = if flags.intersects(Flags::ITALIC) {
 599            FontStyle::Italic
 600        } else {
 601            FontStyle::Normal
 602        };
 603
 604        let mut result = TextRun {
 605            len: indexed.c.len_utf8(),
 606            color: fg,
 607            background_color: None,
 608            font: Font {
 609                weight,
 610                style,
 611                ..text_style.font()
 612            },
 613            underline,
 614            strikethrough,
 615        };
 616
 617        if let Some((style, range)) = hyperlink
 618            && range.contains(&indexed.point)
 619        {
 620            if let Some(underline) = style.underline {
 621                result.underline = Some(underline);
 622            }
 623
 624            if let Some(color) = style.color {
 625                result.color = color;
 626            }
 627        }
 628
 629        result
 630    }
 631
 632    fn generic_button_handler<E>(
 633        connection: Entity<Terminal>,
 634        focus_handle: FocusHandle,
 635        steal_focus: bool,
 636        f: impl Fn(&mut Terminal, &E, &mut Context<Terminal>),
 637    ) -> impl Fn(&E, &mut Window, &mut App) {
 638        move |event, window, cx| {
 639            if steal_focus {
 640                window.focus(&focus_handle, cx);
 641            } else if !focus_handle.is_focused(window) {
 642                return;
 643            }
 644            connection.update(cx, |terminal, cx| {
 645                f(terminal, event, cx);
 646
 647                cx.notify();
 648            })
 649        }
 650    }
 651
 652    fn register_mouse_listeners(
 653        &mut self,
 654        mode: TermMode,
 655        hitbox: &Hitbox,
 656        content_mode: &ContentMode,
 657        window: &mut Window,
 658    ) {
 659        let focus = self.focus.clone();
 660        let terminal = self.terminal.clone();
 661        let terminal_view = self.terminal_view.clone();
 662
 663        self.interactivity.on_mouse_down(MouseButton::Left, {
 664            let terminal = terminal.clone();
 665            let focus = focus.clone();
 666            let terminal_view = terminal_view.clone();
 667
 668            move |e, window, cx| {
 669                window.focus(&focus, cx);
 670
 671                let scroll_top = terminal_view.read(cx).scroll_top;
 672                terminal.update(cx, |terminal, cx| {
 673                    let mut adjusted_event = e.clone();
 674                    if scroll_top > Pixels::ZERO {
 675                        adjusted_event.position.y += scroll_top;
 676                    }
 677                    terminal.mouse_down(&adjusted_event, cx);
 678                    cx.notify();
 679                })
 680            }
 681        });
 682
 683        window.on_mouse_event({
 684            let terminal = self.terminal.clone();
 685            let hitbox = hitbox.clone();
 686            let focus = focus.clone();
 687            let terminal_view = terminal_view;
 688            move |e: &MouseMoveEvent, phase, window, cx| {
 689                if phase != DispatchPhase::Bubble {
 690                    return;
 691                }
 692
 693                if e.pressed_button.is_some() && !cx.has_active_drag() && focus.is_focused(window) {
 694                    let hovered = hitbox.is_hovered(window);
 695
 696                    let scroll_top = terminal_view.read(cx).scroll_top;
 697                    terminal.update(cx, |terminal, cx| {
 698                        if terminal.selection_started() || hovered {
 699                            let mut adjusted_event = e.clone();
 700                            if scroll_top > Pixels::ZERO {
 701                                adjusted_event.position.y += scroll_top;
 702                            }
 703                            terminal.mouse_drag(&adjusted_event, hitbox.bounds, cx);
 704                            cx.notify();
 705                        }
 706                    })
 707                }
 708
 709                if hitbox.is_hovered(window) {
 710                    terminal.update(cx, |terminal, cx| {
 711                        terminal.mouse_move(e, cx);
 712                    })
 713                }
 714            }
 715        });
 716
 717        self.interactivity.on_mouse_up(
 718            MouseButton::Left,
 719            TerminalElement::generic_button_handler(
 720                terminal.clone(),
 721                focus.clone(),
 722                false,
 723                move |terminal, e, cx| {
 724                    terminal.mouse_up(e, cx);
 725                },
 726            ),
 727        );
 728        self.interactivity.on_mouse_down(
 729            MouseButton::Middle,
 730            TerminalElement::generic_button_handler(
 731                terminal.clone(),
 732                focus.clone(),
 733                true,
 734                move |terminal, e, cx| {
 735                    terminal.mouse_down(e, cx);
 736                },
 737            ),
 738        );
 739
 740        if content_mode.is_scrollable() {
 741            self.interactivity.on_scroll_wheel({
 742                let terminal_view = self.terminal_view.downgrade();
 743                move |e, window, cx| {
 744                    terminal_view
 745                        .update(cx, |terminal_view, cx| {
 746                            if matches!(terminal_view.mode, TerminalMode::Standalone)
 747                                || terminal_view.focus_handle.is_focused(window)
 748                            {
 749                                terminal_view.scroll_wheel(e, cx);
 750                                cx.notify();
 751                            }
 752                        })
 753                        .ok();
 754                }
 755            });
 756        }
 757
 758        // Mouse mode handlers:
 759        // All mouse modes need the extra click handlers
 760        if mode.intersects(TermMode::MOUSE_MODE) {
 761            self.interactivity.on_mouse_down(
 762                MouseButton::Right,
 763                TerminalElement::generic_button_handler(
 764                    terminal.clone(),
 765                    focus.clone(),
 766                    true,
 767                    move |terminal, e, cx| {
 768                        terminal.mouse_down(e, cx);
 769                    },
 770                ),
 771            );
 772            self.interactivity.on_mouse_up(
 773                MouseButton::Right,
 774                TerminalElement::generic_button_handler(
 775                    terminal.clone(),
 776                    focus.clone(),
 777                    false,
 778                    move |terminal, e, cx| {
 779                        terminal.mouse_up(e, cx);
 780                    },
 781                ),
 782            );
 783            self.interactivity.on_mouse_up(
 784                MouseButton::Middle,
 785                TerminalElement::generic_button_handler(
 786                    terminal,
 787                    focus,
 788                    false,
 789                    move |terminal, e, cx| {
 790                        terminal.mouse_up(e, cx);
 791                    },
 792                ),
 793            );
 794        }
 795    }
 796
 797    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 798        let settings = ThemeSettings::get_global(cx).clone();
 799        let buffer_font_size = settings.buffer_font_size(cx);
 800        let rem_size_scale = {
 801            // Our default UI font size is 14px on a 16px base scale.
 802            // This means the default UI font size is 0.875rems.
 803            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 804
 805            // We then determine the delta between a single rem and the default font
 806            // size scale.
 807            let default_font_size_delta = 1. - default_font_size_scale;
 808
 809            // Finally, we add this delta to 1rem to get the scale factor that
 810            // should be used to scale up the UI.
 811            1. + default_font_size_delta
 812        };
 813
 814        Some(buffer_font_size * rem_size_scale)
 815    }
 816}
 817
 818impl Element for TerminalElement {
 819    type RequestLayoutState = ();
 820    type PrepaintState = LayoutState;
 821
 822    fn id(&self) -> Option<ElementId> {
 823        self.interactivity.element_id.clone()
 824    }
 825
 826    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 827        None
 828    }
 829
 830    fn request_layout(
 831        &mut self,
 832        global_id: Option<&GlobalElementId>,
 833        inspector_id: Option<&gpui::InspectorElementId>,
 834        window: &mut Window,
 835        cx: &mut App,
 836    ) -> (LayoutId, Self::RequestLayoutState) {
 837        let height: Length = match self.terminal_view.read(cx).content_mode(window, cx) {
 838            ContentMode::Inline {
 839                displayed_lines,
 840                total_lines: _,
 841            } => {
 842                let rem_size = window.rem_size();
 843                let line_height = f32::from(window.text_style().font_size.to_pixels(rem_size))
 844                    * TerminalSettings::get_global(cx)
 845                        .line_height
 846                        .value()
 847                        .to_pixels(rem_size);
 848                (displayed_lines * 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: 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                    // TODO: line_height should be an f32 not an AbsoluteLength.
 972                    let line_height = f32::from(font_pixels) * line_height.to_pixels(rem_size);
 973                    let font_id = cx.text_system().resolve_font(&text_style.font());
 974
 975                    let cell_width = text_system
 976                        .advance(font_id, font_pixels, 'm')
 977                        .unwrap()
 978                        .width;
 979                    gutter = cell_width;
 980
 981                    let mut size = bounds.size;
 982                    size.width -= gutter;
 983
 984                    // https://github.com/zed-industries/zed/issues/2750
 985                    // if the terminal is one column wide, rendering 🦀
 986                    // causes alacritty to misbehave.
 987                    if size.width < cell_width * 2.0 {
 988                        size.width = cell_width * 2.0;
 989                    }
 990
 991                    let mut origin = bounds.origin;
 992                    origin.x += gutter;
 993
 994                    (
 995                        TerminalBounds::new(line_height, cell_width, Bounds { origin, size }),
 996                        line_height,
 997                    )
 998                };
 999
1000                let search_matches = self.terminal.read(cx).matches.clone();
1001
1002                let background_color = theme.colors().terminal_background;
1003
1004                let (last_hovered_word, hover_tooltip) =
1005                    self.terminal.update(cx, |terminal, cx| {
1006                        terminal.set_size(dimensions);
1007                        terminal.sync(window, cx);
1008
1009                        if window.modifiers().secondary()
1010                            && bounds.contains(&window.mouse_position())
1011                            && self.terminal_view.read(cx).hover.is_some()
1012                        {
1013                            let registered_hover = self.terminal_view.read(cx).hover.as_ref();
1014                            if terminal.last_content.last_hovered_word.as_ref()
1015                                == registered_hover.map(|hover| &hover.hovered_word)
1016                            {
1017                                (
1018                                    terminal.last_content.last_hovered_word.clone(),
1019                                    registered_hover.map(|hover| hover.tooltip.clone()),
1020                                )
1021                            } else {
1022                                (None, None)
1023                            }
1024                        } else {
1025                            (None, None)
1026                        }
1027                    });
1028
1029                let scroll_top = self.terminal_view.read(cx).scroll_top;
1030                let hyperlink_tooltip = hover_tooltip.map(|hover_tooltip| {
1031                    let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
1032                    let mut element = div()
1033                        .size_full()
1034                        .id("terminal-element")
1035                        .tooltip(Tooltip::text(hover_tooltip))
1036                        .into_any_element();
1037                    element.prepaint_as_root(offset, bounds.size.into(), window, cx);
1038                    element
1039                });
1040
1041                let TerminalContent {
1042                    cells,
1043                    mode,
1044                    display_offset,
1045                    cursor_char,
1046                    selection,
1047                    cursor,
1048                    ..
1049                } = &self.terminal.read(cx).last_content;
1050                let mode = *mode;
1051                let display_offset = *display_offset;
1052
1053                // searches, highlights to a single range representations
1054                let mut relative_highlighted_ranges = Vec::new();
1055                for search_match in search_matches {
1056                    relative_highlighted_ranges.push((search_match, match_color))
1057                }
1058                if let Some(selection) = selection {
1059                    relative_highlighted_ranges
1060                        .push((selection.start..=selection.end, player_color.selection));
1061                }
1062
1063                // then have that representation be converted to the appropriate highlight data structure
1064
1065                let content_mode = self.terminal_view.read(cx).content_mode(window, cx);
1066
1067                // Calculate the intersection of the terminal's bounds with the current
1068                // content mask (the visible viewport after all parent clipping).
1069                // This allows us to only render cells that are actually visible, which is
1070                // critical for performance when terminals are inside scrollable containers
1071                // like the Agent Panel thread view.
1072                //
1073                // This optimization is analogous to the editor optimization in PR #45077
1074                // which fixed performance issues with large AutoHeight editors inside Lists.
1075                let visible_bounds = window.content_mask().bounds;
1076                let intersection = visible_bounds.intersect(&bounds);
1077
1078                // If the terminal is entirely outside the viewport, skip all cell processing.
1079                // This handles the case where the terminal has been scrolled past (above or
1080                // below the viewport), similar to the editor fix in PR #45077 where start_row
1081                // could exceed max_row when the editor was positioned above the viewport.
1082                let (rects, batched_text_runs) = if intersection.size.height <= px(0.)
1083                    || intersection.size.width <= px(0.)
1084                {
1085                    (Vec::new(), Vec::new())
1086                } else if intersection == bounds {
1087                    // Fast path: terminal fully visible, no clipping needed.
1088                    // Avoid grouping/allocation overhead by streaming cells directly.
1089                    TerminalElement::layout_grid(
1090                        cells.iter().cloned(),
1091                        0,
1092                        &text_style,
1093                        last_hovered_word
1094                            .as_ref()
1095                            .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
1096                        minimum_contrast,
1097                        cx,
1098                    )
1099                } else {
1100                    // Calculate which screen rows are visible based on pixel positions.
1101                    // This works for both Scrollable and Inline modes because we filter
1102                    // by screen position (enumerated line group index), not by the cell's
1103                    // internal line number (which can be negative in Scrollable mode for
1104                    // scrollback history).
1105                    let rows_above_viewport =
1106                        ((intersection.top() - bounds.top()).max(px(0.)) / line_height_px) as usize;
1107                    let visible_row_count =
1108                        (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
1313&                        layout.relative_highlighted_ranges
1314                    {
1315                        if let Some((start_y, highlighted_range_lines)) =
1316                            to_highlighted_range_lines(relative_highlighted_range, layout, origin)
1317                        {
1318                            let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
1319                                0.15 * layout.dimensions.line_height
1320                            } else {
1321                                Pixels::ZERO
1322                            };
1323                            let hr = HighlightedRange {
1324                                start_y,
1325                                line_height: layout.dimensions.line_height,
1326                                lines: highlighted_range_lines,
1327                                color: *color,
1328                                corner_radius: corner_radius,
1329                            };
1330                            hr.paint(true, bounds, window);
1331                        }
1332                    }
1333
1334                    // Paint batched text runs instead of individual cells
1335                    let text_paint_start = Instant::now();
1336                    for batch in &layout.batched_text_runs {
1337                        batch.paint(origin, &layout.dimensions, window, cx);
1338                    }
1339                    let text_paint_time = text_paint_start.elapsed();
1340
1341                    if let Some(text_to_mark) = &marked_text_cloned
1342                        && !text_to_mark.is_empty()
1343                            && let Some(ime_bounds) = layout.ime_cursor_bounds {
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.paint(
1373                                    ime_position,
1374                                    layout.dimensions.line_height,
1375                                    gpui::TextAlign::Left,
1376                                    None,
1377                                    window,
1378                                    cx,
1379                                )
1380                                    .log_err();
1381                            }
1382
1383                    if self.cursor_visible && marked_text_cloned.is_none()
1384                        && let Some(mut cursor) = original_cursor {
1385                            cursor.paint(origin, window, cx);
1386                        }
1387
1388                    if let Some(mut element) = block_below_cursor_element {
1389                        element.paint(window, cx);
1390                    }
1391
1392                    if let Some(mut element) = hyperlink_tooltip {
1393                        element.paint(window, cx);
1394                    }
1395                    let total_paint_time = paint_start.elapsed();
1396                    log::debug!(
1397                        "Terminal paint: {} text runs, {} rects, text paint took {:?}, total paint took {:?}",
1398                        layout.batched_text_runs.len(),
1399                        layout.rects.len(),
1400                        text_paint_time,
1401                        total_paint_time
1402                    );
1403                },
1404            );
1405        });
1406    }
1407}
1408
1409impl IntoElement for TerminalElement {
1410    type Element = Self;
1411
1412    fn into_element(self) -> Self::Element {
1413        self
1414    }
1415}
1416
1417struct TerminalInputHandler {
1418    terminal: Entity<Terminal>,
1419    terminal_view: Entity<TerminalView>,
1420    workspace: WeakEntity<Workspace>,
1421    cursor_bounds: Option<Bounds<Pixels>>,
1422}
1423
1424impl InputHandler for TerminalInputHandler {
1425    fn selected_text_range(
1426        &mut self,
1427        _ignore_disabled_input: bool,
1428        _: &mut Window,
1429        cx: &mut App,
1430    ) -> Option<UTF16Selection> {
1431        if self
1432            .terminal
1433            .read(cx)
1434            .last_content
1435            .mode
1436            .contains(TermMode::ALT_SCREEN)
1437        {
1438            None
1439        } else {
1440            Some(UTF16Selection {
1441                range: 0..0,
1442                reversed: false,
1443            })
1444        }
1445    }
1446
1447    fn marked_text_range(
1448        &mut self,
1449        _window: &mut Window,
1450        cx: &mut App,
1451    ) -> Option<std::ops::Range<usize>> {
1452        self.terminal_view.read(cx).marked_text_range()
1453    }
1454
1455    fn text_for_range(
1456        &mut self,
1457        _: std::ops::Range<usize>,
1458        _: &mut Option<std::ops::Range<usize>>,
1459        _: &mut Window,
1460        _: &mut App,
1461    ) -> Option<String> {
1462        None
1463    }
1464
1465    fn replace_text_in_range(
1466        &mut self,
1467        _replacement_range: Option<std::ops::Range<usize>>,
1468        text: &str,
1469        window: &mut Window,
1470        cx: &mut App,
1471    ) {
1472        self.terminal_view.update(cx, |view, view_cx| {
1473            view.clear_marked_text(view_cx);
1474            view.commit_text(text, view_cx);
1475        });
1476
1477        self.workspace
1478            .update(cx, |this, cx| {
1479                window.invalidate_character_coordinates();
1480                let project = this.project().read(cx);
1481                let telemetry = project.client().telemetry().clone();
1482                telemetry.log_edit_event("terminal", project.is_via_remote_server());
1483            })
1484            .ok();
1485    }
1486
1487    fn replace_and_mark_text_in_range(
1488        &mut self,
1489        _range_utf16: Option<std::ops::Range<usize>>,
1490        new_text: &str,
1491        new_marked_range: Option<std::ops::Range<usize>>,
1492        _window: &mut Window,
1493        cx: &mut App,
1494    ) {
1495        self.terminal_view.update(cx, |view, view_cx| {
1496            view.set_marked_text(new_text.to_string(), new_marked_range, view_cx);
1497        });
1498    }
1499
1500    fn unmark_text(&mut self, _window: &mut Window, cx: &mut App) {
1501        self.terminal_view.update(cx, |view, view_cx| {
1502            view.clear_marked_text(view_cx);
1503        });
1504    }
1505
1506    fn bounds_for_range(
1507        &mut self,
1508        range_utf16: std::ops::Range<usize>,
1509        _window: &mut Window,
1510        cx: &mut App,
1511    ) -> Option<Bounds<Pixels>> {
1512        let term_bounds = self.terminal_view.read(cx).terminal_bounds(cx);
1513
1514        let mut bounds = self.cursor_bounds?;
1515        let offset_x = term_bounds.cell_width * range_utf16.start as f32;
1516        bounds.origin.x += offset_x;
1517
1518        Some(bounds)
1519    }
1520
1521    fn apple_press_and_hold_enabled(&mut self) -> bool {
1522        false
1523    }
1524
1525    fn character_index_for_point(
1526        &mut self,
1527        _point: Point<Pixels>,
1528        _window: &mut Window,
1529        _cx: &mut App,
1530    ) -> Option<usize> {
1531        None
1532    }
1533}
1534
1535pub fn is_blank(cell: &IndexedCell) -> bool {
1536    if cell.c != ' ' {
1537        return false;
1538    }
1539
1540    if cell.bg != AnsiColor::Named(NamedColor::Background) {
1541        return false;
1542    }
1543
1544    if cell.hyperlink().is_some() {
1545        return false;
1546    }
1547
1548    if cell
1549        .flags
1550        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1551    {
1552        return false;
1553    }
1554
1555    true
1556}
1557
1558fn to_highlighted_range_lines(
1559    range: &RangeInclusive<AlacPoint>,
1560    layout: &LayoutState,
1561    origin: Point<Pixels>,
1562) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1563    // Step 1. Normalize the points to be viewport relative.
1564    // When display_offset = 1, here's how the grid is arranged:
1565    //-2,0 -2,1...
1566    //--- Viewport top
1567    //-1,0 -1,1...
1568    //--------- Terminal Top
1569    // 0,0  0,1...
1570    // 1,0  1,1...
1571    //--- Viewport Bottom
1572    // 2,0  2,1...
1573    //--------- Terminal Bottom
1574
1575    // Normalize to viewport relative, from terminal relative.
1576    // lines are i32s, which are negative above the top left corner of the terminal
1577    // If the user has scrolled, we use the display_offset to tell us which offset
1578    // of the grid data we should be looking at. But for the rendering step, we don't
1579    // want negatives. We want things relative to the 'viewport' (the area of the grid
1580    // which is currently shown according to the display offset)
1581    let unclamped_start = AlacPoint::new(
1582        range.start().line + layout.display_offset,
1583        range.start().column,
1584    );
1585    let unclamped_end =
1586        AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1587
1588    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1589    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1590        return None;
1591    }
1592
1593    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1594
1595    let clamped_end_line = unclamped_end
1596        .line
1597        .0
1598        .min(layout.dimensions.num_lines() as i32) as usize;
1599
1600    // Convert the start of the range to pixels
1601    let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1602
1603    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1604    //  (also convert to pixels)
1605    let mut highlighted_range_lines = Vec::new();
1606    for line in clamped_start_line..=clamped_end_line {
1607        let mut line_start = 0;
1608        let mut line_end = layout.dimensions.columns();
1609
1610        if line == clamped_start_line && unclamped_start.line.0 >= 0 {
1611            line_start = unclamped_start.column.0;
1612        }
1613        if line == clamped_end_line && unclamped_end.line.0 <= layout.dimensions.num_lines() as i32
1614        {
1615            line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1616        }
1617
1618        highlighted_range_lines.push(HighlightedRangeLine {
1619            start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1620            end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1621        });
1622    }
1623
1624    Some((start_y, highlighted_range_lines))
1625}
1626
1627/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1628pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1629    let colors = theme.colors();
1630    match fg {
1631        // Named and theme defined colors
1632        terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1633            NamedColor::Black => colors.terminal_ansi_black,
1634            NamedColor::Red => colors.terminal_ansi_red,
1635            NamedColor::Green => colors.terminal_ansi_green,
1636            NamedColor::Yellow => colors.terminal_ansi_yellow,
1637            NamedColor::Blue => colors.terminal_ansi_blue,
1638            NamedColor::Magenta => colors.terminal_ansi_magenta,
1639            NamedColor::Cyan => colors.terminal_ansi_cyan,
1640            NamedColor::White => colors.terminal_ansi_white,
1641            NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1642            NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1643            NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1644            NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1645            NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1646            NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1647            NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1648            NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1649            NamedColor::Foreground => colors.terminal_foreground,
1650            NamedColor::Background => colors.terminal_ansi_background,
1651            NamedColor::Cursor => theme.players().local().cursor,
1652            NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1653            NamedColor::DimRed => colors.terminal_ansi_dim_red,
1654            NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1655            NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1656            NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1657            NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1658            NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1659            NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1660            NamedColor::BrightForeground => colors.terminal_bright_foreground,
1661            NamedColor::DimForeground => colors.terminal_dim_foreground,
1662        },
1663        // 'True' colors
1664        terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1665            terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1666        }
1667        // 8 bit, indexed colors
1668        terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1669            terminal::get_color_at_index(*i as usize, theme)
1670        }
1671    }
1672}
1673
1674#[cfg(test)]
1675mod tests {
1676    use super::*;
1677    use gpui::{AbsoluteLength, Hsla, font};
1678    use ui::utils::apca_contrast;
1679
1680    #[test]
1681    fn test_is_decorative_character() {
1682        // Box Drawing characters (U+2500 to U+257F)
1683        assert!(TerminalElement::is_decorative_character('─')); // U+2500
1684        assert!(TerminalElement::is_decorative_character('│')); // U+2502
1685        assert!(TerminalElement::is_decorative_character('┌')); // U+250C
1686        assert!(TerminalElement::is_decorative_character('┐')); // U+2510
1687        assert!(TerminalElement::is_decorative_character('└')); // U+2514
1688        assert!(TerminalElement::is_decorative_character('┘')); // U+2518
1689        assert!(TerminalElement::is_decorative_character('┼')); // U+253C
1690
1691        // Block Elements (U+2580 to U+259F)
1692        assert!(TerminalElement::is_decorative_character('▀')); // U+2580
1693        assert!(TerminalElement::is_decorative_character('▄')); // U+2584
1694        assert!(TerminalElement::is_decorative_character('█')); // U+2588
1695        assert!(TerminalElement::is_decorative_character('░')); // U+2591
1696        assert!(TerminalElement::is_decorative_character('▒')); // U+2592
1697        assert!(TerminalElement::is_decorative_character('▓')); // U+2593
1698
1699        // Geometric Shapes - block/box-like subset (U+25A0 to U+25D7)
1700        assert!(TerminalElement::is_decorative_character('■')); // U+25A0
1701        assert!(TerminalElement::is_decorative_character('□')); // U+25A1
1702        assert!(TerminalElement::is_decorative_character('▲')); // U+25B2
1703        assert!(TerminalElement::is_decorative_character('▼')); // U+25BC
1704        assert!(TerminalElement::is_decorative_character('◆')); // U+25C6
1705        assert!(TerminalElement::is_decorative_character('●')); // U+25CF
1706
1707        // The specific character from the issue
1708        assert!(TerminalElement::is_decorative_character('◗')); // U+25D7
1709        assert!(TerminalElement::is_decorative_character('◘')); // U+25D8 (now included in Geometric Shapes)
1710        assert!(TerminalElement::is_decorative_character('◙')); // U+25D9 (now included in Geometric Shapes)
1711
1712        // Powerline symbols (Private Use Area)
1713        assert!(TerminalElement::is_decorative_character('\u{E0B0}')); // Powerline right triangle
1714        assert!(TerminalElement::is_decorative_character('\u{E0B2}')); // Powerline left triangle
1715        assert!(TerminalElement::is_decorative_character('\u{E0B4}')); // Powerline right half circle (the actual issue!)
1716        assert!(TerminalElement::is_decorative_character('\u{E0B6}')); // Powerline left half circle
1717        assert!(TerminalElement::is_decorative_character('\u{E0CA}')); // Powerline mirrored ice waveform
1718        assert!(TerminalElement::is_decorative_character('\u{E0D7}')); // Powerline left triangle inverted
1719
1720        // Characters that should NOT be considered decorative
1721        assert!(!TerminalElement::is_decorative_character('A')); // Regular letter
1722        assert!(!TerminalElement::is_decorative_character('$')); // Symbol
1723        assert!(!TerminalElement::is_decorative_character(' ')); // Space
1724        assert!(!TerminalElement::is_decorative_character('←')); // U+2190 (Arrow, not in our ranges)
1725        assert!(!TerminalElement::is_decorative_character('→')); // U+2192 (Arrow, not in our ranges)
1726        assert!(!TerminalElement::is_decorative_character('\u{F00C}')); // Font Awesome check (icon, needs contrast)
1727        assert!(!TerminalElement::is_decorative_character('\u{E711}')); // Devicons (icon, needs contrast)
1728        assert!(!TerminalElement::is_decorative_character('\u{EA71}')); // Codicons folder (icon, needs contrast)
1729        assert!(!TerminalElement::is_decorative_character('\u{F401}')); // Octicons (icon, needs contrast)
1730        assert!(!TerminalElement::is_decorative_character('\u{1F600}')); // Emoji (not in our ranges)
1731    }
1732
1733    #[test]
1734    fn test_decorative_character_boundary_cases() {
1735        // Test exact boundaries of our ranges
1736        // Box Drawing range boundaries
1737        assert!(TerminalElement::is_decorative_character('\u{2500}')); // First char
1738        assert!(TerminalElement::is_decorative_character('\u{257F}')); // Last char
1739        assert!(!TerminalElement::is_decorative_character('\u{24FF}')); // Just before
1740
1741        // Block Elements range boundaries
1742        assert!(TerminalElement::is_decorative_character('\u{2580}')); // First char
1743        assert!(TerminalElement::is_decorative_character('\u{259F}')); // Last char
1744
1745        // Geometric Shapes subset boundaries
1746        assert!(TerminalElement::is_decorative_character('\u{25A0}')); // First char
1747        assert!(TerminalElement::is_decorative_character('\u{25FF}')); // Last char
1748        assert!(!TerminalElement::is_decorative_character('\u{2600}')); // Just after
1749    }
1750
1751    #[test]
1752    fn test_decorative_characters_bypass_contrast_adjustment() {
1753        // Decorative characters should not be affected by contrast adjustment
1754
1755        // The specific character from issue #34234
1756        let problematic_char = '◗'; // U+25D7
1757        assert!(
1758            TerminalElement::is_decorative_character(problematic_char),
1759            "Character ◗ (U+25D7) should be recognized as decorative"
1760        );
1761
1762        // Verify some other commonly used decorative characters
1763        assert!(TerminalElement::is_decorative_character('│')); // Vertical line
1764        assert!(TerminalElement::is_decorative_character('─')); // Horizontal line
1765        assert!(TerminalElement::is_decorative_character('█')); // Full block
1766        assert!(TerminalElement::is_decorative_character('▓')); // Dark shade
1767        assert!(TerminalElement::is_decorative_character('■')); // Black square
1768        assert!(TerminalElement::is_decorative_character('●')); // Black circle
1769
1770        // Verify normal text characters are NOT decorative
1771        assert!(!TerminalElement::is_decorative_character('A'));
1772        assert!(!TerminalElement::is_decorative_character('1'));
1773        assert!(!TerminalElement::is_decorative_character('$'));
1774        assert!(!TerminalElement::is_decorative_character(' '));
1775    }
1776
1777    #[test]
1778    fn test_contrast_adjustment_logic() {
1779        // Test the core contrast adjustment logic without needing full app context
1780
1781        // Test case 1: Light colors (poor contrast)
1782        let white_fg = gpui::Hsla {
1783            h: 0.0,
1784            s: 0.0,
1785            l: 1.0,
1786            a: 1.0,
1787        };
1788        let light_gray_bg = gpui::Hsla {
1789            h: 0.0,
1790            s: 0.0,
1791            l: 0.95,
1792            a: 1.0,
1793        };
1794
1795        // Should have poor contrast
1796        let actual_contrast = apca_contrast(white_fg, light_gray_bg).abs();
1797        assert!(
1798            actual_contrast < 30.0,
1799            "White on light gray should have poor APCA contrast: {}",
1800            actual_contrast
1801        );
1802
1803        // After adjustment with minimum APCA contrast of 45, should be darker
1804        let adjusted = ensure_minimum_contrast(white_fg, light_gray_bg, 45.0);
1805        assert!(
1806            adjusted.l < white_fg.l,
1807            "Adjusted color should be darker than original"
1808        );
1809        let adjusted_contrast = apca_contrast(adjusted, light_gray_bg).abs();
1810        assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1811
1812        // Test case 2: Dark colors (poor contrast)
1813        let black_fg = gpui::Hsla {
1814            h: 0.0,
1815            s: 0.0,
1816            l: 0.0,
1817            a: 1.0,
1818        };
1819        let dark_gray_bg = gpui::Hsla {
1820            h: 0.0,
1821            s: 0.0,
1822            l: 0.05,
1823            a: 1.0,
1824        };
1825
1826        // Should have poor contrast
1827        let actual_contrast = apca_contrast(black_fg, dark_gray_bg).abs();
1828        assert!(
1829            actual_contrast < 30.0,
1830            "Black on dark gray should have poor APCA contrast: {}",
1831            actual_contrast
1832        );
1833
1834        // After adjustment with minimum APCA contrast of 45, should be lighter
1835        let adjusted = ensure_minimum_contrast(black_fg, dark_gray_bg, 45.0);
1836        assert!(
1837            adjusted.l > black_fg.l,
1838            "Adjusted color should be lighter than original"
1839        );
1840        let adjusted_contrast = apca_contrast(adjusted, dark_gray_bg).abs();
1841        assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1842
1843        // Test case 3: Already good contrast
1844        let good_contrast = ensure_minimum_contrast(black_fg, white_fg, 45.0);
1845        assert_eq!(
1846            good_contrast, black_fg,
1847            "Good contrast should not be adjusted"
1848        );
1849    }
1850
1851    #[test]
1852    fn test_white_on_white_contrast_issue() {
1853        // This test reproduces the exact issue from the bug report
1854        // where white ANSI text on white background should be adjusted
1855
1856        // Simulate One Light theme colors
1857        let white_fg = gpui::Hsla {
1858            h: 0.0,
1859            s: 0.0,
1860            l: 0.98, // #fafafaff is approximately 98% lightness
1861            a: 1.0,
1862        };
1863        let white_bg = gpui::Hsla {
1864            h: 0.0,
1865            s: 0.0,
1866            l: 0.98, // Same as foreground - this is the problem!
1867            a: 1.0,
1868        };
1869
1870        // With minimum contrast of 0.0, no adjustment should happen
1871        let no_adjust = ensure_minimum_contrast(white_fg, white_bg, 0.0);
1872        assert_eq!(no_adjust, white_fg, "No adjustment with min_contrast 0.0");
1873
1874        // With minimum APCA contrast of 15, it should adjust to a darker color
1875        let adjusted = ensure_minimum_contrast(white_fg, white_bg, 15.0);
1876        assert!(
1877            adjusted.l < white_fg.l,
1878            "White on white should become darker, got l={}",
1879            adjusted.l
1880        );
1881
1882        // Verify the contrast is now acceptable
1883        let new_contrast = apca_contrast(adjusted, white_bg).abs();
1884        assert!(
1885            new_contrast >= 15.0,
1886            "Adjusted APCA contrast {} should be >= 15.0",
1887            new_contrast
1888        );
1889    }
1890
1891    #[test]
1892    fn test_batched_text_run_can_append() {
1893        let style1 = TextRun {
1894            len: 1,
1895            font: font("Helvetica"),
1896            color: Hsla::red(),
1897            ..Default::default()
1898        };
1899
1900        let style2 = TextRun {
1901            len: 1,
1902            font: font("Helvetica"),
1903            color: Hsla::red(),
1904            ..Default::default()
1905        };
1906
1907        let style3 = TextRun {
1908            len: 1,
1909            font: font("Helvetica"),
1910            color: Hsla::blue(), // Different color
1911            ..Default::default()
1912        };
1913
1914        let font_size = AbsoluteLength::Pixels(px(12.0));
1915        let batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style1, font_size);
1916
1917        // Should be able to append same style
1918        assert!(batch.can_append(&style2));
1919
1920        // Should not be able to append different style
1921        assert!(!batch.can_append(&style3));
1922    }
1923
1924    #[test]
1925    fn test_batched_text_run_append() {
1926        let style = TextRun {
1927            len: 1,
1928            font: font("Helvetica"),
1929            color: Hsla::red(),
1930            ..Default::default()
1931        };
1932
1933        let font_size = AbsoluteLength::Pixels(px(12.0));
1934        let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style, font_size);
1935
1936        assert_eq!(batch.text, "a");
1937        assert_eq!(batch.cell_count, 1);
1938        assert_eq!(batch.style.len, 1);
1939
1940        batch.append_char('b');
1941
1942        assert_eq!(batch.text, "ab");
1943        assert_eq!(batch.cell_count, 2);
1944        assert_eq!(batch.style.len, 2);
1945
1946        batch.append_char('c');
1947
1948        assert_eq!(batch.text, "abc");
1949        assert_eq!(batch.cell_count, 3);
1950        assert_eq!(batch.style.len, 3);
1951    }
1952
1953    #[test]
1954    fn test_batched_text_run_append_char() {
1955        let style = TextRun {
1956            len: 1,
1957            font: font("Helvetica"),
1958            color: Hsla::red(),
1959            ..Default::default()
1960        };
1961
1962        let font_size = AbsoluteLength::Pixels(px(12.0));
1963        let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'x', style, font_size);
1964
1965        assert_eq!(batch.text, "x");
1966        assert_eq!(batch.cell_count, 1);
1967        assert_eq!(batch.style.len, 1);
1968
1969        batch.append_char('y');
1970
1971        assert_eq!(batch.text, "xy");
1972        assert_eq!(batch.cell_count, 2);
1973        assert_eq!(batch.style.len, 2);
1974
1975        // Test with multi-byte character
1976        batch.append_char('😀');
1977
1978        assert_eq!(batch.text, "xy😀");
1979        assert_eq!(batch.cell_count, 3);
1980        assert_eq!(batch.style.len, 6); // 1 + 1 + 4 bytes for emoji
1981    }
1982
1983    #[test]
1984    fn test_batched_text_run_append_zero_width_char() {
1985        let style = TextRun {
1986            len: 1,
1987            font: font("Helvetica"),
1988            color: Hsla::red(),
1989            ..Default::default()
1990        };
1991
1992        let font_size = AbsoluteLength::Pixels(px(12.0));
1993        let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'x', style, font_size);
1994
1995        let combining = '\u{0301}';
1996        batch.append_zero_width_chars(&[combining]);
1997
1998        assert_eq!(batch.text, format!("x{}", combining));
1999        assert_eq!(batch.cell_count, 1);
2000        assert_eq!(batch.style.len, 1 + combining.len_utf8());
2001    }
2002
2003    #[test]
2004    fn test_background_region_can_merge() {
2005        let color1 = Hsla::red();
2006        let color2 = Hsla::blue();
2007
2008        // Test horizontal merging
2009        let mut region1 = BackgroundRegion::new(0, 0, color1);
2010        region1.end_col = 5;
2011        let region2 = BackgroundRegion::new(0, 6, color1);
2012        assert!(region1.can_merge_with(&region2));
2013
2014        // Test vertical merging with same column span
2015        let mut region3 = BackgroundRegion::new(0, 0, color1);
2016        region3.end_col = 5;
2017        let mut region4 = BackgroundRegion::new(1, 0, color1);
2018        region4.end_col = 5;
2019        assert!(region3.can_merge_with(&region4));
2020
2021        // Test cannot merge different colors
2022        let region5 = BackgroundRegion::new(0, 0, color1);
2023        let region6 = BackgroundRegion::new(0, 1, color2);
2024        assert!(!region5.can_merge_with(&region6));
2025
2026        // Test cannot merge non-adjacent regions
2027        let region7 = BackgroundRegion::new(0, 0, color1);
2028        let region8 = BackgroundRegion::new(0, 2, color1);
2029        assert!(!region7.can_merge_with(&region8));
2030
2031        // Test cannot merge vertical regions with different column spans
2032        let mut region9 = BackgroundRegion::new(0, 0, color1);
2033        region9.end_col = 5;
2034        let mut region10 = BackgroundRegion::new(1, 0, color1);
2035        region10.end_col = 6;
2036        assert!(!region9.can_merge_with(&region10));
2037    }
2038
2039    #[test]
2040    fn test_background_region_merge() {
2041        let color = Hsla::red();
2042
2043        // Test horizontal merge
2044        let mut region1 = BackgroundRegion::new(0, 0, color);
2045        region1.end_col = 5;
2046        let mut region2 = BackgroundRegion::new(0, 6, color);
2047        region2.end_col = 10;
2048        region1.merge_with(&region2);
2049        assert_eq!(region1.start_col, 0);
2050        assert_eq!(region1.end_col, 10);
2051        assert_eq!(region1.start_line, 0);
2052        assert_eq!(region1.end_line, 0);
2053
2054        // Test vertical merge
2055        let mut region3 = BackgroundRegion::new(0, 0, color);
2056        region3.end_col = 5;
2057        let mut region4 = BackgroundRegion::new(1, 0, color);
2058        region4.end_col = 5;
2059        region3.merge_with(&region4);
2060        assert_eq!(region3.start_col, 0);
2061        assert_eq!(region3.end_col, 5);
2062        assert_eq!(region3.start_line, 0);
2063        assert_eq!(region3.end_line, 1);
2064    }
2065
2066    #[test]
2067    fn test_merge_background_regions() {
2068        let color = Hsla::red();
2069
2070        // Test merging multiple adjacent regions
2071        let regions = vec![
2072            BackgroundRegion::new(0, 0, color),
2073            BackgroundRegion::new(0, 1, color),
2074            BackgroundRegion::new(0, 2, color),
2075            BackgroundRegion::new(1, 0, color),
2076            BackgroundRegion::new(1, 1, color),
2077            BackgroundRegion::new(1, 2, color),
2078        ];
2079
2080        let merged = merge_background_regions(regions);
2081        assert_eq!(merged.len(), 1);
2082        assert_eq!(merged[0].start_line, 0);
2083        assert_eq!(merged[0].end_line, 1);
2084        assert_eq!(merged[0].start_col, 0);
2085        assert_eq!(merged[0].end_col, 2);
2086
2087        // Test with non-mergeable regions
2088        let color2 = Hsla::blue();
2089        let regions2 = vec![
2090            BackgroundRegion::new(0, 0, color),
2091            BackgroundRegion::new(0, 2, color),  // Gap at column 1
2092            BackgroundRegion::new(1, 0, color2), // Different color
2093        ];
2094
2095        let merged2 = merge_background_regions(regions2);
2096        assert_eq!(merged2.len(), 3);
2097    }
2098
2099    #[test]
2100    fn test_screen_position_filtering_with_positive_lines() {
2101        // Test the unified screen-position-based filtering approach.
2102        // This works for both Scrollable and Inline modes because we filter
2103        // by enumerated line group index, not by cell.point.line values.
2104        use itertools::Itertools;
2105        use terminal::IndexedCell;
2106        use terminal::alacritty_terminal::index::{Column, Line, Point as AlacPoint};
2107        use terminal::alacritty_terminal::term::cell::Cell;
2108
2109        // Create mock cells for lines 0-23 (typical terminal with 24 visible lines)
2110        let mut cells = Vec::new();
2111        for line in 0..24i32 {
2112            for col in 0..3i32 {
2113                cells.push(IndexedCell {
2114                    point: AlacPoint::new(Line(line), Column(col as usize)),
2115                    cell: Cell::default(),
2116                });
2117            }
2118        }
2119
2120        // Scenario: Terminal partially scrolled above viewport
2121        // First 5 lines (0-4) are clipped, lines 5-15 should be visible
2122        let rows_above_viewport = 5usize;
2123        let visible_row_count = 11usize;
2124
2125        // Apply the same filtering logic as in the render code
2126        let filtered: Vec<_> = cells
2127            .iter()
2128            .chunk_by(|c| c.point.line)
2129            .into_iter()
2130            .skip(rows_above_viewport)
2131            .take(visible_row_count)
2132            .flat_map(|(_, line_cells)| line_cells)
2133            .collect();
2134
2135        // Should have lines 5-15 (11 lines * 3 cells each = 33 cells)
2136        assert_eq!(filtered.len(), 11 * 3, "Should have 33 cells for 11 lines");
2137
2138        // First filtered cell should be line 5
2139        assert_eq!(
2140            filtered.first().unwrap().point.line,
2141            Line(5),
2142            "First cell should be on line 5"
2143        );
2144
2145        // Last filtered cell should be line 15
2146        assert_eq!(
2147            filtered.last().unwrap().point.line,
2148            Line(15),
2149            "Last cell should be on line 15"
2150        );
2151    }
2152
2153    #[test]
2154    fn test_screen_position_filtering_with_negative_lines() {
2155        // This is the key test! In Scrollable mode, cells have NEGATIVE line numbers
2156        // for scrollback history. The screen-position filtering approach works because
2157        // we filter by enumerated line group index, not by cell.point.line values.
2158        use itertools::Itertools;
2159        use terminal::IndexedCell;
2160        use terminal::alacritty_terminal::index::{Column, Line, Point as AlacPoint};
2161        use terminal::alacritty_terminal::term::cell::Cell;
2162
2163        // Simulate cells from a scrolled terminal with scrollback
2164        // These have negative line numbers representing scrollback history
2165        let mut scrollback_cells = Vec::new();
2166        for line in -588i32..=-578i32 {
2167            for col in 0..80i32 {
2168                scrollback_cells.push(IndexedCell {
2169                    point: AlacPoint::new(Line(line), Column(col as usize)),
2170                    cell: Cell::default(),
2171                });
2172            }
2173        }
2174
2175        // Scenario: First 3 screen rows clipped, show next 5 rows
2176        let rows_above_viewport = 3usize;
2177        let visible_row_count = 5usize;
2178
2179        // Apply the same filtering logic as in the render code
2180        let filtered: Vec<_> = scrollback_cells
2181            .iter()
2182            .chunk_by(|c| c.point.line)
2183            .into_iter()
2184            .skip(rows_above_viewport)
2185            .take(visible_row_count)
2186            .flat_map(|(_, line_cells)| line_cells)
2187            .collect();
2188
2189        // Should have 5 lines * 80 cells = 400 cells
2190        assert_eq!(filtered.len(), 5 * 80, "Should have 400 cells for 5 lines");
2191
2192        // First filtered cell should be line -585 (skipped 3 lines from -588)
2193        assert_eq!(
2194            filtered.first().unwrap().point.line,
2195            Line(-585),
2196            "First cell should be on line -585"
2197        );
2198
2199        // Last filtered cell should be line -581 (5 lines: -585, -584, -583, -582, -581)
2200        assert_eq!(
2201            filtered.last().unwrap().point.line,
2202            Line(-581),
2203            "Last cell should be on line -581"
2204        );
2205    }
2206
2207    #[test]
2208    fn test_screen_position_filtering_skip_all() {
2209        // Test what happens when we skip more rows than exist
2210        use itertools::Itertools;
2211        use terminal::IndexedCell;
2212        use terminal::alacritty_terminal::index::{Column, Line, Point as AlacPoint};
2213        use terminal::alacritty_terminal::term::cell::Cell;
2214
2215        let mut cells = Vec::new();
2216        for line in 0..10i32 {
2217            cells.push(IndexedCell {
2218                point: AlacPoint::new(Line(line), Column(0)),
2219                cell: Cell::default(),
2220            });
2221        }
2222
2223        // Skip more rows than exist
2224        let rows_above_viewport = 100usize;
2225        let visible_row_count = 5usize;
2226
2227        let filtered: Vec<_> = cells
2228            .iter()
2229            .chunk_by(|c| c.point.line)
2230            .into_iter()
2231            .skip(rows_above_viewport)
2232            .take(visible_row_count)
2233            .flat_map(|(_, line_cells)| line_cells)
2234            .collect();
2235
2236        assert_eq!(
2237            filtered.len(),
2238            0,
2239            "Should have no cells when all are skipped"
2240        );
2241    }
2242
2243    #[test]
2244    fn test_layout_grid_positioning_math() {
2245        // Test the math that layout_grid uses for positioning.
2246        // When we skip N rows, we pass N as start_line_offset to layout_grid,
2247        // which positions the first visible line at screen row N.
2248
2249        // Scenario: Terminal at y=-100px, line_height=20px
2250        // First 5 screen rows are above viewport (clipped)
2251        // So we skip 5 rows and pass offset=5 to layout_grid
2252
2253        let terminal_origin_y = -100.0f32;
2254        let line_height = 20.0f32;
2255        let rows_skipped = 5;
2256
2257        // The first visible line (at offset 5) renders at:
2258        // y = terminal_origin + offset * line_height = -100 + 5*20 = 0
2259        let first_visible_y = terminal_origin_y + rows_skipped as f32 * line_height;
2260        assert_eq!(
2261            first_visible_y, 0.0,
2262            "First visible line should be at viewport top (y=0)"
2263        );
2264
2265        // The 6th visible line (at offset 10) renders at:
2266        let sixth_visible_y = terminal_origin_y + (rows_skipped + 5) as f32 * line_height;
2267        assert_eq!(
2268            sixth_visible_y, 100.0,
2269            "6th visible line should be at y=100"
2270        );
2271    }
2272
2273    #[test]
2274    fn test_unified_filtering_works_for_both_modes() {
2275        // This test proves that the unified screen-position filtering approach
2276        // works for BOTH positive line numbers (Inline mode) and negative line
2277        // numbers (Scrollable mode with scrollback).
2278        //
2279        // The key insight: we filter by enumerated line group index (screen position),
2280        // not by cell.point.line values. This makes the filtering agnostic to the
2281        // actual line numbers in the cells.
2282        use itertools::Itertools;
2283        use terminal::IndexedCell;
2284        use terminal::alacritty_terminal::index::{Column, Line, Point as AlacPoint};
2285        use terminal::alacritty_terminal::term::cell::Cell;
2286
2287        // Test with positive line numbers (Inline mode style)
2288        let positive_cells: Vec<_> = (0..10i32)
2289            .flat_map(|line| {
2290                (0..3i32).map(move |col| IndexedCell {
2291                    point: AlacPoint::new(Line(line), Column(col as usize)),
2292                    cell: Cell::default(),
2293                })
2294            })
2295            .collect();
2296
2297        // Test with negative line numbers (Scrollable mode with scrollback)
2298        let negative_cells: Vec<_> = (-10i32..0i32)
2299            .flat_map(|line| {
2300                (0..3i32).map(move |col| IndexedCell {
2301                    point: AlacPoint::new(Line(line), Column(col as usize)),
2302                    cell: Cell::default(),
2303                })
2304            })
2305            .collect();
2306
2307        let rows_to_skip = 3usize;
2308        let rows_to_take = 4usize;
2309
2310        // Filter positive cells
2311        let positive_filtered: Vec<_> = positive_cells
2312            .iter()
2313            .chunk_by(|c| c.point.line)
2314            .into_iter()
2315            .skip(rows_to_skip)
2316            .take(rows_to_take)
2317            .flat_map(|(_, cells)| cells)
2318            .collect();
2319
2320        // Filter negative cells
2321        let negative_filtered: Vec<_> = negative_cells
2322            .iter()
2323            .chunk_by(|c| c.point.line)
2324            .into_iter()
2325            .skip(rows_to_skip)
2326            .take(rows_to_take)
2327            .flat_map(|(_, cells)| cells)
2328            .collect();
2329
2330        // Both should have same count: 4 lines * 3 cells = 12
2331        assert_eq!(positive_filtered.len(), 12);
2332        assert_eq!(negative_filtered.len(), 12);
2333
2334        // Positive: lines 3, 4, 5, 6
2335        assert_eq!(positive_filtered.first().unwrap().point.line, Line(3));
2336        assert_eq!(positive_filtered.last().unwrap().point.line, Line(6));
2337
2338        // Negative: lines -7, -6, -5, -4
2339        assert_eq!(negative_filtered.first().unwrap().point.line, Line(-7));
2340        assert_eq!(negative_filtered.last().unwrap().point.line, Line(-4));
2341    }
2342}