element.rs

   1use super::{
   2    display_map::{BlockContext, ToDisplayPoint},
   3    Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Scroll, Select, SelectPhase,
   4    SoftWrap, ToPoint, MAX_LINE_LEN,
   5};
   6use crate::{
   7    display_map::{BlockStyle, DisplaySnapshot, TransformBlock},
   8    hover_popover::HoverAt,
   9    link_go_to_definition::{
  10        CmdShiftChanged, GoToFetchedDefinition, GoToFetchedTypeDefinition, UpdateGoToDefinitionLink,
  11    },
  12    mouse_context_menu::DeployMouseContextMenu,
  13    EditorStyle,
  14};
  15use clock::ReplicaId;
  16use collections::{BTreeMap, HashMap};
  17use gpui::{
  18    color::Color,
  19    elements::*,
  20    fonts::{HighlightStyle, Underline},
  21    geometry::{
  22        rect::RectF,
  23        vector::{vec2f, Vector2F},
  24        PathBuilder,
  25    },
  26    json::{self, ToJson},
  27    platform::CursorStyle,
  28    text_layout::{self, Line, RunStyle, TextLayoutCache},
  29    AppContext, Axis, Border, CursorRegion, Element, ElementBox, Event, EventContext,
  30    LayoutContext, ModifiersChangedEvent, MouseButton, MouseButtonEvent, MouseMovedEvent,
  31    MutableAppContext, PaintContext, Quad, Scene, ScrollWheelEvent, SizeConstraint, ViewContext,
  32    WeakViewHandle,
  33};
  34use json::json;
  35use language::{Bias, DiagnosticSeverity, OffsetUtf16, Selection};
  36use project::ProjectPath;
  37use settings::Settings;
  38use smallvec::SmallVec;
  39use std::{
  40    cmp::{self, Ordering},
  41    fmt::Write,
  42    iter,
  43    ops::Range,
  44};
  45
  46const MIN_POPOVER_CHARACTER_WIDTH: f32 = 20.;
  47const MIN_POPOVER_LINE_HEIGHT: f32 = 4.;
  48const HOVER_POPOVER_GAP: f32 = 10.;
  49
  50struct SelectionLayout {
  51    head: DisplayPoint,
  52    range: Range<DisplayPoint>,
  53}
  54
  55impl SelectionLayout {
  56    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  57        selection: Selection<T>,
  58        line_mode: bool,
  59        map: &DisplaySnapshot,
  60    ) -> Self {
  61        if line_mode {
  62            let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  63            let point_range = map.expand_to_line(selection.range());
  64            Self {
  65                head: selection.head().to_display_point(map),
  66                range: point_range.start.to_display_point(map)
  67                    ..point_range.end.to_display_point(map),
  68            }
  69        } else {
  70            let selection = selection.map(|p| p.to_display_point(map));
  71            Self {
  72                head: selection.head(),
  73                range: selection.range(),
  74            }
  75        }
  76    }
  77}
  78
  79pub struct EditorElement {
  80    view: WeakViewHandle<Editor>,
  81    style: EditorStyle,
  82    cursor_shape: CursorShape,
  83}
  84
  85impl EditorElement {
  86    pub fn new(
  87        view: WeakViewHandle<Editor>,
  88        style: EditorStyle,
  89        cursor_shape: CursorShape,
  90    ) -> Self {
  91        Self {
  92            view,
  93            style,
  94            cursor_shape,
  95        }
  96    }
  97
  98    fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
  99        self.view.upgrade(cx).unwrap().read(cx)
 100    }
 101
 102    fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
 103    where
 104        F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
 105    {
 106        self.view.upgrade(cx).unwrap().update(cx, f)
 107    }
 108
 109    fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
 110        self.update_view(cx, |view, cx| view.snapshot(cx))
 111    }
 112
 113    fn mouse_down(
 114        &self,
 115        MouseButtonEvent {
 116            position,
 117            ctrl,
 118            alt,
 119            shift,
 120            cmd,
 121            mut click_count,
 122            ..
 123        }: MouseButtonEvent,
 124        layout: &mut LayoutState,
 125        paint: &mut PaintState,
 126        cx: &mut EventContext,
 127    ) -> bool {
 128        if paint.gutter_bounds.contains_point(position) {
 129            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 130        } else if !paint.text_bounds.contains_point(position) {
 131            return false;
 132        }
 133
 134        let snapshot = self.snapshot(cx.app);
 135        let (position, target_position) = paint.point_for_position(&snapshot, layout, position);
 136
 137        if shift && alt {
 138            cx.dispatch_action(Select(SelectPhase::BeginColumnar {
 139                position,
 140                goal_column: target_position.column(),
 141            }));
 142        } else if shift && !ctrl && !alt && !cmd {
 143            cx.dispatch_action(Select(SelectPhase::Extend {
 144                position,
 145                click_count,
 146            }));
 147        } else {
 148            cx.dispatch_action(Select(SelectPhase::Begin {
 149                position,
 150                add: alt,
 151                click_count,
 152            }));
 153        }
 154
 155        true
 156    }
 157
 158    fn mouse_right_down(
 159        &self,
 160        position: Vector2F,
 161        layout: &mut LayoutState,
 162        paint: &mut PaintState,
 163        cx: &mut EventContext,
 164    ) -> bool {
 165        if !paint.text_bounds.contains_point(position) {
 166            return false;
 167        }
 168
 169        let snapshot = self.snapshot(cx.app);
 170        let (point, _) = paint.point_for_position(&snapshot, layout, position);
 171
 172        cx.dispatch_action(DeployMouseContextMenu { position, point });
 173        true
 174    }
 175
 176    fn mouse_up(
 177        &self,
 178        position: Vector2F,
 179        cmd: bool,
 180        shift: bool,
 181        layout: &mut LayoutState,
 182        paint: &mut PaintState,
 183        cx: &mut EventContext,
 184    ) -> bool {
 185        let view = self.view(cx.app.as_ref());
 186        let end_selection = view.has_pending_selection();
 187        let pending_nonempty_selections = view.has_pending_nonempty_selection();
 188
 189        if end_selection {
 190            cx.dispatch_action(Select(SelectPhase::End));
 191        }
 192
 193        if !pending_nonempty_selections && cmd && paint.text_bounds.contains_point(position) {
 194            let (point, target_point) =
 195                paint.point_for_position(&self.snapshot(cx), layout, position);
 196
 197            if point == target_point {
 198                if shift {
 199                    cx.dispatch_action(GoToFetchedTypeDefinition { point });
 200                } else {
 201                    cx.dispatch_action(GoToFetchedDefinition { point });
 202                }
 203
 204                return true;
 205            }
 206        }
 207
 208        end_selection
 209    }
 210
 211    fn mouse_dragged(
 212        &self,
 213        MouseMovedEvent {
 214            cmd,
 215            shift,
 216            position,
 217            ..
 218        }: MouseMovedEvent,
 219        layout: &mut LayoutState,
 220        paint: &mut PaintState,
 221        cx: &mut EventContext,
 222    ) -> bool {
 223        // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
 224        // Don't trigger hover popover if mouse is hovering over context menu
 225        let point = if paint.text_bounds.contains_point(position) {
 226            let (point, target_point) =
 227                paint.point_for_position(&self.snapshot(cx), layout, position);
 228            if point == target_point {
 229                Some(point)
 230            } else {
 231                None
 232            }
 233        } else {
 234            None
 235        };
 236
 237        cx.dispatch_action(UpdateGoToDefinitionLink {
 238            point,
 239            cmd_held: cmd,
 240            shift_held: shift,
 241        });
 242
 243        let view = self.view(cx.app);
 244        if view.has_pending_selection() {
 245            let rect = paint.text_bounds;
 246            let mut scroll_delta = Vector2F::zero();
 247
 248            let vertical_margin = layout.line_height.min(rect.height() / 3.0);
 249            let top = rect.origin_y() + vertical_margin;
 250            let bottom = rect.lower_left().y() - vertical_margin;
 251            if position.y() < top {
 252                scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
 253            }
 254            if position.y() > bottom {
 255                scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
 256            }
 257
 258            let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
 259            let left = rect.origin_x() + horizontal_margin;
 260            let right = rect.upper_right().x() - horizontal_margin;
 261            if position.x() < left {
 262                scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
 263                    left - position.x(),
 264                ))
 265            }
 266            if position.x() > right {
 267                scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
 268                    position.x() - right,
 269                ))
 270            }
 271
 272            let snapshot = self.snapshot(cx.app);
 273            let (position, target_position) = paint.point_for_position(&snapshot, layout, position);
 274
 275            cx.dispatch_action(Select(SelectPhase::Update {
 276                position,
 277                goal_column: target_position.column(),
 278                scroll_position: (snapshot.scroll_position() + scroll_delta)
 279                    .clamp(Vector2F::zero(), layout.scroll_max),
 280            }));
 281
 282            cx.dispatch_action(HoverAt { point });
 283            true
 284        } else {
 285            cx.dispatch_action(HoverAt { point });
 286            false
 287        }
 288    }
 289
 290    fn mouse_moved(
 291        &self,
 292        MouseMovedEvent {
 293            cmd,
 294            shift,
 295            position,
 296            ..
 297        }: MouseMovedEvent,
 298        layout: &LayoutState,
 299        paint: &PaintState,
 300        cx: &mut EventContext,
 301    ) -> bool {
 302        // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
 303        // Don't trigger hover popover if mouse is hovering over context menu
 304        let point = if paint.text_bounds.contains_point(position) {
 305            let (point, target_point) =
 306                paint.point_for_position(&self.snapshot(cx), layout, position);
 307            if point == target_point {
 308                Some(point)
 309            } else {
 310                None
 311            }
 312        } else {
 313            None
 314        };
 315
 316        cx.dispatch_action(UpdateGoToDefinitionLink {
 317            point,
 318            cmd_held: cmd,
 319            shift_held: shift,
 320        });
 321
 322        if paint
 323            .context_menu_bounds
 324            .map_or(false, |context_menu_bounds| {
 325                context_menu_bounds.contains_point(position)
 326            })
 327        {
 328            return false;
 329        }
 330
 331        if paint
 332            .hover_popover_bounds
 333            .iter()
 334            .any(|hover_bounds| hover_bounds.contains_point(position))
 335        {
 336            return false;
 337        }
 338
 339        cx.dispatch_action(HoverAt { point });
 340        true
 341    }
 342
 343    fn modifiers_changed(&self, event: ModifiersChangedEvent, cx: &mut EventContext) -> bool {
 344        cx.dispatch_action(CmdShiftChanged {
 345            cmd_down: event.cmd,
 346            shift_down: event.shift,
 347        });
 348        false
 349    }
 350
 351    fn scroll(
 352        &self,
 353        position: Vector2F,
 354        mut delta: Vector2F,
 355        precise: bool,
 356        layout: &mut LayoutState,
 357        paint: &mut PaintState,
 358        cx: &mut EventContext,
 359    ) -> bool {
 360        if !paint.bounds.contains_point(position) {
 361            return false;
 362        }
 363
 364        let snapshot = self.snapshot(cx.app);
 365        let max_glyph_width = layout.em_width;
 366        if !precise {
 367            delta *= vec2f(max_glyph_width, layout.line_height);
 368        }
 369
 370        let scroll_position = snapshot.scroll_position();
 371        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 372        let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
 373        let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), layout.scroll_max);
 374
 375        cx.dispatch_action(Scroll(scroll_position));
 376
 377        true
 378    }
 379
 380    fn paint_background(
 381        &self,
 382        gutter_bounds: RectF,
 383        text_bounds: RectF,
 384        layout: &LayoutState,
 385        cx: &mut PaintContext,
 386    ) {
 387        let bounds = gutter_bounds.union_rect(text_bounds);
 388        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 389        let editor = self.view(cx.app);
 390        cx.scene.push_quad(Quad {
 391            bounds: gutter_bounds,
 392            background: Some(self.style.gutter_background),
 393            border: Border::new(0., Color::transparent_black()),
 394            corner_radius: 0.,
 395        });
 396        cx.scene.push_quad(Quad {
 397            bounds: text_bounds,
 398            background: Some(self.style.background),
 399            border: Border::new(0., Color::transparent_black()),
 400            corner_radius: 0.,
 401        });
 402
 403        if let EditorMode::Full = editor.mode {
 404            let mut active_rows = layout.active_rows.iter().peekable();
 405            while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 406                let mut end_row = *start_row;
 407                while active_rows.peek().map_or(false, |r| {
 408                    *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
 409                }) {
 410                    active_rows.next().unwrap();
 411                    end_row += 1;
 412                }
 413
 414                if !contains_non_empty_selection {
 415                    let origin = vec2f(
 416                        bounds.origin_x(),
 417                        bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
 418                    );
 419                    let size = vec2f(
 420                        bounds.width(),
 421                        layout.line_height * (end_row - start_row + 1) as f32,
 422                    );
 423                    cx.scene.push_quad(Quad {
 424                        bounds: RectF::new(origin, size),
 425                        background: Some(self.style.active_line_background),
 426                        border: Border::default(),
 427                        corner_radius: 0.,
 428                    });
 429                }
 430            }
 431
 432            if let Some(highlighted_rows) = &layout.highlighted_rows {
 433                let origin = vec2f(
 434                    bounds.origin_x(),
 435                    bounds.origin_y() + (layout.line_height * highlighted_rows.start as f32)
 436                        - scroll_top,
 437                );
 438                let size = vec2f(
 439                    bounds.width(),
 440                    layout.line_height * highlighted_rows.len() as f32,
 441                );
 442                cx.scene.push_quad(Quad {
 443                    bounds: RectF::new(origin, size),
 444                    background: Some(self.style.highlighted_line_background),
 445                    border: Border::default(),
 446                    corner_radius: 0.,
 447                });
 448            }
 449        }
 450    }
 451
 452    fn paint_gutter(
 453        &mut self,
 454        bounds: RectF,
 455        visible_bounds: RectF,
 456        layout: &mut LayoutState,
 457        cx: &mut PaintContext,
 458    ) {
 459        let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
 460        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 461            if let Some(line) = line {
 462                let line_origin = bounds.origin()
 463                    + vec2f(
 464                        bounds.width() - line.width() - layout.gutter_padding,
 465                        ix as f32 * layout.line_height - (scroll_top % layout.line_height),
 466                    );
 467                line.paint(line_origin, visible_bounds, layout.line_height, cx);
 468            }
 469        }
 470
 471        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
 472            let mut x = bounds.width() - layout.gutter_padding;
 473            let mut y = *row as f32 * layout.line_height - scroll_top;
 474            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
 475            y += (layout.line_height - indicator.size().y()) / 2.;
 476            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
 477        }
 478    }
 479
 480    fn paint_text(
 481        &mut self,
 482        bounds: RectF,
 483        visible_bounds: RectF,
 484        layout: &mut LayoutState,
 485        paint: &mut PaintState,
 486        cx: &mut PaintContext,
 487    ) {
 488        let view = self.view(cx.app);
 489        let style = &self.style;
 490        let local_replica_id = view.replica_id(cx);
 491        let scroll_position = layout.snapshot.scroll_position();
 492        let start_row = scroll_position.y() as u32;
 493        let scroll_top = scroll_position.y() * layout.line_height;
 494        let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 495        let max_glyph_width = layout.em_width;
 496        let scroll_left = scroll_position.x() * max_glyph_width;
 497        let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
 498
 499        cx.scene.push_layer(Some(bounds));
 500
 501        cx.scene.push_cursor_region(CursorRegion {
 502            bounds,
 503            style: if !view.link_go_to_definition_state.definitions.is_empty() {
 504                CursorStyle::PointingHand
 505            } else {
 506                CursorStyle::IBeam
 507            },
 508        });
 509
 510        for (range, color) in &layout.highlighted_ranges {
 511            self.paint_highlighted_range(
 512                range.clone(),
 513                start_row,
 514                end_row,
 515                *color,
 516                0.,
 517                0.15 * layout.line_height,
 518                layout,
 519                content_origin,
 520                scroll_top,
 521                scroll_left,
 522                bounds,
 523                cx,
 524            );
 525        }
 526
 527        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 528        for (replica_id, selections) in &layout.selections {
 529            let selection_style = style.replica_selection_style(*replica_id);
 530            let corner_radius = 0.15 * layout.line_height;
 531
 532            for selection in selections {
 533                self.paint_highlighted_range(
 534                    selection.range.clone(),
 535                    start_row,
 536                    end_row,
 537                    selection_style.selection,
 538                    corner_radius,
 539                    corner_radius * 2.,
 540                    layout,
 541                    content_origin,
 542                    scroll_top,
 543                    scroll_left,
 544                    bounds,
 545                    cx,
 546                );
 547
 548                if view.show_local_cursors() || *replica_id != local_replica_id {
 549                    let cursor_position = selection.head;
 550                    if (start_row..end_row).contains(&cursor_position.row()) {
 551                        let cursor_row_layout =
 552                            &layout.line_layouts[(cursor_position.row() - start_row) as usize];
 553                        let cursor_column = cursor_position.column() as usize;
 554
 555                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 556                        let mut block_width =
 557                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 558                        if block_width == 0.0 {
 559                            block_width = layout.em_width;
 560                        }
 561
 562                        let block_text =
 563                            if let CursorShape::Block = self.cursor_shape {
 564                                layout.snapshot.chars_at(cursor_position).next().and_then(
 565                                    |character| {
 566                                        let font_id =
 567                                            cursor_row_layout.font_for_index(cursor_column)?;
 568                                        let text = character.to_string();
 569
 570                                        Some(cx.text_layout_cache.layout_str(
 571                                            &text,
 572                                            cursor_row_layout.font_size(),
 573                                            &[(
 574                                                text.len(),
 575                                                RunStyle {
 576                                                    font_id,
 577                                                    color: style.background,
 578                                                    underline: Default::default(),
 579                                                },
 580                                            )],
 581                                        ))
 582                                    },
 583                                )
 584                            } else {
 585                                None
 586                            };
 587
 588                        let x = cursor_character_x - scroll_left;
 589                        let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
 590                        cursors.push(Cursor {
 591                            color: selection_style.cursor,
 592                            block_width,
 593                            origin: vec2f(x, y),
 594                            line_height: layout.line_height,
 595                            shape: self.cursor_shape,
 596                            block_text,
 597                        });
 598                    }
 599                }
 600            }
 601        }
 602
 603        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 604            // Draw glyphs
 605            for (ix, line) in layout.line_layouts.iter().enumerate() {
 606                let row = start_row + ix as u32;
 607                line.paint(
 608                    content_origin
 609                        + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
 610                    visible_text_bounds,
 611                    layout.line_height,
 612                    cx,
 613                );
 614            }
 615        }
 616
 617        cx.scene.push_layer(Some(bounds));
 618        for cursor in cursors {
 619            cursor.paint(content_origin, cx);
 620        }
 621        cx.scene.pop_layer();
 622
 623        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 624            cx.scene.push_stacking_context(None);
 625            let cursor_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
 626            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 627            let y = (position.row() + 1) as f32 * layout.line_height - scroll_top;
 628            let mut list_origin = content_origin + vec2f(x, y);
 629            let list_width = context_menu.size().x();
 630            let list_height = context_menu.size().y();
 631
 632            // Snap the right edge of the list to the right edge of the window if
 633            // its horizontal bounds overflow.
 634            if list_origin.x() + list_width > cx.window_size.x() {
 635                list_origin.set_x((cx.window_size.x() - list_width).max(0.));
 636            }
 637
 638            if list_origin.y() + list_height > bounds.max_y() {
 639                list_origin.set_y(list_origin.y() - layout.line_height - list_height);
 640            }
 641
 642            context_menu.paint(
 643                list_origin,
 644                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 645                cx,
 646            );
 647
 648            paint.context_menu_bounds = Some(RectF::new(list_origin, context_menu.size()));
 649
 650            cx.scene.pop_stacking_context();
 651        }
 652
 653        if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
 654            cx.scene.push_stacking_context(None);
 655
 656            // This is safe because we check on layout whether the required row is available
 657            let hovered_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
 658
 659            // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
 660            // height. This is the size we will use to decide whether to render popovers above or below
 661            // the hovered line.
 662            let first_size = hover_popovers[0].size();
 663            let height_to_reserve =
 664                first_size.y() + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.line_height;
 665
 666            // Compute Hovered Point
 667            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
 668            let y = position.row() as f32 * layout.line_height - scroll_top;
 669            let hovered_point = content_origin + vec2f(x, y);
 670
 671            paint.hover_popover_bounds.clear();
 672
 673            if hovered_point.y() - height_to_reserve > 0.0 {
 674                // There is enough space above. Render popovers above the hovered point
 675                let mut current_y = hovered_point.y();
 676                for hover_popover in hover_popovers {
 677                    let size = hover_popover.size();
 678                    let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
 679
 680                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 681                    if x_out_of_bounds < 0.0 {
 682                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 683                    }
 684
 685                    hover_popover.paint(
 686                        popover_origin,
 687                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 688                        cx,
 689                    );
 690
 691                    paint.hover_popover_bounds.push(
 692                        RectF::new(popover_origin, hover_popover.size())
 693                            .dilate(Vector2F::new(0., 5.)),
 694                    );
 695
 696                    current_y = popover_origin.y() - HOVER_POPOVER_GAP;
 697                }
 698            } else {
 699                // There is not enough space above. Render popovers below the hovered point
 700                let mut current_y = hovered_point.y() + layout.line_height;
 701                for hover_popover in hover_popovers {
 702                    let size = hover_popover.size();
 703                    let mut popover_origin = vec2f(hovered_point.x(), current_y);
 704
 705                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 706                    if x_out_of_bounds < 0.0 {
 707                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 708                    }
 709
 710                    hover_popover.paint(
 711                        popover_origin,
 712                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 713                        cx,
 714                    );
 715
 716                    paint.hover_popover_bounds.push(
 717                        RectF::new(popover_origin, hover_popover.size())
 718                            .dilate(Vector2F::new(0., 5.)),
 719                    );
 720
 721                    current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
 722                }
 723            }
 724
 725            cx.scene.pop_stacking_context();
 726        }
 727
 728        cx.scene.pop_layer();
 729    }
 730
 731    #[allow(clippy::too_many_arguments)]
 732    fn paint_highlighted_range(
 733        &self,
 734        range: Range<DisplayPoint>,
 735        start_row: u32,
 736        end_row: u32,
 737        color: Color,
 738        corner_radius: f32,
 739        line_end_overshoot: f32,
 740        layout: &LayoutState,
 741        content_origin: Vector2F,
 742        scroll_top: f32,
 743        scroll_left: f32,
 744        bounds: RectF,
 745        cx: &mut PaintContext,
 746    ) {
 747        if range.start != range.end {
 748            let row_range = if range.end.column() == 0 {
 749                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
 750            } else {
 751                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
 752            };
 753
 754            let highlighted_range = HighlightedRange {
 755                color,
 756                line_height: layout.line_height,
 757                corner_radius,
 758                start_y: content_origin.y() + row_range.start as f32 * layout.line_height
 759                    - scroll_top,
 760                lines: row_range
 761                    .into_iter()
 762                    .map(|row| {
 763                        let line_layout = &layout.line_layouts[(row - start_row) as usize];
 764                        HighlightedRangeLine {
 765                            start_x: if row == range.start.row() {
 766                                content_origin.x()
 767                                    + line_layout.x_for_index(range.start.column() as usize)
 768                                    - scroll_left
 769                            } else {
 770                                content_origin.x() - scroll_left
 771                            },
 772                            end_x: if row == range.end.row() {
 773                                content_origin.x()
 774                                    + line_layout.x_for_index(range.end.column() as usize)
 775                                    - scroll_left
 776                            } else {
 777                                content_origin.x() + line_layout.width() + line_end_overshoot
 778                                    - scroll_left
 779                            },
 780                        }
 781                    })
 782                    .collect(),
 783            };
 784
 785            highlighted_range.paint(bounds, cx.scene);
 786        }
 787    }
 788
 789    fn paint_blocks(
 790        &mut self,
 791        bounds: RectF,
 792        visible_bounds: RectF,
 793        layout: &mut LayoutState,
 794        cx: &mut PaintContext,
 795    ) {
 796        let scroll_position = layout.snapshot.scroll_position();
 797        let scroll_left = scroll_position.x() * layout.em_width;
 798        let scroll_top = scroll_position.y() * layout.line_height;
 799
 800        for block in &mut layout.blocks {
 801            let mut origin =
 802                bounds.origin() + vec2f(0., block.row as f32 * layout.line_height - scroll_top);
 803            if !matches!(block.style, BlockStyle::Sticky) {
 804                origin += vec2f(-scroll_left, 0.);
 805            }
 806            block.element.paint(origin, visible_bounds, cx);
 807        }
 808    }
 809
 810    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
 811        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
 812        let style = &self.style;
 813
 814        cx.text_layout_cache
 815            .layout_str(
 816                "1".repeat(digit_count).as_str(),
 817                style.text.font_size,
 818                &[(
 819                    digit_count,
 820                    RunStyle {
 821                        font_id: style.text.font_id,
 822                        color: Color::black(),
 823                        underline: Default::default(),
 824                    },
 825                )],
 826            )
 827            .width()
 828    }
 829
 830    fn layout_line_numbers(
 831        &self,
 832        rows: Range<u32>,
 833        active_rows: &BTreeMap<u32, bool>,
 834        snapshot: &EditorSnapshot,
 835        cx: &LayoutContext,
 836    ) -> Vec<Option<text_layout::Line>> {
 837        let style = &self.style;
 838        let include_line_numbers = snapshot.mode == EditorMode::Full;
 839        let mut line_number_layouts = Vec::with_capacity(rows.len());
 840        let mut line_number = String::new();
 841        for (ix, row) in snapshot
 842            .buffer_rows(rows.start)
 843            .take((rows.end - rows.start) as usize)
 844            .enumerate()
 845        {
 846            let display_row = rows.start + ix as u32;
 847            let color = if active_rows.contains_key(&display_row) {
 848                style.line_number_active
 849            } else {
 850                style.line_number
 851            };
 852            if let Some(buffer_row) = row {
 853                if include_line_numbers {
 854                    line_number.clear();
 855                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
 856                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
 857                        &line_number,
 858                        style.text.font_size,
 859                        &[(
 860                            line_number.len(),
 861                            RunStyle {
 862                                font_id: style.text.font_id,
 863                                color,
 864                                underline: Default::default(),
 865                            },
 866                        )],
 867                    )));
 868                }
 869            } else {
 870                line_number_layouts.push(None);
 871            }
 872        }
 873
 874        line_number_layouts
 875    }
 876
 877    fn layout_lines(
 878        &mut self,
 879        rows: Range<u32>,
 880        snapshot: &EditorSnapshot,
 881        cx: &LayoutContext,
 882    ) -> Vec<text_layout::Line> {
 883        if rows.start >= rows.end {
 884            return Vec::new();
 885        }
 886
 887        // When the editor is empty and unfocused, then show the placeholder.
 888        if snapshot.is_empty() && !snapshot.is_focused() {
 889            let placeholder_style = self
 890                .style
 891                .placeholder_text
 892                .as_ref()
 893                .unwrap_or(&self.style.text);
 894            let placeholder_text = snapshot.placeholder_text();
 895            let placeholder_lines = placeholder_text
 896                .as_ref()
 897                .map_or("", AsRef::as_ref)
 898                .split('\n')
 899                .skip(rows.start as usize)
 900                .chain(iter::repeat(""))
 901                .take(rows.len());
 902            placeholder_lines
 903                .map(|line| {
 904                    cx.text_layout_cache.layout_str(
 905                        line,
 906                        placeholder_style.font_size,
 907                        &[(
 908                            line.len(),
 909                            RunStyle {
 910                                font_id: placeholder_style.font_id,
 911                                color: placeholder_style.color,
 912                                underline: Default::default(),
 913                            },
 914                        )],
 915                    )
 916                })
 917                .collect()
 918        } else {
 919            let style = &self.style;
 920            let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
 921                let mut highlight_style = chunk
 922                    .syntax_highlight_id
 923                    .and_then(|id| id.style(&style.syntax));
 924
 925                if let Some(chunk_highlight) = chunk.highlight_style {
 926                    if let Some(highlight_style) = highlight_style.as_mut() {
 927                        highlight_style.highlight(chunk_highlight);
 928                    } else {
 929                        highlight_style = Some(chunk_highlight);
 930                    }
 931                }
 932
 933                let mut diagnostic_highlight = HighlightStyle::default();
 934
 935                if chunk.is_unnecessary {
 936                    diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
 937                }
 938
 939                if let Some(severity) = chunk.diagnostic_severity {
 940                    // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
 941                    if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
 942                        let diagnostic_style = super::diagnostic_style(severity, true, style);
 943                        diagnostic_highlight.underline = Some(Underline {
 944                            color: Some(diagnostic_style.message.text.color),
 945                            thickness: 1.0.into(),
 946                            squiggly: true,
 947                        });
 948                    }
 949                }
 950
 951                if let Some(highlight_style) = highlight_style.as_mut() {
 952                    highlight_style.highlight(diagnostic_highlight);
 953                } else {
 954                    highlight_style = Some(diagnostic_highlight);
 955                }
 956
 957                (chunk.text, highlight_style)
 958            });
 959            layout_highlighted_chunks(
 960                chunks,
 961                &style.text,
 962                cx.text_layout_cache,
 963                cx.font_cache,
 964                MAX_LINE_LEN,
 965                rows.len() as usize,
 966            )
 967        }
 968    }
 969
 970    #[allow(clippy::too_many_arguments)]
 971    fn layout_blocks(
 972        &mut self,
 973        rows: Range<u32>,
 974        snapshot: &EditorSnapshot,
 975        editor_width: f32,
 976        scroll_width: f32,
 977        gutter_padding: f32,
 978        gutter_width: f32,
 979        em_width: f32,
 980        text_x: f32,
 981        line_height: f32,
 982        style: &EditorStyle,
 983        line_layouts: &[text_layout::Line],
 984        cx: &mut LayoutContext,
 985    ) -> (f32, Vec<BlockLayout>) {
 986        let editor = if let Some(editor) = self.view.upgrade(cx) {
 987            editor
 988        } else {
 989            return Default::default();
 990        };
 991
 992        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
 993        let scroll_x = snapshot.scroll_position.x();
 994        let (fixed_blocks, non_fixed_blocks) = snapshot
 995            .blocks_in_range(rows.clone())
 996            .partition::<Vec<_>, _>(|(_, block)| match block {
 997                TransformBlock::ExcerptHeader { .. } => false,
 998                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
 999            });
1000        let mut render_block = |block: &TransformBlock, width: f32| {
1001            let mut element = match block {
1002                TransformBlock::Custom(block) => {
1003                    let align_to = block
1004                        .position()
1005                        .to_point(&snapshot.buffer_snapshot)
1006                        .to_display_point(snapshot);
1007                    let anchor_x = text_x
1008                        + if rows.contains(&align_to.row()) {
1009                            line_layouts[(align_to.row() - rows.start) as usize]
1010                                .x_for_index(align_to.column() as usize)
1011                        } else {
1012                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
1013                                .x_for_index(align_to.column() as usize)
1014                        };
1015
1016                    cx.render(&editor, |_, cx| {
1017                        block.render(&mut BlockContext {
1018                            cx,
1019                            anchor_x,
1020                            gutter_padding,
1021                            line_height,
1022                            scroll_x,
1023                            gutter_width,
1024                            em_width,
1025                        })
1026                    })
1027                }
1028                TransformBlock::ExcerptHeader {
1029                    key,
1030                    buffer,
1031                    range,
1032                    starts_new_buffer,
1033                    ..
1034                } => {
1035                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1036                        let jump_position = range
1037                            .primary
1038                            .as_ref()
1039                            .map_or(range.context.start, |primary| primary.start);
1040                        let jump_action = crate::Jump {
1041                            path: ProjectPath {
1042                                worktree_id: file.worktree_id(cx),
1043                                path: file.path.clone(),
1044                            },
1045                            position: language::ToPoint::to_point(&jump_position, buffer),
1046                            anchor: jump_position,
1047                        };
1048
1049                        enum JumpIcon {}
1050                        cx.render(&editor, |_, cx| {
1051                            MouseEventHandler::new::<JumpIcon, _, _>(*key, cx, |state, _| {
1052                                let style = style.jump_icon.style_for(state, false);
1053                                Svg::new("icons/arrow_up_right_8.svg")
1054                                    .with_color(style.color)
1055                                    .constrained()
1056                                    .with_width(style.icon_width)
1057                                    .aligned()
1058                                    .contained()
1059                                    .with_style(style.container)
1060                                    .constrained()
1061                                    .with_width(style.button_width)
1062                                    .with_height(style.button_width)
1063                                    .boxed()
1064                            })
1065                            .with_cursor_style(CursorStyle::PointingHand)
1066                            .on_click(MouseButton::Left, move |_, cx| {
1067                                cx.dispatch_action(jump_action.clone())
1068                            })
1069                            .with_tooltip::<JumpIcon, _>(
1070                                *key,
1071                                "Jump to Buffer".to_string(),
1072                                Some(Box::new(crate::OpenExcerpts)),
1073                                tooltip_style.clone(),
1074                                cx,
1075                            )
1076                            .aligned()
1077                            .flex_float()
1078                            .boxed()
1079                        })
1080                    });
1081
1082                    if *starts_new_buffer {
1083                        let style = &self.style.diagnostic_path_header;
1084                        let font_size =
1085                            (style.text_scale_factor * self.style.text.font_size).round();
1086
1087                        let mut filename = None;
1088                        let mut parent_path = None;
1089                        if let Some(file) = buffer.file() {
1090                            let path = file.path();
1091                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1092                            parent_path =
1093                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1094                        }
1095
1096                        Flex::row()
1097                            .with_child(
1098                                Label::new(
1099                                    filename.unwrap_or_else(|| "untitled".to_string()),
1100                                    style.filename.text.clone().with_font_size(font_size),
1101                                )
1102                                .contained()
1103                                .with_style(style.filename.container)
1104                                .aligned()
1105                                .boxed(),
1106                            )
1107                            .with_children(parent_path.map(|path| {
1108                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1109                                    .contained()
1110                                    .with_style(style.path.container)
1111                                    .aligned()
1112                                    .boxed()
1113                            }))
1114                            .with_children(jump_icon)
1115                            .contained()
1116                            .with_style(style.container)
1117                            .with_padding_left(gutter_padding)
1118                            .with_padding_right(gutter_padding)
1119                            .expanded()
1120                            .named("path header block")
1121                    } else {
1122                        let text_style = self.style.text.clone();
1123                        Flex::row()
1124                            .with_child(Label::new("".to_string(), text_style).boxed())
1125                            .with_children(jump_icon)
1126                            .contained()
1127                            .with_padding_left(gutter_padding)
1128                            .with_padding_right(gutter_padding)
1129                            .expanded()
1130                            .named("collapsed context")
1131                    }
1132                }
1133            };
1134
1135            element.layout(
1136                SizeConstraint {
1137                    min: Vector2F::zero(),
1138                    max: vec2f(width, block.height() as f32 * line_height),
1139                },
1140                cx,
1141            );
1142            element
1143        };
1144
1145        let mut fixed_block_max_width = 0f32;
1146        let mut blocks = Vec::new();
1147        for (row, block) in fixed_blocks {
1148            let element = render_block(block, f32::INFINITY);
1149            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1150            blocks.push(BlockLayout {
1151                row,
1152                element,
1153                style: BlockStyle::Fixed,
1154            });
1155        }
1156        for (row, block) in non_fixed_blocks {
1157            let style = match block {
1158                TransformBlock::Custom(block) => block.style(),
1159                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1160            };
1161            let width = match style {
1162                BlockStyle::Sticky => editor_width,
1163                BlockStyle::Flex => editor_width
1164                    .max(fixed_block_max_width)
1165                    .max(gutter_width + scroll_width),
1166                BlockStyle::Fixed => unreachable!(),
1167            };
1168            let element = render_block(block, width);
1169            blocks.push(BlockLayout {
1170                row,
1171                element,
1172                style,
1173            });
1174        }
1175        (
1176            scroll_width.max(fixed_block_max_width - gutter_width),
1177            blocks,
1178        )
1179    }
1180}
1181
1182impl Element for EditorElement {
1183    type LayoutState = LayoutState;
1184    type PaintState = PaintState;
1185
1186    fn layout(
1187        &mut self,
1188        constraint: SizeConstraint,
1189        cx: &mut LayoutContext,
1190    ) -> (Vector2F, Self::LayoutState) {
1191        let mut size = constraint.max;
1192        if size.x().is_infinite() {
1193            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1194        }
1195
1196        let snapshot = self.snapshot(cx.app);
1197        let style = self.style.clone();
1198        let line_height = style.text.line_height(cx.font_cache);
1199
1200        let gutter_padding;
1201        let gutter_width;
1202        let gutter_margin;
1203        if snapshot.mode == EditorMode::Full {
1204            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1205            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1206            gutter_margin = -style.text.descent(cx.font_cache);
1207        } else {
1208            gutter_padding = 0.0;
1209            gutter_width = 0.0;
1210            gutter_margin = 0.0;
1211        };
1212
1213        let text_width = size.x() - gutter_width;
1214        let em_width = style.text.em_width(cx.font_cache);
1215        let em_advance = style.text.em_advance(cx.font_cache);
1216        let overscroll = vec2f(em_width, 0.);
1217        let snapshot = self.update_view(cx.app, |view, cx| {
1218            let wrap_width = match view.soft_wrap_mode(cx) {
1219                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1220                SoftWrap::EditorWidth => {
1221                    Some(text_width - gutter_margin - overscroll.x() - em_width)
1222                }
1223                SoftWrap::Column(column) => Some(column as f32 * em_advance),
1224            };
1225
1226            if view.set_wrap_width(wrap_width, cx) {
1227                view.snapshot(cx)
1228            } else {
1229                snapshot
1230            }
1231        });
1232
1233        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1234        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1235            size.set_y(
1236                scroll_height
1237                    .min(constraint.max_along(Axis::Vertical))
1238                    .max(constraint.min_along(Axis::Vertical))
1239                    .min(line_height * max_lines as f32),
1240            )
1241        } else if let EditorMode::SingleLine = snapshot.mode {
1242            size.set_y(
1243                line_height
1244                    .min(constraint.max_along(Axis::Vertical))
1245                    .max(constraint.min_along(Axis::Vertical)),
1246            )
1247        } else if size.y().is_infinite() {
1248            size.set_y(scroll_height);
1249        }
1250        let gutter_size = vec2f(gutter_width, size.y());
1251        let text_size = vec2f(text_width, size.y());
1252
1253        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1254            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1255            let snapshot = view.snapshot(cx);
1256            (autoscroll_horizontally, snapshot)
1257        });
1258
1259        let scroll_position = snapshot.scroll_position();
1260        // The scroll position is a fractional point, the whole number of which represents
1261        // the top of the window in terms of display rows.
1262        let start_row = scroll_position.y() as u32;
1263        let scroll_top = scroll_position.y() * line_height;
1264
1265        // Add 1 to ensure selections bleed off screen
1266        let end_row = 1 + cmp::min(
1267            ((scroll_top + size.y()) / line_height).ceil() as u32,
1268            snapshot.max_point().row(),
1269        );
1270
1271        let start_anchor = if start_row == 0 {
1272            Anchor::min()
1273        } else {
1274            snapshot
1275                .buffer_snapshot
1276                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1277        };
1278        let end_anchor = if end_row > snapshot.max_point().row() {
1279            Anchor::max()
1280        } else {
1281            snapshot
1282                .buffer_snapshot
1283                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1284        };
1285
1286        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1287        let mut active_rows = BTreeMap::new();
1288        let mut highlighted_rows = None;
1289        let mut highlighted_ranges = Vec::new();
1290        self.update_view(cx.app, |view, cx| {
1291            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1292
1293            highlighted_rows = view.highlighted_rows();
1294            let theme = cx.global::<Settings>().theme.as_ref();
1295            highlighted_ranges = view.background_highlights_in_range(
1296                start_anchor.clone()..end_anchor.clone(),
1297                &display_map,
1298                theme,
1299            );
1300
1301            let mut remote_selections = HashMap::default();
1302            for (replica_id, line_mode, selection) in display_map
1303                .buffer_snapshot
1304                .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1305            {
1306                // The local selections match the leader's selections.
1307                if Some(replica_id) == view.leader_replica_id {
1308                    continue;
1309                }
1310                remote_selections
1311                    .entry(replica_id)
1312                    .or_insert(Vec::new())
1313                    .push(SelectionLayout::new(selection, line_mode, &display_map));
1314            }
1315            selections.extend(remote_selections);
1316
1317            if view.show_local_selections {
1318                let mut local_selections = view
1319                    .selections
1320                    .disjoint_in_range(start_anchor..end_anchor, cx);
1321                local_selections.extend(view.selections.pending(cx));
1322                for selection in &local_selections {
1323                    let is_empty = selection.start == selection.end;
1324                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
1325                    let selection_end = snapshot.next_line_boundary(selection.end).1;
1326                    for row in cmp::max(selection_start.row(), start_row)
1327                        ..=cmp::min(selection_end.row(), end_row)
1328                    {
1329                        let contains_non_empty_selection =
1330                            active_rows.entry(row).or_insert(!is_empty);
1331                        *contains_non_empty_selection |= !is_empty;
1332                    }
1333                }
1334
1335                // Render the local selections in the leader's color when following.
1336                let local_replica_id = view
1337                    .leader_replica_id
1338                    .unwrap_or_else(|| view.replica_id(cx));
1339
1340                selections.push((
1341                    local_replica_id,
1342                    local_selections
1343                        .into_iter()
1344                        .map(|selection| {
1345                            SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1346                        })
1347                        .collect(),
1348                ));
1349            }
1350        });
1351
1352        let line_number_layouts =
1353            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1354
1355        let mut max_visible_line_width = 0.0;
1356        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1357        for line in &line_layouts {
1358            if line.width() > max_visible_line_width {
1359                max_visible_line_width = line.width();
1360            }
1361        }
1362
1363        let style = self.style.clone();
1364        let longest_line_width = layout_line(
1365            snapshot.longest_row(),
1366            &snapshot,
1367            &style,
1368            cx.text_layout_cache,
1369        )
1370        .width();
1371        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1372        let em_width = style.text.em_width(cx.font_cache);
1373        let (scroll_width, blocks) = self.layout_blocks(
1374            start_row..end_row,
1375            &snapshot,
1376            size.x(),
1377            scroll_width,
1378            gutter_padding,
1379            gutter_width,
1380            em_width,
1381            gutter_width + gutter_margin,
1382            line_height,
1383            &style,
1384            &line_layouts,
1385            cx,
1386        );
1387
1388        let max_row = snapshot.max_point().row();
1389        let scroll_max = vec2f(
1390            ((scroll_width - text_size.x()) / em_width).max(0.0),
1391            max_row.saturating_sub(1) as f32,
1392        );
1393
1394        self.update_view(cx.app, |view, cx| {
1395            let clamped = view.clamp_scroll_left(scroll_max.x());
1396
1397            let autoscrolled = if autoscroll_horizontally {
1398                view.autoscroll_horizontally(
1399                    start_row,
1400                    text_size.x(),
1401                    scroll_width,
1402                    em_width,
1403                    &line_layouts,
1404                    cx,
1405                )
1406            } else {
1407                false
1408            };
1409
1410            if clamped || autoscrolled {
1411                snapshot = view.snapshot(cx);
1412            }
1413        });
1414
1415        let mut context_menu = None;
1416        let mut code_actions_indicator = None;
1417        let mut hover = None;
1418        cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1419            let newest_selection_head = view
1420                .selections
1421                .newest::<usize>(cx)
1422                .head()
1423                .to_display_point(&snapshot);
1424
1425            let style = view.style(cx);
1426            if (start_row..end_row).contains(&newest_selection_head.row()) {
1427                if view.context_menu_visible() {
1428                    context_menu =
1429                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1430                }
1431
1432                code_actions_indicator = view
1433                    .render_code_actions_indicator(&style, cx)
1434                    .map(|indicator| (newest_selection_head.row(), indicator));
1435            }
1436
1437            let visible_rows = start_row..start_row + line_layouts.len() as u32;
1438            hover = view.hover_state.render(&snapshot, &style, visible_rows, cx);
1439        });
1440
1441        if let Some((_, context_menu)) = context_menu.as_mut() {
1442            context_menu.layout(
1443                SizeConstraint {
1444                    min: Vector2F::zero(),
1445                    max: vec2f(
1446                        cx.window_size.x() * 0.7,
1447                        (12. * line_height).min((size.y() - line_height) / 2.),
1448                    ),
1449                },
1450                cx,
1451            );
1452        }
1453
1454        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1455            indicator.layout(
1456                SizeConstraint::strict_along(
1457                    Axis::Vertical,
1458                    line_height * style.code_actions.vertical_scale,
1459                ),
1460                cx,
1461            );
1462        }
1463
1464        if let Some((_, hover_popovers)) = hover.as_mut() {
1465            for hover_popover in hover_popovers.iter_mut() {
1466                hover_popover.layout(
1467                    SizeConstraint {
1468                        min: Vector2F::zero(),
1469                        max: vec2f(
1470                            (120. * em_width) // Default size
1471                                .min(size.x() / 2.) // Shrink to half of the editor width
1472                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1473                            (16. * line_height) // Default size
1474                                .min(size.y() / 2.) // Shrink to half of the editor height
1475                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1476                        ),
1477                    },
1478                    cx,
1479                );
1480            }
1481        }
1482
1483        (
1484            size,
1485            LayoutState {
1486                size,
1487                scroll_max,
1488                gutter_size,
1489                gutter_padding,
1490                text_size,
1491                gutter_margin,
1492                snapshot,
1493                active_rows,
1494                highlighted_rows,
1495                highlighted_ranges,
1496                line_layouts,
1497                line_number_layouts,
1498                blocks,
1499                line_height,
1500                em_width,
1501                em_advance,
1502                selections,
1503                context_menu,
1504                code_actions_indicator,
1505                hover_popovers: hover,
1506            },
1507        )
1508    }
1509
1510    fn paint(
1511        &mut self,
1512        bounds: RectF,
1513        visible_bounds: RectF,
1514        layout: &mut Self::LayoutState,
1515        cx: &mut PaintContext,
1516    ) -> Self::PaintState {
1517        cx.scene.push_layer(Some(bounds));
1518
1519        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1520        let text_bounds = RectF::new(
1521            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1522            layout.text_size,
1523        );
1524
1525        let mut paint_state = PaintState {
1526            bounds,
1527            gutter_bounds,
1528            text_bounds,
1529            context_menu_bounds: None,
1530            hover_popover_bounds: Default::default(),
1531        };
1532
1533        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1534        if layout.gutter_size.x() > 0. {
1535            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1536        }
1537        self.paint_text(text_bounds, visible_bounds, layout, &mut paint_state, cx);
1538
1539        if !layout.blocks.is_empty() {
1540            cx.scene.push_layer(Some(bounds));
1541            self.paint_blocks(bounds, visible_bounds, layout, cx);
1542            cx.scene.pop_layer();
1543        }
1544
1545        cx.scene.pop_layer();
1546
1547        paint_state
1548    }
1549
1550    fn dispatch_event(
1551        &mut self,
1552        event: &Event,
1553        _: RectF,
1554        _: RectF,
1555        layout: &mut LayoutState,
1556        paint: &mut PaintState,
1557        cx: &mut EventContext,
1558    ) -> bool {
1559        if let Some((_, context_menu)) = &mut layout.context_menu {
1560            if context_menu.dispatch_event(event, cx) {
1561                return true;
1562            }
1563        }
1564
1565        if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1566            if indicator.dispatch_event(event, cx) {
1567                return true;
1568            }
1569        }
1570
1571        if let Some((_, popover_elements)) = &mut layout.hover_popovers {
1572            for popover_element in popover_elements.iter_mut() {
1573                if popover_element.dispatch_event(event, cx) {
1574                    return true;
1575                }
1576            }
1577        }
1578
1579        for block in &mut layout.blocks {
1580            if block.element.dispatch_event(event, cx) {
1581                return true;
1582            }
1583        }
1584
1585        match event {
1586            &Event::MouseDown(
1587                event @ MouseButtonEvent {
1588                    button: MouseButton::Left,
1589                    ..
1590                },
1591            ) => self.mouse_down(event, layout, paint, cx),
1592
1593            &Event::MouseDown(MouseButtonEvent {
1594                button: MouseButton::Right,
1595                position,
1596                ..
1597            }) => self.mouse_right_down(position, layout, paint, cx),
1598
1599            &Event::MouseUp(MouseButtonEvent {
1600                button: MouseButton::Left,
1601                position,
1602                cmd,
1603                shift,
1604                ..
1605            }) => self.mouse_up(position, cmd, shift, layout, paint, cx),
1606
1607            Event::MouseMoved(
1608                event @ MouseMovedEvent {
1609                    pressed_button: Some(MouseButton::Left),
1610                    ..
1611                },
1612            ) => self.mouse_dragged(*event, layout, paint, cx),
1613
1614            Event::ScrollWheel(ScrollWheelEvent {
1615                position,
1616                delta,
1617                precise,
1618                ..
1619            }) => self.scroll(*position, *delta, *precise, layout, paint, cx),
1620
1621            &Event::ModifiersChanged(event) => self.modifiers_changed(event, cx),
1622
1623            &Event::MouseMoved(event) => self.mouse_moved(event, layout, paint, cx),
1624
1625            _ => false,
1626        }
1627    }
1628
1629    fn rect_for_text_range(
1630        &self,
1631        range_utf16: Range<usize>,
1632        bounds: RectF,
1633        _: RectF,
1634        layout: &Self::LayoutState,
1635        _: &Self::PaintState,
1636        _: &gpui::MeasurementContext,
1637    ) -> Option<RectF> {
1638        let text_bounds = RectF::new(
1639            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1640            layout.text_size,
1641        );
1642        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
1643        let scroll_position = layout.snapshot.scroll_position();
1644        let start_row = scroll_position.y() as u32;
1645        let scroll_top = scroll_position.y() * layout.line_height;
1646        let scroll_left = scroll_position.x() * layout.em_width;
1647
1648        let range_start =
1649            OffsetUtf16(range_utf16.start).to_display_point(&layout.snapshot.display_snapshot);
1650        if range_start.row() < start_row {
1651            return None;
1652        }
1653
1654        let line = layout
1655            .line_layouts
1656            .get((range_start.row() - start_row) as usize)?;
1657        let range_start_x = line.x_for_index(range_start.column() as usize);
1658        let range_start_y = range_start.row() as f32 * layout.line_height;
1659        Some(RectF::new(
1660            content_origin + vec2f(range_start_x, range_start_y + layout.line_height)
1661                - vec2f(scroll_left, scroll_top),
1662            vec2f(layout.em_width, layout.line_height),
1663        ))
1664    }
1665
1666    fn debug(
1667        &self,
1668        bounds: RectF,
1669        _: &Self::LayoutState,
1670        _: &Self::PaintState,
1671        _: &gpui::DebugContext,
1672    ) -> json::Value {
1673        json!({
1674            "type": "BufferElement",
1675            "bounds": bounds.to_json()
1676        })
1677    }
1678}
1679
1680pub struct LayoutState {
1681    size: Vector2F,
1682    scroll_max: Vector2F,
1683    gutter_size: Vector2F,
1684    gutter_padding: f32,
1685    gutter_margin: f32,
1686    text_size: Vector2F,
1687    snapshot: EditorSnapshot,
1688    active_rows: BTreeMap<u32, bool>,
1689    highlighted_rows: Option<Range<u32>>,
1690    line_layouts: Vec<text_layout::Line>,
1691    line_number_layouts: Vec<Option<text_layout::Line>>,
1692    blocks: Vec<BlockLayout>,
1693    line_height: f32,
1694    em_width: f32,
1695    em_advance: f32,
1696    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1697    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1698    context_menu: Option<(DisplayPoint, ElementBox)>,
1699    code_actions_indicator: Option<(u32, ElementBox)>,
1700    hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
1701}
1702
1703struct BlockLayout {
1704    row: u32,
1705    element: ElementBox,
1706    style: BlockStyle,
1707}
1708
1709fn layout_line(
1710    row: u32,
1711    snapshot: &EditorSnapshot,
1712    style: &EditorStyle,
1713    layout_cache: &TextLayoutCache,
1714) -> text_layout::Line {
1715    let mut line = snapshot.line(row);
1716
1717    if line.len() > MAX_LINE_LEN {
1718        let mut len = MAX_LINE_LEN;
1719        while !line.is_char_boundary(len) {
1720            len -= 1;
1721        }
1722
1723        line.truncate(len);
1724    }
1725
1726    layout_cache.layout_str(
1727        &line,
1728        style.text.font_size,
1729        &[(
1730            snapshot.line_len(row) as usize,
1731            RunStyle {
1732                font_id: style.text.font_id,
1733                color: Color::black(),
1734                underline: Default::default(),
1735            },
1736        )],
1737    )
1738}
1739
1740pub struct PaintState {
1741    bounds: RectF,
1742    gutter_bounds: RectF,
1743    text_bounds: RectF,
1744    context_menu_bounds: Option<RectF>,
1745    hover_popover_bounds: Vec<RectF>,
1746}
1747
1748impl PaintState {
1749    /// Returns two display points:
1750    /// 1. The nearest *valid* position in the editor
1751    /// 2. An unclipped, potentially *invalid* position that maps directly to
1752    ///    the given pixel position.
1753    fn point_for_position(
1754        &self,
1755        snapshot: &EditorSnapshot,
1756        layout: &LayoutState,
1757        position: Vector2F,
1758    ) -> (DisplayPoint, DisplayPoint) {
1759        let scroll_position = snapshot.scroll_position();
1760        let position = position - self.text_bounds.origin();
1761        let y = position.y().max(0.0).min(layout.size.y());
1762        let x = position.x() + (scroll_position.x() * layout.em_width);
1763        let row = (y / layout.line_height + scroll_position.y()) as u32;
1764        let (column, x_overshoot) = if let Some(line) = layout
1765            .line_layouts
1766            .get(row as usize - scroll_position.y() as usize)
1767        {
1768            if let Some(ix) = line.index_for_x(x) {
1769                (ix as u32, 0.0)
1770            } else {
1771                (line.len() as u32, 0f32.max(x - line.width()))
1772            }
1773        } else {
1774            (0, x)
1775        };
1776
1777        let mut target_point = DisplayPoint::new(row, column);
1778        let point = snapshot.clip_point(target_point, Bias::Left);
1779        *target_point.column_mut() += (x_overshoot / layout.em_advance) as u32;
1780
1781        (point, target_point)
1782    }
1783}
1784
1785#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1786pub enum CursorShape {
1787    Bar,
1788    Block,
1789    Underscore,
1790    Hollow,
1791}
1792
1793impl Default for CursorShape {
1794    fn default() -> Self {
1795        CursorShape::Bar
1796    }
1797}
1798
1799#[derive(Debug)]
1800pub struct Cursor {
1801    origin: Vector2F,
1802    block_width: f32,
1803    line_height: f32,
1804    color: Color,
1805    shape: CursorShape,
1806    block_text: Option<Line>,
1807}
1808
1809impl Cursor {
1810    pub fn new(
1811        origin: Vector2F,
1812        block_width: f32,
1813        line_height: f32,
1814        color: Color,
1815        shape: CursorShape,
1816        block_text: Option<Line>,
1817    ) -> Cursor {
1818        Cursor {
1819            origin,
1820            block_width,
1821            line_height,
1822            color,
1823            shape,
1824            block_text,
1825        }
1826    }
1827
1828    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
1829        RectF::new(
1830            self.origin + origin,
1831            vec2f(self.block_width, self.line_height),
1832        )
1833    }
1834
1835    pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
1836        let bounds = match self.shape {
1837            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
1838            CursorShape::Block | CursorShape::Hollow => RectF::new(
1839                self.origin + origin,
1840                vec2f(self.block_width, self.line_height),
1841            ),
1842            CursorShape::Underscore => RectF::new(
1843                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
1844                vec2f(self.block_width, 2.0),
1845            ),
1846        };
1847
1848        //Draw background or border quad
1849        if matches!(self.shape, CursorShape::Hollow) {
1850            cx.scene.push_quad(Quad {
1851                bounds,
1852                background: None,
1853                border: Border::all(1., self.color),
1854                corner_radius: 0.,
1855            });
1856        } else {
1857            cx.scene.push_quad(Quad {
1858                bounds,
1859                background: Some(self.color),
1860                border: Default::default(),
1861                corner_radius: 0.,
1862            });
1863        }
1864
1865        if let Some(block_text) = &self.block_text {
1866            block_text.paint(self.origin + origin, bounds, self.line_height, cx);
1867        }
1868    }
1869
1870    pub fn shape(&self) -> CursorShape {
1871        self.shape
1872    }
1873}
1874
1875#[derive(Debug)]
1876pub struct HighlightedRange {
1877    pub start_y: f32,
1878    pub line_height: f32,
1879    pub lines: Vec<HighlightedRangeLine>,
1880    pub color: Color,
1881    pub corner_radius: f32,
1882}
1883
1884#[derive(Debug)]
1885pub struct HighlightedRangeLine {
1886    pub start_x: f32,
1887    pub end_x: f32,
1888}
1889
1890impl HighlightedRange {
1891    pub fn paint(&self, bounds: RectF, scene: &mut Scene) {
1892        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1893            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1894            self.paint_lines(
1895                self.start_y + self.line_height,
1896                &self.lines[1..],
1897                bounds,
1898                scene,
1899            );
1900        } else {
1901            self.paint_lines(self.start_y, &self.lines, bounds, scene);
1902        }
1903    }
1904
1905    fn paint_lines(
1906        &self,
1907        start_y: f32,
1908        lines: &[HighlightedRangeLine],
1909        bounds: RectF,
1910        scene: &mut Scene,
1911    ) {
1912        if lines.is_empty() {
1913            return;
1914        }
1915
1916        let mut path = PathBuilder::new();
1917        let first_line = lines.first().unwrap();
1918        let last_line = lines.last().unwrap();
1919
1920        let first_top_left = vec2f(first_line.start_x, start_y);
1921        let first_top_right = vec2f(first_line.end_x, start_y);
1922
1923        let curve_height = vec2f(0., self.corner_radius);
1924        let curve_width = |start_x: f32, end_x: f32| {
1925            let max = (end_x - start_x) / 2.;
1926            let width = if max < self.corner_radius {
1927                max
1928            } else {
1929                self.corner_radius
1930            };
1931
1932            vec2f(width, 0.)
1933        };
1934
1935        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1936        path.reset(first_top_right - top_curve_width);
1937        path.curve_to(first_top_right + curve_height, first_top_right);
1938
1939        let mut iter = lines.iter().enumerate().peekable();
1940        while let Some((ix, line)) = iter.next() {
1941            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1942
1943            if let Some((_, next_line)) = iter.peek() {
1944                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1945
1946                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1947                    Ordering::Equal => {
1948                        path.line_to(bottom_right);
1949                    }
1950                    Ordering::Less => {
1951                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1952                        path.line_to(bottom_right - curve_height);
1953                        if self.corner_radius > 0. {
1954                            path.curve_to(bottom_right - curve_width, bottom_right);
1955                        }
1956                        path.line_to(next_top_right + curve_width);
1957                        if self.corner_radius > 0. {
1958                            path.curve_to(next_top_right + curve_height, next_top_right);
1959                        }
1960                    }
1961                    Ordering::Greater => {
1962                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1963                        path.line_to(bottom_right - curve_height);
1964                        if self.corner_radius > 0. {
1965                            path.curve_to(bottom_right + curve_width, bottom_right);
1966                        }
1967                        path.line_to(next_top_right - curve_width);
1968                        if self.corner_radius > 0. {
1969                            path.curve_to(next_top_right + curve_height, next_top_right);
1970                        }
1971                    }
1972                }
1973            } else {
1974                let curve_width = curve_width(line.start_x, line.end_x);
1975                path.line_to(bottom_right - curve_height);
1976                if self.corner_radius > 0. {
1977                    path.curve_to(bottom_right - curve_width, bottom_right);
1978                }
1979
1980                let bottom_left = vec2f(line.start_x, bottom_right.y());
1981                path.line_to(bottom_left + curve_width);
1982                if self.corner_radius > 0. {
1983                    path.curve_to(bottom_left - curve_height, bottom_left);
1984                }
1985            }
1986        }
1987
1988        if first_line.start_x > last_line.start_x {
1989            let curve_width = curve_width(last_line.start_x, first_line.start_x);
1990            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1991            path.line_to(second_top_left + curve_height);
1992            if self.corner_radius > 0. {
1993                path.curve_to(second_top_left + curve_width, second_top_left);
1994            }
1995            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1996            path.line_to(first_bottom_left - curve_width);
1997            if self.corner_radius > 0. {
1998                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1999            }
2000        }
2001
2002        path.line_to(first_top_left + curve_height);
2003        if self.corner_radius > 0. {
2004            path.curve_to(first_top_left + top_curve_width, first_top_left);
2005        }
2006        path.line_to(first_top_right - top_curve_width);
2007
2008        scene.push_path(path.build(self.color, Some(bounds)));
2009    }
2010}
2011
2012pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2013    delta.powf(1.5) / 100.0
2014}
2015
2016fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2017    delta.powf(1.2) / 300.0
2018}
2019
2020#[cfg(test)]
2021mod tests {
2022    use std::sync::Arc;
2023
2024    use super::*;
2025    use crate::{
2026        display_map::{BlockDisposition, BlockProperties},
2027        Editor, MultiBuffer,
2028    };
2029    use settings::Settings;
2030    use util::test::sample_text;
2031
2032    #[gpui::test]
2033    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
2034        cx.set_global(Settings::test(cx));
2035        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2036        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2037            Editor::new(EditorMode::Full, buffer, None, None, cx)
2038        });
2039        let element = EditorElement::new(
2040            editor.downgrade(),
2041            editor.read(cx).style(cx),
2042            CursorShape::Bar,
2043        );
2044
2045        let layouts = editor.update(cx, |editor, cx| {
2046            let snapshot = editor.snapshot(cx);
2047            let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2048            let layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2049            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &layout_cx)
2050        });
2051        assert_eq!(layouts.len(), 6);
2052    }
2053
2054    #[gpui::test]
2055    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
2056        cx.set_global(Settings::test(cx));
2057        let buffer = MultiBuffer::build_simple("", cx);
2058        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2059            Editor::new(EditorMode::Full, buffer, None, None, cx)
2060        });
2061
2062        editor.update(cx, |editor, cx| {
2063            editor.set_placeholder_text("hello", cx);
2064            editor.insert_blocks(
2065                [BlockProperties {
2066                    style: BlockStyle::Fixed,
2067                    disposition: BlockDisposition::Above,
2068                    height: 3,
2069                    position: Anchor::min(),
2070                    render: Arc::new(|_| Empty::new().boxed()),
2071                }],
2072                cx,
2073            );
2074
2075            // Blur the editor so that it displays placeholder text.
2076            cx.blur();
2077        });
2078
2079        let mut element = EditorElement::new(
2080            editor.downgrade(),
2081            editor.read(cx).style(cx),
2082            CursorShape::Bar,
2083        );
2084
2085        let mut scene = Scene::new(1.0);
2086        let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2087        let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2088        let (size, mut state) = element.layout(
2089            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2090            &mut layout_cx,
2091        );
2092
2093        assert_eq!(state.line_layouts.len(), 4);
2094        assert_eq!(
2095            state
2096                .line_number_layouts
2097                .iter()
2098                .map(Option::is_some)
2099                .collect::<Vec<_>>(),
2100            &[false, false, false, true]
2101        );
2102
2103        // Don't panic.
2104        let bounds = RectF::new(Default::default(), size);
2105        let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2106        element.paint(bounds, bounds, &mut state, &mut paint_cx);
2107    }
2108}