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