terminal_element.rs

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