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