terminal_element.rs

   1use editor::{Cursor, HighlightedRange, HighlightedRangeLine};
   2use gpui::{
   3    black, div, fill, point, px, red, relative, AnyElement, AsyncWindowContext, AvailableSpace,
   4    BorrowWindow, Bounds, DispatchPhase, Element, ElementId, ExternalPaths, FocusHandle, Font,
   5    FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveElement, InteractiveElementState,
   6    Interactivity, IntoElement, LayoutId, Model, ModelContext, ModifiersChangedEvent, MouseButton,
   7    Pixels, PlatformInputHandler, Point, Rgba, ShapedLine, Size, StatefulInteractiveElement,
   8    Styled, 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: Interactivity,
 149}
 150
 151impl InteractiveElement for TerminalElement {
 152    fn interactivity(&mut self) -> &mut 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(theme.colors().link_text_hover),
 399            font_weight: None,
 400            font_style: None,
 401            background_color: None,
 402            underline: Some(UnderlineStyle {
 403                thickness: px(1.0),
 404                color: Some(theme.colors().link_text_hover),
 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        &mut self,
 609        origin: Point<Pixels>,
 610        mode: TermMode,
 611        bounds: Bounds<Pixels>,
 612        cx: &mut WindowContext,
 613    ) {
 614        let focus = self.focus.clone();
 615        let terminal = self.terminal.clone();
 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                //todo!(context menu)
 623                // v.context_menu.update(cx, |menu, _cx| menu.delay_cancel());
 624                terminal.update(cx, |terminal, cx| {
 625                    terminal.mouse_down(&e, origin);
 626
 627                    cx.notify();
 628                })
 629            }
 630        });
 631        self.interactivity.on_mouse_move({
 632            let terminal = terminal.clone();
 633            let focus = focus.clone();
 634            move |e, cx| {
 635                if e.pressed_button.is_some() && focus.is_focused(cx) && !cx.has_active_drag() {
 636                    terminal.update(cx, |terminal, cx| {
 637                        terminal.mouse_drag(e, origin, bounds);
 638                        cx.notify();
 639                    })
 640                }
 641            }
 642        });
 643        self.interactivity.on_mouse_up(
 644            MouseButton::Left,
 645            TerminalElement::generic_button_handler(
 646                terminal.clone(),
 647                origin,
 648                focus.clone(),
 649                move |terminal, origin, e, cx| {
 650                    terminal.mouse_up(&e, origin, cx);
 651                },
 652            ),
 653        );
 654        self.interactivity.on_click({
 655            let terminal = terminal.clone();
 656            move |e, cx| {
 657                if e.down.button == MouseButton::Right {
 658                    let mouse_mode = terminal.update(cx, |terminal, _cx| {
 659                        terminal.mouse_mode(e.down.modifiers.shift)
 660                    });
 661
 662                    if !mouse_mode {
 663                        //todo!(context menu)
 664                        // view.deploy_context_menu(e.position, cx);
 665                    }
 666                }
 667            }
 668        });
 669
 670        self.interactivity.on_mouse_move({
 671            let terminal = terminal.clone();
 672            let focus = focus.clone();
 673            move |e, cx| {
 674                if focus.is_focused(cx) {
 675                    terminal.update(cx, |terminal, cx| {
 676                        terminal.mouse_move(&e, origin);
 677                        cx.notify();
 678                    })
 679                }
 680            }
 681        });
 682        self.interactivity.on_scroll_wheel({
 683            let terminal = terminal.clone();
 684            move |e, cx| {
 685                terminal.update(cx, |terminal, cx| {
 686                    terminal.scroll_wheel(e, origin);
 687                    cx.notify();
 688                })
 689            }
 690        });
 691
 692        self.interactivity.on_drop::<ExternalPaths>({
 693            let focus = focus.clone();
 694            let terminal = terminal.clone();
 695            move |external_paths, cx| {
 696                cx.focus(&focus);
 697                let mut new_text = external_paths
 698                    .paths()
 699                    .iter()
 700                    .map(|path| format!(" {path:?}"))
 701                    .join("");
 702                new_text.push(' ');
 703                terminal.update(cx, |terminal, _| {
 704                    // todo!() long paths are not displayed properly albeit the text is there
 705                    terminal.paste(&new_text);
 706                });
 707            }
 708        });
 709
 710        // Mouse mode handlers:
 711        // All mouse modes need the extra click handlers
 712        if mode.intersects(TermMode::MOUSE_MODE) {
 713            self.interactivity.on_mouse_down(
 714                MouseButton::Right,
 715                TerminalElement::generic_button_handler(
 716                    terminal.clone(),
 717                    origin,
 718                    focus.clone(),
 719                    move |terminal, origin, e, _cx| {
 720                        terminal.mouse_down(&e, origin);
 721                    },
 722                ),
 723            );
 724            self.interactivity.on_mouse_down(
 725                MouseButton::Middle,
 726                TerminalElement::generic_button_handler(
 727                    terminal.clone(),
 728                    origin,
 729                    focus.clone(),
 730                    move |terminal, origin, e, _cx| {
 731                        terminal.mouse_down(&e, origin);
 732                    },
 733                ),
 734            );
 735            self.interactivity.on_mouse_up(
 736                MouseButton::Right,
 737                TerminalElement::generic_button_handler(
 738                    terminal.clone(),
 739                    origin,
 740                    focus.clone(),
 741                    move |terminal, origin, e, cx| {
 742                        terminal.mouse_up(&e, origin, cx);
 743                    },
 744                ),
 745            );
 746            self.interactivity.on_mouse_up(
 747                MouseButton::Middle,
 748                TerminalElement::generic_button_handler(
 749                    terminal,
 750                    origin,
 751                    focus,
 752                    move |terminal, origin, e, cx| {
 753                        terminal.mouse_up(&e, origin, cx);
 754                    },
 755                ),
 756            );
 757        }
 758    }
 759}
 760
 761impl Element for TerminalElement {
 762    type State = InteractiveElementState;
 763
 764    fn layout(
 765        &mut self,
 766        element_state: Option<Self::State>,
 767        cx: &mut WindowContext<'_>,
 768    ) -> (LayoutId, Self::State) {
 769        let (layout_id, interactive_state) =
 770            self.interactivity
 771                .layout(element_state, cx, |mut style, cx| {
 772                    style.size.width = relative(1.).into();
 773                    style.size.height = relative(1.).into();
 774                    let layout_id = cx.request_layout(&style, None);
 775
 776                    layout_id
 777                });
 778
 779        (layout_id, interactive_state)
 780    }
 781
 782    fn paint(
 783        &mut self,
 784        bounds: Bounds<Pixels>,
 785        state: &mut Self::State,
 786        cx: &mut WindowContext<'_>,
 787    ) {
 788        let mut layout = self.compute_layout(bounds, cx);
 789
 790        let theme = cx.theme();
 791
 792        cx.paint_quad(fill(bounds, layout.background_color));
 793        let origin = bounds.origin + Point::new(layout.gutter, px(0.));
 794
 795        let terminal_input_handler = TerminalInputHandler {
 796            cx: cx.to_async(),
 797            terminal: self.terminal.clone(),
 798            cursor_bounds: layout
 799                .cursor
 800                .as_ref()
 801                .map(|cursor| cursor.bounding_rect(origin)),
 802        };
 803
 804        let terminal_focus_handle = self.focus.clone();
 805        let terminal_handle = self.terminal.clone();
 806        self.register_mouse_listeners(origin, layout.mode, bounds, cx);
 807
 808        // todo!(change this to work in terms of on_drag_move or some such)
 809        // .drag_over::<ExternalPaths>(|style| {
 810        //     // todo!() why does not it work? z-index of elements?
 811        //     style.bg(cx.theme().colors().ghost_element_hover)
 812        // })
 813
 814        let mut interactivity = mem::take(&mut self.interactivity);
 815        interactivity.paint(bounds, bounds.size, state, cx, |_, _, cx| {
 816            cx.handle_input(&self.focus, terminal_input_handler);
 817
 818            self.register_key_listeners(cx);
 819
 820            for rect in &layout.rects {
 821                rect.paint(origin, &layout, cx);
 822            }
 823
 824            cx.with_z_index(1, |cx| {
 825                for (relative_highlighted_range, color) in layout.relative_highlighted_ranges.iter()
 826                {
 827                    if let Some((start_y, highlighted_range_lines)) =
 828                        to_highlighted_range_lines(relative_highlighted_range, &layout, origin)
 829                    {
 830                        let hr = HighlightedRange {
 831                            start_y, //Need to change this
 832                            line_height: layout.size.line_height,
 833                            lines: highlighted_range_lines,
 834                            color: color.clone(),
 835                            //Copied from editor. TODO: move to theme or something
 836                            corner_radius: 0.15 * layout.size.line_height,
 837                        };
 838                        hr.paint(bounds, cx);
 839                    }
 840                }
 841            });
 842
 843            cx.with_z_index(2, |cx| {
 844                for cell in &layout.cells {
 845                    cell.paint(origin, &layout, bounds, cx);
 846                }
 847            });
 848
 849            if self.cursor_visible {
 850                cx.with_z_index(3, |cx| {
 851                    if let Some(cursor) = &layout.cursor {
 852                        cursor.paint(origin, cx);
 853                    }
 854                });
 855            }
 856
 857            if let Some(mut element) = layout.hyperlink_tooltip.take() {
 858                let width: AvailableSpace = bounds.size.width.into();
 859                let height: AvailableSpace = bounds.size.height.into();
 860                element.draw(origin, Size { width, height }, cx)
 861            }
 862        });
 863    }
 864}
 865
 866impl IntoElement for TerminalElement {
 867    type Element = Self;
 868
 869    fn element_id(&self) -> Option<ElementId> {
 870        Some("terminal".into())
 871    }
 872
 873    fn into_element(self) -> Self::Element {
 874        self
 875    }
 876}
 877
 878struct TerminalInputHandler {
 879    cx: AsyncWindowContext,
 880    terminal: Model<Terminal>,
 881    cursor_bounds: Option<Bounds<Pixels>>,
 882}
 883
 884impl PlatformInputHandler for TerminalInputHandler {
 885    fn selected_text_range(&mut self) -> Option<std::ops::Range<usize>> {
 886        self.cx
 887            .update(|_, cx| {
 888                if self
 889                    .terminal
 890                    .read(cx)
 891                    .last_content
 892                    .mode
 893                    .contains(TermMode::ALT_SCREEN)
 894                {
 895                    None
 896                } else {
 897                    Some(0..0)
 898                }
 899            })
 900            .ok()
 901            .flatten()
 902    }
 903
 904    fn marked_text_range(&mut self) -> Option<std::ops::Range<usize>> {
 905        None
 906    }
 907
 908    fn text_for_range(&mut self, range_utf16: std::ops::Range<usize>) -> Option<String> {
 909        None
 910    }
 911
 912    fn replace_text_in_range(
 913        &mut self,
 914        _replacement_range: Option<std::ops::Range<usize>>,
 915        text: &str,
 916    ) {
 917        self.cx
 918            .update(|_, cx| {
 919                self.terminal.update(cx, |terminal, _| {
 920                    terminal.input(text.into());
 921                })
 922            })
 923            .ok();
 924    }
 925
 926    fn replace_and_mark_text_in_range(
 927        &mut self,
 928        _range_utf16: Option<std::ops::Range<usize>>,
 929        _new_text: &str,
 930        _new_selected_range: Option<std::ops::Range<usize>>,
 931    ) {
 932    }
 933
 934    fn unmark_text(&mut self) {}
 935
 936    fn bounds_for_range(&mut self, _range_utf16: std::ops::Range<usize>) -> Option<Bounds<Pixels>> {
 937        self.cursor_bounds
 938    }
 939}
 940
 941fn is_blank(cell: &IndexedCell) -> bool {
 942    if cell.c != ' ' {
 943        return false;
 944    }
 945
 946    if cell.bg != AnsiColor::Named(NamedColor::Background) {
 947        return false;
 948    }
 949
 950    if cell.hyperlink().is_some() {
 951        return false;
 952    }
 953
 954    if cell
 955        .flags
 956        .intersects(Flags::ALL_UNDERLINES | Flags::INVERSE | Flags::STRIKEOUT)
 957    {
 958        return false;
 959    }
 960
 961    return true;
 962}
 963
 964fn to_highlighted_range_lines(
 965    range: &RangeInclusive<AlacPoint>,
 966    layout: &LayoutState,
 967    origin: Point<Pixels>,
 968) -> Option<(Pixels, Vec<HighlightedRangeLine>)> {
 969    // Step 1. Normalize the points to be viewport relative.
 970    // When display_offset = 1, here's how the grid is arranged:
 971    //-2,0 -2,1...
 972    //--- Viewport top
 973    //-1,0 -1,1...
 974    //--------- Terminal Top
 975    // 0,0  0,1...
 976    // 1,0  1,1...
 977    //--- Viewport Bottom
 978    // 2,0  2,1...
 979    //--------- Terminal Bottom
 980
 981    // Normalize to viewport relative, from terminal relative.
 982    // lines are i32s, which are negative above the top left corner of the terminal
 983    // If the user has scrolled, we use the display_offset to tell us which offset
 984    // of the grid data we should be looking at. But for the rendering step, we don't
 985    // want negatives. We want things relative to the 'viewport' (the area of the grid
 986    // which is currently shown according to the display offset)
 987    let unclamped_start = AlacPoint::new(
 988        range.start().line + layout.display_offset,
 989        range.start().column,
 990    );
 991    let unclamped_end =
 992        AlacPoint::new(range.end().line + layout.display_offset, range.end().column);
 993
 994    // Step 2. Clamp range to viewport, and return None if it doesn't overlap
 995    if unclamped_end.line.0 < 0 || unclamped_start.line.0 > layout.size.num_lines() as i32 {
 996        return None;
 997    }
 998
 999    let clamped_start_line = unclamped_start.line.0.max(0) as usize;
1000    let clamped_end_line = unclamped_end.line.0.min(layout.size.num_lines() as i32) as usize;
1001    //Convert the start of the range to pixels
1002    let start_y = origin.y + clamped_start_line as f32 * layout.size.line_height;
1003
1004    // Step 3. Expand ranges that cross lines into a collection of single-line ranges.
1005    //  (also convert to pixels)
1006    let mut highlighted_range_lines = Vec::new();
1007    for line in clamped_start_line..=clamped_end_line {
1008        let mut line_start = 0;
1009        let mut line_end = layout.size.columns();
1010
1011        if line == clamped_start_line {
1012            line_start = unclamped_start.column.0 as usize;
1013        }
1014        if line == clamped_end_line {
1015            line_end = unclamped_end.column.0 as usize + 1; //+1 for inclusive
1016        }
1017
1018        highlighted_range_lines.push(HighlightedRangeLine {
1019            start_x: origin.x + line_start as f32 * layout.size.cell_width,
1020            end_x: origin.x + line_end as f32 * layout.size.cell_width,
1021        });
1022    }
1023
1024    Some((start_y, highlighted_range_lines))
1025}
1026
1027///Converts a 2, 8, or 24 bit color ANSI color to the GPUI equivalent
1028fn convert_color(fg: &terminal::alacritty_terminal::ansi::Color, theme: &Theme) -> Hsla {
1029    let colors = theme.colors();
1030    match fg {
1031        //Named and theme defined colors
1032        terminal::alacritty_terminal::ansi::Color::Named(n) => match n {
1033            NamedColor::Black => colors.terminal_ansi_black,
1034            NamedColor::Red => colors.terminal_ansi_red,
1035            NamedColor::Green => colors.terminal_ansi_green,
1036            NamedColor::Yellow => colors.terminal_ansi_yellow,
1037            NamedColor::Blue => colors.terminal_ansi_blue,
1038            NamedColor::Magenta => colors.terminal_ansi_magenta,
1039            NamedColor::Cyan => colors.terminal_ansi_cyan,
1040            NamedColor::White => colors.terminal_ansi_white,
1041            NamedColor::BrightBlack => colors.terminal_ansi_bright_black,
1042            NamedColor::BrightRed => colors.terminal_ansi_bright_red,
1043            NamedColor::BrightGreen => colors.terminal_ansi_bright_green,
1044            NamedColor::BrightYellow => colors.terminal_ansi_bright_yellow,
1045            NamedColor::BrightBlue => colors.terminal_ansi_bright_blue,
1046            NamedColor::BrightMagenta => colors.terminal_ansi_bright_magenta,
1047            NamedColor::BrightCyan => colors.terminal_ansi_bright_cyan,
1048            NamedColor::BrightWhite => colors.terminal_ansi_bright_white,
1049            NamedColor::Foreground => colors.text,
1050            NamedColor::Background => colors.background,
1051            NamedColor::Cursor => theme.players().local().cursor,
1052
1053            // todo!(more colors)
1054            NamedColor::DimBlack => red(),
1055            NamedColor::DimRed => red(),
1056            NamedColor::DimGreen => red(),
1057            NamedColor::DimYellow => red(),
1058            NamedColor::DimBlue => red(),
1059            NamedColor::DimMagenta => red(),
1060            NamedColor::DimCyan => red(),
1061            NamedColor::DimWhite => red(),
1062            NamedColor::BrightForeground => red(),
1063            NamedColor::DimForeground => red(),
1064        },
1065        //'True' colors
1066        terminal::alacritty_terminal::ansi::Color::Spec(rgb) => rgba_color(rgb.r, rgb.g, rgb.b),
1067        //8 bit, indexed colors
1068        terminal::alacritty_terminal::ansi::Color::Indexed(i) => {
1069            get_color_at_index(&(*i as usize), theme)
1070        }
1071    }
1072}
1073
1074///Converts an 8 bit ANSI color to it's GPUI equivalent.
1075///Accepts usize for compatibility with the alacritty::Colors interface,
1076///Other than that use case, should only be called with values in the [0,255] range
1077pub fn get_color_at_index(index: &usize, theme: &Theme) -> Hsla {
1078    let colors = theme.colors();
1079
1080    match index {
1081        //0-15 are the same as the named colors above
1082        0 => colors.terminal_ansi_black,
1083        1 => colors.terminal_ansi_red,
1084        2 => colors.terminal_ansi_green,
1085        3 => colors.terminal_ansi_yellow,
1086        4 => colors.terminal_ansi_blue,
1087        5 => colors.terminal_ansi_magenta,
1088        6 => colors.terminal_ansi_cyan,
1089        7 => colors.terminal_ansi_white,
1090        8 => colors.terminal_ansi_bright_black,
1091        9 => colors.terminal_ansi_bright_red,
1092        10 => colors.terminal_ansi_bright_green,
1093        11 => colors.terminal_ansi_bright_yellow,
1094        12 => colors.terminal_ansi_bright_blue,
1095        13 => colors.terminal_ansi_bright_magenta,
1096        14 => colors.terminal_ansi_bright_cyan,
1097        15 => colors.terminal_ansi_bright_white,
1098        //16-231 are mapped to their RGB colors on a 0-5 range per channel
1099        16..=231 => {
1100            let (r, g, b) = rgb_for_index(&(*index as u8)); //Split the index into it's ANSI-RGB components
1101            let step = (u8::MAX as f32 / 5.).floor() as u8; //Split the RGB range into 5 chunks, with floor so no overflow
1102            rgba_color(r * step, g * step, b * step) //Map the ANSI-RGB components to an RGB color
1103        }
1104        //232-255 are a 24 step grayscale from black to white
1105        232..=255 => {
1106            let i = *index as u8 - 232; //Align index to 0..24
1107            let step = (u8::MAX as f32 / 24.).floor() as u8; //Split the RGB grayscale values into 24 chunks
1108            rgba_color(i * step, i * step, i * step) //Map the ANSI-grayscale components to the RGB-grayscale
1109        }
1110        //For compatibility with the alacritty::Colors interface
1111        256 => colors.text,
1112        257 => colors.background,
1113        258 => theme.players().local().cursor,
1114
1115        // todo!(more colors)
1116        259 => red(),                      //style.dim_black,
1117        260 => red(),                      //style.dim_red,
1118        261 => red(),                      //style.dim_green,
1119        262 => red(),                      //style.dim_yellow,
1120        263 => red(),                      //style.dim_blue,
1121        264 => red(),                      //style.dim_magenta,
1122        265 => red(),                      //style.dim_cyan,
1123        266 => red(),                      //style.dim_white,
1124        267 => red(),                      //style.bright_foreground,
1125        268 => colors.terminal_ansi_black, //'Dim Background', non-standard color
1126
1127        _ => black(),
1128    }
1129}
1130
1131///Generates the rgb channels in [0, 5] for a given index into the 6x6x6 ANSI color cube
1132///See: [8 bit ansi color](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit).
1133///
1134///Wikipedia gives a formula for calculating the index for a given color:
1135///
1136///index = 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
1137///
1138///This function does the reverse, calculating the r, g, and b components from a given index.
1139fn rgb_for_index(i: &u8) -> (u8, u8, u8) {
1140    debug_assert!((&16..=&231).contains(&i));
1141    let i = i - 16;
1142    let r = (i - (i % 36)) / 36;
1143    let g = ((i % 36) - (i % 6)) / 6;
1144    let b = (i % 36) % 6;
1145    (r, g, b)
1146}
1147
1148fn rgba_color(r: u8, g: u8, b: u8) -> Hsla {
1149    Rgba {
1150        r: (r as f32 / 255.) as f32,
1151        g: (g as f32 / 255.) as f32,
1152        b: (b as f32 / 255.) as f32,
1153        a: 1.,
1154    }
1155    .into()
1156}
1157
1158#[cfg(test)]
1159mod tests {
1160    use crate::terminal_element::rgb_for_index;
1161
1162    #[test]
1163    fn test_rgb_for_index() {
1164        //Test every possible value in the color cube
1165        for i in 16..=231 {
1166            let (r, g, b) = rgb_for_index(&(i as u8));
1167            assert_eq!(i, 16 + 36 * r + 6 * g + b);
1168        }
1169    }
1170}