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::{GitGutter, Settings};
  41use smallvec::SmallVec;
  42use std::{
  43    cmp::{self, Ordering},
  44    fmt::Write,
  45    iter,
  46    ops::{DerefMut, 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_row: u32,
 538            last_diff: Option<&'a DiffHunk<u32>>,
 539        }
 540
 541        fn diff_quad(
 542            hunk: &DiffHunk<u32>,
 543            gutter_layout: &GutterLayout,
 544            diff_style: &DiffStyle,
 545        ) -> Quad {
 546            let color = match hunk.status() {
 547                DiffHunkStatus::Added => diff_style.inserted,
 548                DiffHunkStatus::Modified => diff_style.modified,
 549
 550                //TODO: This rendering is entirely a horrible hack
 551                DiffHunkStatus::Removed => {
 552                    let row = hunk.buffer_range.start;
 553
 554                    let offset = gutter_layout.line_height / 2.;
 555                    let start_y =
 556                        row as f32 * gutter_layout.line_height + offset - gutter_layout.scroll_top;
 557                    let end_y = start_y + gutter_layout.line_height;
 558
 559                    let width = diff_style.removed_width_em * gutter_layout.line_height;
 560                    let highlight_origin = gutter_layout.bounds.origin() + vec2f(-width, start_y);
 561                    let highlight_size = vec2f(width * 2., end_y - start_y);
 562                    let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 563
 564                    return Quad {
 565                        bounds: highlight_bounds,
 566                        background: Some(diff_style.deleted),
 567                        border: Border::new(0., Color::transparent_black()),
 568                        corner_radius: 1. * gutter_layout.line_height,
 569                    };
 570                }
 571            };
 572
 573            let start_row = hunk.buffer_range.start;
 574            let end_row = hunk.buffer_range.end;
 575
 576            let start_y = start_row as f32 * gutter_layout.line_height - gutter_layout.scroll_top;
 577            let end_y = end_row as f32 * gutter_layout.line_height - gutter_layout.scroll_top;
 578
 579            let width = diff_style.width_em * gutter_layout.line_height;
 580            let highlight_origin = gutter_layout.bounds.origin() + vec2f(-width, start_y);
 581            let highlight_size = vec2f(width * 2., end_y - start_y);
 582            let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 583
 584            Quad {
 585                bounds: highlight_bounds,
 586                background: Some(color),
 587                border: Border::new(0., Color::transparent_black()),
 588                corner_radius: diff_style.corner_radius * gutter_layout.line_height,
 589            }
 590        }
 591
 592        let scroll_position = layout.position_map.snapshot.scroll_position();
 593        let gutter_layout = {
 594            let line_height = layout.position_map.line_height;
 595            GutterLayout {
 596                scroll_top: scroll_position.y() * line_height,
 597                line_height,
 598                bounds,
 599            }
 600        };
 601
 602        let mut diff_layout = DiffLayout {
 603            buffer_row: scroll_position.y() as u32,
 604            last_diff: None,
 605        };
 606
 607        let diff_style = &cx.global::<Settings>().theme.editor.diff.clone();
 608        let show_gutter = matches!(
 609            &cx.global::<Settings>()
 610                .git_overrides
 611                .git_gutter
 612                .unwrap_or_default(),
 613            GitGutter::TrackedFiles
 614        );
 615
 616        // line is `None` when there's a line wrap
 617        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 618            if let Some(line) = line {
 619                let line_origin = bounds.origin()
 620                    + vec2f(
 621                        bounds.width() - line.width() - layout.gutter_padding,
 622                        ix as f32 * gutter_layout.line_height
 623                            - (gutter_layout.scroll_top % gutter_layout.line_height),
 624                    );
 625
 626                line.paint(line_origin, visible_bounds, gutter_layout.line_height, cx);
 627
 628                if show_gutter {
 629                    //This line starts a buffer line, so let's do the diff calculation
 630                    let new_hunk = get_hunk(diff_layout.buffer_row, &layout.diff_hunks);
 631
 632                    let (is_ending, is_starting) = match (diff_layout.last_diff, new_hunk) {
 633                        (Some(old_hunk), Some(new_hunk)) if new_hunk == old_hunk => (false, false),
 634                        (a, b) => (a.is_some(), b.is_some()),
 635                    };
 636
 637                    if is_ending {
 638                        let last_hunk = diff_layout.last_diff.take().unwrap();
 639                        cx.scene
 640                            .push_quad(diff_quad(last_hunk, &gutter_layout, diff_style));
 641                    }
 642
 643                    if is_starting {
 644                        let new_hunk = new_hunk.unwrap();
 645                        diff_layout.last_diff = Some(new_hunk);
 646                    };
 647
 648                    diff_layout.buffer_row += 1;
 649                }
 650            }
 651        }
 652
 653        // If we ran out with a diff hunk still being prepped, paint it now
 654        if let Some(last_hunk) = diff_layout.last_diff {
 655            cx.scene
 656                .push_quad(diff_quad(last_hunk, &gutter_layout, diff_style))
 657        }
 658
 659        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
 660            let mut x = bounds.width() - layout.gutter_padding;
 661            let mut y = *row as f32 * gutter_layout.line_height - gutter_layout.scroll_top;
 662            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
 663            y += (gutter_layout.line_height - indicator.size().y()) / 2.;
 664            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
 665        }
 666    }
 667
 668    fn paint_text(
 669        &mut self,
 670        bounds: RectF,
 671        visible_bounds: RectF,
 672        layout: &mut LayoutState,
 673        cx: &mut PaintContext,
 674    ) {
 675        let view = self.view(cx.app);
 676        let style = &self.style;
 677        let local_replica_id = view.replica_id(cx);
 678        let scroll_position = layout.position_map.snapshot.scroll_position();
 679        let start_row = scroll_position.y() as u32;
 680        let scroll_top = scroll_position.y() * layout.position_map.line_height;
 681        let end_row =
 682            ((scroll_top + bounds.height()) / layout.position_map.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
 683        let max_glyph_width = layout.position_map.em_width;
 684        let scroll_left = scroll_position.x() * max_glyph_width;
 685        let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
 686
 687        cx.scene.push_layer(Some(bounds));
 688
 689        cx.scene.push_cursor_region(CursorRegion {
 690            bounds,
 691            style: if !view.link_go_to_definition_state.definitions.is_empty() {
 692                CursorStyle::PointingHand
 693            } else {
 694                CursorStyle::IBeam
 695            },
 696        });
 697
 698        for (range, color) in &layout.highlighted_ranges {
 699            self.paint_highlighted_range(
 700                range.clone(),
 701                start_row,
 702                end_row,
 703                *color,
 704                0.,
 705                0.15 * layout.position_map.line_height,
 706                layout,
 707                content_origin,
 708                scroll_top,
 709                scroll_left,
 710                bounds,
 711                cx,
 712            );
 713        }
 714
 715        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 716        for (replica_id, selections) in &layout.selections {
 717            let selection_style = style.replica_selection_style(*replica_id);
 718            let corner_radius = 0.15 * layout.position_map.line_height;
 719
 720            for selection in selections {
 721                self.paint_highlighted_range(
 722                    selection.range.clone(),
 723                    start_row,
 724                    end_row,
 725                    selection_style.selection,
 726                    corner_radius,
 727                    corner_radius * 2.,
 728                    layout,
 729                    content_origin,
 730                    scroll_top,
 731                    scroll_left,
 732                    bounds,
 733                    cx,
 734                );
 735
 736                if view.show_local_cursors() || *replica_id != local_replica_id {
 737                    let cursor_position = selection.head;
 738                    if (start_row..end_row).contains(&cursor_position.row()) {
 739                        let cursor_row_layout = &layout.position_map.line_layouts
 740                            [(cursor_position.row() - start_row) as usize];
 741                        let cursor_column = cursor_position.column() as usize;
 742
 743                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 744                        let mut block_width =
 745                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 746                        if block_width == 0.0 {
 747                            block_width = layout.position_map.em_width;
 748                        }
 749                        let block_text = if let CursorShape::Block = self.cursor_shape {
 750                            layout
 751                                .position_map
 752                                .snapshot
 753                                .chars_at(cursor_position)
 754                                .next()
 755                                .and_then(|character| {
 756                                    let font_id =
 757                                        cursor_row_layout.font_for_index(cursor_column)?;
 758                                    let text = character.to_string();
 759
 760                                    Some(cx.text_layout_cache.layout_str(
 761                                        &text,
 762                                        cursor_row_layout.font_size(),
 763                                        &[(
 764                                            text.len(),
 765                                            RunStyle {
 766                                                font_id,
 767                                                color: style.background,
 768                                                underline: Default::default(),
 769                                            },
 770                                        )],
 771                                    ))
 772                                })
 773                        } else {
 774                            None
 775                        };
 776
 777                        let x = cursor_character_x - scroll_left;
 778                        let y = cursor_position.row() as f32 * layout.position_map.line_height
 779                            - scroll_top;
 780                        cursors.push(Cursor {
 781                            color: selection_style.cursor,
 782                            block_width,
 783                            origin: vec2f(x, y),
 784                            line_height: layout.position_map.line_height,
 785                            shape: self.cursor_shape,
 786                            block_text,
 787                        });
 788                    }
 789                }
 790            }
 791        }
 792
 793        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 794            // Draw glyphs
 795            for (ix, line) in layout.position_map.line_layouts.iter().enumerate() {
 796                let row = start_row + ix as u32;
 797                line.paint(
 798                    content_origin
 799                        + vec2f(
 800                            -scroll_left,
 801                            row as f32 * layout.position_map.line_height - scroll_top,
 802                        ),
 803                    visible_text_bounds,
 804                    layout.position_map.line_height,
 805                    cx,
 806                );
 807            }
 808        }
 809
 810        cx.scene.push_layer(Some(bounds));
 811        for cursor in cursors {
 812            cursor.paint(content_origin, cx);
 813        }
 814        cx.scene.pop_layer();
 815
 816        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 817            cx.scene.push_stacking_context(None);
 818            let cursor_row_layout =
 819                &layout.position_map.line_layouts[(position.row() - start_row) as usize];
 820            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 821            let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
 822            let mut list_origin = content_origin + vec2f(x, y);
 823            let list_width = context_menu.size().x();
 824            let list_height = context_menu.size().y();
 825
 826            // Snap the right edge of the list to the right edge of the window if
 827            // its horizontal bounds overflow.
 828            if list_origin.x() + list_width > cx.window_size.x() {
 829                list_origin.set_x((cx.window_size.x() - list_width).max(0.));
 830            }
 831
 832            if list_origin.y() + list_height > bounds.max_y() {
 833                list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
 834            }
 835
 836            context_menu.paint(
 837                list_origin,
 838                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 839                cx,
 840            );
 841
 842            cx.scene.pop_stacking_context();
 843        }
 844
 845        if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
 846            cx.scene.push_stacking_context(None);
 847
 848            // This is safe because we check on layout whether the required row is available
 849            let hovered_row_layout =
 850                &layout.position_map.line_layouts[(position.row() - start_row) as usize];
 851
 852            // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
 853            // height. This is the size we will use to decide whether to render popovers above or below
 854            // the hovered line.
 855            let first_size = hover_popovers[0].size();
 856            let height_to_reserve = first_size.y()
 857                + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
 858
 859            // Compute Hovered Point
 860            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
 861            let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
 862            let hovered_point = content_origin + vec2f(x, y);
 863
 864            if hovered_point.y() - height_to_reserve > 0.0 {
 865                // There is enough space above. Render popovers above the hovered point
 866                let mut current_y = hovered_point.y();
 867                for hover_popover in hover_popovers {
 868                    let size = hover_popover.size();
 869                    let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
 870
 871                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 872                    if x_out_of_bounds < 0.0 {
 873                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 874                    }
 875
 876                    hover_popover.paint(
 877                        popover_origin,
 878                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 879                        cx,
 880                    );
 881
 882                    current_y = popover_origin.y() - HOVER_POPOVER_GAP;
 883                }
 884            } else {
 885                // There is not enough space above. Render popovers below the hovered point
 886                let mut current_y = hovered_point.y() + layout.position_map.line_height;
 887                for hover_popover in hover_popovers {
 888                    let size = hover_popover.size();
 889                    let mut popover_origin = vec2f(hovered_point.x(), current_y);
 890
 891                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 892                    if x_out_of_bounds < 0.0 {
 893                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 894                    }
 895
 896                    hover_popover.paint(
 897                        popover_origin,
 898                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 899                        cx,
 900                    );
 901
 902                    current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
 903                }
 904            }
 905
 906            cx.scene.pop_stacking_context();
 907        }
 908
 909        cx.scene.pop_layer();
 910    }
 911
 912    fn paint_scrollbar(&mut self, bounds: RectF, layout: &mut LayoutState, cx: &mut PaintContext) {
 913        enum ScrollbarMouseHandlers {}
 914        let row_range = if let Some(row_range) = &layout.scrollbar_row_range {
 915            row_range
 916        } else {
 917            return;
 918        };
 919
 920        let style = &self.style.theme.scrollbar;
 921        let top = bounds.min_y();
 922        let bottom = bounds.max_y();
 923        let height = bounds.height();
 924
 925        let max_row = layout.max_row + row_range.len() as u32;
 926        let scrollbar_start = row_range.start as f32 / max_row as f32;
 927        let scrollbar_end = row_range.end as f32 / max_row as f32;
 928
 929        let thumb_top = top + scrollbar_start * height;
 930        let thumb_bottom = top + scrollbar_end * height;
 931        let right = bounds.max_x();
 932        let left = right - style.width;
 933        let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
 934        let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
 935
 936        cx.scene.push_quad(Quad {
 937            bounds: track_bounds,
 938            border: style.track.border,
 939            background: style.track.background_color,
 940            ..Default::default()
 941        });
 942        cx.scene.push_quad(Quad {
 943            bounds: thumb_bounds,
 944            border: style.thumb.border,
 945            background: style.thumb.background_color,
 946            corner_radius: style.thumb.corner_radius,
 947        });
 948        cx.scene.push_cursor_region(CursorRegion {
 949            bounds: track_bounds,
 950            style: CursorStyle::Arrow,
 951        });
 952
 953        let view = self.view.clone();
 954        cx.scene.push_mouse_region(
 955            MouseRegion::new::<ScrollbarMouseHandlers>(
 956                self.view.id(),
 957                self.view.id(),
 958                track_bounds,
 959            )
 960            .on_down(MouseButton::Left, {
 961                let view = view.clone();
 962                let row_range_len = row_range.len();
 963                move |e, cx| {
 964                    let y = e.position.y();
 965                    if y < thumb_top || thumb_bottom < y {
 966                        if let Some(view) = view.upgrade(cx.deref_mut()) {
 967                            view.update(cx.deref_mut(), |view, cx| {
 968                                let center_row =
 969                                    ((y - top) * max_row as f32 / height).round() as u32;
 970                                let top_row = center_row.saturating_sub(row_range_len as u32 / 2);
 971                                let mut position = view.scroll_position(cx);
 972                                position.set_y(top_row as f32);
 973                                view.set_scroll_position(position, cx);
 974                            });
 975                        }
 976                    }
 977                }
 978            })
 979            .on_drag(MouseButton::Left, {
 980                let view = view.clone();
 981                move |e, cx| {
 982                    let y = e.prev_mouse_position.y();
 983                    let new_y = e.position.y();
 984                    if thumb_top < y && y < thumb_bottom {
 985                        if let Some(view) = view.upgrade(cx.deref_mut()) {
 986                            view.update(cx.deref_mut(), |view, cx| {
 987                                let mut position = view.scroll_position(cx);
 988                                position
 989                                    .set_y(position.y() + (new_y - y) * (max_row as f32) / height);
 990                                if position.y() < 0.0 {
 991                                    position.set_y(0.);
 992                                }
 993                                view.set_scroll_position(position, cx);
 994                            });
 995                        }
 996                    }
 997                }
 998            }),
 999        );
1000    }
1001
1002    #[allow(clippy::too_many_arguments)]
1003    fn paint_highlighted_range(
1004        &self,
1005        range: Range<DisplayPoint>,
1006        start_row: u32,
1007        end_row: u32,
1008        color: Color,
1009        corner_radius: f32,
1010        line_end_overshoot: f32,
1011        layout: &LayoutState,
1012        content_origin: Vector2F,
1013        scroll_top: f32,
1014        scroll_left: f32,
1015        bounds: RectF,
1016        cx: &mut PaintContext,
1017    ) {
1018        if range.start != range.end {
1019            let row_range = if range.end.column() == 0 {
1020                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1021            } else {
1022                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1023            };
1024
1025            let highlighted_range = HighlightedRange {
1026                color,
1027                line_height: layout.position_map.line_height,
1028                corner_radius,
1029                start_y: content_origin.y()
1030                    + row_range.start as f32 * layout.position_map.line_height
1031                    - scroll_top,
1032                lines: row_range
1033                    .into_iter()
1034                    .map(|row| {
1035                        let line_layout =
1036                            &layout.position_map.line_layouts[(row - start_row) as usize];
1037                        HighlightedRangeLine {
1038                            start_x: if row == range.start.row() {
1039                                content_origin.x()
1040                                    + line_layout.x_for_index(range.start.column() as usize)
1041                                    - scroll_left
1042                            } else {
1043                                content_origin.x() - scroll_left
1044                            },
1045                            end_x: if row == range.end.row() {
1046                                content_origin.x()
1047                                    + line_layout.x_for_index(range.end.column() as usize)
1048                                    - scroll_left
1049                            } else {
1050                                content_origin.x() + line_layout.width() + line_end_overshoot
1051                                    - scroll_left
1052                            },
1053                        }
1054                    })
1055                    .collect(),
1056            };
1057
1058            highlighted_range.paint(bounds, cx.scene);
1059        }
1060    }
1061
1062    fn paint_blocks(
1063        &mut self,
1064        bounds: RectF,
1065        visible_bounds: RectF,
1066        layout: &mut LayoutState,
1067        cx: &mut PaintContext,
1068    ) {
1069        let scroll_position = layout.position_map.snapshot.scroll_position();
1070        let scroll_left = scroll_position.x() * layout.position_map.em_width;
1071        let scroll_top = scroll_position.y() * layout.position_map.line_height;
1072
1073        for block in &mut layout.blocks {
1074            let mut origin = bounds.origin()
1075                + vec2f(
1076                    0.,
1077                    block.row as f32 * layout.position_map.line_height - scroll_top,
1078                );
1079            if !matches!(block.style, BlockStyle::Sticky) {
1080                origin += vec2f(-scroll_left, 0.);
1081            }
1082            block.element.paint(origin, visible_bounds, cx);
1083        }
1084    }
1085
1086    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
1087        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
1088        let style = &self.style;
1089
1090        cx.text_layout_cache
1091            .layout_str(
1092                "1".repeat(digit_count).as_str(),
1093                style.text.font_size,
1094                &[(
1095                    digit_count,
1096                    RunStyle {
1097                        font_id: style.text.font_id,
1098                        color: Color::black(),
1099                        underline: Default::default(),
1100                    },
1101                )],
1102            )
1103            .width()
1104    }
1105
1106    fn layout_line_numbers(
1107        &self,
1108        rows: Range<u32>,
1109        active_rows: &BTreeMap<u32, bool>,
1110        snapshot: &EditorSnapshot,
1111        cx: &LayoutContext,
1112    ) -> Vec<Option<text_layout::Line>> {
1113        let style = &self.style;
1114        let include_line_numbers = snapshot.mode == EditorMode::Full;
1115        let mut line_number_layouts = Vec::with_capacity(rows.len());
1116        let mut line_number = String::new();
1117        for (ix, row) in snapshot
1118            .buffer_rows(rows.start)
1119            .take((rows.end - rows.start) as usize)
1120            .enumerate()
1121        {
1122            let display_row = rows.start + ix as u32;
1123            let color = if active_rows.contains_key(&display_row) {
1124                style.line_number_active
1125            } else {
1126                style.line_number
1127            };
1128            if let Some(buffer_row) = row {
1129                if include_line_numbers {
1130                    line_number.clear();
1131                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1132                    line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
1133                        &line_number,
1134                        style.text.font_size,
1135                        &[(
1136                            line_number.len(),
1137                            RunStyle {
1138                                font_id: style.text.font_id,
1139                                color,
1140                                underline: Default::default(),
1141                            },
1142                        )],
1143                    )));
1144                }
1145            } else {
1146                line_number_layouts.push(None);
1147            }
1148        }
1149
1150        line_number_layouts
1151    }
1152
1153    fn layout_lines(
1154        &mut self,
1155        rows: Range<u32>,
1156        snapshot: &EditorSnapshot,
1157        cx: &LayoutContext,
1158    ) -> Vec<text_layout::Line> {
1159        if rows.start >= rows.end {
1160            return Vec::new();
1161        }
1162
1163        // When the editor is empty and unfocused, then show the placeholder.
1164        if snapshot.is_empty() && !snapshot.is_focused() {
1165            let placeholder_style = self
1166                .style
1167                .placeholder_text
1168                .as_ref()
1169                .unwrap_or(&self.style.text);
1170            let placeholder_text = snapshot.placeholder_text();
1171            let placeholder_lines = placeholder_text
1172                .as_ref()
1173                .map_or("", AsRef::as_ref)
1174                .split('\n')
1175                .skip(rows.start as usize)
1176                .chain(iter::repeat(""))
1177                .take(rows.len());
1178            placeholder_lines
1179                .map(|line| {
1180                    cx.text_layout_cache.layout_str(
1181                        line,
1182                        placeholder_style.font_size,
1183                        &[(
1184                            line.len(),
1185                            RunStyle {
1186                                font_id: placeholder_style.font_id,
1187                                color: placeholder_style.color,
1188                                underline: Default::default(),
1189                            },
1190                        )],
1191                    )
1192                })
1193                .collect()
1194        } else {
1195            let style = &self.style;
1196            let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
1197                let mut highlight_style = chunk
1198                    .syntax_highlight_id
1199                    .and_then(|id| id.style(&style.syntax));
1200
1201                if let Some(chunk_highlight) = chunk.highlight_style {
1202                    if let Some(highlight_style) = highlight_style.as_mut() {
1203                        highlight_style.highlight(chunk_highlight);
1204                    } else {
1205                        highlight_style = Some(chunk_highlight);
1206                    }
1207                }
1208
1209                let mut diagnostic_highlight = HighlightStyle::default();
1210
1211                if chunk.is_unnecessary {
1212                    diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1213                }
1214
1215                if let Some(severity) = chunk.diagnostic_severity {
1216                    // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1217                    if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1218                        let diagnostic_style = super::diagnostic_style(severity, true, style);
1219                        diagnostic_highlight.underline = Some(Underline {
1220                            color: Some(diagnostic_style.message.text.color),
1221                            thickness: 1.0.into(),
1222                            squiggly: true,
1223                        });
1224                    }
1225                }
1226
1227                if let Some(highlight_style) = highlight_style.as_mut() {
1228                    highlight_style.highlight(diagnostic_highlight);
1229                } else {
1230                    highlight_style = Some(diagnostic_highlight);
1231                }
1232
1233                (chunk.text, highlight_style)
1234            });
1235            layout_highlighted_chunks(
1236                chunks,
1237                &style.text,
1238                cx.text_layout_cache,
1239                cx.font_cache,
1240                MAX_LINE_LEN,
1241                rows.len() as usize,
1242            )
1243        }
1244    }
1245
1246    #[allow(clippy::too_many_arguments)]
1247    fn layout_blocks(
1248        &mut self,
1249        rows: Range<u32>,
1250        snapshot: &EditorSnapshot,
1251        editor_width: f32,
1252        scroll_width: f32,
1253        gutter_padding: f32,
1254        gutter_width: f32,
1255        em_width: f32,
1256        text_x: f32,
1257        line_height: f32,
1258        style: &EditorStyle,
1259        line_layouts: &[text_layout::Line],
1260        cx: &mut LayoutContext,
1261    ) -> (f32, Vec<BlockLayout>) {
1262        let editor = if let Some(editor) = self.view.upgrade(cx) {
1263            editor
1264        } else {
1265            return Default::default();
1266        };
1267
1268        let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
1269        let scroll_x = snapshot.scroll_position.x();
1270        let (fixed_blocks, non_fixed_blocks) = snapshot
1271            .blocks_in_range(rows.clone())
1272            .partition::<Vec<_>, _>(|(_, block)| match block {
1273                TransformBlock::ExcerptHeader { .. } => false,
1274                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1275            });
1276        let mut render_block = |block: &TransformBlock, width: f32| {
1277            let mut element = match block {
1278                TransformBlock::Custom(block) => {
1279                    let align_to = block
1280                        .position()
1281                        .to_point(&snapshot.buffer_snapshot)
1282                        .to_display_point(snapshot);
1283                    let anchor_x = text_x
1284                        + if rows.contains(&align_to.row()) {
1285                            line_layouts[(align_to.row() - rows.start) as usize]
1286                                .x_for_index(align_to.column() as usize)
1287                        } else {
1288                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
1289                                .x_for_index(align_to.column() as usize)
1290                        };
1291
1292                    cx.render(&editor, |_, cx| {
1293                        block.render(&mut BlockContext {
1294                            cx,
1295                            anchor_x,
1296                            gutter_padding,
1297                            line_height,
1298                            scroll_x,
1299                            gutter_width,
1300                            em_width,
1301                        })
1302                    })
1303                }
1304                TransformBlock::ExcerptHeader {
1305                    key,
1306                    buffer,
1307                    range,
1308                    starts_new_buffer,
1309                    ..
1310                } => {
1311                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1312                        let jump_position = range
1313                            .primary
1314                            .as_ref()
1315                            .map_or(range.context.start, |primary| primary.start);
1316                        let jump_action = crate::Jump {
1317                            path: ProjectPath {
1318                                worktree_id: file.worktree_id(cx),
1319                                path: file.path.clone(),
1320                            },
1321                            position: language::ToPoint::to_point(&jump_position, buffer),
1322                            anchor: jump_position,
1323                        };
1324
1325                        enum JumpIcon {}
1326                        cx.render(&editor, |_, cx| {
1327                            MouseEventHandler::<JumpIcon>::new(*key, cx, |state, _| {
1328                                let style = style.jump_icon.style_for(state, false);
1329                                Svg::new("icons/arrow_up_right_8.svg")
1330                                    .with_color(style.color)
1331                                    .constrained()
1332                                    .with_width(style.icon_width)
1333                                    .aligned()
1334                                    .contained()
1335                                    .with_style(style.container)
1336                                    .constrained()
1337                                    .with_width(style.button_width)
1338                                    .with_height(style.button_width)
1339                                    .boxed()
1340                            })
1341                            .with_cursor_style(CursorStyle::PointingHand)
1342                            .on_click(MouseButton::Left, move |_, cx| {
1343                                cx.dispatch_action(jump_action.clone())
1344                            })
1345                            .with_tooltip::<JumpIcon, _>(
1346                                *key,
1347                                "Jump to Buffer".to_string(),
1348                                Some(Box::new(crate::OpenExcerpts)),
1349                                tooltip_style.clone(),
1350                                cx,
1351                            )
1352                            .aligned()
1353                            .flex_float()
1354                            .boxed()
1355                        })
1356                    });
1357
1358                    if *starts_new_buffer {
1359                        let style = &self.style.diagnostic_path_header;
1360                        let font_size =
1361                            (style.text_scale_factor * self.style.text.font_size).round();
1362
1363                        let mut filename = None;
1364                        let mut parent_path = None;
1365                        if let Some(file) = buffer.file() {
1366                            let path = file.path();
1367                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1368                            parent_path =
1369                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1370                        }
1371
1372                        Flex::row()
1373                            .with_child(
1374                                Label::new(
1375                                    filename.unwrap_or_else(|| "untitled".to_string()),
1376                                    style.filename.text.clone().with_font_size(font_size),
1377                                )
1378                                .contained()
1379                                .with_style(style.filename.container)
1380                                .aligned()
1381                                .boxed(),
1382                            )
1383                            .with_children(parent_path.map(|path| {
1384                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1385                                    .contained()
1386                                    .with_style(style.path.container)
1387                                    .aligned()
1388                                    .boxed()
1389                            }))
1390                            .with_children(jump_icon)
1391                            .contained()
1392                            .with_style(style.container)
1393                            .with_padding_left(gutter_padding)
1394                            .with_padding_right(gutter_padding)
1395                            .expanded()
1396                            .named("path header block")
1397                    } else {
1398                        let text_style = self.style.text.clone();
1399                        Flex::row()
1400                            .with_child(Label::new("".to_string(), text_style).boxed())
1401                            .with_children(jump_icon)
1402                            .contained()
1403                            .with_padding_left(gutter_padding)
1404                            .with_padding_right(gutter_padding)
1405                            .expanded()
1406                            .named("collapsed context")
1407                    }
1408                }
1409            };
1410
1411            element.layout(
1412                SizeConstraint {
1413                    min: Vector2F::zero(),
1414                    max: vec2f(width, block.height() as f32 * line_height),
1415                },
1416                cx,
1417            );
1418            element
1419        };
1420
1421        let mut fixed_block_max_width = 0f32;
1422        let mut blocks = Vec::new();
1423        for (row, block) in fixed_blocks {
1424            let element = render_block(block, f32::INFINITY);
1425            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1426            blocks.push(BlockLayout {
1427                row,
1428                element,
1429                style: BlockStyle::Fixed,
1430            });
1431        }
1432        for (row, block) in non_fixed_blocks {
1433            let style = match block {
1434                TransformBlock::Custom(block) => block.style(),
1435                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1436            };
1437            let width = match style {
1438                BlockStyle::Sticky => editor_width,
1439                BlockStyle::Flex => editor_width
1440                    .max(fixed_block_max_width)
1441                    .max(gutter_width + scroll_width),
1442                BlockStyle::Fixed => unreachable!(),
1443            };
1444            let element = render_block(block, width);
1445            blocks.push(BlockLayout {
1446                row,
1447                element,
1448                style,
1449            });
1450        }
1451        (
1452            scroll_width.max(fixed_block_max_width - gutter_width),
1453            blocks,
1454        )
1455    }
1456}
1457
1458/// Get the hunk that contains buffer_line, starting from start_idx
1459/// Returns none if there is none found, and
1460fn get_hunk(buffer_line: u32, hunks: &[DiffHunk<u32>]) -> Option<&DiffHunk<u32>> {
1461    for i in 0..hunks.len() {
1462        // Safety: Index out of bounds is handled by the check above
1463        let hunk = hunks.get(i).unwrap();
1464        if hunk.buffer_range.contains(&(buffer_line as u32)) {
1465            return Some(hunk);
1466        } else if hunk.status() == DiffHunkStatus::Removed && buffer_line == hunk.buffer_range.start
1467        {
1468            return Some(hunk);
1469        } else if hunk.buffer_range.start > buffer_line as u32 {
1470            // If we've passed the buffer_line, just stop
1471            return None;
1472        }
1473    }
1474
1475    // We reached the end of the array without finding a hunk, just return none.
1476    return None;
1477}
1478
1479impl Element for EditorElement {
1480    type LayoutState = LayoutState;
1481    type PaintState = ();
1482
1483    fn layout(
1484        &mut self,
1485        constraint: SizeConstraint,
1486        cx: &mut LayoutContext,
1487    ) -> (Vector2F, Self::LayoutState) {
1488        let mut size = constraint.max;
1489        if size.x().is_infinite() {
1490            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1491        }
1492
1493        let snapshot = self.snapshot(cx.app);
1494        let style = self.style.clone();
1495        let line_height = style.text.line_height(cx.font_cache);
1496
1497        let gutter_padding;
1498        let gutter_width;
1499        let gutter_margin;
1500        if snapshot.mode == EditorMode::Full {
1501            gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1502            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1503            gutter_margin = -style.text.descent(cx.font_cache);
1504        } else {
1505            gutter_padding = 0.0;
1506            gutter_width = 0.0;
1507            gutter_margin = 0.0;
1508        };
1509
1510        let text_width = size.x() - gutter_width;
1511        let em_width = style.text.em_width(cx.font_cache);
1512        let em_advance = style.text.em_advance(cx.font_cache);
1513        let overscroll = vec2f(em_width, 0.);
1514        let snapshot = self.update_view(cx.app, |view, cx| {
1515            let wrap_width = match view.soft_wrap_mode(cx) {
1516                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1517                SoftWrap::EditorWidth => {
1518                    Some(text_width - gutter_margin - overscroll.x() - em_width)
1519                }
1520                SoftWrap::Column(column) => Some(column as f32 * em_advance),
1521            };
1522
1523            if view.set_wrap_width(wrap_width, cx) {
1524                view.snapshot(cx)
1525            } else {
1526                snapshot
1527            }
1528        });
1529
1530        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1531        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1532            size.set_y(
1533                scroll_height
1534                    .min(constraint.max_along(Axis::Vertical))
1535                    .max(constraint.min_along(Axis::Vertical))
1536                    .min(line_height * max_lines as f32),
1537            )
1538        } else if let EditorMode::SingleLine = snapshot.mode {
1539            size.set_y(
1540                line_height
1541                    .min(constraint.max_along(Axis::Vertical))
1542                    .max(constraint.min_along(Axis::Vertical)),
1543            )
1544        } else if size.y().is_infinite() {
1545            size.set_y(scroll_height);
1546        }
1547        let gutter_size = vec2f(gutter_width, size.y());
1548        let text_size = vec2f(text_width, size.y());
1549
1550        let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1551            let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1552            let snapshot = view.snapshot(cx);
1553            (autoscroll_horizontally, snapshot)
1554        });
1555
1556        let scroll_position = snapshot.scroll_position();
1557        // The scroll position is a fractional point, the whole number of which represents
1558        // the top of the window in terms of display rows.
1559        let start_row = scroll_position.y() as u32;
1560        let visible_row_count = (size.y() / line_height).ceil() as u32;
1561        let max_row = snapshot.max_point().row();
1562
1563        // Add 1 to ensure selections bleed off screen
1564        let end_row = 1 + cmp::min(start_row + visible_row_count, max_row);
1565
1566        let start_anchor = if start_row == 0 {
1567            Anchor::min()
1568        } else {
1569            snapshot
1570                .buffer_snapshot
1571                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1572        };
1573        let end_anchor = if end_row > max_row {
1574            Anchor::max()
1575        } else {
1576            snapshot
1577                .buffer_snapshot
1578                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1579        };
1580
1581        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1582        let mut active_rows = BTreeMap::new();
1583        let mut highlighted_rows = None;
1584        let mut highlighted_ranges = Vec::new();
1585        self.update_view(cx.app, |view, cx| {
1586            let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1587
1588            highlighted_rows = view.highlighted_rows();
1589            let theme = cx.global::<Settings>().theme.as_ref();
1590            highlighted_ranges = view.background_highlights_in_range(
1591                start_anchor.clone()..end_anchor.clone(),
1592                &display_map,
1593                theme,
1594            );
1595
1596            let mut remote_selections = HashMap::default();
1597            for (replica_id, line_mode, selection) in display_map
1598                .buffer_snapshot
1599                .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1600            {
1601                // The local selections match the leader's selections.
1602                if Some(replica_id) == view.leader_replica_id {
1603                    continue;
1604                }
1605                remote_selections
1606                    .entry(replica_id)
1607                    .or_insert(Vec::new())
1608                    .push(SelectionLayout::new(selection, line_mode, &display_map));
1609            }
1610            selections.extend(remote_selections);
1611
1612            if view.show_local_selections {
1613                let mut local_selections = view
1614                    .selections
1615                    .disjoint_in_range(start_anchor..end_anchor, cx);
1616                local_selections.extend(view.selections.pending(cx));
1617                for selection in &local_selections {
1618                    let is_empty = selection.start == selection.end;
1619                    let selection_start = snapshot.prev_line_boundary(selection.start).1;
1620                    let selection_end = snapshot.next_line_boundary(selection.end).1;
1621                    for row in cmp::max(selection_start.row(), start_row)
1622                        ..=cmp::min(selection_end.row(), end_row)
1623                    {
1624                        let contains_non_empty_selection =
1625                            active_rows.entry(row).or_insert(!is_empty);
1626                        *contains_non_empty_selection |= !is_empty;
1627                    }
1628                }
1629
1630                // Render the local selections in the leader's color when following.
1631                let local_replica_id = view
1632                    .leader_replica_id
1633                    .unwrap_or_else(|| view.replica_id(cx));
1634
1635                selections.push((
1636                    local_replica_id,
1637                    local_selections
1638                        .into_iter()
1639                        .map(|selection| {
1640                            SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1641                        })
1642                        .collect(),
1643                ));
1644            }
1645        });
1646
1647        let line_number_layouts =
1648            self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1649
1650        let diff_hunks = snapshot
1651            .buffer_snapshot
1652            .git_diff_hunks_in_range(start_row..end_row)
1653            .collect();
1654
1655        let scrollbar_row_range = if snapshot.mode == EditorMode::Full {
1656            Some(start_row..(start_row + visible_row_count))
1657        } else {
1658            None
1659        };
1660
1661        let mut max_visible_line_width = 0.0;
1662        let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1663        for line in &line_layouts {
1664            if line.width() > max_visible_line_width {
1665                max_visible_line_width = line.width();
1666            }
1667        }
1668
1669        let style = self.style.clone();
1670        let longest_line_width = layout_line(
1671            snapshot.longest_row(),
1672            &snapshot,
1673            &style,
1674            cx.text_layout_cache,
1675        )
1676        .width();
1677        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1678        let em_width = style.text.em_width(cx.font_cache);
1679        let (scroll_width, blocks) = self.layout_blocks(
1680            start_row..end_row,
1681            &snapshot,
1682            size.x(),
1683            scroll_width,
1684            gutter_padding,
1685            gutter_width,
1686            em_width,
1687            gutter_width + gutter_margin,
1688            line_height,
1689            &style,
1690            &line_layouts,
1691            cx,
1692        );
1693
1694        let scroll_max = vec2f(
1695            ((scroll_width - text_size.x()) / em_width).max(0.0),
1696            max_row.saturating_sub(1) as f32,
1697        );
1698
1699        self.update_view(cx.app, |view, cx| {
1700            let clamped = view.clamp_scroll_left(scroll_max.x());
1701
1702            let autoscrolled = if autoscroll_horizontally {
1703                view.autoscroll_horizontally(
1704                    start_row,
1705                    text_size.x(),
1706                    scroll_width,
1707                    em_width,
1708                    &line_layouts,
1709                    cx,
1710                )
1711            } else {
1712                false
1713            };
1714
1715            if clamped || autoscrolled {
1716                snapshot = view.snapshot(cx);
1717            }
1718        });
1719
1720        let mut context_menu = None;
1721        let mut code_actions_indicator = None;
1722        let mut hover = None;
1723        cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1724            let newest_selection_head = view
1725                .selections
1726                .newest::<usize>(cx)
1727                .head()
1728                .to_display_point(&snapshot);
1729
1730            let style = view.style(cx);
1731            if (start_row..end_row).contains(&newest_selection_head.row()) {
1732                if view.context_menu_visible() {
1733                    context_menu =
1734                        view.render_context_menu(newest_selection_head, style.clone(), cx);
1735                }
1736
1737                code_actions_indicator = view
1738                    .render_code_actions_indicator(&style, cx)
1739                    .map(|indicator| (newest_selection_head.row(), indicator));
1740            }
1741
1742            let visible_rows = start_row..start_row + line_layouts.len() as u32;
1743            hover = view.hover_state.render(&snapshot, &style, visible_rows, cx);
1744        });
1745
1746        if let Some((_, context_menu)) = context_menu.as_mut() {
1747            context_menu.layout(
1748                SizeConstraint {
1749                    min: Vector2F::zero(),
1750                    max: vec2f(
1751                        cx.window_size.x() * 0.7,
1752                        (12. * line_height).min((size.y() - line_height) / 2.),
1753                    ),
1754                },
1755                cx,
1756            );
1757        }
1758
1759        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1760            indicator.layout(
1761                SizeConstraint::strict_along(
1762                    Axis::Vertical,
1763                    line_height * style.code_actions.vertical_scale,
1764                ),
1765                cx,
1766            );
1767        }
1768
1769        if let Some((_, hover_popovers)) = hover.as_mut() {
1770            for hover_popover in hover_popovers.iter_mut() {
1771                hover_popover.layout(
1772                    SizeConstraint {
1773                        min: Vector2F::zero(),
1774                        max: vec2f(
1775                            (120. * em_width) // Default size
1776                                .min(size.x() / 2.) // Shrink to half of the editor width
1777                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1778                            (16. * line_height) // Default size
1779                                .min(size.y() / 2.) // Shrink to half of the editor height
1780                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1781                        ),
1782                    },
1783                    cx,
1784                );
1785            }
1786        }
1787
1788        (
1789            size,
1790            LayoutState {
1791                position_map: Arc::new(PositionMap {
1792                    size,
1793                    scroll_max,
1794                    line_layouts,
1795                    line_height,
1796                    em_width,
1797                    em_advance,
1798                    snapshot,
1799                }),
1800                gutter_size,
1801                gutter_padding,
1802                text_size,
1803                scrollbar_row_range,
1804                max_row,
1805                gutter_margin,
1806                active_rows,
1807                highlighted_rows,
1808                highlighted_ranges,
1809                line_number_layouts,
1810                diff_hunks,
1811                blocks,
1812                selections,
1813                context_menu,
1814                code_actions_indicator,
1815                hover_popovers: hover,
1816            },
1817        )
1818    }
1819
1820    fn paint(
1821        &mut self,
1822        bounds: RectF,
1823        visible_bounds: RectF,
1824        layout: &mut Self::LayoutState,
1825        cx: &mut PaintContext,
1826    ) -> Self::PaintState {
1827        cx.scene.push_layer(Some(bounds));
1828
1829        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1830        let text_bounds = RectF::new(
1831            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1832            layout.text_size,
1833        );
1834
1835        Self::attach_mouse_handlers(
1836            &self.view,
1837            &layout.position_map,
1838            visible_bounds,
1839            text_bounds,
1840            gutter_bounds,
1841            bounds,
1842            cx,
1843        );
1844
1845        self.paint_background(gutter_bounds, text_bounds, layout, cx);
1846        if layout.gutter_size.x() > 0. {
1847            self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1848        }
1849        self.paint_text(text_bounds, visible_bounds, layout, cx);
1850
1851        cx.scene.push_layer(Some(bounds));
1852        if !layout.blocks.is_empty() {
1853            self.paint_blocks(bounds, visible_bounds, layout, cx);
1854        }
1855        self.paint_scrollbar(bounds, layout, cx);
1856        cx.scene.pop_layer();
1857
1858        cx.scene.pop_layer();
1859    }
1860
1861    fn dispatch_event(
1862        &mut self,
1863        event: &Event,
1864        _: RectF,
1865        _: RectF,
1866        _: &mut LayoutState,
1867        _: &mut (),
1868        cx: &mut EventContext,
1869    ) -> bool {
1870        if let Event::ModifiersChanged(event) = event {
1871            self.modifiers_changed(*event, cx);
1872        }
1873
1874        false
1875    }
1876
1877    fn rect_for_text_range(
1878        &self,
1879        range_utf16: Range<usize>,
1880        bounds: RectF,
1881        _: RectF,
1882        layout: &Self::LayoutState,
1883        _: &Self::PaintState,
1884        _: &gpui::MeasurementContext,
1885    ) -> Option<RectF> {
1886        let text_bounds = RectF::new(
1887            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1888            layout.text_size,
1889        );
1890        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
1891        let scroll_position = layout.position_map.snapshot.scroll_position();
1892        let start_row = scroll_position.y() as u32;
1893        let scroll_top = scroll_position.y() * layout.position_map.line_height;
1894        let scroll_left = scroll_position.x() * layout.position_map.em_width;
1895
1896        let range_start = OffsetUtf16(range_utf16.start)
1897            .to_display_point(&layout.position_map.snapshot.display_snapshot);
1898        if range_start.row() < start_row {
1899            return None;
1900        }
1901
1902        let line = layout
1903            .position_map
1904            .line_layouts
1905            .get((range_start.row() - start_row) as usize)?;
1906        let range_start_x = line.x_for_index(range_start.column() as usize);
1907        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
1908        Some(RectF::new(
1909            content_origin
1910                + vec2f(
1911                    range_start_x,
1912                    range_start_y + layout.position_map.line_height,
1913                )
1914                - vec2f(scroll_left, scroll_top),
1915            vec2f(
1916                layout.position_map.em_width,
1917                layout.position_map.line_height,
1918            ),
1919        ))
1920    }
1921
1922    fn debug(
1923        &self,
1924        bounds: RectF,
1925        _: &Self::LayoutState,
1926        _: &Self::PaintState,
1927        _: &gpui::DebugContext,
1928    ) -> json::Value {
1929        json!({
1930            "type": "BufferElement",
1931            "bounds": bounds.to_json()
1932        })
1933    }
1934}
1935
1936pub struct LayoutState {
1937    position_map: Arc<PositionMap>,
1938    gutter_size: Vector2F,
1939    gutter_padding: f32,
1940    gutter_margin: f32,
1941    text_size: Vector2F,
1942    active_rows: BTreeMap<u32, bool>,
1943    highlighted_rows: Option<Range<u32>>,
1944    line_number_layouts: Vec<Option<text_layout::Line>>,
1945    blocks: Vec<BlockLayout>,
1946    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1947    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1948    scrollbar_row_range: Option<Range<u32>>,
1949    max_row: u32,
1950    context_menu: Option<(DisplayPoint, ElementBox)>,
1951    diff_hunks: Vec<DiffHunk<u32>>,
1952    code_actions_indicator: Option<(u32, ElementBox)>,
1953    hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
1954}
1955
1956pub struct PositionMap {
1957    size: Vector2F,
1958    line_height: f32,
1959    scroll_max: Vector2F,
1960    em_width: f32,
1961    em_advance: f32,
1962    line_layouts: Vec<text_layout::Line>,
1963    snapshot: EditorSnapshot,
1964}
1965
1966impl PositionMap {
1967    /// Returns two display points:
1968    /// 1. The nearest *valid* position in the editor
1969    /// 2. An unclipped, potentially *invalid* position that maps directly to
1970    ///    the given pixel position.
1971    fn point_for_position(
1972        &self,
1973        text_bounds: RectF,
1974        position: Vector2F,
1975    ) -> (DisplayPoint, DisplayPoint) {
1976        let scroll_position = self.snapshot.scroll_position();
1977        let position = position - text_bounds.origin();
1978        let y = position.y().max(0.0).min(self.size.y());
1979        let x = position.x() + (scroll_position.x() * self.em_width);
1980        let row = (y / self.line_height + scroll_position.y()) as u32;
1981        let (column, x_overshoot) = if let Some(line) = self
1982            .line_layouts
1983            .get(row as usize - scroll_position.y() as usize)
1984        {
1985            if let Some(ix) = line.index_for_x(x) {
1986                (ix as u32, 0.0)
1987            } else {
1988                (line.len() as u32, 0f32.max(x - line.width()))
1989            }
1990        } else {
1991            (0, x)
1992        };
1993
1994        let mut target_point = DisplayPoint::new(row, column);
1995        let point = self.snapshot.clip_point(target_point, Bias::Left);
1996        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
1997
1998        (point, target_point)
1999    }
2000}
2001
2002struct BlockLayout {
2003    row: u32,
2004    element: ElementBox,
2005    style: BlockStyle,
2006}
2007
2008fn layout_line(
2009    row: u32,
2010    snapshot: &EditorSnapshot,
2011    style: &EditorStyle,
2012    layout_cache: &TextLayoutCache,
2013) -> text_layout::Line {
2014    let mut line = snapshot.line(row);
2015
2016    if line.len() > MAX_LINE_LEN {
2017        let mut len = MAX_LINE_LEN;
2018        while !line.is_char_boundary(len) {
2019            len -= 1;
2020        }
2021
2022        line.truncate(len);
2023    }
2024
2025    layout_cache.layout_str(
2026        &line,
2027        style.text.font_size,
2028        &[(
2029            snapshot.line_len(row) as usize,
2030            RunStyle {
2031                font_id: style.text.font_id,
2032                color: Color::black(),
2033                underline: Default::default(),
2034            },
2035        )],
2036    )
2037}
2038
2039#[derive(Copy, Clone, PartialEq, Eq, Debug)]
2040pub enum CursorShape {
2041    Bar,
2042    Block,
2043    Underscore,
2044    Hollow,
2045}
2046
2047impl Default for CursorShape {
2048    fn default() -> Self {
2049        CursorShape::Bar
2050    }
2051}
2052
2053#[derive(Debug)]
2054pub struct Cursor {
2055    origin: Vector2F,
2056    block_width: f32,
2057    line_height: f32,
2058    color: Color,
2059    shape: CursorShape,
2060    block_text: Option<Line>,
2061}
2062
2063impl Cursor {
2064    pub fn new(
2065        origin: Vector2F,
2066        block_width: f32,
2067        line_height: f32,
2068        color: Color,
2069        shape: CursorShape,
2070        block_text: Option<Line>,
2071    ) -> Cursor {
2072        Cursor {
2073            origin,
2074            block_width,
2075            line_height,
2076            color,
2077            shape,
2078            block_text,
2079        }
2080    }
2081
2082    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2083        RectF::new(
2084            self.origin + origin,
2085            vec2f(self.block_width, self.line_height),
2086        )
2087    }
2088
2089    pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
2090        let bounds = match self.shape {
2091            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2092            CursorShape::Block | CursorShape::Hollow => RectF::new(
2093                self.origin + origin,
2094                vec2f(self.block_width, self.line_height),
2095            ),
2096            CursorShape::Underscore => RectF::new(
2097                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2098                vec2f(self.block_width, 2.0),
2099            ),
2100        };
2101
2102        //Draw background or border quad
2103        if matches!(self.shape, CursorShape::Hollow) {
2104            cx.scene.push_quad(Quad {
2105                bounds,
2106                background: None,
2107                border: Border::all(1., self.color),
2108                corner_radius: 0.,
2109            });
2110        } else {
2111            cx.scene.push_quad(Quad {
2112                bounds,
2113                background: Some(self.color),
2114                border: Default::default(),
2115                corner_radius: 0.,
2116            });
2117        }
2118
2119        if let Some(block_text) = &self.block_text {
2120            block_text.paint(self.origin + origin, bounds, self.line_height, cx);
2121        }
2122    }
2123
2124    pub fn shape(&self) -> CursorShape {
2125        self.shape
2126    }
2127}
2128
2129#[derive(Debug)]
2130pub struct HighlightedRange {
2131    pub start_y: f32,
2132    pub line_height: f32,
2133    pub lines: Vec<HighlightedRangeLine>,
2134    pub color: Color,
2135    pub corner_radius: f32,
2136}
2137
2138#[derive(Debug)]
2139pub struct HighlightedRangeLine {
2140    pub start_x: f32,
2141    pub end_x: f32,
2142}
2143
2144impl HighlightedRange {
2145    pub fn paint(&self, bounds: RectF, scene: &mut Scene) {
2146        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2147            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2148            self.paint_lines(
2149                self.start_y + self.line_height,
2150                &self.lines[1..],
2151                bounds,
2152                scene,
2153            );
2154        } else {
2155            self.paint_lines(self.start_y, &self.lines, bounds, scene);
2156        }
2157    }
2158
2159    fn paint_lines(
2160        &self,
2161        start_y: f32,
2162        lines: &[HighlightedRangeLine],
2163        bounds: RectF,
2164        scene: &mut Scene,
2165    ) {
2166        if lines.is_empty() {
2167            return;
2168        }
2169
2170        let mut path = PathBuilder::new();
2171        let first_line = lines.first().unwrap();
2172        let last_line = lines.last().unwrap();
2173
2174        let first_top_left = vec2f(first_line.start_x, start_y);
2175        let first_top_right = vec2f(first_line.end_x, start_y);
2176
2177        let curve_height = vec2f(0., self.corner_radius);
2178        let curve_width = |start_x: f32, end_x: f32| {
2179            let max = (end_x - start_x) / 2.;
2180            let width = if max < self.corner_radius {
2181                max
2182            } else {
2183                self.corner_radius
2184            };
2185
2186            vec2f(width, 0.)
2187        };
2188
2189        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2190        path.reset(first_top_right - top_curve_width);
2191        path.curve_to(first_top_right + curve_height, first_top_right);
2192
2193        let mut iter = lines.iter().enumerate().peekable();
2194        while let Some((ix, line)) = iter.next() {
2195            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2196
2197            if let Some((_, next_line)) = iter.peek() {
2198                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2199
2200                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2201                    Ordering::Equal => {
2202                        path.line_to(bottom_right);
2203                    }
2204                    Ordering::Less => {
2205                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2206                        path.line_to(bottom_right - curve_height);
2207                        if self.corner_radius > 0. {
2208                            path.curve_to(bottom_right - curve_width, bottom_right);
2209                        }
2210                        path.line_to(next_top_right + curve_width);
2211                        if self.corner_radius > 0. {
2212                            path.curve_to(next_top_right + curve_height, next_top_right);
2213                        }
2214                    }
2215                    Ordering::Greater => {
2216                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2217                        path.line_to(bottom_right - curve_height);
2218                        if self.corner_radius > 0. {
2219                            path.curve_to(bottom_right + curve_width, bottom_right);
2220                        }
2221                        path.line_to(next_top_right - curve_width);
2222                        if self.corner_radius > 0. {
2223                            path.curve_to(next_top_right + curve_height, next_top_right);
2224                        }
2225                    }
2226                }
2227            } else {
2228                let curve_width = curve_width(line.start_x, line.end_x);
2229                path.line_to(bottom_right - curve_height);
2230                if self.corner_radius > 0. {
2231                    path.curve_to(bottom_right - curve_width, bottom_right);
2232                }
2233
2234                let bottom_left = vec2f(line.start_x, bottom_right.y());
2235                path.line_to(bottom_left + curve_width);
2236                if self.corner_radius > 0. {
2237                    path.curve_to(bottom_left - curve_height, bottom_left);
2238                }
2239            }
2240        }
2241
2242        if first_line.start_x > last_line.start_x {
2243            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2244            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2245            path.line_to(second_top_left + curve_height);
2246            if self.corner_radius > 0. {
2247                path.curve_to(second_top_left + curve_width, second_top_left);
2248            }
2249            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2250            path.line_to(first_bottom_left - curve_width);
2251            if self.corner_radius > 0. {
2252                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2253            }
2254        }
2255
2256        path.line_to(first_top_left + curve_height);
2257        if self.corner_radius > 0. {
2258            path.curve_to(first_top_left + top_curve_width, first_top_left);
2259        }
2260        path.line_to(first_top_right - top_curve_width);
2261
2262        scene.push_path(path.build(self.color, Some(bounds)));
2263    }
2264}
2265
2266pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2267    delta.powf(1.5) / 100.0
2268}
2269
2270fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2271    delta.powf(1.2) / 300.0
2272}
2273
2274#[cfg(test)]
2275mod tests {
2276    use std::sync::Arc;
2277
2278    use super::*;
2279    use crate::{
2280        display_map::{BlockDisposition, BlockProperties},
2281        Editor, MultiBuffer,
2282    };
2283    use settings::Settings;
2284    use util::test::sample_text;
2285
2286    #[gpui::test]
2287    fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
2288        cx.set_global(Settings::test(cx));
2289        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2290        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2291            Editor::new(EditorMode::Full, buffer, None, None, cx)
2292        });
2293        let element = EditorElement::new(
2294            editor.downgrade(),
2295            editor.read(cx).style(cx),
2296            CursorShape::Bar,
2297        );
2298
2299        let layouts = editor.update(cx, |editor, cx| {
2300            let snapshot = editor.snapshot(cx);
2301            let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2302            let layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2303            element.layout_line_numbers(0..6, &Default::default(), &snapshot, &layout_cx)
2304        });
2305        assert_eq!(layouts.len(), 6);
2306    }
2307
2308    #[gpui::test]
2309    fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
2310        cx.set_global(Settings::test(cx));
2311        let buffer = MultiBuffer::build_simple("", cx);
2312        let (window_id, editor) = cx.add_window(Default::default(), |cx| {
2313            Editor::new(EditorMode::Full, buffer, None, None, cx)
2314        });
2315
2316        editor.update(cx, |editor, cx| {
2317            editor.set_placeholder_text("hello", cx);
2318            editor.insert_blocks(
2319                [BlockProperties {
2320                    style: BlockStyle::Fixed,
2321                    disposition: BlockDisposition::Above,
2322                    height: 3,
2323                    position: Anchor::min(),
2324                    render: Arc::new(|_| Empty::new().boxed()),
2325                }],
2326                cx,
2327            );
2328
2329            // Blur the editor so that it displays placeholder text.
2330            cx.blur();
2331        });
2332
2333        let mut element = EditorElement::new(
2334            editor.downgrade(),
2335            editor.read(cx).style(cx),
2336            CursorShape::Bar,
2337        );
2338
2339        let mut scene = Scene::new(1.0);
2340        let mut presenter = cx.build_presenter(window_id, 30., Default::default());
2341        let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2342        let (size, mut state) = element.layout(
2343            SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2344            &mut layout_cx,
2345        );
2346
2347        assert_eq!(state.position_map.line_layouts.len(), 4);
2348        assert_eq!(
2349            state
2350                .line_number_layouts
2351                .iter()
2352                .map(Option::is_some)
2353                .collect::<Vec<_>>(),
2354            &[false, false, false, true]
2355        );
2356
2357        // Don't panic.
2358        let bounds = RectF::new(Default::default(), size);
2359        let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2360        element.paint(bounds, bounds, &mut state, &mut paint_cx);
2361    }
2362}