terminal_element.rs

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