terminal_element.rs

   1use crate::color_contrast;
   2use editor::{CursorLayout, HighlightedRange, HighlightedRangeLine};
   3use gpui::{
   4    AnyElement, App, AvailableSpace, Bounds, ContentMask, Context, DispatchPhase, Element,
   5    ElementId, Entity, FocusHandle, Font, FontStyle, FontWeight, GlobalElementId, HighlightStyle,
   6    Hitbox, Hsla, InputHandler, InteractiveElement, Interactivity, IntoElement, LayoutId, Length,
   7    ModifiersChangedEvent, MouseButton, MouseMoveEvent, Pixels, Point, ShapedLine,
   8    StatefulInteractiveElement, StrikethroughStyle, Styled, TextRun, TextStyle, UTF16Selection,
   9    UnderlineStyle, WeakEntity, WhiteSpace, Window, WindowTextSystem, div, fill, point, px,
  10    relative, size,
  11};
  12use itertools::Itertools;
  13use language::CursorShape;
  14use settings::Settings;
  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::{ParentElement, Tooltip};
  30use util::ResultExt;
  31use workspace::Workspace;
  32
  33use std::mem;
  34use std::{fmt::Debug, ops::RangeInclusive, rc::Rc};
  35
  36use crate::{BlockContext, BlockProperties, ContentMode, TerminalMode, TerminalView};
  37
  38/// The information generated during layout that is necessary for painting.
  39pub struct LayoutState {
  40    hitbox: Hitbox,
  41    cells: Vec<LayoutCell>,
  42    rects: Vec<LayoutRect>,
  43    relative_highlighted_ranges: Vec<(RangeInclusive<AlacPoint>, Hsla)>,
  44    cursor: Option<CursorLayout>,
  45    background_color: Hsla,
  46    dimensions: TerminalBounds,
  47    mode: TermMode,
  48    display_offset: usize,
  49    hyperlink_tooltip: Option<AnyElement>,
  50    gutter: Pixels,
  51    block_below_cursor_element: Option<AnyElement>,
  52    base_text_style: TextStyle,
  53    content_mode: ContentMode,
  54}
  55
  56/// Helper struct for converting data between Alacritty's cursor points, and displayed cursor points.
  57struct DisplayCursor {
  58    line: i32,
  59    col: usize,
  60}
  61
  62impl DisplayCursor {
  63    fn from(cursor_point: AlacPoint, display_offset: usize) -> Self {
  64        Self {
  65            line: cursor_point.line.0 + display_offset as i32,
  66            col: cursor_point.column.0,
  67        }
  68    }
  69
  70    pub fn line(&self) -> i32 {
  71        self.line
  72    }
  73
  74    pub fn col(&self) -> usize {
  75        self.col
  76    }
  77}
  78
  79#[derive(Debug, Default)]
  80pub struct LayoutCell {
  81    pub point: AlacPoint<i32, i32>,
  82    text: gpui::ShapedLine,
  83}
  84
  85impl LayoutCell {
  86    fn new(point: AlacPoint<i32, i32>, text: gpui::ShapedLine) -> LayoutCell {
  87        LayoutCell { point, text }
  88    }
  89
  90    pub fn paint(
  91        &self,
  92        origin: Point<Pixels>,
  93        dimensions: &TerminalBounds,
  94        _visible_bounds: Bounds<Pixels>,
  95        window: &mut Window,
  96        cx: &mut App,
  97    ) {
  98        let pos = {
  99            let point = self.point;
 100
 101            Point::new(
 102                (origin.x + point.column as f32 * dimensions.cell_width).floor(),
 103                origin.y + point.line as f32 * dimensions.line_height,
 104            )
 105        };
 106
 107        self.text
 108            .paint(pos, dimensions.line_height, window, cx)
 109            .ok();
 110    }
 111}
 112
 113#[derive(Clone, Debug, Default)]
 114pub struct LayoutRect {
 115    point: AlacPoint<i32, i32>,
 116    num_of_cells: usize,
 117    color: Hsla,
 118}
 119
 120impl LayoutRect {
 121    fn new(point: AlacPoint<i32, i32>, num_of_cells: usize, color: Hsla) -> LayoutRect {
 122        LayoutRect {
 123            point,
 124            num_of_cells,
 125            color,
 126        }
 127    }
 128
 129    fn extend(&self) -> Self {
 130        LayoutRect {
 131            point: self.point,
 132            num_of_cells: self.num_of_cells + 1,
 133            color: self.color,
 134        }
 135    }
 136
 137    pub fn paint(&self, origin: Point<Pixels>, dimensions: &TerminalBounds, window: &mut Window) {
 138        let position = {
 139            let alac_point = self.point;
 140            point(
 141                (origin.x + alac_point.column as f32 * dimensions.cell_width).floor(),
 142                origin.y + alac_point.line as f32 * dimensions.line_height,
 143            )
 144        };
 145        let size = point(
 146            (dimensions.cell_width * self.num_of_cells as f32).ceil(),
 147            dimensions.line_height,
 148        )
 149        .into();
 150
 151        window.paint_quad(fill(Bounds::new(position, size), self.color));
 152    }
 153}
 154
 155/// The GPUI element that paints the terminal.
 156/// 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?
 157pub struct TerminalElement {
 158    terminal: Entity<Terminal>,
 159    terminal_view: Entity<TerminalView>,
 160    workspace: WeakEntity<Workspace>,
 161    focus: FocusHandle,
 162    focused: bool,
 163    cursor_visible: bool,
 164    interactivity: Interactivity,
 165    mode: TerminalMode,
 166    block_below_cursor: Option<Rc<BlockProperties>>,
 167}
 168
 169impl InteractiveElement for TerminalElement {
 170    fn interactivity(&mut self) -> &mut Interactivity {
 171        &mut self.interactivity
 172    }
 173}
 174
 175impl StatefulInteractiveElement for TerminalElement {}
 176
 177impl TerminalElement {
 178    pub fn new(
 179        terminal: Entity<Terminal>,
 180        terminal_view: Entity<TerminalView>,
 181        workspace: WeakEntity<Workspace>,
 182        focus: FocusHandle,
 183        focused: bool,
 184        cursor_visible: bool,
 185        block_below_cursor: Option<Rc<BlockProperties>>,
 186        mode: TerminalMode,
 187    ) -> TerminalElement {
 188        TerminalElement {
 189            terminal,
 190            terminal_view,
 191            workspace,
 192            focused,
 193            focus: focus.clone(),
 194            cursor_visible,
 195            block_below_cursor,
 196            mode,
 197            interactivity: Default::default(),
 198        }
 199        .track_focus(&focus)
 200    }
 201
 202    //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
 203
 204    pub fn layout_grid(
 205        grid: impl Iterator<Item = IndexedCell>,
 206        start_line_offset: i32,
 207        text_style: &TextStyle,
 208        text_system: &WindowTextSystem,
 209        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 210        minimum_contrast: f32,
 211        window: &Window,
 212        cx: &App,
 213    ) -> (Vec<LayoutCell>, Vec<LayoutRect>) {
 214        let theme = cx.theme();
 215        let mut cells = vec![];
 216        let mut rects = vec![];
 217
 218        let mut cur_rect: Option<LayoutRect> = None;
 219        let mut cur_alac_color = None;
 220
 221        let linegroups = grid.into_iter().chunk_by(|i| i.point.line);
 222        for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
 223            let alac_line = start_line_offset + line_index as i32;
 224
 225            for cell in line {
 226                let mut fg = cell.fg;
 227                let mut bg = cell.bg;
 228                if cell.flags.contains(Flags::INVERSE) {
 229                    mem::swap(&mut fg, &mut bg);
 230                }
 231
 232                //Expand background rect range
 233                {
 234                    if matches!(bg, Named(NamedColor::Background)) {
 235                        //Continue to next cell, resetting variables if necessary
 236                        cur_alac_color = None;
 237                        if let Some(rect) = cur_rect {
 238                            rects.push(rect);
 239                            cur_rect = None
 240                        }
 241                    } else {
 242                        match cur_alac_color {
 243                            Some(cur_color) => {
 244                                if bg == cur_color {
 245                                    // `cur_rect` can be None if it was moved to the `rects` vec after wrapping around
 246                                    // from one line to the next. The variables are all set correctly but there is no current
 247                                    // rect, so we create one if necessary.
 248                                    cur_rect = cur_rect.map_or_else(
 249                                        || {
 250                                            Some(LayoutRect::new(
 251                                                AlacPoint::new(
 252                                                    alac_line,
 253                                                    cell.point.column.0 as i32,
 254                                                ),
 255                                                1,
 256                                                convert_color(&bg, theme),
 257                                            ))
 258                                        },
 259                                        |rect| Some(rect.extend()),
 260                                    );
 261                                } else {
 262                                    cur_alac_color = Some(bg);
 263                                    if cur_rect.is_some() {
 264                                        rects.push(cur_rect.take().unwrap());
 265                                    }
 266                                    cur_rect = Some(LayoutRect::new(
 267                                        AlacPoint::new(alac_line, cell.point.column.0 as i32),
 268                                        1,
 269                                        convert_color(&bg, theme),
 270                                    ));
 271                                }
 272                            }
 273                            None => {
 274                                cur_alac_color = Some(bg);
 275                                cur_rect = Some(LayoutRect::new(
 276                                    AlacPoint::new(alac_line, cell.point.column.0 as i32),
 277                                    1,
 278                                    convert_color(&bg, theme),
 279                                ));
 280                            }
 281                        }
 282                    }
 283                }
 284
 285                //Layout current cell text
 286                {
 287                    if !is_blank(&cell) {
 288                        let cell_text = cell.c.to_string();
 289                        let cell_style = TerminalElement::cell_style(
 290                            &cell,
 291                            fg,
 292                            bg,
 293                            theme,
 294                            text_style,
 295                            hyperlink,
 296                            minimum_contrast,
 297                        );
 298
 299                        let layout_cell = text_system.shape_line(
 300                            cell_text.into(),
 301                            text_style.font_size.to_pixels(window.rem_size()),
 302                            &[cell_style],
 303                        );
 304
 305                        cells.push(LayoutCell::new(
 306                            AlacPoint::new(alac_line, cell.point.column.0 as i32),
 307                            layout_cell,
 308                        ))
 309                    };
 310                }
 311            }
 312
 313            if cur_rect.is_some() {
 314                rects.push(cur_rect.take().unwrap());
 315            }
 316        }
 317        (cells, rects)
 318    }
 319
 320    /// Computes the cursor position and expected block width, may return a zero width if x_for_index returns
 321    /// the same position for sequential indexes. Use em_width instead
 322    fn shape_cursor(
 323        cursor_point: DisplayCursor,
 324        size: TerminalBounds,
 325        text_fragment: &ShapedLine,
 326    ) -> Option<(Point<Pixels>, Pixels)> {
 327        if cursor_point.line() < size.total_lines() as i32 {
 328            let cursor_width = if text_fragment.width == Pixels::ZERO {
 329                size.cell_width()
 330            } else {
 331                text_fragment.width
 332            };
 333
 334            // Cursor should always surround as much of the text as possible,
 335            // hence when on pixel boundaries round the origin down and the width up
 336            Some((
 337                point(
 338                    (cursor_point.col() as f32 * size.cell_width()).floor(),
 339                    (cursor_point.line() as f32 * size.line_height()).floor(),
 340                ),
 341                cursor_width.ceil(),
 342            ))
 343        } else {
 344            None
 345        }
 346    }
 347
 348    /// Converts the Alacritty cell styles to GPUI text styles and background color.
 349    fn cell_style(
 350        indexed: &IndexedCell,
 351        fg: terminal::alacritty_terminal::vte::ansi::Color,
 352        bg: terminal::alacritty_terminal::vte::ansi::Color,
 353        colors: &Theme,
 354        text_style: &TextStyle,
 355        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 356        minimum_contrast: f32,
 357    ) -> TextRun {
 358        let flags = indexed.cell.flags;
 359        let mut fg = convert_color(&fg, colors);
 360        let bg = convert_color(&bg, colors);
 361
 362        fg = color_contrast::ensure_minimum_contrast(fg, bg, minimum_contrast);
 363
 364        // Ghostty uses (175/255) as the multiplier (~0.69), Alacritty uses 0.66, Kitty
 365        // uses 0.75. We're using 0.7 because it's pretty well in the middle of that.
 366        if flags.intersects(Flags::DIM) {
 367            fg.a *= 0.7;
 368        }
 369
 370        let underline = (flags.intersects(Flags::ALL_UNDERLINES)
 371            || indexed.cell.hyperlink().is_some())
 372        .then(|| UnderlineStyle {
 373            color: Some(fg),
 374            thickness: Pixels::from(1.0),
 375            wavy: flags.contains(Flags::UNDERCURL),
 376        });
 377
 378        let strikethrough = flags
 379            .intersects(Flags::STRIKEOUT)
 380            .then(|| StrikethroughStyle {
 381                color: Some(fg),
 382                thickness: Pixels::from(1.0),
 383            });
 384
 385        let weight = if flags.intersects(Flags::BOLD) {
 386            FontWeight::BOLD
 387        } else {
 388            text_style.font_weight
 389        };
 390
 391        let style = if flags.intersects(Flags::ITALIC) {
 392            FontStyle::Italic
 393        } else {
 394            FontStyle::Normal
 395        };
 396
 397        let mut result = TextRun {
 398            len: indexed.c.len_utf8(),
 399            color: fg,
 400            background_color: None,
 401            font: Font {
 402                weight,
 403                style,
 404                ..text_style.font()
 405            },
 406            underline,
 407            strikethrough,
 408        };
 409
 410        if let Some((style, range)) = hyperlink {
 411            if range.contains(&indexed.point) {
 412                if let Some(underline) = style.underline {
 413                    result.underline = Some(underline);
 414                }
 415
 416                if let Some(color) = style.color {
 417                    result.color = color;
 418                }
 419            }
 420        }
 421
 422        result
 423    }
 424
 425    fn generic_button_handler<E>(
 426        connection: Entity<Terminal>,
 427        focus_handle: FocusHandle,
 428        steal_focus: bool,
 429        f: impl Fn(&mut Terminal, &E, &mut Context<Terminal>),
 430    ) -> impl Fn(&E, &mut Window, &mut App) {
 431        move |event, window, cx| {
 432            if steal_focus {
 433                window.focus(&focus_handle);
 434            } else if !focus_handle.is_focused(window) {
 435                return;
 436            }
 437            connection.update(cx, |terminal, cx| {
 438                f(terminal, event, cx);
 439
 440                cx.notify();
 441            })
 442        }
 443    }
 444
 445    fn register_mouse_listeners(
 446        &mut self,
 447        mode: TermMode,
 448        hitbox: &Hitbox,
 449        content_mode: &ContentMode,
 450        window: &mut Window,
 451    ) {
 452        let focus = self.focus.clone();
 453        let terminal = self.terminal.clone();
 454        let terminal_view = self.terminal_view.clone();
 455
 456        self.interactivity.on_mouse_down(MouseButton::Left, {
 457            let terminal = terminal.clone();
 458            let focus = focus.clone();
 459            let terminal_view = terminal_view.clone();
 460
 461            move |e, window, cx| {
 462                window.focus(&focus);
 463
 464                let scroll_top = terminal_view.read(cx).scroll_top;
 465                terminal.update(cx, |terminal, cx| {
 466                    let mut adjusted_event = e.clone();
 467                    if scroll_top > Pixels::ZERO {
 468                        adjusted_event.position.y += scroll_top;
 469                    }
 470                    terminal.mouse_down(&adjusted_event, cx);
 471                    cx.notify();
 472                })
 473            }
 474        });
 475
 476        window.on_mouse_event({
 477            let terminal = self.terminal.clone();
 478            let hitbox = hitbox.clone();
 479            let focus = focus.clone();
 480            let terminal_view = terminal_view.clone();
 481            move |e: &MouseMoveEvent, phase, window, cx| {
 482                if phase != DispatchPhase::Bubble {
 483                    return;
 484                }
 485
 486                if e.pressed_button.is_some() && !cx.has_active_drag() && focus.is_focused(window) {
 487                    let hovered = hitbox.is_hovered(window);
 488
 489                    let scroll_top = terminal_view.read(cx).scroll_top;
 490                    terminal.update(cx, |terminal, cx| {
 491                        if terminal.selection_started() || hovered {
 492                            let mut adjusted_event = e.clone();
 493                            if scroll_top > Pixels::ZERO {
 494                                adjusted_event.position.y += scroll_top;
 495                            }
 496                            terminal.mouse_drag(&adjusted_event, hitbox.bounds, cx);
 497                            cx.notify();
 498                        }
 499                    })
 500                }
 501
 502                if hitbox.is_hovered(window) {
 503                    terminal.update(cx, |terminal, cx| {
 504                        terminal.mouse_move(e, cx);
 505                    })
 506                }
 507            }
 508        });
 509
 510        self.interactivity.on_mouse_up(
 511            MouseButton::Left,
 512            TerminalElement::generic_button_handler(
 513                terminal.clone(),
 514                focus.clone(),
 515                false,
 516                move |terminal, e, cx| {
 517                    terminal.mouse_up(e, cx);
 518                },
 519            ),
 520        );
 521        self.interactivity.on_mouse_down(
 522            MouseButton::Middle,
 523            TerminalElement::generic_button_handler(
 524                terminal.clone(),
 525                focus.clone(),
 526                true,
 527                move |terminal, e, cx| {
 528                    terminal.mouse_down(e, cx);
 529                },
 530            ),
 531        );
 532
 533        if content_mode.is_scrollable() {
 534            self.interactivity.on_scroll_wheel({
 535                let terminal_view = self.terminal_view.downgrade();
 536                move |e, window, cx| {
 537                    terminal_view
 538                        .update(cx, |terminal_view, cx| {
 539                            if matches!(terminal_view.mode, TerminalMode::Standalone)
 540                                || terminal_view.focus_handle.is_focused(window)
 541                            {
 542                                terminal_view.scroll_wheel(e, cx);
 543                                cx.notify();
 544                            }
 545                        })
 546                        .ok();
 547                }
 548            });
 549        }
 550
 551        // Mouse mode handlers:
 552        // All mouse modes need the extra click handlers
 553        if mode.intersects(TermMode::MOUSE_MODE) {
 554            self.interactivity.on_mouse_down(
 555                MouseButton::Right,
 556                TerminalElement::generic_button_handler(
 557                    terminal.clone(),
 558                    focus.clone(),
 559                    true,
 560                    move |terminal, e, cx| {
 561                        terminal.mouse_down(e, cx);
 562                    },
 563                ),
 564            );
 565            self.interactivity.on_mouse_up(
 566                MouseButton::Right,
 567                TerminalElement::generic_button_handler(
 568                    terminal.clone(),
 569                    focus.clone(),
 570                    false,
 571                    move |terminal, e, cx| {
 572                        terminal.mouse_up(e, cx);
 573                    },
 574                ),
 575            );
 576            self.interactivity.on_mouse_up(
 577                MouseButton::Middle,
 578                TerminalElement::generic_button_handler(
 579                    terminal,
 580                    focus,
 581                    false,
 582                    move |terminal, e, cx| {
 583                        terminal.mouse_up(e, cx);
 584                    },
 585                ),
 586            );
 587        }
 588    }
 589
 590    fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
 591        let settings = ThemeSettings::get_global(cx).clone();
 592        let buffer_font_size = settings.buffer_font_size(cx);
 593        let rem_size_scale = {
 594            // Our default UI font size is 14px on a 16px base scale.
 595            // This means the default UI font size is 0.875rems.
 596            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
 597
 598            // We then determine the delta between a single rem and the default font
 599            // size scale.
 600            let default_font_size_delta = 1. - default_font_size_scale;
 601
 602            // Finally, we add this delta to 1rem to get the scale factor that
 603            // should be used to scale up the UI.
 604            1. + default_font_size_delta
 605        };
 606
 607        Some(buffer_font_size * rem_size_scale)
 608    }
 609}
 610
 611impl Element for TerminalElement {
 612    type RequestLayoutState = ();
 613    type PrepaintState = LayoutState;
 614
 615    fn id(&self) -> Option<ElementId> {
 616        self.interactivity.element_id.clone()
 617    }
 618
 619    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
 620        None
 621    }
 622
 623    fn request_layout(
 624        &mut self,
 625        global_id: Option<&GlobalElementId>,
 626        inspector_id: Option<&gpui::InspectorElementId>,
 627        window: &mut Window,
 628        cx: &mut App,
 629    ) -> (LayoutId, Self::RequestLayoutState) {
 630        let height: Length = match self.terminal_view.read(cx).content_mode(window, cx) {
 631            ContentMode::Inline {
 632                displayed_lines,
 633                total_lines: _,
 634            } => {
 635                let rem_size = window.rem_size();
 636                let line_height = window.text_style().font_size.to_pixels(rem_size)
 637                    * TerminalSettings::get_global(cx)
 638                        .line_height
 639                        .value()
 640                        .to_pixels(rem_size)
 641                        .0;
 642                (displayed_lines * line_height).into()
 643            }
 644            ContentMode::Scrollable => {
 645                if let TerminalMode::Embedded { .. } = &self.mode {
 646                    let term = self.terminal.read(cx);
 647                    if !term.scrolled_to_top() && !term.scrolled_to_bottom() && self.focused {
 648                        self.interactivity.occlude_mouse();
 649                    }
 650                }
 651
 652                relative(1.).into()
 653            }
 654        };
 655
 656        let layout_id = self.interactivity.request_layout(
 657            global_id,
 658            inspector_id,
 659            window,
 660            cx,
 661            |mut style, window, cx| {
 662                style.size.width = relative(1.).into();
 663                style.size.height = height;
 664
 665                window.request_layout(style, None, cx)
 666            },
 667        );
 668        (layout_id, ())
 669    }
 670
 671    fn prepaint(
 672        &mut self,
 673        global_id: Option<&GlobalElementId>,
 674        inspector_id: Option<&gpui::InspectorElementId>,
 675        bounds: Bounds<Pixels>,
 676        _: &mut Self::RequestLayoutState,
 677        window: &mut Window,
 678        cx: &mut App,
 679    ) -> Self::PrepaintState {
 680        let rem_size = self.rem_size(cx);
 681        self.interactivity.prepaint(
 682            global_id,
 683            inspector_id,
 684            bounds,
 685            bounds.size,
 686            window,
 687            cx,
 688            |_, _, hitbox, window, cx| {
 689                let hitbox = hitbox.unwrap();
 690                let settings = ThemeSettings::get_global(cx).clone();
 691
 692                let buffer_font_size = settings.buffer_font_size(cx);
 693
 694                let terminal_settings = TerminalSettings::get_global(cx);
 695                let minimum_contrast = terminal_settings.minimum_contrast;
 696
 697                let font_family = terminal_settings.font_family.as_ref().map_or_else(
 698                    || settings.buffer_font.family.clone(),
 699                    |font_family| font_family.0.clone().into(),
 700                );
 701
 702                let font_fallbacks = terminal_settings
 703                    .font_fallbacks
 704                    .as_ref()
 705                    .or(settings.buffer_font.fallbacks.as_ref())
 706                    .cloned();
 707
 708                let font_features = terminal_settings
 709                    .font_features
 710                    .as_ref()
 711                    .unwrap_or(&settings.buffer_font.features)
 712                    .clone();
 713
 714                let font_weight = terminal_settings.font_weight.unwrap_or_default();
 715
 716                let line_height = terminal_settings.line_height.value();
 717
 718                let font_size = match &self.mode {
 719                    TerminalMode::Embedded { .. } => {
 720                        window.text_style().font_size.to_pixels(window.rem_size())
 721                    }
 722                    TerminalMode::Standalone => terminal_settings
 723                        .font_size
 724                        .map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx)),
 725                };
 726
 727                let theme = cx.theme().clone();
 728
 729                let link_style = HighlightStyle {
 730                    color: Some(theme.colors().link_text_hover),
 731                    font_weight: Some(font_weight),
 732                    font_style: None,
 733                    background_color: None,
 734                    underline: Some(UnderlineStyle {
 735                        thickness: px(1.0),
 736                        color: Some(theme.colors().link_text_hover),
 737                        wavy: false,
 738                    }),
 739                    strikethrough: None,
 740                    fade_out: None,
 741                };
 742
 743                let text_style = TextStyle {
 744                    font_family,
 745                    font_features,
 746                    font_weight,
 747                    font_fallbacks,
 748                    font_size: font_size.into(),
 749                    font_style: FontStyle::Normal,
 750                    line_height: line_height.into(),
 751                    background_color: Some(theme.colors().terminal_ansi_background),
 752                    white_space: WhiteSpace::Normal,
 753                    // These are going to be overridden per-cell
 754                    color: theme.colors().terminal_foreground,
 755                    ..Default::default()
 756                };
 757
 758                let text_system = cx.text_system();
 759                let player_color = theme.players().local();
 760                let match_color = theme.colors().search_match_background;
 761                let gutter;
 762                let (dimensions, line_height_px) = {
 763                    let rem_size = window.rem_size();
 764                    let font_pixels = text_style.font_size.to_pixels(rem_size);
 765                    // TODO: line_height should be an f32 not an AbsoluteLength.
 766                    let line_height = font_pixels * line_height.to_pixels(rem_size).0;
 767                    let font_id = cx.text_system().resolve_font(&text_style.font());
 768
 769                    let cell_width = text_system
 770                        .advance(font_id, font_pixels, 'm')
 771                        .unwrap()
 772                        .width;
 773                    gutter = cell_width;
 774
 775                    let mut size = bounds.size;
 776                    size.width -= gutter;
 777
 778                    // https://github.com/zed-industries/zed/issues/2750
 779                    // if the terminal is one column wide, rendering 🦀
 780                    // causes alacritty to misbehave.
 781                    if size.width < cell_width * 2.0 {
 782                        size.width = cell_width * 2.0;
 783                    }
 784
 785                    let mut origin = bounds.origin;
 786                    origin.x += gutter;
 787
 788                    (
 789                        TerminalBounds::new(line_height, cell_width, Bounds { origin, size }),
 790                        line_height,
 791                    )
 792                };
 793
 794                let search_matches = self.terminal.read(cx).matches.clone();
 795
 796                let background_color = theme.colors().terminal_background;
 797
 798                let (last_hovered_word, hover_tooltip) =
 799                    self.terminal.update(cx, |terminal, cx| {
 800                        terminal.set_size(dimensions);
 801                        terminal.sync(window, cx);
 802
 803                        if window.modifiers().secondary()
 804                            && bounds.contains(&window.mouse_position())
 805                            && self.terminal_view.read(cx).hover.is_some()
 806                        {
 807                            let registered_hover = self.terminal_view.read(cx).hover.as_ref();
 808                            if terminal.last_content.last_hovered_word.as_ref()
 809                                == registered_hover.map(|hover| &hover.hovered_word)
 810                            {
 811                                (
 812                                    terminal.last_content.last_hovered_word.clone(),
 813                                    registered_hover.map(|hover| hover.tooltip.clone()),
 814                                )
 815                            } else {
 816                                (None, None)
 817                            }
 818                        } else {
 819                            (None, None)
 820                        }
 821                    });
 822
 823                let scroll_top = self.terminal_view.read(cx).scroll_top;
 824                let hyperlink_tooltip = hover_tooltip.map(|hover_tooltip| {
 825                    let offset = bounds.origin + point(gutter, px(0.)) - point(px(0.), scroll_top);
 826                    let mut element = div()
 827                        .size_full()
 828                        .id("terminal-element")
 829                        .tooltip(Tooltip::text(hover_tooltip))
 830                        .into_any_element();
 831                    element.prepaint_as_root(offset, bounds.size.into(), window, cx);
 832                    element
 833                });
 834
 835                let TerminalContent {
 836                    cells,
 837                    mode,
 838                    display_offset,
 839                    cursor_char,
 840                    selection,
 841                    cursor,
 842                    ..
 843                } = &self.terminal.read(cx).last_content;
 844                let mode = *mode;
 845                let display_offset = *display_offset;
 846
 847                // searches, highlights to a single range representations
 848                let mut relative_highlighted_ranges = Vec::new();
 849                for search_match in search_matches {
 850                    relative_highlighted_ranges.push((search_match, match_color))
 851                }
 852                if let Some(selection) = selection {
 853                    relative_highlighted_ranges
 854                        .push((selection.start..=selection.end, player_color.selection));
 855                }
 856
 857                // then have that representation be converted to the appropriate highlight data structure
 858
 859                let content_mode = self.terminal_view.read(cx).content_mode(window, cx);
 860                let (cells, rects) = match content_mode {
 861                    ContentMode::Scrollable => TerminalElement::layout_grid(
 862                        cells.iter().cloned(),
 863                        0,
 864                        &text_style,
 865                        window.text_system(),
 866                        last_hovered_word
 867                            .as_ref()
 868                            .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
 869                        minimum_contrast,
 870                        window,
 871                        cx,
 872                    ),
 873                    ContentMode::Inline { .. } => {
 874                        let intersection = window.content_mask().bounds.intersect(&bounds);
 875                        let start_row = (intersection.top() - bounds.top()) / line_height_px;
 876                        let end_row = start_row + intersection.size.height / line_height_px;
 877                        let line_range = (start_row as i32)..=(end_row as i32);
 878
 879                        TerminalElement::layout_grid(
 880                            cells
 881                                .iter()
 882                                .skip_while(|i| &i.point.line < line_range.start())
 883                                .take_while(|i| &i.point.line <= line_range.end())
 884                                .cloned(),
 885                            *line_range.start(),
 886                            &text_style,
 887                            window.text_system(),
 888                            last_hovered_word.as_ref().map(|last_hovered_word| {
 889                                (link_style, &last_hovered_word.word_match)
 890                            }),
 891                            minimum_contrast,
 892                            window,
 893                            cx,
 894                        )
 895                    }
 896                };
 897
 898                // Layout cursor. Rectangle is used for IME, so we should lay it out even
 899                // if we don't end up showing it.
 900                let cursor = if let AlacCursorShape::Hidden = cursor.shape {
 901                    None
 902                } else {
 903                    let cursor_point = DisplayCursor::from(cursor.point, display_offset);
 904                    let cursor_text = {
 905                        let str_trxt = cursor_char.to_string();
 906                        let len = str_trxt.len();
 907                        window.text_system().shape_line(
 908                            str_trxt.into(),
 909                            text_style.font_size.to_pixels(window.rem_size()),
 910                            &[TextRun {
 911                                len,
 912                                font: text_style.font(),
 913                                color: theme.colors().terminal_ansi_background,
 914                                background_color: None,
 915                                underline: Default::default(),
 916                                strikethrough: None,
 917                            }],
 918                        )
 919                    };
 920
 921                    let focused = self.focused;
 922                    TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
 923                        move |(cursor_position, block_width)| {
 924                            let (shape, text) = match cursor.shape {
 925                                AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
 926                                AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
 927                                AlacCursorShape::Underline => (CursorShape::Underline, None),
 928                                AlacCursorShape::Beam => (CursorShape::Bar, None),
 929                                AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
 930                                //This case is handled in the if wrapping the whole cursor layout
 931                                AlacCursorShape::Hidden => unreachable!(),
 932                            };
 933
 934                            CursorLayout::new(
 935                                cursor_position,
 936                                block_width,
 937                                dimensions.line_height,
 938                                theme.players().local().cursor,
 939                                shape,
 940                                text,
 941                            )
 942                        },
 943                    )
 944                };
 945
 946                let block_below_cursor_element = if let Some(block) = &self.block_below_cursor {
 947                    let terminal = self.terminal.read(cx);
 948                    if terminal.last_content.display_offset == 0 {
 949                        let target_line = terminal.last_content.cursor.point.line.0 + 1;
 950                        let render = &block.render;
 951                        let mut block_cx = BlockContext {
 952                            window,
 953                            context: cx,
 954                            dimensions,
 955                        };
 956                        let element = render(&mut block_cx);
 957                        let mut element = div().occlude().child(element).into_any_element();
 958                        let available_space = size(
 959                            AvailableSpace::Definite(dimensions.width() + gutter),
 960                            AvailableSpace::Definite(
 961                                block.height as f32 * dimensions.line_height(),
 962                            ),
 963                        );
 964                        let origin = bounds.origin
 965                            + point(px(0.), target_line as f32 * dimensions.line_height())
 966                            - point(px(0.), scroll_top);
 967                        window.with_rem_size(rem_size, |window| {
 968                            element.prepaint_as_root(origin, available_space, window, cx);
 969                        });
 970                        Some(element)
 971                    } else {
 972                        None
 973                    }
 974                } else {
 975                    None
 976                };
 977
 978                LayoutState {
 979                    hitbox,
 980                    cells,
 981                    cursor,
 982                    background_color,
 983                    dimensions,
 984                    rects,
 985                    relative_highlighted_ranges,
 986                    mode,
 987                    display_offset,
 988                    hyperlink_tooltip,
 989                    gutter,
 990                    block_below_cursor_element,
 991                    base_text_style: text_style,
 992                    content_mode,
 993                }
 994            },
 995        )
 996    }
 997
 998    fn paint(
 999        &mut self,
1000        global_id: Option<&GlobalElementId>,
1001        inspector_id: Option<&gpui::InspectorElementId>,
1002        bounds: Bounds<Pixels>,
1003        _: &mut Self::RequestLayoutState,
1004        layout: &mut Self::PrepaintState,
1005        window: &mut Window,
1006        cx: &mut App,
1007    ) {
1008        window.with_content_mask(Some(ContentMask { bounds }), |window| {
1009            let scroll_top = self.terminal_view.read(cx).scroll_top;
1010
1011            window.paint_quad(fill(bounds, layout.background_color));
1012            let origin =
1013                bounds.origin + Point::new(layout.gutter, px(0.)) - Point::new(px(0.), scroll_top);
1014
1015            let marked_text_cloned: Option<String> = {
1016                let ime_state = self.terminal_view.read(cx);
1017                ime_state.marked_text.clone()
1018            };
1019
1020            let terminal_input_handler = TerminalInputHandler {
1021                terminal: self.terminal.clone(),
1022                terminal_view: self.terminal_view.clone(),
1023                cursor_bounds: layout
1024                    .cursor
1025                    .as_ref()
1026                    .map(|cursor| cursor.bounding_rect(origin)),
1027                workspace: self.workspace.clone(),
1028            };
1029
1030            self.register_mouse_listeners(
1031                layout.mode,
1032                &layout.hitbox,
1033                &layout.content_mode,
1034                window,
1035            );
1036            if window.modifiers().secondary()
1037                && bounds.contains(&window.mouse_position())
1038                && self.terminal_view.read(cx).hover.is_some()
1039            {
1040                window.set_cursor_style(gpui::CursorStyle::PointingHand, &layout.hitbox);
1041            } else {
1042                window.set_cursor_style(gpui::CursorStyle::IBeam, &layout.hitbox);
1043            }
1044
1045            let original_cursor = layout.cursor.take();
1046            let hyperlink_tooltip = layout.hyperlink_tooltip.take();
1047            let block_below_cursor_element = layout.block_below_cursor_element.take();
1048            self.interactivity.paint(
1049                global_id,
1050                inspector_id,
1051                bounds,
1052                Some(&layout.hitbox),
1053                window,
1054                cx,
1055                |_, window, cx| {
1056                    window.handle_input(&self.focus, terminal_input_handler, cx);
1057
1058                    window.on_key_event({
1059                        let this = self.terminal.clone();
1060                        move |event: &ModifiersChangedEvent, phase, window, cx| {
1061                            if phase != DispatchPhase::Bubble {
1062                                return;
1063                            }
1064
1065                            this.update(cx, |term, cx| {
1066                                term.try_modifiers_change(&event.modifiers, window, cx)
1067                            });
1068                        }
1069                    });
1070
1071                    for rect in &layout.rects {
1072                        rect.paint(origin, &layout.dimensions, window);
1073                    }
1074
1075                    for (relative_highlighted_range, color) in
1076                        layout.relative_highlighted_ranges.iter()
1077                    {
1078                        if let Some((start_y, highlighted_range_lines)) =
1079                            to_highlighted_range_lines(relative_highlighted_range, layout, origin)
1080                        {
1081                            let hr = HighlightedRange {
1082                                start_y,
1083                                line_height: layout.dimensions.line_height,
1084                                lines: highlighted_range_lines,
1085                                color: *color,
1086                                corner_radius: 0.15 * layout.dimensions.line_height,
1087                            };
1088                            hr.paint(true, bounds, window);
1089                        }
1090                    }
1091
1092                    for cell in &layout.cells {
1093                        cell.paint(origin, &layout.dimensions, bounds, window, cx);
1094                    }
1095
1096                    if let Some(text_to_mark) = &marked_text_cloned {
1097                        if !text_to_mark.is_empty() {
1098                            if let Some(cursor_layout) = &original_cursor {
1099                                let ime_position = cursor_layout.bounding_rect(origin).origin;
1100                                let mut ime_style = layout.base_text_style.clone();
1101                                ime_style.underline = Some(UnderlineStyle {
1102                                    color: Some(ime_style.color),
1103                                    thickness: px(1.0),
1104                                    wavy: false,
1105                                });
1106
1107                                let shaped_line = window.text_system().shape_line(
1108                                    text_to_mark.clone().into(),
1109                                    ime_style.font_size.to_pixels(window.rem_size()),
1110                                    &[TextRun {
1111                                        len: text_to_mark.len(),
1112                                        font: ime_style.font(),
1113                                        color: ime_style.color,
1114                                        background_color: None,
1115                                        underline: ime_style.underline,
1116                                        strikethrough: None,
1117                                    }],
1118                                );
1119                                shaped_line
1120                                    .paint(ime_position, layout.dimensions.line_height, window, cx)
1121                                    .log_err();
1122                            }
1123                        }
1124                    }
1125
1126                    if self.cursor_visible && marked_text_cloned.is_none() {
1127                        if let Some(mut cursor) = original_cursor {
1128                            cursor.paint(origin, window, cx);
1129                        }
1130                    }
1131
1132                    if let Some(mut element) = block_below_cursor_element {
1133                        element.paint(window, cx);
1134                    }
1135
1136                    if let Some(mut element) = hyperlink_tooltip {
1137                        element.paint(window, cx);
1138                    }
1139                },
1140            );
1141        });
1142    }
1143}
1144
1145impl IntoElement for TerminalElement {
1146    type Element = Self;
1147
1148    fn into_element(self) -> Self::Element {
1149        self
1150    }
1151}
1152
1153struct TerminalInputHandler {
1154    terminal: Entity<Terminal>,
1155    terminal_view: Entity<TerminalView>,
1156    workspace: WeakEntity<Workspace>,
1157    cursor_bounds: Option<Bounds<Pixels>>,
1158}
1159
1160impl InputHandler for TerminalInputHandler {
1161    fn selected_text_range(
1162        &mut self,
1163        _ignore_disabled_input: bool,
1164        _: &mut Window,
1165        cx: &mut App,
1166    ) -> Option<UTF16Selection> {
1167        if self
1168            .terminal
1169            .read(cx)
1170            .last_content
1171            .mode
1172            .contains(TermMode::ALT_SCREEN)
1173        {
1174            None
1175        } else {
1176            Some(UTF16Selection {
1177                range: 0..0,
1178                reversed: false,
1179            })
1180        }
1181    }
1182
1183    fn marked_text_range(
1184        &mut self,
1185        _window: &mut Window,
1186        cx: &mut App,
1187    ) -> Option<std::ops::Range<usize>> {
1188        self.terminal_view.read(cx).marked_text_range()
1189    }
1190
1191    fn text_for_range(
1192        &mut self,
1193        _: std::ops::Range<usize>,
1194        _: &mut Option<std::ops::Range<usize>>,
1195        _: &mut Window,
1196        _: &mut App,
1197    ) -> Option<String> {
1198        None
1199    }
1200
1201    fn replace_text_in_range(
1202        &mut self,
1203        _replacement_range: Option<std::ops::Range<usize>>,
1204        text: &str,
1205        window: &mut Window,
1206        cx: &mut App,
1207    ) {
1208        self.terminal_view.update(cx, |view, view_cx| {
1209            view.clear_marked_text(view_cx);
1210            view.commit_text(text, view_cx);
1211        });
1212
1213        self.workspace
1214            .update(cx, |this, cx| {
1215                window.invalidate_character_coordinates();
1216                let project = this.project().read(cx);
1217                let telemetry = project.client().telemetry().clone();
1218                telemetry.log_edit_event("terminal", project.is_via_ssh());
1219            })
1220            .ok();
1221    }
1222
1223    fn replace_and_mark_text_in_range(
1224        &mut self,
1225        _range_utf16: Option<std::ops::Range<usize>>,
1226        new_text: &str,
1227        new_marked_range: Option<std::ops::Range<usize>>,
1228        _window: &mut Window,
1229        cx: &mut App,
1230    ) {
1231        if let Some(range) = new_marked_range {
1232            self.terminal_view.update(cx, |view, view_cx| {
1233                view.set_marked_text(new_text.to_string(), range, view_cx);
1234            });
1235        }
1236    }
1237
1238    fn unmark_text(&mut self, _window: &mut Window, cx: &mut App) {
1239        self.terminal_view.update(cx, |view, view_cx| {
1240            view.clear_marked_text(view_cx);
1241        });
1242    }
1243
1244    fn bounds_for_range(
1245        &mut self,
1246        range_utf16: std::ops::Range<usize>,
1247        _window: &mut Window,
1248        cx: &mut App,
1249    ) -> Option<Bounds<Pixels>> {
1250        let term_bounds = self.terminal_view.read(cx).terminal_bounds(cx);
1251
1252        let mut bounds = self.cursor_bounds?;
1253        let offset_x = term_bounds.cell_width * range_utf16.start as f32;
1254        bounds.origin.x += offset_x;
1255
1256        Some(bounds)
1257    }
1258
1259    fn apple_press_and_hold_enabled(&mut self) -> bool {
1260        false
1261    }
1262
1263    fn character_index_for_point(
1264        &mut self,
1265        _point: Point<Pixels>,
1266        _window: &mut Window,
1267        _cx: &mut App,
1268    ) -> Option<usize> {
1269        None
1270    }
1271}
1272
1273pub fn is_blank(cell: &IndexedCell) -> bool {
1274    if cell.c != ' ' {
1275        return false;
1276    }
1277
1278    if cell.bg != AnsiColor::Named(NamedColor::Background) {
1279        return false;
1280    }
1281
1282    if cell.hyperlink().is_some() {
1283        return false;
1284    }
1285
1286    if cell
1287        .flags
1288        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
1289    {
1290        return false;
1291    }
1292
1293    true
1294}
1295
1296fn to_highlighted_range_lines(
1297    range: &RangeInclusive<AlacPoint>,
1298    layout: &LayoutState,
1299    origin: Point<Pixels>,
1300) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
1301    // Step 1. Normalize the points to be viewport relative.
1302    // When display_offset = 1, here's how the grid is arranged:
1303    //-2,0 -2,1...
1304    //--- Viewport top
1305    //-1,0 -1,1...
1306    //--------- Terminal Top
1307    // 0,0  0,1...
1308    // 1,0  1,1...
1309    //--- Viewport Bottom
1310    // 2,0  2,1...
1311    //--------- Terminal Bottom
1312
1313    // Normalize to viewport relative, from terminal relative.
1314    // lines are i32s, which are negative above the top left corner of the terminal
1315    // If the user has scrolled, we use the display_offset to tell us which offset
1316    // of the grid data we should be looking at. But for the rendering step, we don't
1317    // want negatives. We want things relative to the 'viewport' (the area of the grid
1318    // which is currently shown according to the display offset)
1319    let unclamped_start = AlacPoint::new(
1320        range.start().line + layout.display_offset,
1321        range.start().column,
1322    );
1323    let unclamped_end =
1324        AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
1325
1326    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
1327    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
1328        return None;
1329    }
1330
1331    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1332    let clamped_end_line = unclamped_end
1333        .line
1334        .0
1335        .min(layout.dimensions.num_lines() as i32) as usize;
1336    //Convert the start of the range to pixels
1337    let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
1338
1339    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1340    //  (also convert to pixels)
1341    let mut highlighted_range_lines = Vec::new();
1342    for line in clamped_start_line..=clamped_end_line {
1343        let mut line_start = 0;
1344        let mut line_end = layout.dimensions.columns();
1345
1346        if line == clamped_start_line {
1347            line_start = unclamped_start.column.0;
1348        }
1349        if line == clamped_end_line {
1350            line_end = unclamped_end.column.0 + 1; // +1 for inclusive
1351        }
1352
1353        highlighted_range_lines.push(HighlightedRangeLine {
1354            start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
1355            end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
1356        });
1357    }
1358
1359    Some((start_y, highlighted_range_lines))
1360}
1361
1362/// Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent.
1363pub fn convert_color(fg: &terminal::alacritty_terminal::vte::ansi::Color, theme: &Theme) -> Hsla {
1364    let colors = theme.colors();
1365    match fg {
1366        // Named and theme defined colors
1367        terminal::alacritty_terminal::vte::ansi::Color::Named(n) => match n {
1368            NamedColor::Black => colors.terminal_ansi_black,
1369            NamedColor::Red => colors.terminal_ansi_red,
1370            NamedColor::Green => colors.terminal_ansi_green,
1371            NamedColor::Yellow => colors.terminal_ansi_yellow,
1372            NamedColor::Blue => colors.terminal_ansi_blue,
1373            NamedColor::Magenta => colors.terminal_ansi_magenta,
1374            NamedColor::Cyan => colors.terminal_ansi_cyan,
1375            NamedColor::White => colors.terminal_ansi_white,
1376            NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1377            NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1378            NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1379            NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1380            NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1381            NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1382            NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1383            NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1384            NamedColor::Foreground => colors.terminal_foreground,
1385            NamedColor::Background => colors.terminal_ansi_background,
1386            NamedColor::Cursor => theme.players().local().cursor,
1387            NamedColor::DimBlack => colors.terminal_ansi_dim_black,
1388            NamedColor::DimRed => colors.terminal_ansi_dim_red,
1389            NamedColor::DimGreen => colors.terminal_ansi_dim_green,
1390            NamedColor::DimYellow => colors.terminal_ansi_dim_yellow,
1391            NamedColor::DimBlue => colors.terminal_ansi_dim_blue,
1392            NamedColor::DimMagenta => colors.terminal_ansi_dim_magenta,
1393            NamedColor::DimCyan => colors.terminal_ansi_dim_cyan,
1394            NamedColor::DimWhite => colors.terminal_ansi_dim_white,
1395            NamedColor::BrightForeground => colors.terminal_bright_foreground,
1396            NamedColor::DimForeground => colors.terminal_dim_foreground,
1397        },
1398        // 'True' colors
1399        terminal::alacritty_terminal::vte::ansi::Color::Spec(rgb) => {
1400            terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1401        }
1402        // 8 bit, indexed colors
1403        terminal::alacritty_terminal::vte::ansi::Color::Indexed(i) => {
1404            terminal::get_color_at_index(*i as usize, theme)
1405        }
1406    }
1407}
1408
1409#[cfg(test)]
1410mod tests {
1411    use super::*;
1412
1413    #[test]
1414    fn test_contrast_adjustment_logic() {
1415        // Test the core contrast adjustment logic without needing full app context
1416
1417        // Test case 1: Light colors (poor contrast)
1418        let white_fg = gpui::Hsla {
1419            h: 0.0,
1420            s: 0.0,
1421            l: 1.0,
1422            a: 1.0,
1423        };
1424        let light_gray_bg = gpui::Hsla {
1425            h: 0.0,
1426            s: 0.0,
1427            l: 0.95,
1428            a: 1.0,
1429        };
1430
1431        // Should have poor contrast
1432        let actual_contrast = color_contrast::apca_contrast(white_fg, light_gray_bg).abs();
1433        assert!(
1434            actual_contrast < 30.0,
1435            "White on light gray should have poor APCA contrast: {}",
1436            actual_contrast
1437        );
1438
1439        // After adjustment with minimum APCA contrast of 45, should be darker
1440        let adjusted = color_contrast::ensure_minimum_contrast(white_fg, light_gray_bg, 45.0);
1441        assert!(
1442            adjusted.l < white_fg.l,
1443            "Adjusted color should be darker than original"
1444        );
1445        let adjusted_contrast = color_contrast::apca_contrast(adjusted, light_gray_bg).abs();
1446        assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1447
1448        // Test case 2: Dark colors (poor contrast)
1449        let black_fg = gpui::Hsla {
1450            h: 0.0,
1451            s: 0.0,
1452            l: 0.0,
1453            a: 1.0,
1454        };
1455        let dark_gray_bg = gpui::Hsla {
1456            h: 0.0,
1457            s: 0.0,
1458            l: 0.05,
1459            a: 1.0,
1460        };
1461
1462        // Should have poor contrast
1463        let actual_contrast = color_contrast::apca_contrast(black_fg, dark_gray_bg).abs();
1464        assert!(
1465            actual_contrast < 30.0,
1466            "Black on dark gray should have poor APCA contrast: {}",
1467            actual_contrast
1468        );
1469
1470        // After adjustment with minimum APCA contrast of 45, should be lighter
1471        let adjusted = color_contrast::ensure_minimum_contrast(black_fg, dark_gray_bg, 45.0);
1472        assert!(
1473            adjusted.l > black_fg.l,
1474            "Adjusted color should be lighter than original"
1475        );
1476        let adjusted_contrast = color_contrast::apca_contrast(adjusted, dark_gray_bg).abs();
1477        assert!(adjusted_contrast >= 45.0, "Should meet minimum contrast");
1478
1479        // Test case 3: Already good contrast
1480        let good_contrast = color_contrast::ensure_minimum_contrast(black_fg, white_fg, 45.0);
1481        assert_eq!(
1482            good_contrast, black_fg,
1483            "Good contrast should not be adjusted"
1484        );
1485    }
1486
1487    #[test]
1488    fn test_white_on_white_contrast_issue() {
1489        // This test reproduces the exact issue from the bug report
1490        // where white ANSI text on white background should be adjusted
1491
1492        // Simulate One Light theme colors
1493        let white_fg = gpui::Hsla {
1494            h: 0.0,
1495            s: 0.0,
1496            l: 0.98, // #fafafaff is approximately 98% lightness
1497            a: 1.0,
1498        };
1499        let white_bg = gpui::Hsla {
1500            h: 0.0,
1501            s: 0.0,
1502            l: 0.98, // Same as foreground - this is the problem!
1503            a: 1.0,
1504        };
1505
1506        // With minimum contrast of 0.0, no adjustment should happen
1507        let no_adjust = color_contrast::ensure_minimum_contrast(white_fg, white_bg, 0.0);
1508        assert_eq!(no_adjust, white_fg, "No adjustment with min_contrast 0.0");
1509
1510        // With minimum APCA contrast of 15, it should adjust to a darker color
1511        let adjusted = color_contrast::ensure_minimum_contrast(white_fg, white_bg, 15.0);
1512        assert!(
1513            adjusted.l < white_fg.l,
1514            "White on white should become darker, got l={}",
1515            adjusted.l
1516        );
1517
1518        // Verify the contrast is now acceptable
1519        let new_contrast = color_contrast::apca_contrast(adjusted, white_bg).abs();
1520        assert!(
1521            new_contrast >= 15.0,
1522            "Adjusted APCA contrast {} should be >= 15.0",
1523            new_contrast
1524        );
1525    }
1526}