terminal_element.rs

   1use crate::color_contrast;
   2use editor::{CursorLayout, HighlightedRange, HighlightedRangeLine};
   3use gpui::{
   4    AbsoluteLength, AnyElement, App, AvailableSpace, Bounds, ContentMask, Context, DispatchPhase,
   5    Element, ElementId, Entity, FocusHandle, Font, FontFeatures, FontStyle, FontWeight,
   6    GlobalElementId, HighlightStyle, Hitbox, Hsla, InputHandler, InteractiveElement, Interactivity,
   7    IntoElement, LayoutId, Length, ModifiersChangedEvent, MouseButton, MouseMoveEvent, Pixels,
   8    Point, ShapedLine, StatefulInteractiveElement, StrikethroughStyle, Styled, TextRun, TextStyle,
   9    UTF16Selection, UnderlineStyle, WeakEntity, WhiteSpace, Window, div, fill, point, px, relative,
  10    size,
  11};
  12use itertools::Itertools;
  13use language::CursorShape;
  14use settings::Settings;
  15use std::time::Instant;
  16use terminal::{
  17    IndexedCell, Terminal, TerminalBounds, TerminalContent,
  18    alacritty_terminal::{
  19        grid::Dimensions,
  20        index::Point as AlacPoint,
  21        term::{TermMode, cell::Flags},
  22        vte::ansi::{
  23            Color::{self as AnsiColor, Named},
  24            CursorShape as AlacCursorShape, NamedColor,
  25        },
  26    },
  27    terminal_settings::TerminalSettings,
  28};
  29use theme::{ActiveTheme, Theme, ThemeSettings};
  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    background_color: Hsla,
  47    dimensions: TerminalBounds,
  48    mode: TermMode,
  49    display_offset: usize,
  50    hyperlink_tooltip: Option<AnyElement>,
  51    gutter: Pixels,
  52    block_below_cursor_element: Option<AnyElement>,
  53    base_text_style: TextStyle,
  54    content_mode: ContentMode,
  55}
  56
  57/// Helper struct for converting data between Alacritty's cursor points, and displayed cursor points.
  58struct DisplayCursor {
  59    line: i32,
  60    col: usize,
  61}
  62
  63impl DisplayCursor {
  64    fn from(cursor_point: AlacPoint, display_offset: usize) -> Self {
  65        Self {
  66            line: cursor_point.line.0 + display_offset as i32,
  67            col: cursor_point.column.0,
  68        }
  69    }
  70
  71    pub fn line(&self) -> i32 {
  72        self.line
  73    }
  74
  75    pub fn col(&self) -> usize {
  76        self.col
  77    }
  78}
  79
  80/// A batched text run that combines multiple adjacent cells with the same style
  81#[derive(Debug)]
  82pub struct BatchedTextRun {
  83    pub start_point: AlacPoint<i32, i32>,
  84    pub text: String,
  85    pub cell_count: usize,
  86    pub style: TextRun,
  87    pub font_size: AbsoluteLength,
  88}
  89
  90impl BatchedTextRun {
  91    fn new_from_char(
  92        start_point: AlacPoint<i32, i32>,
  93        c: char,
  94        style: TextRun,
  95        font_size: AbsoluteLength,
  96    ) -> Self {
  97        let mut text = String::with_capacity(100); // Pre-allocate for typical line length
  98        text.push(c);
  99        BatchedTextRun {
 100            start_point,
 101            text,
 102            cell_count: 1,
 103            style,
 104            font_size,
 105        }
 106    }
 107
 108    fn can_append(&self, other_style: &TextRun) -> bool {
 109        self.style.font == other_style.font
 110            && self.style.color == other_style.color
 111            && self.style.background_color == other_style.background_color
 112            && self.style.underline == other_style.underline
 113            && self.style.strikethrough == other_style.strikethrough
 114    }
 115
 116    fn append_char(&mut self, c: char) {
 117        self.text.push(c);
 118        self.cell_count += 1;
 119        self.style.len += c.len_utf8();
 120    }
 121
 122    pub fn paint(
 123        &self,
 124        origin: Point<Pixels>,
 125        dimensions: &TerminalBounds,
 126        window: &mut Window,
 127        cx: &mut App,
 128    ) {
 129        let pos = Point::new(
 130            (origin.x + self.start_point.column as f32 * dimensions.cell_width).floor(),
 131            origin.y + self.start_point.line as f32 * dimensions.line_height,
 132        );
 133
 134        let _ = window
 135            .text_system()
 136            .shape_line(
 137                self.text.clone().into(),
 138                self.font_size.to_pixels(window.rem_size()),
 139                &[self.style.clone()],
 140                Some(dimensions.cell_width),
 141            )
 142            .paint(pos, dimensions.line_height, window, cx);
 143    }
 144}
 145
 146#[derive(Clone, Debug, Default)]
 147pub struct LayoutRect {
 148    point: AlacPoint<i32, i32>,
 149    num_of_cells: usize,
 150    color: Hsla,
 151}
 152
 153impl LayoutRect {
 154    fn new(point: AlacPoint<i32, i32>, num_of_cells: usize, color: Hsla) -> LayoutRect {
 155        LayoutRect {
 156            point,
 157            num_of_cells,
 158            color,
 159        }
 160    }
 161
 162    pub fn paint(&self, origin: Point<Pixels>, dimensions: &TerminalBounds, window: &mut Window) {
 163        let position = {
 164            let alac_point = self.point;
 165            point(
 166                (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
 167                origin.y + alac_point.line as f32 * dimensions.line_height,
 168            )
 169        };
 170        let size = point(
 171            (dimensions.cell_width * self.num_of_cells as f32).ceil(),
 172            dimensions.line_height,
 173        )
 174        .into();
 175
 176        window.paint_quad(fill(Bounds::new(position, size), self.color));
 177    }
 178}
 179
 180/// Represents a rectangular region with a specific background color
 181#[derive(Debug, Clone)]
 182struct BackgroundRegion {
 183    start_line: i32,
 184    start_col: i32,
 185    end_line: i32,
 186    end_col: i32,
 187    color: Hsla,
 188}
 189
 190impl BackgroundRegion {
 191    fn new(line: i32, col: i32, color: Hsla) -> Self {
 192        BackgroundRegion {
 193            start_line: line,
 194            start_col: col,
 195            end_line: line,
 196            end_col: col,
 197            color,
 198        }
 199    }
 200
 201    /// Check if this region can be merged with another region
 202    fn can_merge_with(&self, other: &BackgroundRegion) -> bool {
 203        if self.color != other.color {
 204            return false;
 205        }
 206
 207        // Check if regions are adjacent horizontally
 208        if self.start_line == other.start_line && self.end_line == other.end_line {
 209            return self.end_col + 1 == other.start_col || other.end_col + 1 == self.start_col;
 210        }
 211
 212        // Check if regions are adjacent vertically with same column span
 213        if self.start_col == other.start_col && self.end_col == other.end_col {
 214            return self.end_line + 1 == other.start_line || other.end_line + 1 == self.start_line;
 215        }
 216
 217        false
 218    }
 219
 220    /// Merge this region with another region
 221    fn merge_with(&mut self, other: &BackgroundRegion) {
 222        self.start_line = self.start_line.min(other.start_line);
 223        self.start_col = self.start_col.min(other.start_col);
 224        self.end_line = self.end_line.max(other.end_line);
 225        self.end_col = self.end_col.max(other.end_col);
 226    }
 227}
 228
 229/// Merge background regions to minimize the number of rectangles
 230fn merge_background_regions(regions: Vec<BackgroundRegion>) -> Vec<BackgroundRegion> {
 231    if regions.is_empty() {
 232        return regions;
 233    }
 234
 235    let mut merged = regions;
 236    let mut changed = true;
 237
 238    // Keep merging until no more merges are possible
 239    while changed {
 240        changed = false;
 241        let mut i = 0;
 242
 243        while i < merged.len() {
 244            let mut j = i + 1;
 245            while j < merged.len() {
 246                if merged[i].can_merge_with(&merged[j]) {
 247                    let other = merged.remove(j);
 248                    merged[i].merge_with(&other);
 249                    changed = true;
 250                } else {
 251                    j += 1;
 252                }
 253            }
 254            i += 1;
 255        }
 256    }
 257
 258    merged
 259}
 260
 261/// The GPUI element that paints the terminal.
 262/// 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?
 263pub struct TerminalElement {
 264    terminal: Entity<Terminal>,
 265    terminal_view: Entity<TerminalView>,
 266    workspace: WeakEntity<Workspace>,
 267    focus: FocusHandle,
 268    focused: bool,
 269    cursor_visible: bool,
 270    interactivity: Interactivity,
 271    mode: TerminalMode,
 272    block_below_cursor: Option<Rc<BlockProperties>>,
 273}
 274
 275impl InteractiveElement for TerminalElement {
 276    fn interactivity(&mut self) -> &mut Interactivity {
 277        &mut self.interactivity
 278    }
 279}
 280
 281impl StatefulInteractiveElement for TerminalElement {}
 282
 283impl TerminalElement {
 284    pub fn new(
 285        terminal: Entity<Terminal>,
 286        terminal_view: Entity<TerminalView>,
 287        workspace: WeakEntity<Workspace>,
 288        focus: FocusHandle,
 289        focused: bool,
 290        cursor_visible: bool,
 291        block_below_cursor: Option<Rc<BlockProperties>>,
 292        mode: TerminalMode,
 293    ) -> TerminalElement {
 294        TerminalElement {
 295            terminal,
 296            terminal_view,
 297            workspace,
 298            focused,
 299            focus: focus.clone(),
 300            cursor_visible,
 301            block_below_cursor,
 302            mode,
 303            interactivity: Default::default(),
 304        }
 305        .track_focus(&focus)
 306    }
 307
 308    //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
 309
 310    pub fn layout_grid(
 311        grid: impl Iterator<Item = IndexedCell>,
 312        start_line_offset: i32,
 313        text_style: &TextStyle,
 314        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 315        minimum_contrast: f32,
 316        cx: &App,
 317    ) -> (Vec<LayoutRect>, Vec<BatchedTextRun>) {
 318        let start_time = Instant::now();
 319        let theme = cx.theme();
 320
 321        // Pre-allocate with estimated capacity to reduce reallocations
 322        let estimated_cells = grid.size_hint().0;
 323        let estimated_runs = estimated_cells / 10; // Estimate ~10 cells per run
 324        let estimated_regions = estimated_cells / 20; // Estimate ~20 cells per background region
 325
 326        let mut batched_runs = Vec::with_capacity(estimated_runs);
 327        let mut cell_count = 0;
 328
 329        // Collect background regions for efficient merging
 330        let mut background_regions: Vec<BackgroundRegion> = Vec::with_capacity(estimated_regions);
 331        let mut current_batch: Option<BatchedTextRun> = None;
 332
 333        // First pass: collect all cells and their backgrounds
 334        let linegroups = grid.into_iter().chunk_by(|i| i.point.line);
 335        for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
 336            let alac_line = start_line_offset + line_index as i32;
 337
 338            // Flush any existing batch at line boundaries
 339            if let Some(batch) = current_batch.take() {
 340                batched_runs.push(batch);
 341            }
 342
 343            let mut previous_cell_had_extras = false;
 344
 345            for cell in line {
 346                let mut fg = cell.fg;
 347                let mut bg = cell.bg;
 348                if cell.flags.contains(Flags::INVERSE) {
 349                    mem::swap(&mut fg, &mut bg);
 350                }
 351
 352                // Collect background regions (skip default background)
 353                if !matches!(bg, Named(NamedColor::Background)) {
 354                    let color = convert_color(&bg, theme);
 355                    let col = cell.point.column.0 as i32;
 356
 357                    // Try to extend the last region if it's on the same line with the same color
 358                    if let Some(last_region) = background_regions.last_mut() {
 359                        if last_region.color == color
 360                            && last_region.start_line == alac_line
 361                            && last_region.end_line == alac_line
 362                            && last_region.end_col + 1 == col
 363                        {
 364                            last_region.end_col = col;
 365                        } else {
 366                            background_regions.push(BackgroundRegion::new(alac_line, col, color));
 367                        }
 368                    } else {
 369                        background_regions.push(BackgroundRegion::new(alac_line, col, color));
 370                    }
 371                }
 372                // Skip wide character spacers - they're just placeholders for the second cell of wide characters
 373                if cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
 374                    continue;
 375                }
 376
 377                // Skip spaces that follow cells with extras (emoji variation sequences)
 378                if cell.c == ' ' && previous_cell_had_extras {
 379                    previous_cell_had_extras = false;
 380                    continue;
 381                }
 382                // Update tracking for next iteration
 383                previous_cell_had_extras = cell.extra.is_some();
 384
 385                //Layout current cell text
 386                {
 387                    if !is_blank(&cell) {
 388                        cell_count += 1;
 389                        let cell_style = TerminalElement::cell_style(
 390                            &cell,
 391                            fg,
 392                            bg,
 393                            theme,
 394                            text_style,
 395                            hyperlink,
 396                            minimum_contrast,
 397                        );
 398
 399                        let cell_point = AlacPoint::new(alac_line, cell.point.column.0 as i32);
 400
 401                        // Try to batch with existing run
 402                        if let Some(ref mut batch) = current_batch {
 403                            if batch.can_append(&cell_style)
 404                                && batch.start_point.line == cell_point.line
 405                                && batch.start_point.column + batch.cell_count as i32
 406                                    == cell_point.column
 407                            {
 408                                batch.append_char(cell.c);
 409                            } else {
 410                                // Flush current batch and start new one
 411                                let old_batch = current_batch.take().unwrap();
 412                                batched_runs.push(old_batch);
 413                                current_batch = Some(BatchedTextRun::new_from_char(
 414                                    cell_point,
 415                                    cell.c,
 416                                    cell_style,
 417                                    text_style.font_size,
 418                                ));
 419                            }
 420                        } else {
 421                            // Start new batch
 422                            current_batch = Some(BatchedTextRun::new_from_char(
 423                                cell_point,
 424                                cell.c,
 425                                cell_style,
 426                                text_style.font_size,
 427                            ));
 428                        }
 429                    };
 430                }
 431            }
 432        }
 433
 434        // Flush any remaining batch
 435        if let Some(batch) = current_batch {
 436            batched_runs.push(batch);
 437        }
 438
 439        // Second pass: merge background regions and convert to layout rects
 440        let region_count = background_regions.len();
 441        let merged_regions = merge_background_regions(background_regions);
 442        let mut rects = Vec::with_capacity(merged_regions.len() * 2); // Estimate 2 rects per merged region
 443
 444        // Convert merged regions to layout rects
 445        // Since LayoutRect only supports single-line rectangles, we need to split multi-line regions
 446        for region in merged_regions {
 447            for line in region.start_line..=region.end_line {
 448                rects.push(LayoutRect::new(
 449                    AlacPoint::new(line, region.start_col),
 450                    (region.end_col - region.start_col + 1) as usize,
 451                    region.color,
 452                ));
 453            }
 454        }
 455
 456        let layout_time = start_time.elapsed();
 457        log::debug!(
 458            "Terminal layout_grid: {} cells processed, {} batched runs created, {} rects (from {} merged regions), layout took {:?}",
 459            cell_count,
 460            batched_runs.len(),
 461            rects.len(),
 462            region_count,
 463            layout_time
 464        );
 465
 466        (rects, batched_runs)
 467    }
 468
 469    /// Computes the cursor position and expected block width, may return a zero width if x_for_index returns
 470    /// the same position for sequential indexes. Use em_width instead
 471    fn shape_cursor(
 472        cursor_point: DisplayCursor,
 473        size: TerminalBounds,
 474        text_fragment: &ShapedLine,
 475    ) -> Option<(Point<Pixels>, Pixels)> {
 476        if cursor_point.line() < size.total_lines() as i32 {
 477            let cursor_width = if text_fragment.width == Pixels::ZERO {
 478                size.cell_width()
 479            } else {
 480                text_fragment.width
 481            };
 482
 483            // Cursor should always surround as much of the text as possible,
 484            // hence when on pixel boundaries round the origin down and the width up
 485            Some((
 486                point(
 487                    (cursor_point.col() as f32 * size.cell_width()).floor(),
 488                    (cursor_point.line() as f32 * size.line_height()).floor(),
 489                ),
 490                cursor_width.ceil(),
 491            ))
 492        } else {
 493            None
 494        }
 495    }
 496
 497    /// Converts the Alacritty cell styles to GPUI text styles and background color.
 498    fn cell_style(
 499        indexed: &IndexedCell,
 500        fg: terminal::alacritty_terminal::vte::ansi::Color,
 501        bg: terminal::alacritty_terminal::vte::ansi::Color,
 502        colors: &Theme,
 503        text_style: &TextStyle,
 504        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 505        minimum_contrast: f32,
 506    ) -> TextRun {
 507        let flags = indexed.cell.flags;
 508        let mut fg = convert_color(&fg, colors);
 509        let bg = convert_color(&bg, colors);
 510
 511        fg = color_contrast::ensure_minimum_contrast(fg, bg, minimum_contrast);
 512
 513        // Ghostty uses (175/255) as the multiplier (~0.69), Alacritty uses 0.66, Kitty
 514        // uses 0.75. We're using 0.7 because it's pretty well in the middle of that.
 515        if flags.intersects(Flags::DIM) {
 516            fg.a *= 0.7;
 517        }
 518
 519        let underline = (flags.intersects(Flags::ALL_UNDERLINES)
 520            || indexed.cell.hyperlink().is_some())
 521        .then(|| UnderlineStyle {
 522            color: Some(fg),
 523            thickness: Pixels::from(1.0),
 524            wavy: flags.contains(Flags::UNDERCURL),
 525        });
 526
 527        let strikethrough = flags
 528            .intersects(Flags::STRIKEOUT)
 529            .then(|| StrikethroughStyle {
 530                color: Some(fg),
 531                thickness: Pixels::from(1.0),
 532            });
 533
 534        let weight = if flags.intersects(Flags::BOLD) {
 535            FontWeight::BOLD
 536        } else {
 537            text_style.font_weight
 538        };
 539
 540        let style = if flags.intersects(Flags::ITALIC) {
 541            FontStyle::Italic
 542        } else {
 543            FontStyle::Normal
 544        };
 545
 546        let mut result = TextRun {
 547            len: indexed.c.len_utf8(),
 548            color: fg,
 549            background_color: None,
 550            font: Font {
 551                weight,
 552                style,
 553                ..text_style.font()
 554            },
 555            underline,
 556            strikethrough,
 557        };
 558
 559        if let Some((style, range)) = hyperlink {
 560            if range.contains(&indexed.point) {
 561                if let Some(underline) = style.underline {
 562                    result.underline = Some(underline);
 563                }
 564
 565                if let Some(color) = style.color {
 566                    result.color = color;
 567                }
 568            }
 569        }
 570
 571        result
 572    }
 573
 574    fn generic_button_handler<E>(
 575        connection: Entity<Terminal>,
 576        focus_handle: FocusHandle,
 577        steal_focus: bool,
 578        f: impl Fn(&mut Terminal, &E, &mut Context<Terminal>),
 579    ) -> impl Fn(&E, &mut Window, &mut App) {
 580        move |event, window, cx| {
 581            if steal_focus {
 582                window.focus(&focus_handle);
 583            } else if !focus_handle.is_focused(window) {
 584                return;
 585            }
 586            connection.update(cx, |terminal, cx| {
 587                f(terminal, event, cx);
 588
 589                cx.notify();
 590            })
 591        }
 592    }
 593
 594    fn register_mouse_listeners(
 595        &mut self,
 596        mode: TermMode,
 597        hitbox: &Hitbox,
 598        content_mode: &ContentMode,
 599        window: &mut Window,
 600    ) {
 601        let focus = self.focus.clone();
 602        let terminal = self.terminal.clone();
 603        let terminal_view = self.terminal_view.clone();
 604
 605        self.interactivity.on_mouse_down(MouseButton::Left, {
 606            let terminal = terminal.clone();
 607            let focus = focus.clone();
 608            let terminal_view = terminal_view.clone();
 609
 610            move |e, window, cx| {
 611                window.focus(&focus);
 612
 613                let scroll_top = terminal_view.read(cx).scroll_top;
 614                terminal.update(cx, |terminal, cx| {
 615                    let mut adjusted_event = e.clone();
 616                    if scroll_top > Pixels::ZERO {
 617                        adjusted_event.position.y += scroll_top;
 618                    }
 619                    terminal.mouse_down(&adjusted_event, cx);
 620                    cx.notify();
 621                })
 622            }
 623        });
 624
 625        window.on_mouse_event({
 626            let terminal = self.terminal.clone();
 627            let hitbox = hitbox.clone();
 628            let focus = focus.clone();
 629            let terminal_view = terminal_view.clone();
 630            move |e: &MouseMoveEvent, phase, window, cx| {
 631                if phase != DispatchPhase::Bubble {
 632                    return;
 633                }
 634
 635                if e.pressed_button.is_some() && !cx.has_active_drag() && focus.is_focused(window) {
 636                    let hovered = hitbox.is_hovered(window);
 637
 638                    let scroll_top = terminal_view.read(cx).scroll_top;
 639                    terminal.update(cx, |terminal, cx| {
 640                        if terminal.selection_started() || hovered {
 641                            let mut adjusted_event = e.clone();
 642                            if scroll_top > Pixels::ZERO {
 643                                adjusted_event.position.y += scroll_top;
 644                            }
 645                            terminal.mouse_drag(&adjusted_event, hitbox.bounds, cx);
 646                            cx.notify();
 647                        }
 648                    })
 649                }
 650
 651                if hitbox.is_hovered(window) {
 652                    terminal.update(cx, |terminal, cx| {
 653                        terminal.mouse_move(e, cx);
 654                    })
 655                }
 656            }
 657        });
 658
 659        self.interactivity.on_mouse_up(
 660            MouseButton::Left,
 661            TerminalElement::generic_button_handler(
 662                terminal.clone(),
 663                focus.clone(),
 664                false,
 665                move |terminal, e, cx| {
 666                    terminal.mouse_up(e, cx);
 667                },
 668            ),
 669        );
 670        self.interactivity.on_mouse_down(
 671            MouseButton::Middle,
 672            TerminalElement::generic_button_handler(
 673                terminal.clone(),
 674                focus.clone(),
 675                true,
 676                move |terminal, e, cx| {
 677                    terminal.mouse_down(e, cx);
 678                },
 679            ),
 680        );
 681
 682        if content_mode.is_scrollable() {
 683            self.interactivity.on_scroll_wheel({
 684                let terminal_view = self.terminal_view.downgrade();
 685                move |e, window, cx| {
 686                    terminal_view
 687                        .update(cx, |terminal_view, cx| {
 688                            if matches!(terminal_view.mode, TerminalMode::Standalone)
 689                                || terminal_view.focus_handle.is_focused(window)
 690                            {
 691                                terminal_view.scroll_wheel(e, cx);
 692                                cx.notify();
 693                            }
 694                        })
 695                        .ok();
 696                }
 697            });
 698        }
 699
 700        // Mouse mode handlers:
 701        // All mouse modes need the extra click handlers
 702        if mode.intersects(TermMode::MOUSE_MODE) {
 703            self.interactivity.on_mouse_down(
 704                MouseButton::Right,
 705                TerminalElement::generic_button_handler(
 706                    terminal.clone(),
 707                    focus.clone(),
 708                    true,
 709                    move |terminal, e, cx| {
 710                        terminal.mouse_down(e, cx);
 711                    },
 712                ),
 713            );
 714            self.interactivity.on_mouse_up(
 715                MouseButton::Right,
 716                TerminalElement::generic_button_handler(
 717                    terminal.clone(),
 718                    focus.clone(),
 719                    false,
 720                    move |terminal, e, cx| {
 721                        terminal.mouse_up(e, cx);
 722                    },
 723                ),
 724            );
 725            self.interactivity.on_mouse_up(
 726                MouseButton::Middle,
 727                TerminalElement::generic_button_handler(
 728                    terminal,
 729                    focus,
 730                    false,
 731                    move |terminal, e, cx| {
 732                        terminal.mouse_up(e, cx);
 733                    },
 734                ),
 735            );
 736        }
 737    }
 738
 739    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 740        let settings = ThemeSettings::get_global(cx).clone();
 741        let buffer_font_size = settings.buffer_font_size(cx);
 742        let rem_size_scale = {
 743            // Our default UI font size is 14px on a 16px base scale.
 744            // This means the default UI font size is 0.875rems.
 745            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 746
 747            // We then determine the delta between a single rem and the default font
 748            // size scale.
 749            let default_font_size_delta = 1. - default_font_size_scale;
 750
 751            // Finally, we add this delta to 1rem to get the scale factor that
 752            // should be used to scale up the UI.
 753            1. + default_font_size_delta
 754        };
 755
 756        Some(buffer_font_size * rem_size_scale)
 757    }
 758}
 759
 760impl Element for TerminalElement {
 761    type RequestLayoutState = ();
 762    type PrepaintState = LayoutState;
 763
 764    fn id(&self) -> Option<ElementId> {
 765        self.interactivity.element_id.clone()
 766    }
 767
 768    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 769        None
 770    }
 771
 772    fn request_layout(
 773        &mut self,
 774        global_id: Option<&GlobalElementId>,
 775        inspector_id: Option<&gpui::InspectorElementId>,
 776        window: &mut Window,
 777        cx: &mut App,
 778    ) -> (LayoutId, Self::RequestLayoutState) {
 779        let height: Length = match self.terminal_view.read(cx).content_mode(window, cx) {
 780            ContentMode::Inline {
 781                displayed_lines,
 782                total_lines: _,
 783            } => {
 784                let rem_size = window.rem_size();
 785                let line_height = window.text_style().font_size.to_pixels(rem_size)
 786                    * TerminalSettings::get_global(cx)
 787                        .line_height
 788                        .value()
 789                        .to_pixels(rem_size)
 790                        .0;
 791                (displayed_lines * line_height).into()
 792            }
 793            ContentMode::Scrollable => {
 794                if let TerminalMode::Embedded { .. } = &self.mode {
 795                    let term = self.terminal.read(cx);
 796                    if !term.scrolled_to_top() && !term.scrolled_to_bottom() && self.focused {
 797                        self.interactivity.occlude_mouse();
 798                    }
 799                }
 800
 801                relative(1.).into()
 802            }
 803        };
 804
 805        let layout_id = self.interactivity.request_layout(
 806            global_id,
 807            inspector_id,
 808            window,
 809            cx,
 810            |mut style, window, cx| {
 811                style.size.width = relative(1.).into();
 812                style.size.height = height;
 813
 814                window.request_layout(style, None, cx)
 815            },
 816        );
 817        (layout_id, ())
 818    }
 819
 820    fn prepaint(
 821        &mut self,
 822        global_id: Option<&GlobalElementId>,
 823        inspector_id: Option<&gpui::InspectorElementId>,
 824        bounds: Bounds<Pixels>,
 825        _: &mut Self::RequestLayoutState,
 826        window: &mut Window,
 827        cx: &mut App,
 828    ) -> Self::PrepaintState {
 829        let rem_size = self.rem_size(cx);
 830        self.interactivity.prepaint(
 831            global_id,
 832            inspector_id,
 833            bounds,
 834            bounds.size,
 835            window,
 836            cx,
 837            |_, _, hitbox, window, cx| {
 838                let hitbox = hitbox.unwrap();
 839                let settings = ThemeSettings::get_global(cx).clone();
 840
 841                let buffer_font_size = settings.buffer_font_size(cx);
 842
 843                let terminal_settings = TerminalSettings::get_global(cx);
 844                let minimum_contrast = terminal_settings.minimum_contrast;
 845
 846                let font_family = terminal_settings.font_family.as_ref().map_or_else(
 847                    || settings.buffer_font.family.clone(),
 848                    |font_family| font_family.0.clone().into(),
 849                );
 850
 851                let font_fallbacks = terminal_settings
 852                    .font_fallbacks
 853                    .as_ref()
 854                    .or(settings.buffer_font.fallbacks.as_ref())
 855                    .cloned();
 856
 857                let font_features = terminal_settings
 858                    .font_features
 859                    .as_ref()
 860                    .unwrap_or(&FontFeatures::disable_ligatures())
 861                    .clone();
 862
 863                let font_weight = terminal_settings.font_weight.unwrap_or_default();
 864
 865                let line_height = terminal_settings.line_height.value();
 866
 867                let font_size = match &self.mode {
 868                    TerminalMode::Embedded { .. } => {
 869                        window.text_style().font_size.to_pixels(window.rem_size())
 870                    }
 871                    TerminalMode::Standalone => terminal_settings
 872                        .font_size
 873                        .map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx)),
 874                };
 875
 876                let theme = cx.theme().clone();
 877
 878                let link_style = HighlightStyle {
 879                    color: Some(theme.colors().link_text_hover),
 880                    font_weight: Some(font_weight),
 881                    font_style: None,
 882                    background_color: None,
 883                    underline: Some(UnderlineStyle {
 884                        thickness: px(1.0),
 885                        color: Some(theme.colors().link_text_hover),
 886                        wavy: false,
 887                    }),
 888                    strikethrough: None,
 889                    fade_out: None,
 890                };
 891
 892                let text_style = TextStyle {
 893                    font_family,
 894                    font_features,
 895                    font_weight,
 896                    font_fallbacks,
 897                    font_size: font_size.into(),
 898                    font_style: FontStyle::Normal,
 899                    line_height: line_height.into(),
 900                    background_color: Some(theme.colors().terminal_ansi_background),
 901                    white_space: WhiteSpace::Normal,
 902                    // These are going to be overridden per-cell
 903                    color: theme.colors().terminal_foreground,
 904                    ..Default::default()
 905                };
 906
 907                let text_system = cx.text_system();
 908                let player_color = theme.players().local();
 909                let match_color = theme.colors().search_match_background;
 910                let gutter;
 911                let (dimensions, line_height_px) = {
 912                    let rem_size = window.rem_size();
 913                    let font_pixels = text_style.font_size.to_pixels(rem_size);
 914                    // TODO: line_height should be an f32 not an AbsoluteLength.
 915                    let line_height = font_pixels * line_height.to_pixels(rem_size).0;
 916                    let font_id = cx.text_system().resolve_font(&text_style.font());
 917
 918                    let cell_width = text_system
 919                        .advance(font_id, font_pixels, 'm')
 920                        .unwrap()
 921                        .width;
 922                    gutter = cell_width;
 923
 924                    let mut size = bounds.size;
 925                    size.width -= gutter;
 926
 927                    // https://github.com/zed-industries/zed/issues/2750
 928                    // if the terminal is one column wide, rendering 🦀
 929                    // causes alacritty to misbehave.
 930                    if size.width < cell_width * 2.0 {
 931                        size.width = cell_width * 2.0;
 932                    }
 933
 934                    let mut origin = bounds.origin;
 935                    origin.x += gutter;
 936
 937                    (
 938                        TerminalBounds::new(line_height, cell_width, Bounds { origin, size }),
 939                        line_height,
 940                    )
 941                };
 942
 943                let search_matches = self.terminal.read(cx).matches.clone();
 944
 945                let background_color = theme.colors().terminal_background;
 946
 947                let (last_hovered_word, hover_tooltip) =
 948                    self.terminal.update(cx, |terminal, cx| {
 949                        terminal.set_size(dimensions);
 950                        terminal.sync(window, cx);
 951
 952                        if window.modifiers().secondary()
 953                            && bounds.contains(&window.mouse_position())
 954                            && self.terminal_view.read(cx).hover.is_some()
 955                        {
 956                            let registered_hover = self.terminal_view.read(cx).hover.as_ref();
 957                            if terminal.last_content.last_hovered_word.as_ref()
 958                                == registered_hover.map(|hover| &hover.hovered_word)
 959                            {
 960                                (
 961                                    terminal.last_content.last_hovered_word.clone(),
 962                                    registered_hover.map(|hover| hover.tooltip.clone()),
 963                                )
 964                            } else {
 965                                (None, None)
 966                            }
 967                        } else {
 968                            (None, None)
 969                        }
 970                    });
 971
 972                let scroll_top = self.terminal_view.read(cx).scroll_top;
 973                let hyperlink_tooltip = hover_tooltip.map(|hover_tooltip| {
 974                    let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
 975                    let mut element = div()
 976                        .size_full()
 977                        .id("terminal-element")
 978                        .tooltip(Tooltip::text(hover_tooltip))
 979                        .into_any_element();
 980                    element.prepaint_as_root(offset, bounds.size.into(), window, cx);
 981                    element
 982                });
 983
 984                let TerminalContent {
 985                    cells,
 986                    mode,
 987                    display_offset,
 988                    cursor_char,
 989                    selection,
 990                    cursor,
 991                    ..
 992                } = &self.terminal.read(cx).last_content;
 993                let mode = *mode;
 994                let display_offset = *display_offset;
 995
 996                // searches, highlights to a single range representations
 997                let mut relative_highlighted_ranges = Vec::new();
 998                for search_match in search_matches {
 999                    relative_highlighted_ranges.push((search_match, match_color))
1000                }
1001                if let Some(selection) = selection {
1002                    relative_highlighted_ranges
1003                        .push((selection.start..=selection.end, player_color.selection));
1004                }
1005
1006                // then have that representation be converted to the appropriate highlight data structure
1007
1008                let content_mode = self.terminal_view.read(cx).content_mode(window, cx);
1009                let (rects, batched_text_runs) = match content_mode {
1010                    ContentMode::Scrollable => {
1011                        // In scrollable mode, the terminal already provides cells
1012                        // that are correctly positioned for the current viewport
1013                        // based on its display_offset. We don't need additional filtering.
1014                        TerminalElement::layout_grid(
1015                            cells.iter().cloned(),
1016                            0,
1017                            &text_style,
1018                            last_hovered_word.as_ref().map(|last_hovered_word| {
1019                                (link_style, &last_hovered_word.word_match)
1020                            }),
1021                            minimum_contrast,
1022                            cx,
1023                        )
1024                    }
1025                    ContentMode::Inline { .. } => {
1026                        let intersection = window.content_mask().bounds.intersect(&bounds);
1027                        let start_row = (intersection.top() - bounds.top()) / line_height_px;
1028                        let end_row = start_row + intersection.size.height / line_height_px;
1029                        let line_range = (start_row as i32)..=(end_row as i32);
1030
1031                        TerminalElement::layout_grid(
1032                            cells
1033                                .iter()
1034                                .skip_while(|i| &i.point.line < line_range.start())
1035                                .take_while(|i| &i.point.line <= line_range.end())
1036                                .cloned(),
1037                            *line_range.start(),
1038                            &text_style,
1039                            last_hovered_word.as_ref().map(|last_hovered_word| {
1040                                (link_style, &last_hovered_word.word_match)
1041                            }),
1042                            minimum_contrast,
1043                            cx,
1044                        )
1045                    }
1046                };
1047
1048                // Layout cursor. Rectangle is used for IME, so we should lay it out even
1049                // if we don't end up showing it.
1050                let cursor = if let AlacCursorShape::Hidden = cursor.shape {
1051                    None
1052                } else {
1053                    let cursor_point = DisplayCursor::from(cursor.point, display_offset);
1054                    let cursor_text = {
1055                        let str_trxt = cursor_char.to_string();
1056                        let len = str_trxt.len();
1057                        window.text_system().shape_line(
1058                            str_trxt.into(),
1059                            text_style.font_size.to_pixels(window.rem_size()),
1060                            &[TextRun {
1061                                len,
1062                                font: text_style.font(),
1063                                color: theme.colors().terminal_ansi_background,
1064                                background_color: None,
1065                                underline: Default::default(),
1066                                strikethrough: None,
1067                            }],
1068                            None,
1069                        )
1070                    };
1071
1072                    let focused = self.focused;
1073                    TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
1074                        move |(cursor_position, block_width)| {
1075                            let (shape, text) = match cursor.shape {
1076                                AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
1077                                AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
1078                                AlacCursorShape::Underline => (CursorShape::Underline, None),
1079                                AlacCursorShape::Beam => (CursorShape::Bar, None),
1080                                AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
1081                                //This case is handled in the if wrapping the whole cursor layout
1082                                AlacCursorShape::Hidden => unreachable!(),
1083                            };
1084
1085                            CursorLayout::new(
1086                                cursor_position,
1087                                block_width,
1088                                dimensions.line_height,
1089                                theme.players().local().cursor,
1090                                shape,
1091                                text,
1092                            )
1093                        },
1094                    )
1095                };
1096
1097                let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
1098                    let terminal = self.terminal.read(cx);
1099                    if terminal.last_content.display_offset == 0 {
1100                        let target_line = terminal.last_content.cursor.point.line.0 + 1;
1101                        let render = &block.render;
1102                        let mut block_cx = BlockContext {
1103                            window,
1104                            context: cx,
1105                            dimensions,
1106                        };
1107                        let element = render(&mut block_cx);
1108                        let mut element = div().occlude().child(element).into_any_element();
1109                        let available_space = size(
1110                            AvailableSpace::Definite(dimensions.width() + gutter),
1111                            AvailableSpace::Definite(
1112                                block.height as f32 * dimensions.line_height(),
1113                            ),
1114                        );
1115                        let origin = bounds.origin
1116                            + point(px(0.), target_line as f32 * dimensions.line_height())
1117                            - point(px(0.), scroll_top);
1118                        window.with_rem_size(rem_size, |window| {
1119                            element.prepaint_as_root(origin, available_space, window, cx);
1120                        });
1121                        Some(element)
1122                    } else {
1123                        None
1124                    }
1125                } else {
1126                    None
1127                };
1128
1129                LayoutState {
1130                    hitbox,
1131                    batched_text_runs,
1132                    cursor,
1133                    background_color,
1134                    dimensions,
1135                    rects,
1136                    relative_highlighted_ranges,
1137                    mode,
1138                    display_offset,
1139                    hyperlink_tooltip,
1140                    gutter,
1141                    block_below_cursor_element,
1142                    base_text_style: text_style,
1143                    content_mode,
1144                }
1145            },
1146        )
1147    }
1148
1149    fn paint(
1150        &mut self,
1151        global_id: Option<&GlobalElementId>,
1152        inspector_id: Option<&gpui::InspectorElementId>,
1153        bounds: Bounds<Pixels>,
1154        _: &mut Self::RequestLayoutState,
1155        layout: &mut Self::PrepaintState,
1156        window: &mut Window,
1157        cx: &mut App,
1158    ) {
1159        let paint_start = Instant::now();
1160        window.with_content_mask(Some(ContentMask { bounds }), |window| {
1161            let scroll_top = self.terminal_view.read(cx).scroll_top;
1162
1163            window.paint_quad(fill(bounds, layout.background_color));
1164            let origin =
1165                bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
1166
1167            let marked_text_cloned: Option<String> = {
1168                let ime_state = self.terminal_view.read(cx);
1169                ime_state.marked_text.clone()
1170            };
1171
1172            let terminal_input_handler = TerminalInputHandler {
1173                terminal: self.terminal.clone(),
1174                terminal_view: self.terminal_view.clone(),
1175                cursor_bounds: layout
1176                    .cursor
1177                    .as_ref()
1178                    .map(|cursor| cursor.bounding_rect(origin)),
1179                workspace: self.workspace.clone(),
1180            };
1181
1182            self.register_mouse_listeners(
1183                layout.mode,
1184                &layout.hitbox,
1185                &layout.content_mode,
1186                window,
1187            );
1188            if window.modifiers().secondary()
1189                && bounds.contains(&window.mouse_position())
1190                && self.terminal_view.read(cx).hover.is_some()
1191            {
1192                window.set_cursor_style(gpui::CursorStyle::PointingHand, &layout.hitbox);
1193            } else {
1194                window.set_cursor_style(gpui::CursorStyle::IBeam, &layout.hitbox);
1195            }
1196
1197            let original_cursor = layout.cursor.take();
1198            let hyperlink_tooltip = layout.hyperlink_tooltip.take();
1199            let block_below_cursor_element = layout.block_below_cursor_element.take();
1200            self.interactivity.paint(
1201                global_id,
1202                inspector_id,
1203                bounds,
1204                Some(&layout.hitbox),
1205                window,
1206                cx,
1207                |_, window, cx| {
1208                    window.handle_input(&self.focus, terminal_input_handler, cx);
1209
1210                    window.on_key_event({
1211                        let this = self.terminal.clone();
1212                        move |event: &ModifiersChangedEvent, phase, window, cx| {
1213                            if phase != DispatchPhase::Bubble {
1214                                return;
1215                            }
1216
1217                            this.update(cx, |term, cx| {
1218                                term.try_modifiers_change(&event.modifiers, window, cx)
1219                            });
1220                        }
1221                    });
1222
1223                    for rect in &layout.rects {
1224                        rect.paint(origin, &layout.dimensions, window);
1225                    }
1226
1227                    for (relative_highlighted_range, color) in
1228                        layout.relative_highlighted_ranges.iter()
1229                    {
1230                        if let Some((start_y, highlighted_range_lines)) =
1231                            to_highlighted_range_lines(relative_highlighted_range, layout, origin)
1232                        {
1233                            let hr = HighlightedRange {
1234                                start_y,
1235                                line_height: layout.dimensions.line_height,
1236                                lines: highlighted_range_lines,
1237                                color: *color,
1238                                corner_radius: 0.15 * layout.dimensions.line_height,
1239                            };
1240                            hr.paint(true, bounds, window);
1241                        }
1242                    }
1243
1244                    // Paint batched text runs instead of individual cells
1245                    let text_paint_start = Instant::now();
1246                    for batch in &layout.batched_text_runs {
1247                        batch.paint(origin, &layout.dimensions, window, cx);
1248                    }
1249                    let text_paint_time = text_paint_start.elapsed();
1250
1251                    if let Some(text_to_mark) = &marked_text_cloned {
1252                        if !text_to_mark.is_empty() {
1253                            if let Some(cursor_layout) = &original_cursor {
1254                                let ime_position = cursor_layout.bounding_rect(origin).origin;
1255                                let mut ime_style = layout.base_text_style.clone();
1256                                ime_style.underline = Some(UnderlineStyle {
1257                                    color: Some(ime_style.color),
1258                                    thickness: px(1.0),
1259                                    wavy: false,
1260                                });
1261
1262                                let shaped_line = window.text_system().shape_line(
1263                                    text_to_mark.clone().into(),
1264                                    ime_style.font_size.to_pixels(window.rem_size()),
1265                                    &[TextRun {
1266                                        len: text_to_mark.len(),
1267                                        font: ime_style.font(),
1268                                        color: ime_style.color,
1269                                        background_color: None,
1270                                        underline: ime_style.underline,
1271                                        strikethrough: None,
1272                                    }],
1273                                    None
1274                                );
1275                                shaped_line
1276                                    .paint(ime_position, layout.dimensions.line_height, window, cx)
1277                                    .log_err();
1278                            }
1279                        }
1280                    }
1281
1282                    if self.cursor_visible && marked_text_cloned.is_none() {
1283                        if let Some(mut cursor) = original_cursor {
1284                            cursor.paint(origin, window, cx);
1285                        }
1286                    }
1287
1288                    if let Some(mut element) = block_below_cursor_element {
1289                        element.paint(window, cx);
1290                    }
1291
1292                    if let Some(mut element) = hyperlink_tooltip {
1293                        element.paint(window, cx);
1294                    }
1295                    let total_paint_time = paint_start.elapsed();
1296                    log::debug!(
1297                        "Terminal paint: {} text runs, {} rects, text paint took {:?}, total paint took {:?}",
1298                        layout.batched_text_runs.len(),
1299                        layout.rects.len(),
1300                        text_paint_time,
1301                        total_paint_time
1302                    );
1303                },
1304            );
1305        });
1306    }
1307}
1308
1309impl IntoElement for TerminalElement {
1310    type Element = Self;
1311
1312    fn into_element(self) -> Self::Element {
1313        self
1314    }
1315}
1316
1317struct TerminalInputHandler {
1318    terminal: Entity<Terminal>,
1319    terminal_view: Entity<TerminalView>,
1320    workspace: WeakEntity<Workspace>,
1321    cursor_bounds: Option<Bounds<Pixels>>,
1322}
1323
1324impl InputHandler for TerminalInputHandler {
1325    fn selected_text_range(
1326        &mut self,
1327        _ignore_disabled_input: bool,
1328        _: &mut Window,
1329        cx: &mut App,
1330    ) -> Option<UTF16Selection> {
1331        if self
1332            .terminal
1333            .read(cx)
1334            .last_content
1335            .mode
1336            .contains(TermMode::ALT_SCREEN)
1337        {
1338            None
1339        } else {
1340            Some(UTF16Selection {
1341                range: 0..0,
1342                reversed: false,
1343            })
1344        }
1345    }
1346
1347    fn marked_text_range(
1348        &mut self,
1349        _window: &mut Window,
1350        cx: &mut App,
1351    ) -> Option<std::ops::Range<usize>> {
1352        self.terminal_view.read(cx).marked_text_range()
1353    }
1354
1355    fn text_for_range(
1356        &mut self,
1357        _: std::ops::Range<usize>,
1358        _: &mut Option<std::ops::Range<usize>>,
1359        _: &mut Window,
1360        _: &mut App,
1361    ) -> Option<String> {
1362        None
1363    }
1364
1365    fn replace_text_in_range(
1366        &mut self,
1367        _replacement_range: Option<std::ops::Range<usize>>,
1368        text: &str,
1369        window: &mut Window,
1370        cx: &mut App,
1371    ) {
1372        self.terminal_view.update(cx, |view, view_cx| {
1373            view.clear_marked_text(view_cx);
1374            view.commit_text(text, view_cx);
1375        });
1376
1377        self.workspace
1378            .update(cx, |this, cx| {
1379                window.invalidate_character_coordinates();
1380                let project = this.project().read(cx);
1381                let telemetry = project.client().telemetry().clone();
1382                telemetry.log_edit_event("terminal", project.is_via_ssh());
1383            })
1384            .ok();
1385    }
1386
1387    fn replace_and_mark_text_in_range(
1388        &mut self,
1389        _range_utf16: Option<std::ops::Range<usize>>,
1390        new_text: &str,
1391        new_marked_range: Option<std::ops::Range<usize>>,
1392        _window: &mut Window,
1393        cx: &mut App,
1394    ) {
1395        if let Some(range) = new_marked_range {
1396            self.terminal_view.update(cx, |view, view_cx| {
1397                view.set_marked_text(new_text.to_string(), range, view_cx);
1398            });
1399        }
1400    }
1401
1402    fn unmark_text(&mut self, _window: &mut Window, cx: &mut App) {
1403        self.terminal_view.update(cx, |view, view_cx| {
1404            view.clear_marked_text(view_cx);
1405        });
1406    }
1407
1408    fn bounds_for_range(
1409        &mut self,
1410        range_utf16: std::ops::Range<usize>,
1411        _window: &mut Window,
1412        cx: &mut App,
1413    ) -> Option<Bounds<Pixels>> {
1414        let term_bounds = self.terminal_view.read(cx).terminal_bounds(cx);
1415
1416        let mut bounds = self.cursor_bounds?;
1417        let offset_x = term_bounds.cell_width * range_utf16.start as f32;
1418        bounds.origin.x += offset_x;
1419
1420        Some(bounds)
1421    }
1422
1423    fn apple_press_and_hold_enabled(&mut self) -> bool {
1424        false
1425    }
1426
1427    fn character_index_for_point(
1428        &mut self,
1429        _point: Point<Pixels>,
1430        _window: &mut Window,
1431        _cx: &mut App,
1432    ) -> Option<usize> {
1433        None
1434    }
1435}
1436
1437pub fn is_blank(cell: &IndexedCell) -> bool {
1438    if cell.c != ' ' {
1439        return false;
1440    }
1441
1442    if cell.bg != AnsiColor::Named(NamedColor::Background) {
1443        return false;
1444    }
1445
1446    if cell.hyperlink().is_some() {
1447        return false;
1448    }
1449
1450    if cell
1451        .flags
1452        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1453    {
1454        return false;
1455    }
1456
1457    return true;
1458}
1459
1460fn to_highlighted_range_lines(
1461    range: &RangeInclusive<AlacPoint>,
1462    layout: &LayoutState,
1463    origin: Point<Pixels>,
1464) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1465    // Step 1. Normalize the points to be viewport relative.
1466    // When display_offset = 1, here's how the grid is arranged:
1467    //-2,0 -2,1...
1468    //--- Viewport top
1469    //-1,0 -1,1...
1470    //--------- Terminal Top
1471    // 0,0  0,1...
1472    // 1,0  1,1...
1473    //--- Viewport Bottom
1474    // 2,0  2,1...
1475    //--------- Terminal Bottom
1476
1477    // Normalize to viewport relative, from terminal relative.
1478    // lines are i32s, which are negative above the top left corner of the terminal
1479    // If the user has scrolled, we use the display_offset to tell us which offset
1480    // of the grid data we should be looking at. But for the rendering step, we don't
1481    // want negatives. We want things relative to the 'viewport' (the area of the grid
1482    // which is currently shown according to the display offset)
1483    let unclamped_start = AlacPoint::new(
1484        range.start().line + layout.display_offset,
1485        range.start().column,
1486    );
1487    let unclamped_end =
1488        AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1489
1490    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1491    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1492        return None;
1493    }
1494
1495    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1496    let clamped_end_line = unclamped_end
1497        .line
1498        .0
1499        .min(layout.dimensions.num_lines() as i32) as usize;
1500    //Convert the start of the range to pixels
1501    let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1502
1503    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1504    //  (also convert to pixels)
1505    let mut highlighted_range_lines = Vec::new();
1506    for line in clamped_start_line..=clamped_end_line {
1507        let mut line_start = 0;
1508        let mut line_end = layout.dimensions.columns();
1509
1510        if line == clamped_start_line {
1511            line_start = unclamped_start.column.0;
1512        }
1513        if line == clamped_end_line {
1514            line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1515        }
1516
1517        highlighted_range_lines.push(HighlightedRangeLine {
1518            start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1519            end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1520        });
1521    }
1522
1523    Some((start_y, highlighted_range_lines))
1524}
1525
1526/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1527pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1528    let colors = theme.colors();
1529    match fg {
1530        // Named and theme defined colors
1531        terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1532            NamedColor::Black => colors.terminal_ansi_black,
1533            NamedColor::Red => colors.terminal_ansi_red,
1534            NamedColor::Green => colors.terminal_ansi_green,
1535            NamedColor::Yellow => colors.terminal_ansi_yellow,
1536            NamedColor::Blue => colors.terminal_ansi_blue,
1537            NamedColor::Magenta => colors.terminal_ansi_magenta,
1538            NamedColor::Cyan => colors.terminal_ansi_cyan,
1539            NamedColor::White => colors.terminal_ansi_white,
1540            NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1541            NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1542            NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1543            NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1544            NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1545            NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1546            NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1547            NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1548            NamedColor::Foreground => colors.terminal_foreground,
1549            NamedColor::Background => colors.terminal_ansi_background,
1550            NamedColor::Cursor => theme.players().local().cursor,
1551            NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1552            NamedColor::DimRed => colors.terminal_ansi_dim_red,
1553            NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1554            NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1555            NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1556            NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1557            NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1558            NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1559            NamedColor::BrightForeground => colors.terminal_bright_foreground,
1560            NamedColor::DimForeground => colors.terminal_dim_foreground,
1561        },
1562        // 'True' colors
1563        terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1564            terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1565        }
1566        // 8 bit, indexed colors
1567        terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1568            terminal::get_color_at_index(*i as usize, theme)
1569        }
1570    }
1571}
1572
1573#[cfg(test)]
1574mod tests {
1575    use super::*;
1576    use gpui::{AbsoluteLength, Hsla, font};
1577
1578    #[test]
1579    fn test_contrast_adjustment_logic() {
1580        // Test the core contrast adjustment logic without needing full app context
1581
1582        // Test case 1: Light colors (poor contrast)
1583        let white_fg = gpui::Hsla {
1584            h: 0.0,
1585            s: 0.0,
1586            l: 1.0,
1587            a: 1.0,
1588        };
1589        let light_gray_bg = gpui::Hsla {
1590            h: 0.0,
1591            s: 0.0,
1592            l: 0.95,
1593            a: 1.0,
1594        };
1595
1596        // Should have poor contrast
1597        let actual_contrast = color_contrast::apca_contrast(white_fg, light_gray_bg).abs();
1598        assert!(
1599            actual_contrast < 30.0,
1600            "White on light gray should have poor APCA contrast: {}",
1601            actual_contrast
1602        );
1603
1604        // After adjustment with minimum APCA contrast of 45, should be darker
1605        let adjusted = color_contrast::ensure_minimum_contrast(white_fg, light_gray_bg, 45.0);
1606        assert!(
1607            adjusted.l < white_fg.l,
1608            "Adjusted color should be darker than original"
1609        );
1610        let adjusted_contrast = color_contrast::apca_contrast(adjusted, light_gray_bg).abs();
1611        assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1612
1613        // Test case 2: Dark colors (poor contrast)
1614        let black_fg = gpui::Hsla {
1615            h: 0.0,
1616            s: 0.0,
1617            l: 0.0,
1618            a: 1.0,
1619        };
1620        let dark_gray_bg = gpui::Hsla {
1621            h: 0.0,
1622            s: 0.0,
1623            l: 0.05,
1624            a: 1.0,
1625        };
1626
1627        // Should have poor contrast
1628        let actual_contrast = color_contrast::apca_contrast(black_fg, dark_gray_bg).abs();
1629        assert!(
1630            actual_contrast < 30.0,
1631            "Black on dark gray should have poor APCA contrast: {}",
1632            actual_contrast
1633        );
1634
1635        // After adjustment with minimum APCA contrast of 45, should be lighter
1636        let adjusted = color_contrast::ensure_minimum_contrast(black_fg, dark_gray_bg, 45.0);
1637        assert!(
1638            adjusted.l > black_fg.l,
1639            "Adjusted color should be lighter than original"
1640        );
1641        let adjusted_contrast = color_contrast::apca_contrast(adjusted, dark_gray_bg).abs();
1642        assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1643
1644        // Test case 3: Already good contrast
1645        let good_contrast = color_contrast::ensure_minimum_contrast(black_fg, white_fg, 45.0);
1646        assert_eq!(
1647            good_contrast, black_fg,
1648            "Good contrast should not be adjusted"
1649        );
1650    }
1651
1652    #[test]
1653    fn test_white_on_white_contrast_issue() {
1654        // This test reproduces the exact issue from the bug report
1655        // where white ANSI text on white background should be adjusted
1656
1657        // Simulate One Light theme colors
1658        let white_fg = gpui::Hsla {
1659            h: 0.0,
1660            s: 0.0,
1661            l: 0.98, // #fafafaff is approximately 98% lightness
1662            a: 1.0,
1663        };
1664        let white_bg = gpui::Hsla {
1665            h: 0.0,
1666            s: 0.0,
1667            l: 0.98, // Same as foreground - this is the problem!
1668            a: 1.0,
1669        };
1670
1671        // With minimum contrast of 0.0, no adjustment should happen
1672        let no_adjust = color_contrast::ensure_minimum_contrast(white_fg, white_bg, 0.0);
1673        assert_eq!(no_adjust, white_fg, "No adjustment with min_contrast 0.0");
1674
1675        // With minimum APCA contrast of 15, it should adjust to a darker color
1676        let adjusted = color_contrast::ensure_minimum_contrast(white_fg, white_bg, 15.0);
1677        assert!(
1678            adjusted.l < white_fg.l,
1679            "White on white should become darker, got l={}",
1680            adjusted.l
1681        );
1682
1683        // Verify the contrast is now acceptable
1684        let new_contrast = color_contrast::apca_contrast(adjusted, white_bg).abs();
1685        assert!(
1686            new_contrast >= 15.0,
1687            "Adjusted APCA contrast {} should be >= 15.0",
1688            new_contrast
1689        );
1690    }
1691
1692    #[test]
1693    fn test_batched_text_run_can_append() {
1694        let style1 = TextRun {
1695            len: 1,
1696            font: font("Helvetica"),
1697            color: Hsla::red(),
1698            background_color: None,
1699            underline: None,
1700            strikethrough: None,
1701        };
1702
1703        let style2 = TextRun {
1704            len: 1,
1705            font: font("Helvetica"),
1706            color: Hsla::red(),
1707            background_color: None,
1708            underline: None,
1709            strikethrough: None,
1710        };
1711
1712        let style3 = TextRun {
1713            len: 1,
1714            font: font("Helvetica"),
1715            color: Hsla::blue(), // Different color
1716            background_color: None,
1717            underline: None,
1718            strikethrough: None,
1719        };
1720
1721        let font_size = AbsoluteLength::Pixels(px(12.0));
1722        let batch =
1723            BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style1.clone(), font_size);
1724
1725        // Should be able to append same style
1726        assert!(batch.can_append(&style2));
1727
1728        // Should not be able to append different style
1729        assert!(!batch.can_append(&style3));
1730    }
1731
1732    #[test]
1733    fn test_batched_text_run_append() {
1734        let style = TextRun {
1735            len: 1,
1736            font: font("Helvetica"),
1737            color: Hsla::red(),
1738            background_color: None,
1739            underline: None,
1740            strikethrough: None,
1741        };
1742
1743        let font_size = AbsoluteLength::Pixels(px(12.0));
1744        let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'a', style, font_size);
1745
1746        assert_eq!(batch.text, "a");
1747        assert_eq!(batch.cell_count, 1);
1748        assert_eq!(batch.style.len, 1);
1749
1750        batch.append_char('b');
1751
1752        assert_eq!(batch.text, "ab");
1753        assert_eq!(batch.cell_count, 2);
1754        assert_eq!(batch.style.len, 2);
1755
1756        batch.append_char('c');
1757
1758        assert_eq!(batch.text, "abc");
1759        assert_eq!(batch.cell_count, 3);
1760        assert_eq!(batch.style.len, 3);
1761    }
1762
1763    #[test]
1764    fn test_batched_text_run_append_char() {
1765        let style = TextRun {
1766            len: 1,
1767            font: font("Helvetica"),
1768            color: Hsla::red(),
1769            background_color: None,
1770            underline: None,
1771            strikethrough: None,
1772        };
1773
1774        let font_size = AbsoluteLength::Pixels(px(12.0));
1775        let mut batch = BatchedTextRun::new_from_char(AlacPoint::new(0, 0), 'x', style, font_size);
1776
1777        assert_eq!(batch.text, "x");
1778        assert_eq!(batch.cell_count, 1);
1779        assert_eq!(batch.style.len, 1);
1780
1781        batch.append_char('y');
1782
1783        assert_eq!(batch.text, "xy");
1784        assert_eq!(batch.cell_count, 2);
1785        assert_eq!(batch.style.len, 2);
1786
1787        // Test with multi-byte character
1788        batch.append_char('😀');
1789
1790        assert_eq!(batch.text, "xy😀");
1791        assert_eq!(batch.cell_count, 3);
1792        assert_eq!(batch.style.len, 6); // 1 + 1 + 4 bytes for emoji
1793    }
1794
1795    #[test]
1796    fn test_background_region_can_merge() {
1797        let color1 = Hsla::red();
1798        let color2 = Hsla::blue();
1799
1800        // Test horizontal merging
1801        let mut region1 = BackgroundRegion::new(0, 0, color1);
1802        region1.end_col = 5;
1803        let region2 = BackgroundRegion::new(0, 6, color1);
1804        assert!(region1.can_merge_with(&region2));
1805
1806        // Test vertical merging with same column span
1807        let mut region3 = BackgroundRegion::new(0, 0, color1);
1808        region3.end_col = 5;
1809        let mut region4 = BackgroundRegion::new(1, 0, color1);
1810        region4.end_col = 5;
1811        assert!(region3.can_merge_with(&region4));
1812
1813        // Test cannot merge different colors
1814        let region5 = BackgroundRegion::new(0, 0, color1);
1815        let region6 = BackgroundRegion::new(0, 1, color2);
1816        assert!(!region5.can_merge_with(&region6));
1817
1818        // Test cannot merge non-adjacent regions
1819        let region7 = BackgroundRegion::new(0, 0, color1);
1820        let region8 = BackgroundRegion::new(0, 2, color1);
1821        assert!(!region7.can_merge_with(&region8));
1822
1823        // Test cannot merge vertical regions with different column spans
1824        let mut region9 = BackgroundRegion::new(0, 0, color1);
1825        region9.end_col = 5;
1826        let mut region10 = BackgroundRegion::new(1, 0, color1);
1827        region10.end_col = 6;
1828        assert!(!region9.can_merge_with(&region10));
1829    }
1830
1831    #[test]
1832    fn test_background_region_merge() {
1833        let color = Hsla::red();
1834
1835        // Test horizontal merge
1836        let mut region1 = BackgroundRegion::new(0, 0, color);
1837        region1.end_col = 5;
1838        let mut region2 = BackgroundRegion::new(0, 6, color);
1839        region2.end_col = 10;
1840        region1.merge_with(&region2);
1841        assert_eq!(region1.start_col, 0);
1842        assert_eq!(region1.end_col, 10);
1843        assert_eq!(region1.start_line, 0);
1844        assert_eq!(region1.end_line, 0);
1845
1846        // Test vertical merge
1847        let mut region3 = BackgroundRegion::new(0, 0, color);
1848        region3.end_col = 5;
1849        let mut region4 = BackgroundRegion::new(1, 0, color);
1850        region4.end_col = 5;
1851        region3.merge_with(&region4);
1852        assert_eq!(region3.start_col, 0);
1853        assert_eq!(region3.end_col, 5);
1854        assert_eq!(region3.start_line, 0);
1855        assert_eq!(region3.end_line, 1);
1856    }
1857
1858    #[test]
1859    fn test_merge_background_regions() {
1860        let color = Hsla::red();
1861
1862        // Test merging multiple adjacent regions
1863        let regions = vec![
1864            BackgroundRegion::new(0, 0, color),
1865            BackgroundRegion::new(0, 1, color),
1866            BackgroundRegion::new(0, 2, color),
1867            BackgroundRegion::new(1, 0, color),
1868            BackgroundRegion::new(1, 1, color),
1869            BackgroundRegion::new(1, 2, color),
1870        ];
1871
1872        let merged = merge_background_regions(regions);
1873        assert_eq!(merged.len(), 1);
1874        assert_eq!(merged[0].start_line, 0);
1875        assert_eq!(merged[0].end_line, 1);
1876        assert_eq!(merged[0].start_col, 0);
1877        assert_eq!(merged[0].end_col, 2);
1878
1879        // Test with non-mergeable regions
1880        let color2 = Hsla::blue();
1881        let regions2 = vec![
1882            BackgroundRegion::new(0, 0, color),
1883            BackgroundRegion::new(0, 2, color),  // Gap at column 1
1884            BackgroundRegion::new(1, 0, color2), // Different color
1885        ];
1886
1887        let merged2 = merge_background_regions(regions2);
1888        assert_eq!(merged2.len(), 3);
1889    }
1890}