element.rs

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