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