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