terminal_element.rs

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