terminal_element.rs

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