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