element.rs

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