terminal_element.rs

   1use editor::{Cursor, HighlightedRange, HighlightedRangeLine};
   2use gpui::{
   3    div, fill, point, px, red, relative, AnyElement, AsyncWindowContext, AvailableSpace,
   4    BorrowWindow, Bounds, DispatchPhase, Element, ElementId, FocusHandle, Font, FontStyle,
   5    FontWeight, HighlightStyle, Hsla, InteractiveBounds, InteractiveElement,
   6    InteractiveElementState, Interactivity, IntoElement, LayoutId, Model, ModelContext,
   7    ModifiersChangedEvent, MouseButton, MouseMoveEvent, Pixels, PlatformInputHandler, Point,
   8    ShapedLine, StatefulInteractiveElement, Styled, TextRun, TextStyle, TextSystem, UnderlineStyle,
   9    WhiteSpace, WindowContext,
  10};
  11use itertools::Itertools;
  12use language::CursorShape;
  13use settings::Settings;
  14use terminal::{
  15    alacritty_terminal::ansi::NamedColor,
  16    alacritty_terminal::{
  17        ansi::{Color as AnsiColor, Color::Named, CursorShape as AlacCursorShape},
  18        grid::Dimensions,
  19        index::Point as AlacPoint,
  20        term::{cell::Flags, TermMode},
  21    },
  22    terminal_settings::TerminalSettings,
  23    IndexedCell, Terminal, TerminalContent, TerminalSize,
  24};
  25use theme::{ActiveTheme, Theme, ThemeSettings};
  26use ui::Tooltip;
  27
  28use std::mem;
  29use std::{fmt::Debug, ops::RangeInclusive};
  30
  31///The information generated during layout that is necessary for painting
  32pub struct LayoutState {
  33    cells: Vec<LayoutCell>,
  34    rects: Vec<LayoutRect>,
  35    relative_highlighted_ranges: Vec<(RangeInclusive<AlacPoint>, Hsla)>,
  36    cursor: Option<Cursor>,
  37    background_color: Hsla,
  38    dimensions: TerminalSize,
  39    mode: TermMode,
  40    display_offset: usize,
  41    hyperlink_tooltip: Option<AnyElement>,
  42    gutter: Pixels,
  43}
  44
  45///Helper struct for converting data between alacritty's cursor points, and displayed cursor points
  46struct DisplayCursor {
  47    line: i32,
  48    col: usize,
  49}
  50
  51impl DisplayCursor {
  52    fn from(cursor_point: AlacPoint, display_offset: usize) -> Self {
  53        Self {
  54            line: cursor_point.line.0 + display_offset as i32,
  55            col: cursor_point.column.0,
  56        }
  57    }
  58
  59    pub fn line(&self) -> i32 {
  60        self.line
  61    }
  62
  63    pub fn col(&self) -> usize {
  64        self.col
  65    }
  66}
  67
  68#[derive(Debug, Default)]
  69struct LayoutCell {
  70    point: AlacPoint<i32, i32>,
  71    text: gpui::ShapedLine,
  72}
  73
  74impl LayoutCell {
  75    fn new(point: AlacPoint<i32, i32>, text: gpui::ShapedLine) -> LayoutCell {
  76        LayoutCell { point, text }
  77    }
  78
  79    fn paint(
  80        &self,
  81        origin: Point<Pixels>,
  82        layout: &LayoutState,
  83        _visible_bounds: Bounds<Pixels>,
  84        cx: &mut WindowContext,
  85    ) {
  86        let pos = {
  87            let point = self.point;
  88
  89            Point::new(
  90                (origin.x + point.column as f32 * layout.dimensions.cell_width).floor(),
  91                origin.y + point.line as f32 * layout.dimensions.line_height,
  92            )
  93        };
  94
  95        self.text.paint(pos, layout.dimensions.line_height, cx).ok();
  96    }
  97}
  98
  99#[derive(Clone, Debug, Default)]
 100struct LayoutRect {
 101    point: AlacPoint<i32, i32>,
 102    num_of_cells: usize,
 103    color: Hsla,
 104}
 105
 106impl LayoutRect {
 107    fn new(point: AlacPoint<i32, i32>, num_of_cells: usize, color: Hsla) -> LayoutRect {
 108        LayoutRect {
 109            point,
 110            num_of_cells,
 111            color,
 112        }
 113    }
 114
 115    fn extend(&self) -> Self {
 116        LayoutRect {
 117            point: self.point,
 118            num_of_cells: self.num_of_cells + 1,
 119            color: self.color,
 120        }
 121    }
 122
 123    fn paint(&self, origin: Point<Pixels>, layout: &LayoutState, cx: &mut WindowContext) {
 124        let position = {
 125            let alac_point = self.point;
 126            point(
 127                (origin.x + alac_point.column as f32 * layout.dimensions.cell_width).floor(),
 128                origin.y + alac_point.line as f32 * layout.dimensions.line_height,
 129            )
 130        };
 131        let size = point(
 132            (layout.dimensions.cell_width * self.num_of_cells as f32).ceil(),
 133            layout.dimensions.line_height,
 134        )
 135        .into();
 136
 137        cx.paint_quad(fill(Bounds::new(position, size), self.color));
 138    }
 139}
 140
 141///The GPUI element that paints the terminal.
 142///We need to keep a reference to the view for mouse events, do we need it for any other terminal stuff, or can we move that to connection?
 143pub struct TerminalElement {
 144    terminal: Model<Terminal>,
 145    focus: FocusHandle,
 146    focused: bool,
 147    cursor_visible: bool,
 148    can_navigate_to_selected_word: bool,
 149    interactivity: Interactivity,
 150}
 151
 152impl InteractiveElement for TerminalElement {
 153    fn interactivity(&mut self) -> &mut Interactivity {
 154        &mut self.interactivity
 155    }
 156}
 157
 158impl StatefulInteractiveElement for TerminalElement {}
 159
 160impl TerminalElement {
 161    pub fn new(
 162        terminal: Model<Terminal>,
 163        focus: FocusHandle,
 164        focused: bool,
 165        cursor_visible: bool,
 166        can_navigate_to_selected_word: bool,
 167    ) -> TerminalElement {
 168        TerminalElement {
 169            terminal,
 170            focused,
 171            focus: focus.clone(),
 172            cursor_visible,
 173            can_navigate_to_selected_word,
 174            interactivity: Default::default(),
 175        }
 176        .track_focus(&focus)
 177        .element
 178    }
 179
 180    //Vec<Range<AlacPoint>> -> Clip out the parts of the ranges
 181
 182    fn layout_grid(
 183        grid: &Vec<IndexedCell>,
 184        text_style: &TextStyle,
 185        // terminal_theme: &TerminalStyle,
 186        text_system: &TextSystem,
 187        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 188        cx: &WindowContext<'_>,
 189    ) -> (Vec<LayoutCell>, Vec<LayoutRect>) {
 190        let theme = cx.theme();
 191        let mut cells = vec![];
 192        let mut rects = vec![];
 193
 194        let mut cur_rect: Option<LayoutRect> = None;
 195        let mut cur_alac_color = None;
 196
 197        let linegroups = grid.into_iter().group_by(|i| i.point.line);
 198        for (line_index, (_, line)) in linegroups.into_iter().enumerate() {
 199            for cell in line {
 200                let mut fg = cell.fg;
 201                let mut bg = cell.bg;
 202                if cell.flags.contains(Flags::INVERSE) {
 203                    mem::swap(&mut fg, &mut bg);
 204                }
 205
 206                //Expand background rect range
 207                {
 208                    if matches!(bg, Named(NamedColor::Background)) {
 209                        //Continue to next cell, resetting variables if necessary
 210                        cur_alac_color = None;
 211                        if let Some(rect) = cur_rect {
 212                            rects.push(rect);
 213                            cur_rect = None
 214                        }
 215                    } else {
 216                        match cur_alac_color {
 217                            Some(cur_color) => {
 218                                if bg == cur_color {
 219                                    cur_rect = cur_rect.take().map(|rect| rect.extend());
 220                                } else {
 221                                    cur_alac_color = Some(bg);
 222                                    if cur_rect.is_some() {
 223                                        rects.push(cur_rect.take().unwrap());
 224                                    }
 225                                    cur_rect = Some(LayoutRect::new(
 226                                        AlacPoint::new(
 227                                            line_index as i32,
 228                                            cell.point.column.0 as i32,
 229                                        ),
 230                                        1,
 231                                        convert_color(&bg, theme),
 232                                    ));
 233                                }
 234                            }
 235                            None => {
 236                                cur_alac_color = Some(bg);
 237                                cur_rect = Some(LayoutRect::new(
 238                                    AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
 239                                    1,
 240                                    convert_color(&bg, &theme),
 241                                ));
 242                            }
 243                        }
 244                    }
 245                }
 246
 247                //Layout current cell text
 248                {
 249                    let cell_text = cell.c.to_string();
 250                    if !is_blank(&cell) {
 251                        let cell_style =
 252                            TerminalElement::cell_style(&cell, fg, theme, text_style, hyperlink);
 253
 254                        let layout_cell = text_system
 255                            .shape_line(
 256                                cell_text.into(),
 257                                text_style.font_size.to_pixels(cx.rem_size()),
 258                                &[cell_style],
 259                            )
 260                            .unwrap();
 261
 262                        cells.push(LayoutCell::new(
 263                            AlacPoint::new(line_index as i32, cell.point.column.0 as i32),
 264                            layout_cell,
 265                        ))
 266                    };
 267                }
 268            }
 269
 270            if cur_rect.is_some() {
 271                rects.push(cur_rect.take().unwrap());
 272            }
 273        }
 274        (cells, rects)
 275    }
 276
 277    // Compute the cursor position and expected block width, may return a zero width if x_for_index returns
 278    // the same position for sequential indexes. Use em_width instead
 279    fn shape_cursor(
 280        cursor_point: DisplayCursor,
 281        size: TerminalSize,
 282        text_fragment: &ShapedLine,
 283    ) -> Option<(Point<Pixels>, Pixels)> {
 284        if cursor_point.line() < size.total_lines() as i32 {
 285            let cursor_width = if text_fragment.width == Pixels::ZERO {
 286                size.cell_width()
 287            } else {
 288                text_fragment.width
 289            };
 290
 291            // Cursor should always surround as much of the text as possible,
 292            // hence when on pixel boundaries round the origin down and the width up
 293            Some((
 294                point(
 295                    (cursor_point.col() as f32 * size.cell_width()).floor(),
 296                    (cursor_point.line() as f32 * size.line_height()).floor(),
 297                ),
 298                cursor_width.ceil(),
 299            ))
 300        } else {
 301            None
 302        }
 303    }
 304
 305    /// Convert the Alacritty cell styles to GPUI text styles and background color
 306    fn cell_style(
 307        indexed: &IndexedCell,
 308        fg: terminal::alacritty_terminal::ansi::Color,
 309        // bg: terminal::alacritty_terminal::ansi::Color,
 310        colors: &Theme,
 311        text_style: &TextStyle,
 312        hyperlink: Option<(HighlightStyle, &RangeInclusive<AlacPoint>)>,
 313    ) -> TextRun {
 314        let flags = indexed.cell.flags;
 315        let fg = convert_color(&fg, &colors);
 316        // let bg = convert_color(&bg, &colors);
 317
 318        let underline = (flags.intersects(Flags::ALL_UNDERLINES)
 319            || indexed.cell.hyperlink().is_some())
 320        .then(|| UnderlineStyle {
 321            color: Some(fg),
 322            thickness: Pixels::from(1.0),
 323            wavy: flags.contains(Flags::UNDERCURL),
 324        });
 325
 326        let weight = if flags.intersects(Flags::BOLD | Flags::DIM_BOLD) {
 327            FontWeight::BOLD
 328        } else {
 329            FontWeight::NORMAL
 330        };
 331
 332        let style = if flags.intersects(Flags::ITALIC) {
 333            FontStyle::Italic
 334        } else {
 335            FontStyle::Normal
 336        };
 337
 338        let mut result = TextRun {
 339            len: indexed.c.len_utf8() as usize,
 340            color: fg,
 341            background_color: None,
 342            font: Font {
 343                weight,
 344                style,
 345                ..text_style.font()
 346            },
 347            underline,
 348        };
 349
 350        if let Some((style, range)) = hyperlink {
 351            if range.contains(&indexed.point) {
 352                if let Some(underline) = style.underline {
 353                    result.underline = Some(underline);
 354                }
 355
 356                if let Some(color) = style.color {
 357                    result.color = color;
 358                }
 359            }
 360        }
 361
 362        result
 363    }
 364
 365    fn compute_layout(&self, bounds: Bounds<gpui::Pixels>, cx: &mut WindowContext) -> LayoutState {
 366        let settings = ThemeSettings::get_global(cx).clone();
 367
 368        let buffer_font_size = settings.buffer_font_size(cx);
 369
 370        let terminal_settings = TerminalSettings::get_global(cx);
 371        let font_family = terminal_settings
 372            .font_family
 373            .as_ref()
 374            .map(|string| string.clone().into())
 375            .unwrap_or(settings.buffer_font.family);
 376
 377        let font_features = terminal_settings
 378            .font_features
 379            .clone()
 380            .unwrap_or(settings.buffer_font.features.clone());
 381
 382        let line_height = terminal_settings.line_height.value();
 383        let font_size = terminal_settings.font_size.clone();
 384
 385        let font_size =
 386            font_size.map_or(buffer_font_size, |size| theme::adjusted_font_size(size, cx));
 387
 388        let theme = cx.theme().clone();
 389
 390        let link_style = HighlightStyle {
 391            color: Some(theme.colors().link_text_hover),
 392            font_weight: None,
 393            font_style: None,
 394            background_color: None,
 395            underline: Some(UnderlineStyle {
 396                thickness: px(1.0),
 397                color: Some(theme.colors().link_text_hover),
 398                wavy: false,
 399            }),
 400            fade_out: None,
 401        };
 402
 403        let text_style = TextStyle {
 404            font_family,
 405            font_features,
 406            font_size: font_size.into(),
 407            font_style: FontStyle::Normal,
 408            line_height: line_height.into(),
 409            background_color: None,
 410            white_space: WhiteSpace::Normal,
 411            // These are going to be overridden per-cell
 412            underline: None,
 413            color: theme.colors().text,
 414            font_weight: FontWeight::NORMAL,
 415        };
 416
 417        let text_system = cx.text_system();
 418        let selection_color = theme.players().local();
 419        let match_color = theme.colors().search_match_background;
 420        let gutter;
 421        let dimensions = {
 422            let rem_size = cx.rem_size();
 423            let font_pixels = text_style.font_size.to_pixels(rem_size);
 424            let line_height = font_pixels * line_height.to_pixels(rem_size);
 425            let font_id = cx.text_system().resolve_font(&text_style.font());
 426
 427            let cell_width = text_system
 428                .advance(font_id, font_pixels, 'm')
 429                .unwrap()
 430                .width;
 431            gutter = cell_width;
 432
 433            let mut size = bounds.size.clone();
 434            size.width -= gutter;
 435
 436            TerminalSize::new(line_height, cell_width, size)
 437        };
 438
 439        let search_matches = self.terminal.read(cx).matches.clone();
 440
 441        let background_color = theme.colors().terminal_background;
 442
 443        let last_hovered_word = self.terminal.update(cx, |terminal, cx| {
 444            terminal.set_size(dimensions);
 445            terminal.try_sync(cx);
 446            if self.can_navigate_to_selected_word && terminal.can_navigate_to_selected_word() {
 447                terminal.last_content.last_hovered_word.clone()
 448            } else {
 449                None
 450            }
 451        });
 452
 453        let interactive_text_bounds = InteractiveBounds {
 454            bounds,
 455            stacking_order: cx.stacking_order().clone(),
 456        };
 457        if interactive_text_bounds.visibly_contains(&cx.mouse_position(), cx) {
 458            if self.can_navigate_to_selected_word && last_hovered_word.is_some() {
 459                cx.set_cursor_style(gpui::CursorStyle::PointingHand)
 460            } else {
 461                cx.set_cursor_style(gpui::CursorStyle::IBeam)
 462            }
 463        }
 464
 465        let hyperlink_tooltip = last_hovered_word.clone().map(|hovered_word| {
 466            div()
 467                .size_full()
 468                .id("terminal-element")
 469                .tooltip(move |cx| Tooltip::text(hovered_word.word.clone(), cx))
 470                .into_any_element()
 471        });
 472
 473        let TerminalContent {
 474            cells,
 475            mode,
 476            display_offset,
 477            cursor_char,
 478            selection,
 479            cursor,
 480            ..
 481        } = &self.terminal.read(cx).last_content;
 482
 483        // searches, highlights to a single range representations
 484        let mut relative_highlighted_ranges = Vec::new();
 485        for search_match in search_matches {
 486            relative_highlighted_ranges.push((search_match, match_color))
 487        }
 488        if let Some(selection) = selection {
 489            relative_highlighted_ranges
 490                .push((selection.start..=selection.end, selection_color.cursor));
 491        }
 492
 493        // then have that representation be converted to the appropriate highlight data structure
 494
 495        let (cells, rects) = TerminalElement::layout_grid(
 496            cells,
 497            &text_style,
 498            &cx.text_system(),
 499            last_hovered_word
 500                .as_ref()
 501                .map(|last_hovered_word| (link_style, &last_hovered_word.word_match)),
 502            cx,
 503        );
 504
 505        //Layout cursor. Rectangle is used for IME, so we should lay it out even
 506        //if we don't end up showing it.
 507        let cursor = if let AlacCursorShape::Hidden = cursor.shape {
 508            None
 509        } else {
 510            let cursor_point = DisplayCursor::from(cursor.point, *display_offset);
 511            let cursor_text = {
 512                let str_trxt = cursor_char.to_string();
 513                let len = str_trxt.len();
 514                cx.text_system()
 515                    .shape_line(
 516                        str_trxt.into(),
 517                        text_style.font_size.to_pixels(cx.rem_size()),
 518                        &[TextRun {
 519                            len,
 520                            font: text_style.font(),
 521                            color: theme.colors().terminal_background,
 522                            background_color: None,
 523                            underline: Default::default(),
 524                        }],
 525                    )
 526                    .unwrap()
 527            };
 528
 529            let focused = self.focused;
 530            TerminalElement::shape_cursor(cursor_point, dimensions, &cursor_text).map(
 531                move |(cursor_position, block_width)| {
 532                    let (shape, text) = match cursor.shape {
 533                        AlacCursorShape::Block if !focused => (CursorShape::Hollow, None),
 534                        AlacCursorShape::Block => (CursorShape::Block, Some(cursor_text)),
 535                        AlacCursorShape::Underline => (CursorShape::Underscore, None),
 536                        AlacCursorShape::Beam => (CursorShape::Bar, None),
 537                        AlacCursorShape::HollowBlock => (CursorShape::Hollow, None),
 538                        //This case is handled in the if wrapping the whole cursor layout
 539                        AlacCursorShape::Hidden => unreachable!(),
 540                    };
 541
 542                    Cursor::new(
 543                        cursor_position,
 544                        block_width,
 545                        dimensions.line_height,
 546                        theme.players().local().cursor,
 547                        shape,
 548                        text,
 549                    )
 550                },
 551            )
 552        };
 553
 554        //Done!
 555        LayoutState {
 556            cells,
 557            cursor,
 558            background_color,
 559            dimensions,
 560            rects,
 561            relative_highlighted_ranges,
 562            mode: *mode,
 563            display_offset: *display_offset,
 564            hyperlink_tooltip,
 565            gutter,
 566        }
 567    }
 568
 569    fn generic_button_handler<E>(
 570        connection: Model<Terminal>,
 571        origin: Point<Pixels>,
 572        focus_handle: FocusHandle,
 573        f: impl Fn(&mut Terminal, Point<Pixels>, &E, &mut ModelContext<Terminal>),
 574    ) -> impl Fn(&E, &mut WindowContext) {
 575        move |event, cx| {
 576            cx.focus(&focus_handle);
 577            connection.update(cx, |terminal, cx| {
 578                f(terminal, origin, event, cx);
 579
 580                cx.notify();
 581            })
 582        }
 583    }
 584
 585    fn register_key_listeners(&self, cx: &mut WindowContext) {
 586        cx.on_key_event({
 587            let this = self.terminal.clone();
 588            move |event: &ModifiersChangedEvent, phase, cx| {
 589                if phase != DispatchPhase::Bubble {
 590                    return;
 591                }
 592
 593                let handled =
 594                    this.update(cx, |term, _| term.try_modifiers_change(&event.modifiers));
 595
 596                if handled {
 597                    cx.notify();
 598                }
 599            }
 600        });
 601    }
 602
 603    fn register_mouse_listeners(
 604        &mut self,
 605        origin: Point<Pixels>,
 606        mode: TermMode,
 607        bounds: Bounds<Pixels>,
 608        cx: &mut WindowContext,
 609    ) {
 610        let focus = self.focus.clone();
 611        let terminal = self.terminal.clone();
 612        let interactive_bounds = InteractiveBounds {
 613            bounds: bounds.intersect(&cx.content_mask().bounds),
 614            stacking_order: cx.stacking_order().clone(),
 615        };
 616
 617        self.interactivity.on_mouse_down(MouseButton::Left, {
 618            let terminal = terminal.clone();
 619            let focus = focus.clone();
 620            move |e, cx| {
 621                cx.focus(&focus);
 622                terminal.update(cx, |terminal, cx| {
 623                    terminal.mouse_down(&e, origin);
 624                    cx.notify();
 625                })
 626            }
 627        });
 628
 629        cx.on_mouse_event({
 630            let bounds = bounds.clone();
 631            let focus = self.focus.clone();
 632            let terminal = self.terminal.clone();
 633            move |e: &MouseMoveEvent, phase, cx| {
 634                if phase != DispatchPhase::Bubble || !focus.is_focused(cx) {
 635                    return;
 636                }
 637
 638                if e.pressed_button.is_some() && !cx.has_active_drag() {
 639                    terminal.update(cx, |terminal, cx| {
 640                        terminal.mouse_drag(e, origin, bounds);
 641                        cx.notify();
 642                    })
 643                }
 644
 645                if interactive_bounds.visibly_contains(&e.position, cx) {
 646                    terminal.update(cx, |terminal, cx| {
 647                        terminal.mouse_move(&e, origin);
 648                        cx.notify();
 649                    })
 650                }
 651            }
 652        });
 653
 654        self.interactivity.on_mouse_up(
 655            MouseButton::Left,
 656            TerminalElement::generic_button_handler(
 657                terminal.clone(),
 658                origin,
 659                focus.clone(),
 660                move |terminal, origin, e, cx| {
 661                    terminal.mouse_up(&e, origin, cx);
 662                },
 663            ),
 664        );
 665        self.interactivity.on_scroll_wheel({
 666            let terminal = terminal.clone();
 667            move |e, cx| {
 668                terminal.update(cx, |terminal, cx| {
 669                    terminal.scroll_wheel(e, origin);
 670                    cx.notify();
 671                })
 672            }
 673        });
 674
 675        // Mouse mode handlers:
 676        // All mouse modes need the extra click handlers
 677        if mode.intersects(TermMode::MOUSE_MODE) {
 678            self.interactivity.on_mouse_down(
 679                MouseButton::Right,
 680                TerminalElement::generic_button_handler(
 681                    terminal.clone(),
 682                    origin,
 683                    focus.clone(),
 684                    move |terminal, origin, e, _cx| {
 685                        terminal.mouse_down(&e, origin);
 686                    },
 687                ),
 688            );
 689            self.interactivity.on_mouse_down(
 690                MouseButton::Middle,
 691                TerminalElement::generic_button_handler(
 692                    terminal.clone(),
 693                    origin,
 694                    focus.clone(),
 695                    move |terminal, origin, e, _cx| {
 696                        terminal.mouse_down(&e, origin);
 697                    },
 698                ),
 699            );
 700            self.interactivity.on_mouse_up(
 701                MouseButton::Right,
 702                TerminalElement::generic_button_handler(
 703                    terminal.clone(),
 704                    origin,
 705                    focus.clone(),
 706                    move |terminal, origin, e, cx| {
 707                        terminal.mouse_up(&e, origin, cx);
 708                    },
 709                ),
 710            );
 711            self.interactivity.on_mouse_up(
 712                MouseButton::Middle,
 713                TerminalElement::generic_button_handler(
 714                    terminal,
 715                    origin,
 716                    focus,
 717                    move |terminal, origin, e, cx| {
 718                        terminal.mouse_up(&e, origin, cx);
 719                    },
 720                ),
 721            );
 722        }
 723    }
 724}
 725
 726impl Element for TerminalElement {
 727    type State = InteractiveElementState;
 728
 729    fn request_layout(
 730        &mut self,
 731        element_state: Option<Self::State>,
 732        cx: &mut WindowContext<'_>,
 733    ) -> (LayoutId, Self::State) {
 734        let (layout_id, interactive_state) =
 735            self.interactivity
 736                .layout(element_state, cx, |mut style, cx| {
 737                    style.size.width = relative(1.).into();
 738                    style.size.height = relative(1.).into();
 739                    let layout_id = cx.request_layout(&style, None);
 740
 741                    layout_id
 742                });
 743
 744        (layout_id, interactive_state)
 745    }
 746
 747    fn paint(
 748        &mut self,
 749        bounds: Bounds<Pixels>,
 750        state: &mut Self::State,
 751        cx: &mut WindowContext<'_>,
 752    ) {
 753        let mut layout = self.compute_layout(bounds, cx);
 754
 755        cx.paint_quad(fill(bounds, layout.background_color));
 756        let origin = bounds.origin + Point::new(layout.gutter, px(0.));
 757
 758        let terminal_input_handler = TerminalInputHandler {
 759            cx: cx.to_async(),
 760            terminal: self.terminal.clone(),
 761            cursor_bounds: layout
 762                .cursor
 763                .as_ref()
 764                .map(|cursor| cursor.bounding_rect(origin)),
 765        };
 766
 767        self.register_mouse_listeners(origin, layout.mode, bounds, cx);
 768
 769        let mut interactivity = mem::take(&mut self.interactivity);
 770        interactivity.paint(bounds, bounds.size, state, cx, |_, _, cx| {
 771            cx.handle_input(&self.focus, terminal_input_handler);
 772
 773            self.register_key_listeners(cx);
 774
 775            for rect in &layout.rects {
 776                rect.paint(origin, &layout, cx);
 777            }
 778
 779            cx.with_z_index(1, |cx| {
 780                for (relative_highlighted_range, color) in layout.relative_highlighted_ranges.iter()
 781                {
 782                    if let Some((start_y, highlighted_range_lines)) =
 783                        to_highlighted_range_lines(relative_highlighted_range, &layout, origin)
 784                    {
 785                        let hr = HighlightedRange {
 786                            start_y, //Need to change this
 787                            line_height: layout.dimensions.line_height,
 788                            lines: highlighted_range_lines,
 789                            color: color.clone(),
 790                            //Copied from editor. TODO: move to theme or something
 791                            corner_radius: 0.15 * layout.dimensions.line_height,
 792                        };
 793                        hr.paint(bounds, cx);
 794                    }
 795                }
 796            });
 797
 798            cx.with_z_index(2, |cx| {
 799                for cell in &layout.cells {
 800                    cell.paint(origin, &layout, bounds, cx);
 801                }
 802            });
 803
 804            if self.cursor_visible {
 805                cx.with_z_index(3, |cx| {
 806                    if let Some(cursor) = &layout.cursor {
 807                        cursor.paint(origin, cx);
 808                    }
 809                });
 810            }
 811
 812            if let Some(mut element) = layout.hyperlink_tooltip.take() {
 813                element.draw(origin, bounds.size.map(AvailableSpace::Definite), cx)
 814            }
 815        });
 816    }
 817}
 818
 819impl IntoElement for TerminalElement {
 820    type Element = Self;
 821
 822    fn element_id(&self) -> Option<ElementId> {
 823        Some("terminal".into())
 824    }
 825
 826    fn into_element(self) -> Self::Element {
 827        self
 828    }
 829}
 830
 831struct TerminalInputHandler {
 832    cx: AsyncWindowContext,
 833    terminal: Model<Terminal>,
 834    cursor_bounds: Option<Bounds<Pixels>>,
 835}
 836
 837impl PlatformInputHandler for TerminalInputHandler {
 838    fn selected_text_range(&mut self) -> Option<std::ops::Range<usize>> {
 839        self.cx
 840            .update(|_, cx| {
 841                if self
 842                    .terminal
 843                    .read(cx)
 844                    .last_content
 845                    .mode
 846                    .contains(TermMode::ALT_SCREEN)
 847                {
 848                    None
 849                } else {
 850                    Some(0..0)
 851                }
 852            })
 853            .ok()
 854            .flatten()
 855    }
 856
 857    fn marked_text_range(&mut self) -> Option<std::ops::Range<usize>> {
 858        None
 859    }
 860
 861    fn text_for_range(&mut self, _: std::ops::Range<usize>) -> Option<String> {
 862        None
 863    }
 864
 865    fn replace_text_in_range(
 866        &mut self,
 867        _replacement_range: Option<std::ops::Range<usize>>,
 868        text: &str,
 869    ) {
 870        self.cx
 871            .update(|_, cx| {
 872                self.terminal.update(cx, |terminal, _| {
 873                    terminal.input(text.into());
 874                })
 875            })
 876            .ok();
 877    }
 878
 879    fn replace_and_mark_text_in_range(
 880        &mut self,
 881        _range_utf16: Option<std::ops::Range<usize>>,
 882        _new_text: &str,
 883        _new_selected_range: Option<std::ops::Range<usize>>,
 884    ) {
 885    }
 886
 887    fn unmark_text(&mut self) {}
 888
 889    fn bounds_for_range(&mut self, _range_utf16: std::ops::Range<usize>) -> Option<Bounds<Pixels>> {
 890        self.cursor_bounds
 891    }
 892}
 893
 894fn is_blank(cell: &IndexedCell) -> bool {
 895    if cell.c != ' ' {
 896        return false;
 897    }
 898
 899    if cell.bg != AnsiColor::Named(NamedColor::Background) {
 900        return false;
 901    }
 902
 903    if cell.hyperlink().is_some() {
 904        return false;
 905    }
 906
 907    if cell
 908        .flags
 909        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
 910    {
 911        return false;
 912    }
 913
 914    return true;
 915}
 916
 917fn to_highlighted_range_lines(
 918    range: &RangeInclusive<AlacPoint>,
 919    layout: &LayoutState,
 920    origin: Point<Pixels>,
 921) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
 922    // Step 1. Normalize the points to be viewport relative.
 923    // When display_offset = 1, here's how the grid is arranged:
 924    //-2,0 -2,1...
 925    //--- Viewport top
 926    //-1,0 -1,1...
 927    //--------- Terminal Top
 928    // 0,0  0,1...
 929    // 1,0  1,1...
 930    //--- Viewport Bottom
 931    // 2,0  2,1...
 932    //--------- Terminal Bottom
 933
 934    // Normalize to viewport relative, from terminal relative.
 935    // lines are i32s, which are negative above the top left corner of the terminal
 936    // If the user has scrolled, we use the display_offset to tell us which offset
 937    // of the grid data we should be looking at. But for the rendering step, we don't
 938    // want negatives. We want things relative to the 'viewport' (the area of the grid
 939    // which is currently shown according to the display offset)
 940    let unclamped_start = AlacPoint::new(
 941        range.start().line + layout.display_offset,
 942        range.start().column,
 943    );
 944    let unclamped_end =
 945        AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
 946
 947    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
 948    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.dimensions.num_lines() as i32 {
 949        return None;
 950    }
 951
 952    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
 953    let clamped_end_line = unclamped_end
 954        .line
 955        .0
 956        .min(layout.dimensions.num_lines() as i32) as usize;
 957    //Convert the start of the range to pixels
 958    let start_y = origin.y + clamped_start_line as f32 * layout.dimensions.line_height;
 959
 960    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
 961    //  (also convert to pixels)
 962    let mut highlighted_range_lines = Vec::new();
 963    for line in clamped_start_line..=clamped_end_line {
 964        let mut line_start = 0;
 965        let mut line_end = layout.dimensions.columns();
 966
 967        if line == clamped_start_line {
 968            line_start = unclamped_start.column.0 as usize;
 969        }
 970        if line == clamped_end_line {
 971            line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
 972        }
 973
 974        highlighted_range_lines.push(HighlightedRangeLine {
 975            start_x: origin.x + line_start as f32 * layout.dimensions.cell_width,
 976            end_x: origin.x + line_end as f32 * layout.dimensions.cell_width,
 977        });
 978    }
 979
 980    Some((start_y, highlighted_range_lines))
 981}
 982
 983///Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent
 984fn convert_color(fg: &terminal::alacritty_terminal::ansi::Color, theme: &Theme) -> Hsla {
 985    let colors = theme.colors();
 986    match fg {
 987        //Named and theme defined colors
 988        terminal::alacritty_terminal::ansi::Color::Named(n) => match n {
 989            NamedColor::Black => colors.terminal_ansi_black,
 990            NamedColor::Red => colors.terminal_ansi_red,
 991            NamedColor::Green => colors.terminal_ansi_green,
 992            NamedColor::Yellow => colors.terminal_ansi_yellow,
 993            NamedColor::Blue => colors.terminal_ansi_blue,
 994            NamedColor::Magenta => colors.terminal_ansi_magenta,
 995            NamedColor::Cyan => colors.terminal_ansi_cyan,
 996            NamedColor::White => colors.terminal_ansi_white,
 997            NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
 998            NamedColor::BrightRed => colors.terminal_ansi_bright_red,
 999            NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1000            NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1001            NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1002            NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1003            NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1004            NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1005            NamedColor::Foreground => colors.text,
1006            NamedColor::Background => colors.background,
1007            NamedColor::Cursor => theme.players().local().cursor,
1008
1009            // todo!(more colors)
1010            NamedColor::DimBlack => red(),
1011            NamedColor::DimRed => red(),
1012            NamedColor::DimGreen => red(),
1013            NamedColor::DimYellow => red(),
1014            NamedColor::DimBlue => red(),
1015            NamedColor::DimMagenta => red(),
1016            NamedColor::DimCyan => red(),
1017            NamedColor::DimWhite => red(),
1018            NamedColor::BrightForeground => red(),
1019            NamedColor::DimForeground => red(),
1020        },
1021        //'True' colors
1022        terminal::alacritty_terminal::ansi::Color::Spec(rgb) => {
1023            terminal::rgba_color(rgb.r, rgb.g, rgb.b)
1024        }
1025        //8 bit, indexed colors
1026        terminal::alacritty_terminal::ansi::Color::Indexed(i) => {
1027            terminal::get_color_at_index(*i as usize, theme)
1028        }
1029    }
1030}