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