element.rs

   1use super::{
   2    display_map::{BlockContext, ToDisplayPoint},
   3    Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, SelectPhase, SoftWrap, ToPoint,
   4    MAX_LINE_LEN,
   5};
   6use crate::{
   7    display_map::{BlockStyle, DisplaySnapshot, FoldStatus, TransformBlock},
   8    editor_settings::ShowScrollbar,
   9    git::{diff_hunk_to_display, DisplayDiffHunk},
  10    hover_popover::{
  11        hide_hover, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH,
  12        MIN_POPOVER_LINE_HEIGHT,
  13    },
  14    link_go_to_definition::{
  15        go_to_fetched_definition, go_to_fetched_type_definition, update_go_to_definition_link,
  16    },
  17    mouse_context_menu, EditorSettings, EditorStyle, GutterHover, UnfoldAt,
  18};
  19use clock::ReplicaId;
  20use collections::{BTreeMap, HashMap};
  21use git::diff::DiffHunkStatus;
  22use gpui::{
  23    color::Color,
  24    elements::*,
  25    fonts::{HighlightStyle, TextStyle, Underline},
  26    geometry::{
  27        rect::RectF,
  28        vector::{vec2f, Vector2F},
  29        PathBuilder,
  30    },
  31    json::{self, ToJson},
  32    platform::{CursorStyle, Modifiers, MouseButton, MouseButtonEvent, MouseMovedEvent},
  33    text_layout::{self, Line, RunStyle, TextLayoutCache},
  34    AnyElement, Axis, Border, CursorRegion, Element, EventContext, FontCache, LayoutContext,
  35    MouseRegion, Quad, SceneBuilder, SizeConstraint, ViewContext, WindowContext,
  36};
  37use itertools::Itertools;
  38use json::json;
  39use language::{
  40    language_settings::ShowWhitespaceSetting, Bias, CursorShape, DiagnosticSeverity, OffsetUtf16,
  41    Selection,
  42};
  43use project::{
  44    project_settings::{GitGutterSetting, ProjectSettings},
  45    ProjectPath,
  46};
  47use smallvec::SmallVec;
  48use std::{
  49    borrow::Cow,
  50    cmp::{self, Ordering},
  51    fmt::Write,
  52    iter,
  53    ops::Range,
  54    sync::Arc,
  55};
  56use text::Point;
  57use workspace::item::Item;
  58
  59enum FoldMarkers {}
  60
  61struct SelectionLayout {
  62    head: DisplayPoint,
  63    cursor_shape: CursorShape,
  64    range: Range<DisplayPoint>,
  65}
  66
  67impl SelectionLayout {
  68    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  69        selection: Selection<T>,
  70        line_mode: bool,
  71        cursor_shape: CursorShape,
  72        map: &DisplaySnapshot,
  73    ) -> Self {
  74        if line_mode {
  75            let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  76            let point_range = map.expand_to_line(selection.range());
  77            Self {
  78                head: selection.head().to_display_point(map),
  79                cursor_shape,
  80                range: point_range.start.to_display_point(map)
  81                    ..point_range.end.to_display_point(map),
  82            }
  83        } else {
  84            let selection = selection.map(|p| p.to_display_point(map));
  85            Self {
  86                head: selection.head(),
  87                cursor_shape,
  88                range: selection.range(),
  89            }
  90        }
  91    }
  92}
  93
  94#[derive(Clone)]
  95pub struct EditorElement {
  96    style: Arc<EditorStyle>,
  97}
  98
  99impl EditorElement {
 100    pub fn new(style: EditorStyle) -> Self {
 101        Self {
 102            style: Arc::new(style),
 103        }
 104    }
 105
 106    fn attach_mouse_handlers(
 107        scene: &mut SceneBuilder,
 108        position_map: &Arc<PositionMap>,
 109        has_popovers: bool,
 110        visible_bounds: RectF,
 111        text_bounds: RectF,
 112        gutter_bounds: RectF,
 113        bounds: RectF,
 114        cx: &mut ViewContext<Editor>,
 115    ) {
 116        enum EditorElementMouseHandlers {}
 117        scene.push_mouse_region(
 118            MouseRegion::new::<EditorElementMouseHandlers>(
 119                cx.view_id(),
 120                cx.view_id(),
 121                visible_bounds,
 122            )
 123            .on_down(MouseButton::Left, {
 124                let position_map = position_map.clone();
 125                move |event, editor, cx| {
 126                    if !Self::mouse_down(
 127                        editor,
 128                        event.platform_event,
 129                        position_map.as_ref(),
 130                        text_bounds,
 131                        gutter_bounds,
 132                        cx,
 133                    ) {
 134                        cx.propagate_event();
 135                    }
 136                }
 137            })
 138            .on_down(MouseButton::Right, {
 139                let position_map = position_map.clone();
 140                move |event, editor, cx| {
 141                    if !Self::mouse_right_down(
 142                        editor,
 143                        event.position,
 144                        position_map.as_ref(),
 145                        text_bounds,
 146                        cx,
 147                    ) {
 148                        cx.propagate_event();
 149                    }
 150                }
 151            })
 152            .on_up(MouseButton::Left, {
 153                let position_map = position_map.clone();
 154                move |event, editor, cx| {
 155                    if !Self::mouse_up(
 156                        editor,
 157                        event.position,
 158                        event.cmd,
 159                        event.shift,
 160                        position_map.as_ref(),
 161                        text_bounds,
 162                        cx,
 163                    ) {
 164                        cx.propagate_event()
 165                    }
 166                }
 167            })
 168            .on_drag(MouseButton::Left, {
 169                let position_map = position_map.clone();
 170                move |event, editor, cx| {
 171                    if !Self::mouse_dragged(
 172                        editor,
 173                        event.platform_event,
 174                        position_map.as_ref(),
 175                        text_bounds,
 176                        cx,
 177                    ) {
 178                        cx.propagate_event()
 179                    }
 180                }
 181            })
 182            .on_move({
 183                let position_map = position_map.clone();
 184                move |event, editor, cx| {
 185                    if !Self::mouse_moved(
 186                        editor,
 187                        event.platform_event,
 188                        &position_map,
 189                        text_bounds,
 190                        cx,
 191                    ) {
 192                        cx.propagate_event()
 193                    }
 194                }
 195            })
 196            .on_move_out(move |_, editor: &mut Editor, cx| {
 197                if has_popovers {
 198                    hide_hover(editor, cx);
 199                }
 200            })
 201            .on_scroll({
 202                let position_map = position_map.clone();
 203                move |event, editor, cx| {
 204                    if !Self::scroll(
 205                        editor,
 206                        event.position,
 207                        *event.delta.raw(),
 208                        event.delta.precise(),
 209                        &position_map,
 210                        bounds,
 211                        cx,
 212                    ) {
 213                        cx.propagate_event()
 214                    }
 215                }
 216            }),
 217        );
 218
 219        enum GutterHandlers {}
 220        scene.push_mouse_region(
 221            MouseRegion::new::<GutterHandlers>(cx.view_id(), cx.view_id() + 1, gutter_bounds)
 222                .on_hover(|hover, editor: &mut Editor, cx| {
 223                    editor.gutter_hover(
 224                        &GutterHover {
 225                            hovered: hover.started,
 226                        },
 227                        cx,
 228                    );
 229                }),
 230        )
 231    }
 232
 233    fn mouse_down(
 234        editor: &mut Editor,
 235        MouseButtonEvent {
 236            position,
 237            modifiers:
 238                Modifiers {
 239                    shift,
 240                    ctrl,
 241                    alt,
 242                    cmd,
 243                    ..
 244                },
 245            mut click_count,
 246            ..
 247        }: MouseButtonEvent,
 248        position_map: &PositionMap,
 249        text_bounds: RectF,
 250        gutter_bounds: RectF,
 251        cx: &mut EventContext<Editor>,
 252    ) -> bool {
 253        if gutter_bounds.contains_point(position) {
 254            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 255        } else if !text_bounds.contains_point(position) {
 256            return false;
 257        }
 258
 259        let (position, target_position) = position_map.point_for_position(text_bounds, position);
 260
 261        if shift && alt {
 262            editor.select(
 263                SelectPhase::BeginColumnar {
 264                    position,
 265                    goal_column: target_position.column(),
 266                },
 267                cx,
 268            );
 269        } else if shift && !ctrl && !alt && !cmd {
 270            editor.select(
 271                SelectPhase::Extend {
 272                    position,
 273                    click_count,
 274                },
 275                cx,
 276            );
 277        } else {
 278            editor.select(
 279                SelectPhase::Begin {
 280                    position,
 281                    add: alt,
 282                    click_count,
 283                },
 284                cx,
 285            );
 286        }
 287
 288        true
 289    }
 290
 291    fn mouse_right_down(
 292        editor: &mut Editor,
 293        position: Vector2F,
 294        position_map: &PositionMap,
 295        text_bounds: RectF,
 296        cx: &mut EventContext<Editor>,
 297    ) -> bool {
 298        if !text_bounds.contains_point(position) {
 299            return false;
 300        }
 301
 302        let (point, _) = position_map.point_for_position(text_bounds, position);
 303        mouse_context_menu::deploy_context_menu(editor, position, point, cx);
 304        true
 305    }
 306
 307    fn mouse_up(
 308        editor: &mut Editor,
 309        position: Vector2F,
 310        cmd: bool,
 311        shift: bool,
 312        position_map: &PositionMap,
 313        text_bounds: RectF,
 314        cx: &mut EventContext<Editor>,
 315    ) -> bool {
 316        let end_selection = editor.has_pending_selection();
 317        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 318
 319        if end_selection {
 320            editor.select(SelectPhase::End, cx);
 321        }
 322
 323        if !pending_nonempty_selections && cmd && text_bounds.contains_point(position) {
 324            let (point, target_point) = position_map.point_for_position(text_bounds, position);
 325
 326            if point == target_point {
 327                if shift {
 328                    go_to_fetched_type_definition(editor, point, cx);
 329                } else {
 330                    go_to_fetched_definition(editor, point, cx);
 331                }
 332
 333                return true;
 334            }
 335        }
 336
 337        end_selection
 338    }
 339
 340    fn mouse_dragged(
 341        editor: &mut Editor,
 342        MouseMovedEvent {
 343            modifiers: Modifiers { cmd, shift, .. },
 344            position,
 345            ..
 346        }: MouseMovedEvent,
 347        position_map: &PositionMap,
 348        text_bounds: RectF,
 349        cx: &mut EventContext<Editor>,
 350    ) -> bool {
 351        // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
 352        // Don't trigger hover popover if mouse is hovering over context menu
 353        let point = if text_bounds.contains_point(position) {
 354            let (point, target_point) = position_map.point_for_position(text_bounds, position);
 355            if point == target_point {
 356                Some(point)
 357            } else {
 358                None
 359            }
 360        } else {
 361            None
 362        };
 363
 364        update_go_to_definition_link(editor, point, cmd, shift, cx);
 365
 366        if editor.has_pending_selection() {
 367            let mut scroll_delta = Vector2F::zero();
 368
 369            let vertical_margin = position_map.line_height.min(text_bounds.height() / 3.0);
 370            let top = text_bounds.origin_y() + vertical_margin;
 371            let bottom = text_bounds.lower_left().y() - vertical_margin;
 372            if position.y() < top {
 373                scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
 374            }
 375            if position.y() > bottom {
 376                scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
 377            }
 378
 379            let horizontal_margin = position_map.line_height.min(text_bounds.width() / 3.0);
 380            let left = text_bounds.origin_x() + horizontal_margin;
 381            let right = text_bounds.upper_right().x() - horizontal_margin;
 382            if position.x() < left {
 383                scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
 384                    left - position.x(),
 385                ))
 386            }
 387            if position.x() > right {
 388                scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
 389                    position.x() - right,
 390                ))
 391            }
 392
 393            let (position, target_position) =
 394                position_map.point_for_position(text_bounds, position);
 395
 396            editor.select(
 397                SelectPhase::Update {
 398                    position,
 399                    goal_column: target_position.column(),
 400                    scroll_position: (position_map.snapshot.scroll_position() + scroll_delta)
 401                        .clamp(Vector2F::zero(), position_map.scroll_max),
 402                },
 403                cx,
 404            );
 405            hover_at(editor, point, cx);
 406            true
 407        } else {
 408            hover_at(editor, point, cx);
 409            false
 410        }
 411    }
 412
 413    fn mouse_moved(
 414        editor: &mut Editor,
 415        MouseMovedEvent {
 416            modifiers: Modifiers { shift, cmd, .. },
 417            position,
 418            ..
 419        }: MouseMovedEvent,
 420        position_map: &PositionMap,
 421        text_bounds: RectF,
 422        cx: &mut ViewContext<Editor>,
 423    ) -> bool {
 424        // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
 425        // Don't trigger hover popover if mouse is hovering over context menu
 426        let point = position_to_display_point(position, text_bounds, position_map);
 427
 428        update_go_to_definition_link(editor, point, cmd, shift, cx);
 429        hover_at(editor, point, cx);
 430
 431        true
 432    }
 433
 434    fn scroll(
 435        editor: &mut Editor,
 436        position: Vector2F,
 437        mut delta: Vector2F,
 438        precise: bool,
 439        position_map: &PositionMap,
 440        bounds: RectF,
 441        cx: &mut ViewContext<Editor>,
 442    ) -> bool {
 443        if !bounds.contains_point(position) {
 444            return false;
 445        }
 446
 447        let line_height = position_map.line_height;
 448        let max_glyph_width = position_map.em_width;
 449
 450        let axis = if precise {
 451            //Trackpad
 452            position_map.snapshot.ongoing_scroll.filter(&mut delta)
 453        } else {
 454            //Not trackpad
 455            delta *= vec2f(max_glyph_width, line_height);
 456            None //Resets ongoing scroll
 457        };
 458
 459        let scroll_position = position_map.snapshot.scroll_position();
 460        let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
 461        let y = (scroll_position.y() * line_height - delta.y()) / line_height;
 462        let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), position_map.scroll_max);
 463        editor.scroll(scroll_position, axis, cx);
 464
 465        true
 466    }
 467
 468    fn paint_background(
 469        &self,
 470        scene: &mut SceneBuilder,
 471        gutter_bounds: RectF,
 472        text_bounds: RectF,
 473        layout: &LayoutState,
 474    ) {
 475        let bounds = gutter_bounds.union_rect(text_bounds);
 476        let scroll_top =
 477            layout.position_map.snapshot.scroll_position().y() * layout.position_map.line_height;
 478        scene.push_quad(Quad {
 479            bounds: gutter_bounds,
 480            background: Some(self.style.gutter_background),
 481            border: Border::new(0., Color::transparent_black()),
 482            corner_radius: 0.,
 483        });
 484        scene.push_quad(Quad {
 485            bounds: text_bounds,
 486            background: Some(self.style.background),
 487            border: Border::new(0., Color::transparent_black()),
 488            corner_radius: 0.,
 489        });
 490
 491        if let EditorMode::Full = layout.mode {
 492            let mut active_rows = layout.active_rows.iter().peekable();
 493            while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
 494                let mut end_row = *start_row;
 495                while active_rows.peek().map_or(false, |r| {
 496                    *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
 497                }) {
 498                    active_rows.next().unwrap();
 499                    end_row += 1;
 500                }
 501
 502                if !contains_non_empty_selection {
 503                    let origin = vec2f(
 504                        bounds.origin_x(),
 505                        bounds.origin_y() + (layout.position_map.line_height * *start_row as f32)
 506                            - scroll_top,
 507                    );
 508                    let size = vec2f(
 509                        bounds.width(),
 510                        layout.position_map.line_height * (end_row - start_row + 1) as f32,
 511                    );
 512                    scene.push_quad(Quad {
 513                        bounds: RectF::new(origin, size),
 514                        background: Some(self.style.active_line_background),
 515                        border: Border::default(),
 516                        corner_radius: 0.,
 517                    });
 518                }
 519            }
 520
 521            if let Some(highlighted_rows) = &layout.highlighted_rows {
 522                let origin = vec2f(
 523                    bounds.origin_x(),
 524                    bounds.origin_y()
 525                        + (layout.position_map.line_height * highlighted_rows.start as f32)
 526                        - scroll_top,
 527                );
 528                let size = vec2f(
 529                    bounds.width(),
 530                    layout.position_map.line_height * highlighted_rows.len() as f32,
 531                );
 532                scene.push_quad(Quad {
 533                    bounds: RectF::new(origin, size),
 534                    background: Some(self.style.highlighted_line_background),
 535                    border: Border::default(),
 536                    corner_radius: 0.,
 537                });
 538            }
 539        }
 540    }
 541
 542    fn paint_gutter(
 543        &mut self,
 544        scene: &mut SceneBuilder,
 545        bounds: RectF,
 546        visible_bounds: RectF,
 547        layout: &mut LayoutState,
 548        editor: &mut Editor,
 549        cx: &mut ViewContext<Editor>,
 550    ) {
 551        let line_height = layout.position_map.line_height;
 552
 553        let scroll_position = layout.position_map.snapshot.scroll_position();
 554        let scroll_top = scroll_position.y() * line_height;
 555
 556        let show_gutter = matches!(
 557            settings::get::<ProjectSettings>(cx).git.git_gutter,
 558            Some(GitGutterSetting::TrackedFiles)
 559        );
 560
 561        if show_gutter {
 562            Self::paint_diff_hunks(scene, bounds, layout, cx);
 563        }
 564
 565        for (ix, line) in layout.line_number_layouts.iter().enumerate() {
 566            if let Some(line) = line {
 567                let line_origin = bounds.origin()
 568                    + vec2f(
 569                        bounds.width() - line.width() - layout.gutter_padding,
 570                        ix as f32 * line_height - (scroll_top % line_height),
 571                    );
 572
 573                line.paint(scene, line_origin, visible_bounds, line_height, cx);
 574            }
 575        }
 576
 577        for (ix, fold_indicator) in layout.fold_indicators.iter_mut().enumerate() {
 578            if let Some(indicator) = fold_indicator.as_mut() {
 579                let position = vec2f(
 580                    bounds.width() - layout.gutter_padding,
 581                    ix as f32 * line_height - (scroll_top % line_height),
 582                );
 583                let centering_offset = vec2f(
 584                    (layout.gutter_padding + layout.gutter_margin - indicator.size().x()) / 2.,
 585                    (line_height - indicator.size().y()) / 2.,
 586                );
 587
 588                let indicator_origin = bounds.origin() + position + centering_offset;
 589
 590                indicator.paint(scene, indicator_origin, visible_bounds, editor, cx);
 591            }
 592        }
 593
 594        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
 595            let mut x = 0.;
 596            let mut y = *row as f32 * line_height - scroll_top;
 597            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
 598            y += (line_height - indicator.size().y()) / 2.;
 599            indicator.paint(
 600                scene,
 601                bounds.origin() + vec2f(x, y),
 602                visible_bounds,
 603                editor,
 604                cx,
 605            );
 606        }
 607    }
 608
 609    fn paint_diff_hunks(
 610        scene: &mut SceneBuilder,
 611        bounds: RectF,
 612        layout: &mut LayoutState,
 613        cx: &mut ViewContext<Editor>,
 614    ) {
 615        let diff_style = &theme::current(cx).editor.diff.clone();
 616        let line_height = layout.position_map.line_height;
 617
 618        let scroll_position = layout.position_map.snapshot.scroll_position();
 619        let scroll_top = scroll_position.y() * line_height;
 620
 621        for hunk in &layout.display_hunks {
 622            let (display_row_range, status) = match hunk {
 623                //TODO: This rendering is entirely a horrible hack
 624                &DisplayDiffHunk::Folded { display_row: row } => {
 625                    let start_y = row as f32 * line_height - scroll_top;
 626                    let end_y = start_y + line_height;
 627
 628                    let width = diff_style.removed_width_em * line_height;
 629                    let highlight_origin = bounds.origin() + vec2f(-width, start_y);
 630                    let highlight_size = vec2f(width * 2., end_y - start_y);
 631                    let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 632
 633                    scene.push_quad(Quad {
 634                        bounds: highlight_bounds,
 635                        background: Some(diff_style.modified),
 636                        border: Border::new(0., Color::transparent_black()),
 637                        corner_radius: 1. * line_height,
 638                    });
 639
 640                    continue;
 641                }
 642
 643                DisplayDiffHunk::Unfolded {
 644                    display_row_range,
 645                    status,
 646                } => (display_row_range, status),
 647            };
 648
 649            let color = match status {
 650                DiffHunkStatus::Added => diff_style.inserted,
 651                DiffHunkStatus::Modified => diff_style.modified,
 652
 653                //TODO: This rendering is entirely a horrible hack
 654                DiffHunkStatus::Removed => {
 655                    let row = display_row_range.start;
 656
 657                    let offset = line_height / 2.;
 658                    let start_y = row as f32 * line_height - offset - scroll_top;
 659                    let end_y = start_y + line_height;
 660
 661                    let width = diff_style.removed_width_em * line_height;
 662                    let highlight_origin = bounds.origin() + vec2f(-width, start_y);
 663                    let highlight_size = vec2f(width * 2., end_y - start_y);
 664                    let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 665
 666                    scene.push_quad(Quad {
 667                        bounds: highlight_bounds,
 668                        background: Some(diff_style.deleted),
 669                        border: Border::new(0., Color::transparent_black()),
 670                        corner_radius: 1. * line_height,
 671                    });
 672
 673                    continue;
 674                }
 675            };
 676
 677            let start_row = display_row_range.start;
 678            let end_row = display_row_range.end;
 679
 680            let start_y = start_row as f32 * line_height - scroll_top;
 681            let end_y = end_row as f32 * line_height - scroll_top;
 682
 683            let width = diff_style.width_em * line_height;
 684            let highlight_origin = bounds.origin() + vec2f(-width, start_y);
 685            let highlight_size = vec2f(width * 2., end_y - start_y);
 686            let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 687
 688            scene.push_quad(Quad {
 689                bounds: highlight_bounds,
 690                background: Some(color),
 691                border: Border::new(0., Color::transparent_black()),
 692                corner_radius: diff_style.corner_radius * line_height,
 693            });
 694        }
 695    }
 696
 697    fn paint_text(
 698        &mut self,
 699        scene: &mut SceneBuilder,
 700        bounds: RectF,
 701        visible_bounds: RectF,
 702        layout: &mut LayoutState,
 703        editor: &mut Editor,
 704        cx: &mut ViewContext<Editor>,
 705    ) {
 706        let style = &self.style;
 707        let local_replica_id = editor.replica_id(cx);
 708        let scroll_position = layout.position_map.snapshot.scroll_position();
 709        let start_row = layout.visible_display_row_range.start;
 710        let scroll_top = scroll_position.y() * layout.position_map.line_height;
 711        let max_glyph_width = layout.position_map.em_width;
 712        let scroll_left = scroll_position.x() * max_glyph_width;
 713        let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
 714        let line_end_overshoot = 0.15 * layout.position_map.line_height;
 715        let whitespace_setting = editor.buffer.read(cx).settings_at(0, cx).show_whitespaces;
 716
 717        scene.push_layer(Some(bounds));
 718
 719        scene.push_cursor_region(CursorRegion {
 720            bounds,
 721            style: if !editor.link_go_to_definition_state.definitions.is_empty() {
 722                CursorStyle::PointingHand
 723            } else {
 724                CursorStyle::IBeam
 725            },
 726        });
 727
 728        let fold_corner_radius =
 729            self.style.folds.ellipses.corner_radius_factor * layout.position_map.line_height;
 730        for (id, range, color) in layout.fold_ranges.iter() {
 731            self.paint_highlighted_range(
 732                scene,
 733                range.clone(),
 734                *color,
 735                fold_corner_radius,
 736                fold_corner_radius * 2.,
 737                layout,
 738                content_origin,
 739                scroll_top,
 740                scroll_left,
 741                bounds,
 742            );
 743
 744            for bound in range_to_bounds(
 745                &range,
 746                content_origin,
 747                scroll_left,
 748                scroll_top,
 749                &layout.visible_display_row_range,
 750                line_end_overshoot,
 751                &layout.position_map,
 752            ) {
 753                scene.push_cursor_region(CursorRegion {
 754                    bounds: bound,
 755                    style: CursorStyle::PointingHand,
 756                });
 757
 758                let display_row = range.start.row();
 759
 760                let buffer_row = DisplayPoint::new(display_row, 0)
 761                    .to_point(&layout.position_map.snapshot.display_snapshot)
 762                    .row;
 763
 764                scene.push_mouse_region(
 765                    MouseRegion::new::<FoldMarkers>(cx.view_id(), *id as usize, bound)
 766                        .on_click(MouseButton::Left, move |_, editor: &mut Editor, cx| {
 767                            editor.unfold_at(&UnfoldAt { buffer_row }, cx)
 768                        })
 769                        .with_notify_on_hover(true)
 770                        .with_notify_on_click(true),
 771                )
 772            }
 773        }
 774
 775        for (range, color) in &layout.highlighted_ranges {
 776            self.paint_highlighted_range(
 777                scene,
 778                range.clone(),
 779                *color,
 780                0.,
 781                line_end_overshoot,
 782                layout,
 783                content_origin,
 784                scroll_top,
 785                scroll_left,
 786                bounds,
 787            );
 788        }
 789
 790        let mut cursors = SmallVec::<[Cursor; 32]>::new();
 791        let corner_radius = 0.15 * layout.position_map.line_height;
 792        let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
 793
 794        for (replica_id, selections) in &layout.selections {
 795            let replica_id = *replica_id;
 796            let selection_style = style.replica_selection_style(replica_id);
 797
 798            for selection in selections {
 799                if !selection.range.is_empty()
 800                    && (replica_id == local_replica_id
 801                        || Some(replica_id) == editor.leader_replica_id)
 802                {
 803                    invisible_display_ranges.push(selection.range.clone());
 804                }
 805                self.paint_highlighted_range(
 806                    scene,
 807                    selection.range.clone(),
 808                    selection_style.selection,
 809                    corner_radius,
 810                    corner_radius * 2.,
 811                    layout,
 812                    content_origin,
 813                    scroll_top,
 814                    scroll_left,
 815                    bounds,
 816                );
 817
 818                if editor.show_local_cursors(cx) || replica_id != local_replica_id {
 819                    let cursor_position = selection.head;
 820                    if layout
 821                        .visible_display_row_range
 822                        .contains(&cursor_position.row())
 823                    {
 824                        let cursor_row_layout = &layout.position_map.line_layouts
 825                            [(cursor_position.row() - start_row) as usize]
 826                            .line;
 827                        let cursor_column = cursor_position.column() as usize;
 828
 829                        let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 830                        let mut block_width =
 831                            cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 832                        if block_width == 0.0 {
 833                            block_width = layout.position_map.em_width;
 834                        }
 835                        let block_text = if let CursorShape::Block = selection.cursor_shape {
 836                            layout
 837                                .position_map
 838                                .snapshot
 839                                .chars_at(cursor_position)
 840                                .next()
 841                                .and_then(|(character, _)| {
 842                                    let font_id =
 843                                        cursor_row_layout.font_for_index(cursor_column)?;
 844                                    let text = character.to_string();
 845
 846                                    Some(cx.text_layout_cache().layout_str(
 847                                        &text,
 848                                        cursor_row_layout.font_size(),
 849                                        &[(
 850                                            text.len(),
 851                                            RunStyle {
 852                                                font_id,
 853                                                color: style.background,
 854                                                underline: Default::default(),
 855                                            },
 856                                        )],
 857                                    ))
 858                                })
 859                        } else {
 860                            None
 861                        };
 862
 863                        let x = cursor_character_x - scroll_left;
 864                        let y = cursor_position.row() as f32 * layout.position_map.line_height
 865                            - scroll_top;
 866                        cursors.push(Cursor {
 867                            color: selection_style.cursor,
 868                            block_width,
 869                            origin: vec2f(x, y),
 870                            line_height: layout.position_map.line_height,
 871                            shape: selection.cursor_shape,
 872                            block_text,
 873                        });
 874                    }
 875                }
 876            }
 877        }
 878
 879        if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
 880            for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
 881                let row = start_row + ix as u32;
 882                line_with_invisibles.draw(
 883                    layout,
 884                    row,
 885                    scroll_top,
 886                    scene,
 887                    content_origin,
 888                    scroll_left,
 889                    visible_text_bounds,
 890                    whitespace_setting,
 891                    &invisible_display_ranges,
 892                    visible_bounds,
 893                    cx,
 894                )
 895            }
 896        }
 897
 898        scene.paint_layer(Some(bounds), |scene| {
 899            for cursor in cursors {
 900                cursor.paint(scene, content_origin, cx);
 901            }
 902        });
 903
 904        if let Some((position, context_menu)) = layout.context_menu.as_mut() {
 905            scene.push_stacking_context(None, None);
 906            let cursor_row_layout =
 907                &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
 908            let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
 909            let y = (position.row() + 1) as f32 * layout.position_map.line_height - scroll_top;
 910            let mut list_origin = content_origin + vec2f(x, y);
 911            let list_width = context_menu.size().x();
 912            let list_height = context_menu.size().y();
 913
 914            // Snap the right edge of the list to the right edge of the window if
 915            // its horizontal bounds overflow.
 916            if list_origin.x() + list_width > cx.window_size().x() {
 917                list_origin.set_x((cx.window_size().x() - list_width).max(0.));
 918            }
 919
 920            if list_origin.y() + list_height > bounds.max_y() {
 921                list_origin.set_y(list_origin.y() - layout.position_map.line_height - list_height);
 922            }
 923
 924            context_menu.paint(
 925                scene,
 926                list_origin,
 927                RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 928                editor,
 929                cx,
 930            );
 931
 932            scene.pop_stacking_context();
 933        }
 934
 935        if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
 936            scene.push_stacking_context(None, None);
 937
 938            // This is safe because we check on layout whether the required row is available
 939            let hovered_row_layout =
 940                &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
 941
 942            // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
 943            // height. This is the size we will use to decide whether to render popovers above or below
 944            // the hovered line.
 945            let first_size = hover_popovers[0].size();
 946            let height_to_reserve = first_size.y()
 947                + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.position_map.line_height;
 948
 949            // Compute Hovered Point
 950            let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
 951            let y = position.row() as f32 * layout.position_map.line_height - scroll_top;
 952            let hovered_point = content_origin + vec2f(x, y);
 953
 954            if hovered_point.y() - height_to_reserve > 0.0 {
 955                // There is enough space above. Render popovers above the hovered point
 956                let mut current_y = hovered_point.y();
 957                for hover_popover in hover_popovers {
 958                    let size = hover_popover.size();
 959                    let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
 960
 961                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 962                    if x_out_of_bounds < 0.0 {
 963                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 964                    }
 965
 966                    hover_popover.paint(
 967                        scene,
 968                        popover_origin,
 969                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 970                        editor,
 971                        cx,
 972                    );
 973
 974                    current_y = popover_origin.y() - HOVER_POPOVER_GAP;
 975                }
 976            } else {
 977                // There is not enough space above. Render popovers below the hovered point
 978                let mut current_y = hovered_point.y() + layout.position_map.line_height;
 979                for hover_popover in hover_popovers {
 980                    let size = hover_popover.size();
 981                    let mut popover_origin = vec2f(hovered_point.x(), current_y);
 982
 983                    let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
 984                    if x_out_of_bounds < 0.0 {
 985                        popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
 986                    }
 987
 988                    hover_popover.paint(
 989                        scene,
 990                        popover_origin,
 991                        RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
 992                        editor,
 993                        cx,
 994                    );
 995
 996                    current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
 997                }
 998            }
 999
1000            scene.pop_stacking_context();
1001        }
1002
1003        scene.pop_layer();
1004    }
1005
1006    fn paint_scrollbar(
1007        &mut self,
1008        scene: &mut SceneBuilder,
1009        bounds: RectF,
1010        layout: &mut LayoutState,
1011        cx: &mut ViewContext<Editor>,
1012    ) {
1013        enum ScrollbarMouseHandlers {}
1014        if layout.mode != EditorMode::Full {
1015            return;
1016        }
1017
1018        let style = &self.style.theme.scrollbar;
1019
1020        let top = bounds.min_y();
1021        let bottom = bounds.max_y();
1022        let right = bounds.max_x();
1023        let left = right - style.width;
1024        let row_range = &layout.scrollbar_row_range;
1025        let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1026
1027        let mut height = bounds.height();
1028        let mut first_row_y_offset = 0.0;
1029
1030        // Impose a minimum height on the scrollbar thumb
1031        let row_height = height / max_row;
1032        let min_thumb_height =
1033            style.min_height_factor * cx.font_cache.line_height(self.style.text.font_size);
1034        let thumb_height = (row_range.end - row_range.start) * row_height;
1035        if thumb_height < min_thumb_height {
1036            first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1037            height -= min_thumb_height - thumb_height;
1038        }
1039
1040        let y_for_row = |row: f32| -> f32 { top + first_row_y_offset + row * row_height };
1041
1042        let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1043        let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1044        let track_bounds = RectF::from_points(vec2f(left, top), vec2f(right, bottom));
1045        let thumb_bounds = RectF::from_points(vec2f(left, thumb_top), vec2f(right, thumb_bottom));
1046
1047        if layout.show_scrollbars {
1048            scene.push_quad(Quad {
1049                bounds: track_bounds,
1050                border: style.track.border,
1051                background: style.track.background_color,
1052                ..Default::default()
1053            });
1054
1055            if layout.is_singleton && settings::get::<EditorSettings>(cx).scrollbar.git_diff {
1056                let diff_style = theme::current(cx).editor.scrollbar.git.clone();
1057                for hunk in layout
1058                    .position_map
1059                    .snapshot
1060                    .buffer_snapshot
1061                    .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1062                {
1063                    let start_display = Point::new(hunk.buffer_range.start, 0)
1064                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1065                    let end_display = Point::new(hunk.buffer_range.end, 0)
1066                        .to_display_point(&layout.position_map.snapshot.display_snapshot);
1067                    let start_y = y_for_row(start_display.row() as f32);
1068                    let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1069                        y_for_row((end_display.row() + 1) as f32)
1070                    } else {
1071                        y_for_row((end_display.row()) as f32)
1072                    };
1073
1074                    if end_y - start_y < 1. {
1075                        end_y = start_y + 1.;
1076                    }
1077                    let bounds = RectF::from_points(vec2f(left, start_y), vec2f(right, end_y));
1078
1079                    let color = match hunk.status() {
1080                        DiffHunkStatus::Added => diff_style.inserted,
1081                        DiffHunkStatus::Modified => diff_style.modified,
1082                        DiffHunkStatus::Removed => diff_style.deleted,
1083                    };
1084
1085                    let border = Border {
1086                        width: 1.,
1087                        color: style.thumb.border.color,
1088                        overlay: false,
1089                        top: false,
1090                        right: true,
1091                        bottom: false,
1092                        left: true,
1093                    };
1094
1095                    scene.push_quad(Quad {
1096                        bounds,
1097                        background: Some(color),
1098                        border,
1099                        corner_radius: style.thumb.corner_radius,
1100                    })
1101                }
1102            }
1103
1104            scene.push_quad(Quad {
1105                bounds: thumb_bounds,
1106                border: style.thumb.border,
1107                background: style.thumb.background_color,
1108                corner_radius: style.thumb.corner_radius,
1109            });
1110        }
1111
1112        scene.push_cursor_region(CursorRegion {
1113            bounds: track_bounds,
1114            style: CursorStyle::Arrow,
1115        });
1116        scene.push_mouse_region(
1117            MouseRegion::new::<ScrollbarMouseHandlers>(cx.view_id(), cx.view_id(), track_bounds)
1118                .on_move(move |_, editor: &mut Editor, cx| {
1119                    editor.scroll_manager.show_scrollbar(cx);
1120                })
1121                .on_down(MouseButton::Left, {
1122                    let row_range = row_range.clone();
1123                    move |event, editor: &mut Editor, cx| {
1124                        let y = event.position.y();
1125                        if y < thumb_top || thumb_bottom < y {
1126                            let center_row = ((y - top) * max_row as f32 / height).round() as u32;
1127                            let top_row = center_row
1128                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1129                            let mut position = editor.scroll_position(cx);
1130                            position.set_y(top_row as f32);
1131                            editor.set_scroll_position(position, cx);
1132                        } else {
1133                            editor.scroll_manager.show_scrollbar(cx);
1134                        }
1135                    }
1136                })
1137                .on_drag(MouseButton::Left, {
1138                    move |event, editor: &mut Editor, cx| {
1139                        let y = event.prev_mouse_position.y();
1140                        let new_y = event.position.y();
1141                        if thumb_top < y && y < thumb_bottom {
1142                            let mut position = editor.scroll_position(cx);
1143                            position.set_y(position.y() + (new_y - y) * (max_row as f32) / height);
1144                            if position.y() < 0.0 {
1145                                position.set_y(0.);
1146                            }
1147                            editor.set_scroll_position(position, cx);
1148                        }
1149                    }
1150                }),
1151        );
1152    }
1153
1154    #[allow(clippy::too_many_arguments)]
1155    fn paint_highlighted_range(
1156        &self,
1157        scene: &mut SceneBuilder,
1158        range: Range<DisplayPoint>,
1159        color: Color,
1160        corner_radius: f32,
1161        line_end_overshoot: f32,
1162        layout: &LayoutState,
1163        content_origin: Vector2F,
1164        scroll_top: f32,
1165        scroll_left: f32,
1166        bounds: RectF,
1167    ) {
1168        let start_row = layout.visible_display_row_range.start;
1169        let end_row = layout.visible_display_row_range.end;
1170        if range.start != range.end {
1171            let row_range = if range.end.column() == 0 {
1172                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1173            } else {
1174                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1175            };
1176
1177            let highlighted_range = HighlightedRange {
1178                color,
1179                line_height: layout.position_map.line_height,
1180                corner_radius,
1181                start_y: content_origin.y()
1182                    + row_range.start as f32 * layout.position_map.line_height
1183                    - scroll_top,
1184                lines: row_range
1185                    .into_iter()
1186                    .map(|row| {
1187                        let line_layout =
1188                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
1189                        HighlightedRangeLine {
1190                            start_x: if row == range.start.row() {
1191                                content_origin.x()
1192                                    + line_layout.x_for_index(range.start.column() as usize)
1193                                    - scroll_left
1194                            } else {
1195                                content_origin.x() - scroll_left
1196                            },
1197                            end_x: if row == range.end.row() {
1198                                content_origin.x()
1199                                    + line_layout.x_for_index(range.end.column() as usize)
1200                                    - scroll_left
1201                            } else {
1202                                content_origin.x() + line_layout.width() + line_end_overshoot
1203                                    - scroll_left
1204                            },
1205                        }
1206                    })
1207                    .collect(),
1208            };
1209
1210            highlighted_range.paint(bounds, scene);
1211        }
1212    }
1213
1214    fn paint_blocks(
1215        &mut self,
1216        scene: &mut SceneBuilder,
1217        bounds: RectF,
1218        visible_bounds: RectF,
1219        layout: &mut LayoutState,
1220        editor: &mut Editor,
1221        cx: &mut ViewContext<Editor>,
1222    ) {
1223        let scroll_position = layout.position_map.snapshot.scroll_position();
1224        let scroll_left = scroll_position.x() * layout.position_map.em_width;
1225        let scroll_top = scroll_position.y() * layout.position_map.line_height;
1226
1227        for block in &mut layout.blocks {
1228            let mut origin = bounds.origin()
1229                + vec2f(
1230                    0.,
1231                    block.row as f32 * layout.position_map.line_height - scroll_top,
1232                );
1233            if !matches!(block.style, BlockStyle::Sticky) {
1234                origin += vec2f(-scroll_left, 0.);
1235            }
1236            block
1237                .element
1238                .paint(scene, origin, visible_bounds, editor, cx);
1239        }
1240    }
1241
1242    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &ViewContext<Editor>) -> f32 {
1243        let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
1244        let style = &self.style;
1245
1246        cx.text_layout_cache()
1247            .layout_str(
1248                "1".repeat(digit_count).as_str(),
1249                style.text.font_size,
1250                &[(
1251                    digit_count,
1252                    RunStyle {
1253                        font_id: style.text.font_id,
1254                        color: Color::black(),
1255                        underline: Default::default(),
1256                    },
1257                )],
1258            )
1259            .width()
1260    }
1261
1262    //Folds contained in a hunk are ignored apart from shrinking visual size
1263    //If a fold contains any hunks then that fold line is marked as modified
1264    fn layout_git_gutters(
1265        &self,
1266        display_rows: Range<u32>,
1267        snapshot: &EditorSnapshot,
1268    ) -> Vec<DisplayDiffHunk> {
1269        let buffer_snapshot = &snapshot.buffer_snapshot;
1270
1271        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1272            .to_point(snapshot)
1273            .row;
1274        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1275            .to_point(snapshot)
1276            .row;
1277
1278        buffer_snapshot
1279            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1280            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1281            .dedup()
1282            .collect()
1283    }
1284
1285    fn layout_line_numbers(
1286        &self,
1287        rows: Range<u32>,
1288        active_rows: &BTreeMap<u32, bool>,
1289        is_singleton: bool,
1290        snapshot: &EditorSnapshot,
1291        cx: &ViewContext<Editor>,
1292    ) -> (
1293        Vec<Option<text_layout::Line>>,
1294        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1295    ) {
1296        let style = &self.style;
1297        let include_line_numbers = snapshot.mode == EditorMode::Full;
1298        let mut line_number_layouts = Vec::with_capacity(rows.len());
1299        let mut fold_statuses = Vec::with_capacity(rows.len());
1300        let mut line_number = String::new();
1301        for (ix, row) in snapshot
1302            .buffer_rows(rows.start)
1303            .take((rows.end - rows.start) as usize)
1304            .enumerate()
1305        {
1306            let display_row = rows.start + ix as u32;
1307            let (active, color) = if active_rows.contains_key(&display_row) {
1308                (true, style.line_number_active)
1309            } else {
1310                (false, style.line_number)
1311            };
1312            if let Some(buffer_row) = row {
1313                if include_line_numbers {
1314                    line_number.clear();
1315                    write!(&mut line_number, "{}", buffer_row + 1).unwrap();
1316                    line_number_layouts.push(Some(cx.text_layout_cache().layout_str(
1317                        &line_number,
1318                        style.text.font_size,
1319                        &[(
1320                            line_number.len(),
1321                            RunStyle {
1322                                font_id: style.text.font_id,
1323                                color,
1324                                underline: Default::default(),
1325                            },
1326                        )],
1327                    )));
1328                    fold_statuses.push(
1329                        is_singleton
1330                            .then(|| {
1331                                snapshot
1332                                    .fold_for_line(buffer_row)
1333                                    .map(|fold_status| (fold_status, buffer_row, active))
1334                            })
1335                            .flatten(),
1336                    )
1337                }
1338            } else {
1339                fold_statuses.push(None);
1340                line_number_layouts.push(None);
1341            }
1342        }
1343
1344        (line_number_layouts, fold_statuses)
1345    }
1346
1347    fn layout_lines(
1348        &mut self,
1349        rows: Range<u32>,
1350        line_number_layouts: &[Option<Line>],
1351        snapshot: &EditorSnapshot,
1352        cx: &ViewContext<Editor>,
1353    ) -> Vec<LineWithInvisibles> {
1354        if rows.start >= rows.end {
1355            return Vec::new();
1356        }
1357
1358        // When the editor is empty and unfocused, then show the placeholder.
1359        if snapshot.is_empty() {
1360            let placeholder_style = self
1361                .style
1362                .placeholder_text
1363                .as_ref()
1364                .unwrap_or(&self.style.text);
1365            let placeholder_text = snapshot.placeholder_text();
1366            let placeholder_lines = placeholder_text
1367                .as_ref()
1368                .map_or("", AsRef::as_ref)
1369                .split('\n')
1370                .skip(rows.start as usize)
1371                .chain(iter::repeat(""))
1372                .take(rows.len());
1373            placeholder_lines
1374                .map(|line| {
1375                    cx.text_layout_cache().layout_str(
1376                        line,
1377                        placeholder_style.font_size,
1378                        &[(
1379                            line.len(),
1380                            RunStyle {
1381                                font_id: placeholder_style.font_id,
1382                                color: placeholder_style.color,
1383                                underline: Default::default(),
1384                            },
1385                        )],
1386                    )
1387                })
1388                .map(|line| LineWithInvisibles {
1389                    line,
1390                    invisibles: Vec::new(),
1391                })
1392                .collect()
1393        } else {
1394            let style = &self.style;
1395            let chunks = snapshot
1396                .chunks(rows.clone(), true, Some(style.theme.suggestion))
1397                .map(|chunk| {
1398                    let mut highlight_style = chunk
1399                        .syntax_highlight_id
1400                        .and_then(|id| id.style(&style.syntax));
1401
1402                    if let Some(chunk_highlight) = chunk.highlight_style {
1403                        if let Some(highlight_style) = highlight_style.as_mut() {
1404                            highlight_style.highlight(chunk_highlight);
1405                        } else {
1406                            highlight_style = Some(chunk_highlight);
1407                        }
1408                    }
1409
1410                    let mut diagnostic_highlight = HighlightStyle::default();
1411
1412                    if chunk.is_unnecessary {
1413                        diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
1414                    }
1415
1416                    if let Some(severity) = chunk.diagnostic_severity {
1417                        // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
1418                        if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
1419                            let diagnostic_style = super::diagnostic_style(severity, true, style);
1420                            diagnostic_highlight.underline = Some(Underline {
1421                                color: Some(diagnostic_style.message.text.color),
1422                                thickness: 1.0.into(),
1423                                squiggly: true,
1424                            });
1425                        }
1426                    }
1427
1428                    if let Some(highlight_style) = highlight_style.as_mut() {
1429                        highlight_style.highlight(diagnostic_highlight);
1430                    } else {
1431                        highlight_style = Some(diagnostic_highlight);
1432                    }
1433
1434                    HighlightedChunk {
1435                        chunk: chunk.text,
1436                        style: highlight_style,
1437                        is_tab: chunk.is_tab,
1438                    }
1439                });
1440
1441            LineWithInvisibles::from_chunks(
1442                chunks,
1443                &style.text,
1444                cx.text_layout_cache(),
1445                cx.font_cache(),
1446                MAX_LINE_LEN,
1447                rows.len() as usize,
1448                line_number_layouts,
1449                snapshot.mode,
1450            )
1451        }
1452    }
1453
1454    #[allow(clippy::too_many_arguments)]
1455    fn layout_blocks(
1456        &mut self,
1457        rows: Range<u32>,
1458        snapshot: &EditorSnapshot,
1459        editor_width: f32,
1460        scroll_width: f32,
1461        gutter_padding: f32,
1462        gutter_width: f32,
1463        em_width: f32,
1464        text_x: f32,
1465        line_height: f32,
1466        style: &EditorStyle,
1467        line_layouts: &[LineWithInvisibles],
1468        include_root: bool,
1469        editor: &mut Editor,
1470        cx: &mut LayoutContext<Editor>,
1471    ) -> (f32, Vec<BlockLayout>) {
1472        let tooltip_style = theme::current(cx).tooltip.clone();
1473        let scroll_x = snapshot.scroll_anchor.offset.x();
1474        let (fixed_blocks, non_fixed_blocks) = snapshot
1475            .blocks_in_range(rows.clone())
1476            .partition::<Vec<_>, _>(|(_, block)| match block {
1477                TransformBlock::ExcerptHeader { .. } => false,
1478                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1479            });
1480        let mut render_block = |block: &TransformBlock, width: f32| {
1481            let mut element = match block {
1482                TransformBlock::Custom(block) => {
1483                    let align_to = block
1484                        .position()
1485                        .to_point(&snapshot.buffer_snapshot)
1486                        .to_display_point(snapshot);
1487                    let anchor_x = text_x
1488                        + if rows.contains(&align_to.row()) {
1489                            line_layouts[(align_to.row() - rows.start) as usize]
1490                                .line
1491                                .x_for_index(align_to.column() as usize)
1492                        } else {
1493                            layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1494                                .x_for_index(align_to.column() as usize)
1495                        };
1496
1497                    block.render(&mut BlockContext {
1498                        view_context: cx,
1499                        anchor_x,
1500                        gutter_padding,
1501                        line_height,
1502                        scroll_x,
1503                        gutter_width,
1504                        em_width,
1505                    })
1506                }
1507                TransformBlock::ExcerptHeader {
1508                    id,
1509                    buffer,
1510                    range,
1511                    starts_new_buffer,
1512                    ..
1513                } => {
1514                    let id = *id;
1515                    let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
1516                        let jump_path = ProjectPath {
1517                            worktree_id: file.worktree_id(cx),
1518                            path: file.path.clone(),
1519                        };
1520                        let jump_anchor = range
1521                            .primary
1522                            .as_ref()
1523                            .map_or(range.context.start, |primary| primary.start);
1524                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1525
1526                        enum JumpIcon {}
1527                        MouseEventHandler::<JumpIcon, _>::new(id.into(), cx, |state, _| {
1528                            let style = style.jump_icon.style_for(state, false);
1529                            Svg::new("icons/arrow_up_right_8.svg")
1530                                .with_color(style.color)
1531                                .constrained()
1532                                .with_width(style.icon_width)
1533                                .aligned()
1534                                .contained()
1535                                .with_style(style.container)
1536                                .constrained()
1537                                .with_width(style.button_width)
1538                                .with_height(style.button_width)
1539                        })
1540                        .with_cursor_style(CursorStyle::PointingHand)
1541                        .on_click(MouseButton::Left, move |_, editor, cx| {
1542                            if let Some(workspace) = editor
1543                                .workspace
1544                                .as_ref()
1545                                .and_then(|(workspace, _)| workspace.upgrade(cx))
1546                            {
1547                                workspace.update(cx, |workspace, cx| {
1548                                    Editor::jump(
1549                                        workspace,
1550                                        jump_path.clone(),
1551                                        jump_position,
1552                                        jump_anchor,
1553                                        cx,
1554                                    );
1555                                });
1556                            }
1557                        })
1558                        .with_tooltip::<JumpIcon>(
1559                            id.into(),
1560                            "Jump to Buffer".to_string(),
1561                            Some(Box::new(crate::OpenExcerpts)),
1562                            tooltip_style.clone(),
1563                            cx,
1564                        )
1565                        .aligned()
1566                        .flex_float()
1567                    });
1568
1569                    if *starts_new_buffer {
1570                        let style = &self.style.diagnostic_path_header;
1571                        let font_size =
1572                            (style.text_scale_factor * self.style.text.font_size).round();
1573
1574                        let path = buffer.resolve_file_path(cx, include_root);
1575                        let mut filename = None;
1576                        let mut parent_path = None;
1577                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1578                        if let Some(path) = path {
1579                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1580                            parent_path =
1581                                path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1582                        }
1583
1584                        Flex::row()
1585                            .with_child(
1586                                Label::new(
1587                                    filename.unwrap_or_else(|| "untitled".to_string()),
1588                                    style.filename.text.clone().with_font_size(font_size),
1589                                )
1590                                .contained()
1591                                .with_style(style.filename.container)
1592                                .aligned(),
1593                            )
1594                            .with_children(parent_path.map(|path| {
1595                                Label::new(path, style.path.text.clone().with_font_size(font_size))
1596                                    .contained()
1597                                    .with_style(style.path.container)
1598                                    .aligned()
1599                            }))
1600                            .with_children(jump_icon)
1601                            .contained()
1602                            .with_style(style.container)
1603                            .with_padding_left(gutter_padding)
1604                            .with_padding_right(gutter_padding)
1605                            .expanded()
1606                            .into_any_named("path header block")
1607                    } else {
1608                        let text_style = self.style.text.clone();
1609                        Flex::row()
1610                            .with_child(Label::new("", text_style))
1611                            .with_children(jump_icon)
1612                            .contained()
1613                            .with_padding_left(gutter_padding)
1614                            .with_padding_right(gutter_padding)
1615                            .expanded()
1616                            .into_any_named("collapsed context")
1617                    }
1618                }
1619            };
1620
1621            element.layout(
1622                SizeConstraint {
1623                    min: Vector2F::zero(),
1624                    max: vec2f(width, block.height() as f32 * line_height),
1625                },
1626                editor,
1627                cx,
1628            );
1629            element
1630        };
1631
1632        let mut fixed_block_max_width = 0f32;
1633        let mut blocks = Vec::new();
1634        for (row, block) in fixed_blocks {
1635            let element = render_block(block, f32::INFINITY);
1636            fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1637            blocks.push(BlockLayout {
1638                row,
1639                element,
1640                style: BlockStyle::Fixed,
1641            });
1642        }
1643        for (row, block) in non_fixed_blocks {
1644            let style = match block {
1645                TransformBlock::Custom(block) => block.style(),
1646                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1647            };
1648            let width = match style {
1649                BlockStyle::Sticky => editor_width,
1650                BlockStyle::Flex => editor_width
1651                    .max(fixed_block_max_width)
1652                    .max(gutter_width + scroll_width),
1653                BlockStyle::Fixed => unreachable!(),
1654            };
1655            let element = render_block(block, width);
1656            blocks.push(BlockLayout {
1657                row,
1658                element,
1659                style,
1660            });
1661        }
1662        (
1663            scroll_width.max(fixed_block_max_width - gutter_width),
1664            blocks,
1665        )
1666    }
1667}
1668
1669struct HighlightedChunk<'a> {
1670    chunk: &'a str,
1671    style: Option<HighlightStyle>,
1672    is_tab: bool,
1673}
1674
1675#[derive(Debug)]
1676pub struct LineWithInvisibles {
1677    pub line: Line,
1678    invisibles: Vec<Invisible>,
1679}
1680
1681impl LineWithInvisibles {
1682    fn from_chunks<'a>(
1683        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
1684        text_style: &TextStyle,
1685        text_layout_cache: &TextLayoutCache,
1686        font_cache: &Arc<FontCache>,
1687        max_line_len: usize,
1688        max_line_count: usize,
1689        line_number_layouts: &[Option<Line>],
1690        editor_mode: EditorMode,
1691    ) -> Vec<Self> {
1692        let mut layouts = Vec::with_capacity(max_line_count);
1693        let mut line = String::new();
1694        let mut invisibles = Vec::new();
1695        let mut styles = Vec::new();
1696        let mut non_whitespace_added = false;
1697        let mut row = 0;
1698        let mut line_exceeded_max_len = false;
1699        for highlighted_chunk in chunks.chain([HighlightedChunk {
1700            chunk: "\n",
1701            style: None,
1702            is_tab: false,
1703        }]) {
1704            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
1705                if ix > 0 {
1706                    layouts.push(Self {
1707                        line: text_layout_cache.layout_str(&line, text_style.font_size, &styles),
1708                        invisibles: invisibles.drain(..).collect(),
1709                    });
1710
1711                    line.clear();
1712                    styles.clear();
1713                    row += 1;
1714                    line_exceeded_max_len = false;
1715                    non_whitespace_added = false;
1716                    if row == max_line_count {
1717                        return layouts;
1718                    }
1719                }
1720
1721                if !line_chunk.is_empty() && !line_exceeded_max_len {
1722                    let text_style = if let Some(style) = highlighted_chunk.style {
1723                        text_style
1724                            .clone()
1725                            .highlight(style, font_cache)
1726                            .map(Cow::Owned)
1727                            .unwrap_or_else(|_| Cow::Borrowed(text_style))
1728                    } else {
1729                        Cow::Borrowed(text_style)
1730                    };
1731
1732                    if line.len() + line_chunk.len() > max_line_len {
1733                        let mut chunk_len = max_line_len - line.len();
1734                        while !line_chunk.is_char_boundary(chunk_len) {
1735                            chunk_len -= 1;
1736                        }
1737                        line_chunk = &line_chunk[..chunk_len];
1738                        line_exceeded_max_len = true;
1739                    }
1740
1741                    styles.push((
1742                        line_chunk.len(),
1743                        RunStyle {
1744                            font_id: text_style.font_id,
1745                            color: text_style.color,
1746                            underline: text_style.underline,
1747                        },
1748                    ));
1749
1750                    if editor_mode == EditorMode::Full {
1751                        // Line wrap pads its contents with fake whitespaces,
1752                        // avoid printing them
1753                        let inside_wrapped_string = line_number_layouts
1754                            .get(row)
1755                            .and_then(|layout| layout.as_ref())
1756                            .is_none();
1757                        if highlighted_chunk.is_tab {
1758                            if non_whitespace_added || !inside_wrapped_string {
1759                                invisibles.push(Invisible::Tab {
1760                                    line_start_offset: line.len(),
1761                                });
1762                            }
1763                        } else {
1764                            invisibles.extend(
1765                                line_chunk
1766                                    .chars()
1767                                    .enumerate()
1768                                    .filter(|(_, line_char)| {
1769                                        let is_whitespace = line_char.is_whitespace();
1770                                        non_whitespace_added |= !is_whitespace;
1771                                        is_whitespace
1772                                            && (non_whitespace_added || !inside_wrapped_string)
1773                                    })
1774                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
1775                                        line_offset: line.len() + whitespace_index,
1776                                    }),
1777                            )
1778                        }
1779                    }
1780
1781                    line.push_str(line_chunk);
1782                }
1783            }
1784        }
1785
1786        layouts
1787    }
1788
1789    fn draw(
1790        &self,
1791        layout: &LayoutState,
1792        row: u32,
1793        scroll_top: f32,
1794        scene: &mut SceneBuilder,
1795        content_origin: Vector2F,
1796        scroll_left: f32,
1797        visible_text_bounds: RectF,
1798        whitespace_setting: ShowWhitespaceSetting,
1799        selection_ranges: &[Range<DisplayPoint>],
1800        visible_bounds: RectF,
1801        cx: &mut ViewContext<Editor>,
1802    ) {
1803        let line_height = layout.position_map.line_height;
1804        let line_y = row as f32 * line_height - scroll_top;
1805
1806        self.line.paint(
1807            scene,
1808            content_origin + vec2f(-scroll_left, line_y),
1809            visible_text_bounds,
1810            line_height,
1811            cx,
1812        );
1813
1814        self.draw_invisibles(
1815            &selection_ranges,
1816            layout,
1817            content_origin,
1818            scroll_left,
1819            line_y,
1820            row,
1821            scene,
1822            visible_bounds,
1823            line_height,
1824            whitespace_setting,
1825            cx,
1826        );
1827    }
1828
1829    fn draw_invisibles(
1830        &self,
1831        selection_ranges: &[Range<DisplayPoint>],
1832        layout: &LayoutState,
1833        content_origin: Vector2F,
1834        scroll_left: f32,
1835        line_y: f32,
1836        row: u32,
1837        scene: &mut SceneBuilder,
1838        visible_bounds: RectF,
1839        line_height: f32,
1840        whitespace_setting: ShowWhitespaceSetting,
1841        cx: &mut ViewContext<Editor>,
1842    ) {
1843        let allowed_invisibles_regions = match whitespace_setting {
1844            ShowWhitespaceSetting::None => return,
1845            ShowWhitespaceSetting::Selection => Some(selection_ranges),
1846            ShowWhitespaceSetting::All => None,
1847        };
1848
1849        for invisible in &self.invisibles {
1850            let (&token_offset, invisible_symbol) = match invisible {
1851                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
1852                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
1853            };
1854
1855            let x_offset = self.line.x_for_index(token_offset);
1856            let invisible_offset =
1857                (layout.position_map.em_width - invisible_symbol.width()).max(0.0) / 2.0;
1858            let origin = content_origin + vec2f(-scroll_left + x_offset + invisible_offset, line_y);
1859
1860            if let Some(allowed_regions) = allowed_invisibles_regions {
1861                let invisible_point = DisplayPoint::new(row, token_offset as u32);
1862                if !allowed_regions
1863                    .iter()
1864                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
1865                {
1866                    continue;
1867                }
1868            }
1869            invisible_symbol.paint(scene, origin, visible_bounds, line_height, cx);
1870        }
1871    }
1872}
1873
1874#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1875enum Invisible {
1876    Tab { line_start_offset: usize },
1877    Whitespace { line_offset: usize },
1878}
1879
1880impl Element<Editor> for EditorElement {
1881    type LayoutState = LayoutState;
1882    type PaintState = ();
1883
1884    fn layout(
1885        &mut self,
1886        constraint: SizeConstraint,
1887        editor: &mut Editor,
1888        cx: &mut LayoutContext<Editor>,
1889    ) -> (Vector2F, Self::LayoutState) {
1890        let mut size = constraint.max;
1891        if size.x().is_infinite() {
1892            unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1893        }
1894
1895        let snapshot = editor.snapshot(cx);
1896        let style = self.style.clone();
1897        let line_height = style.text.line_height(cx.font_cache());
1898
1899        let gutter_padding;
1900        let gutter_width;
1901        let gutter_margin;
1902        if snapshot.mode == EditorMode::Full {
1903            let em_width = style.text.em_width(cx.font_cache());
1904            gutter_padding = (em_width * style.gutter_padding_factor).round();
1905            gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1906            gutter_margin = -style.text.descent(cx.font_cache());
1907        } else {
1908            gutter_padding = 0.0;
1909            gutter_width = 0.0;
1910            gutter_margin = 0.0;
1911        };
1912
1913        let text_width = size.x() - gutter_width;
1914        let em_width = style.text.em_width(cx.font_cache());
1915        let em_advance = style.text.em_advance(cx.font_cache());
1916        let overscroll = vec2f(em_width, 0.);
1917        let snapshot = {
1918            editor.set_visible_line_count(size.y() / line_height);
1919
1920            let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
1921            let wrap_width = match editor.soft_wrap_mode(cx) {
1922                SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1923                SoftWrap::EditorWidth => editor_width,
1924                SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1925            };
1926
1927            if editor.set_wrap_width(Some(wrap_width), cx) {
1928                editor.snapshot(cx)
1929            } else {
1930                snapshot
1931            }
1932        };
1933
1934        let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1935        if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1936            size.set_y(
1937                scroll_height
1938                    .min(constraint.max_along(Axis::Vertical))
1939                    .max(constraint.min_along(Axis::Vertical))
1940                    .min(line_height * max_lines as f32),
1941            )
1942        } else if let EditorMode::SingleLine = snapshot.mode {
1943            size.set_y(
1944                line_height
1945                    .min(constraint.max_along(Axis::Vertical))
1946                    .max(constraint.min_along(Axis::Vertical)),
1947            )
1948        } else if size.y().is_infinite() {
1949            size.set_y(scroll_height);
1950        }
1951        let gutter_size = vec2f(gutter_width, size.y());
1952        let text_size = vec2f(text_width, size.y());
1953
1954        let autoscroll_horizontally = editor.autoscroll_vertically(size.y(), line_height, cx);
1955        let mut snapshot = editor.snapshot(cx);
1956
1957        let scroll_position = snapshot.scroll_position();
1958        // The scroll position is a fractional point, the whole number of which represents
1959        // the top of the window in terms of display rows.
1960        let start_row = scroll_position.y() as u32;
1961        let height_in_lines = size.y() / line_height;
1962        let max_row = snapshot.max_point().row();
1963
1964        // Add 1 to ensure selections bleed off screen
1965        let end_row = 1 + cmp::min(
1966            (scroll_position.y() + height_in_lines).ceil() as u32,
1967            max_row,
1968        );
1969
1970        let start_anchor = if start_row == 0 {
1971            Anchor::min()
1972        } else {
1973            snapshot
1974                .buffer_snapshot
1975                .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1976        };
1977        let end_anchor = if end_row > max_row {
1978            Anchor::max()
1979        } else {
1980            snapshot
1981                .buffer_snapshot
1982                .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1983        };
1984
1985        let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1986        let mut active_rows = BTreeMap::new();
1987        let mut fold_ranges = Vec::new();
1988        let is_singleton = editor.is_singleton(cx);
1989
1990        let highlighted_rows = editor.highlighted_rows();
1991        let theme = theme::current(cx);
1992        let highlighted_ranges = editor.background_highlights_in_range(
1993            start_anchor..end_anchor,
1994            &snapshot.display_snapshot,
1995            theme.as_ref(),
1996        );
1997
1998        fold_ranges.extend(
1999            snapshot
2000                .folds_in_range(start_anchor..end_anchor)
2001                .map(|anchor| {
2002                    let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2003                    (
2004                        start.row,
2005                        start.to_display_point(&snapshot.display_snapshot)
2006                            ..anchor.end.to_display_point(&snapshot),
2007                    )
2008                }),
2009        );
2010
2011        let mut remote_selections = HashMap::default();
2012        for (replica_id, line_mode, cursor_shape, selection) in snapshot
2013            .buffer_snapshot
2014            .remote_selections_in_range(&(start_anchor..end_anchor))
2015        {
2016            // The local selections match the leader's selections.
2017            if Some(replica_id) == editor.leader_replica_id {
2018                continue;
2019            }
2020            remote_selections
2021                .entry(replica_id)
2022                .or_insert(Vec::new())
2023                .push(SelectionLayout::new(
2024                    selection,
2025                    line_mode,
2026                    cursor_shape,
2027                    &snapshot.display_snapshot,
2028                ));
2029        }
2030        selections.extend(remote_selections);
2031
2032        if editor.show_local_selections {
2033            let mut local_selections = editor
2034                .selections
2035                .disjoint_in_range(start_anchor..end_anchor, cx);
2036            local_selections.extend(editor.selections.pending(cx));
2037            for selection in &local_selections {
2038                let is_empty = selection.start == selection.end;
2039                let selection_start = snapshot.prev_line_boundary(selection.start).1;
2040                let selection_end = snapshot.next_line_boundary(selection.end).1;
2041                for row in cmp::max(selection_start.row(), start_row)
2042                    ..=cmp::min(selection_end.row(), end_row)
2043                {
2044                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2045                    *contains_non_empty_selection |= !is_empty;
2046                }
2047            }
2048
2049            // Render the local selections in the leader's color when following.
2050            let local_replica_id = editor
2051                .leader_replica_id
2052                .unwrap_or_else(|| editor.replica_id(cx));
2053
2054            selections.push((
2055                local_replica_id,
2056                local_selections
2057                    .into_iter()
2058                    .map(|selection| {
2059                        SelectionLayout::new(
2060                            selection,
2061                            editor.selections.line_mode,
2062                            editor.cursor_shape,
2063                            &snapshot.display_snapshot,
2064                        )
2065                    })
2066                    .collect(),
2067            ));
2068        }
2069
2070        let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2071        let show_scrollbars = match scrollbar_settings.show {
2072            ShowScrollbar::Auto => {
2073                // Git
2074                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2075                // Scrollmanager
2076                || editor.scroll_manager.scrollbars_visible()
2077            }
2078            ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2079            ShowScrollbar::Always => true,
2080            ShowScrollbar::Never => false,
2081        };
2082
2083        let include_root = editor
2084            .project
2085            .as_ref()
2086            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2087            .unwrap_or_default();
2088
2089        let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2090            .into_iter()
2091            .map(|(id, fold)| {
2092                let color = self
2093                    .style
2094                    .folds
2095                    .ellipses
2096                    .background
2097                    .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize), false)
2098                    .color;
2099
2100                (id, fold, color)
2101            })
2102            .collect();
2103
2104        let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2105            start_row..end_row,
2106            &active_rows,
2107            is_singleton,
2108            &snapshot,
2109            cx,
2110        );
2111
2112        let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2113
2114        let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
2115
2116        let mut max_visible_line_width = 0.0;
2117        let line_layouts =
2118            self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2119        for line_with_invisibles in &line_layouts {
2120            if line_with_invisibles.line.width() > max_visible_line_width {
2121                max_visible_line_width = line_with_invisibles.line.width();
2122            }
2123        }
2124
2125        let style = self.style.clone();
2126        let longest_line_width = layout_line(
2127            snapshot.longest_row(),
2128            &snapshot,
2129            &style,
2130            cx.text_layout_cache(),
2131        )
2132        .width();
2133        let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
2134        let em_width = style.text.em_width(cx.font_cache());
2135        let (scroll_width, blocks) = self.layout_blocks(
2136            start_row..end_row,
2137            &snapshot,
2138            size.x(),
2139            scroll_width,
2140            gutter_padding,
2141            gutter_width,
2142            em_width,
2143            gutter_width + gutter_margin,
2144            line_height,
2145            &style,
2146            &line_layouts,
2147            include_root,
2148            editor,
2149            cx,
2150        );
2151
2152        let scroll_max = vec2f(
2153            ((scroll_width - text_size.x()) / em_width).max(0.0),
2154            max_row as f32,
2155        );
2156
2157        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x());
2158
2159        let autoscrolled = if autoscroll_horizontally {
2160            editor.autoscroll_horizontally(
2161                start_row,
2162                text_size.x(),
2163                scroll_width,
2164                em_width,
2165                &line_layouts,
2166                cx,
2167            )
2168        } else {
2169            false
2170        };
2171
2172        if clamped || autoscrolled {
2173            snapshot = editor.snapshot(cx);
2174        }
2175
2176        let newest_selection_head = editor
2177            .selections
2178            .newest::<usize>(cx)
2179            .head()
2180            .to_display_point(&snapshot);
2181        let style = editor.style(cx);
2182
2183        let mut context_menu = None;
2184        let mut code_actions_indicator = None;
2185        if (start_row..end_row).contains(&newest_selection_head.row()) {
2186            if editor.context_menu_visible() {
2187                context_menu = editor.render_context_menu(newest_selection_head, style.clone(), cx);
2188            }
2189
2190            let active = matches!(
2191                editor.context_menu,
2192                Some(crate::ContextMenu::CodeActions(_))
2193            );
2194
2195            code_actions_indicator = editor
2196                .render_code_actions_indicator(&style, active, cx)
2197                .map(|indicator| (newest_selection_head.row(), indicator));
2198        }
2199
2200        let visible_rows = start_row..start_row + line_layouts.len() as u32;
2201        let mut hover = editor
2202            .hover_state
2203            .render(&snapshot, &style, visible_rows, cx);
2204        let mode = editor.mode;
2205
2206        let mut fold_indicators = editor.render_fold_indicators(
2207            fold_statuses,
2208            &style,
2209            editor.gutter_hovered,
2210            line_height,
2211            gutter_margin,
2212            cx,
2213        );
2214
2215        if let Some((_, context_menu)) = context_menu.as_mut() {
2216            context_menu.layout(
2217                SizeConstraint {
2218                    min: Vector2F::zero(),
2219                    max: vec2f(
2220                        cx.window_size().x() * 0.7,
2221                        (12. * line_height).min((size.y() - line_height) / 2.),
2222                    ),
2223                },
2224                editor,
2225                cx,
2226            );
2227        }
2228
2229        if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2230            indicator.layout(
2231                SizeConstraint::strict_along(
2232                    Axis::Vertical,
2233                    line_height * style.code_actions.vertical_scale,
2234                ),
2235                editor,
2236                cx,
2237            );
2238        }
2239
2240        for fold_indicator in fold_indicators.iter_mut() {
2241            if let Some(indicator) = fold_indicator.as_mut() {
2242                indicator.layout(
2243                    SizeConstraint::strict_along(
2244                        Axis::Vertical,
2245                        line_height * style.code_actions.vertical_scale,
2246                    ),
2247                    editor,
2248                    cx,
2249                );
2250            }
2251        }
2252
2253        if let Some((_, hover_popovers)) = hover.as_mut() {
2254            for hover_popover in hover_popovers.iter_mut() {
2255                hover_popover.layout(
2256                    SizeConstraint {
2257                        min: Vector2F::zero(),
2258                        max: vec2f(
2259                            (120. * em_width) // Default size
2260                                .min(size.x() / 2.) // Shrink to half of the editor width
2261                                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2262                            (16. * line_height) // Default size
2263                                .min(size.y() / 2.) // Shrink to half of the editor height
2264                                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2265                        ),
2266                    },
2267                    editor,
2268                    cx,
2269                );
2270            }
2271        }
2272
2273        let invisible_symbol_font_size = self.style.text.font_size / 2.0;
2274        let invisible_symbol_style = RunStyle {
2275            color: self.style.whitespace,
2276            font_id: self.style.text.font_id,
2277            underline: Default::default(),
2278        };
2279
2280        (
2281            size,
2282            LayoutState {
2283                mode,
2284                position_map: Arc::new(PositionMap {
2285                    size,
2286                    scroll_max,
2287                    line_layouts,
2288                    line_height,
2289                    em_width,
2290                    em_advance,
2291                    snapshot,
2292                }),
2293                visible_display_row_range: start_row..end_row,
2294                gutter_size,
2295                gutter_padding,
2296                text_size,
2297                scrollbar_row_range,
2298                show_scrollbars,
2299                is_singleton,
2300                max_row,
2301                gutter_margin,
2302                active_rows,
2303                highlighted_rows,
2304                highlighted_ranges,
2305                fold_ranges,
2306                line_number_layouts,
2307                display_hunks,
2308                blocks,
2309                selections,
2310                context_menu,
2311                code_actions_indicator,
2312                fold_indicators,
2313                tab_invisible: cx.text_layout_cache().layout_str(
2314                    "",
2315                    invisible_symbol_font_size,
2316                    &[("".len(), invisible_symbol_style)],
2317                ),
2318                space_invisible: cx.text_layout_cache().layout_str(
2319                    "",
2320                    invisible_symbol_font_size,
2321                    &[("".len(), invisible_symbol_style)],
2322                ),
2323                hover_popovers: hover,
2324            },
2325        )
2326    }
2327
2328    fn paint(
2329        &mut self,
2330        scene: &mut SceneBuilder,
2331        bounds: RectF,
2332        visible_bounds: RectF,
2333        layout: &mut Self::LayoutState,
2334        editor: &mut Editor,
2335        cx: &mut ViewContext<Editor>,
2336    ) -> Self::PaintState {
2337        let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
2338        scene.push_layer(Some(visible_bounds));
2339
2340        let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
2341        let text_bounds = RectF::new(
2342            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2343            layout.text_size,
2344        );
2345
2346        Self::attach_mouse_handlers(
2347            scene,
2348            &layout.position_map,
2349            layout.hover_popovers.is_some(),
2350            visible_bounds,
2351            text_bounds,
2352            gutter_bounds,
2353            bounds,
2354            cx,
2355        );
2356
2357        self.paint_background(scene, gutter_bounds, text_bounds, layout);
2358        if layout.gutter_size.x() > 0. {
2359            self.paint_gutter(scene, gutter_bounds, visible_bounds, layout, editor, cx);
2360        }
2361        self.paint_text(scene, text_bounds, visible_bounds, layout, editor, cx);
2362
2363        scene.push_layer(Some(bounds));
2364        if !layout.blocks.is_empty() {
2365            self.paint_blocks(scene, bounds, visible_bounds, layout, editor, cx);
2366        }
2367        self.paint_scrollbar(scene, bounds, layout, cx);
2368        scene.pop_layer();
2369
2370        scene.pop_layer();
2371    }
2372
2373    fn rect_for_text_range(
2374        &self,
2375        range_utf16: Range<usize>,
2376        bounds: RectF,
2377        _: RectF,
2378        layout: &Self::LayoutState,
2379        _: &Self::PaintState,
2380        _: &Editor,
2381        _: &ViewContext<Editor>,
2382    ) -> Option<RectF> {
2383        let text_bounds = RectF::new(
2384            bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
2385            layout.text_size,
2386        );
2387        let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
2388        let scroll_position = layout.position_map.snapshot.scroll_position();
2389        let start_row = scroll_position.y() as u32;
2390        let scroll_top = scroll_position.y() * layout.position_map.line_height;
2391        let scroll_left = scroll_position.x() * layout.position_map.em_width;
2392
2393        let range_start = OffsetUtf16(range_utf16.start)
2394            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2395        if range_start.row() < start_row {
2396            return None;
2397        }
2398
2399        let line = &layout
2400            .position_map
2401            .line_layouts
2402            .get((range_start.row() - start_row) as usize)?
2403            .line;
2404        let range_start_x = line.x_for_index(range_start.column() as usize);
2405        let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
2406        Some(RectF::new(
2407            content_origin
2408                + vec2f(
2409                    range_start_x,
2410                    range_start_y + layout.position_map.line_height,
2411                )
2412                - vec2f(scroll_left, scroll_top),
2413            vec2f(
2414                layout.position_map.em_width,
2415                layout.position_map.line_height,
2416            ),
2417        ))
2418    }
2419
2420    fn debug(
2421        &self,
2422        bounds: RectF,
2423        _: &Self::LayoutState,
2424        _: &Self::PaintState,
2425        _: &Editor,
2426        _: &ViewContext<Editor>,
2427    ) -> json::Value {
2428        json!({
2429            "type": "BufferElement",
2430            "bounds": bounds.to_json()
2431        })
2432    }
2433}
2434
2435type BufferRow = u32;
2436
2437pub struct LayoutState {
2438    position_map: Arc<PositionMap>,
2439    gutter_size: Vector2F,
2440    gutter_padding: f32,
2441    gutter_margin: f32,
2442    text_size: Vector2F,
2443    mode: EditorMode,
2444    visible_display_row_range: Range<u32>,
2445    active_rows: BTreeMap<u32, bool>,
2446    highlighted_rows: Option<Range<u32>>,
2447    line_number_layouts: Vec<Option<text_layout::Line>>,
2448    display_hunks: Vec<DisplayDiffHunk>,
2449    blocks: Vec<BlockLayout>,
2450    highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
2451    fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)>,
2452    selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
2453    scrollbar_row_range: Range<f32>,
2454    show_scrollbars: bool,
2455    is_singleton: bool,
2456    max_row: u32,
2457    context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
2458    code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
2459    hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
2460    fold_indicators: Vec<Option<AnyElement<Editor>>>,
2461    tab_invisible: Line,
2462    space_invisible: Line,
2463}
2464
2465struct PositionMap {
2466    size: Vector2F,
2467    line_height: f32,
2468    scroll_max: Vector2F,
2469    em_width: f32,
2470    em_advance: f32,
2471    line_layouts: Vec<LineWithInvisibles>,
2472    snapshot: EditorSnapshot,
2473}
2474
2475impl PositionMap {
2476    /// Returns two display points:
2477    /// 1. The nearest *valid* position in the editor
2478    /// 2. An unclipped, potentially *invalid* position that maps directly to
2479    ///    the given pixel position.
2480    fn point_for_position(
2481        &self,
2482        text_bounds: RectF,
2483        position: Vector2F,
2484    ) -> (DisplayPoint, DisplayPoint) {
2485        let scroll_position = self.snapshot.scroll_position();
2486        let position = position - text_bounds.origin();
2487        let y = position.y().max(0.0).min(self.size.y());
2488        let x = position.x() + (scroll_position.x() * self.em_width);
2489        let row = (y / self.line_height + scroll_position.y()) as u32;
2490        let (column, x_overshoot) = if let Some(line) = self
2491            .line_layouts
2492            .get(row as usize - scroll_position.y() as usize)
2493            .map(|line_with_spaces| &line_with_spaces.line)
2494        {
2495            if let Some(ix) = line.index_for_x(x) {
2496                (ix as u32, 0.0)
2497            } else {
2498                (line.len() as u32, 0f32.max(x - line.width()))
2499            }
2500        } else {
2501            (0, x)
2502        };
2503
2504        let mut target_point = DisplayPoint::new(row, column);
2505        let point = self.snapshot.clip_point(target_point, Bias::Left);
2506        *target_point.column_mut() += (x_overshoot / self.em_advance) as u32;
2507
2508        (point, target_point)
2509    }
2510}
2511
2512struct BlockLayout {
2513    row: u32,
2514    element: AnyElement<Editor>,
2515    style: BlockStyle,
2516}
2517
2518fn layout_line(
2519    row: u32,
2520    snapshot: &EditorSnapshot,
2521    style: &EditorStyle,
2522    layout_cache: &TextLayoutCache,
2523) -> text_layout::Line {
2524    let mut line = snapshot.line(row);
2525
2526    if line.len() > MAX_LINE_LEN {
2527        let mut len = MAX_LINE_LEN;
2528        while !line.is_char_boundary(len) {
2529            len -= 1;
2530        }
2531
2532        line.truncate(len);
2533    }
2534
2535    layout_cache.layout_str(
2536        &line,
2537        style.text.font_size,
2538        &[(
2539            snapshot.line_len(row) as usize,
2540            RunStyle {
2541                font_id: style.text.font_id,
2542                color: Color::black(),
2543                underline: Default::default(),
2544            },
2545        )],
2546    )
2547}
2548
2549#[derive(Debug)]
2550pub struct Cursor {
2551    origin: Vector2F,
2552    block_width: f32,
2553    line_height: f32,
2554    color: Color,
2555    shape: CursorShape,
2556    block_text: Option<Line>,
2557}
2558
2559impl Cursor {
2560    pub fn new(
2561        origin: Vector2F,
2562        block_width: f32,
2563        line_height: f32,
2564        color: Color,
2565        shape: CursorShape,
2566        block_text: Option<Line>,
2567    ) -> Cursor {
2568        Cursor {
2569            origin,
2570            block_width,
2571            line_height,
2572            color,
2573            shape,
2574            block_text,
2575        }
2576    }
2577
2578    pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
2579        RectF::new(
2580            self.origin + origin,
2581            vec2f(self.block_width, self.line_height),
2582        )
2583    }
2584
2585    pub fn paint(&self, scene: &mut SceneBuilder, origin: Vector2F, cx: &mut WindowContext) {
2586        let bounds = match self.shape {
2587            CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
2588            CursorShape::Block | CursorShape::Hollow => RectF::new(
2589                self.origin + origin,
2590                vec2f(self.block_width, self.line_height),
2591            ),
2592            CursorShape::Underscore => RectF::new(
2593                self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
2594                vec2f(self.block_width, 2.0),
2595            ),
2596        };
2597
2598        //Draw background or border quad
2599        if matches!(self.shape, CursorShape::Hollow) {
2600            scene.push_quad(Quad {
2601                bounds,
2602                background: None,
2603                border: Border::all(1., self.color),
2604                corner_radius: 0.,
2605            });
2606        } else {
2607            scene.push_quad(Quad {
2608                bounds,
2609                background: Some(self.color),
2610                border: Default::default(),
2611                corner_radius: 0.,
2612            });
2613        }
2614
2615        if let Some(block_text) = &self.block_text {
2616            block_text.paint(scene, self.origin + origin, bounds, self.line_height, cx);
2617        }
2618    }
2619
2620    pub fn shape(&self) -> CursorShape {
2621        self.shape
2622    }
2623}
2624
2625#[derive(Debug)]
2626pub struct HighlightedRange {
2627    pub start_y: f32,
2628    pub line_height: f32,
2629    pub lines: Vec<HighlightedRangeLine>,
2630    pub color: Color,
2631    pub corner_radius: f32,
2632}
2633
2634#[derive(Debug)]
2635pub struct HighlightedRangeLine {
2636    pub start_x: f32,
2637    pub end_x: f32,
2638}
2639
2640impl HighlightedRange {
2641    pub fn paint(&self, bounds: RectF, scene: &mut SceneBuilder) {
2642        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
2643            self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
2644            self.paint_lines(
2645                self.start_y + self.line_height,
2646                &self.lines[1..],
2647                bounds,
2648                scene,
2649            );
2650        } else {
2651            self.paint_lines(self.start_y, &self.lines, bounds, scene);
2652        }
2653    }
2654
2655    fn paint_lines(
2656        &self,
2657        start_y: f32,
2658        lines: &[HighlightedRangeLine],
2659        bounds: RectF,
2660        scene: &mut SceneBuilder,
2661    ) {
2662        if lines.is_empty() {
2663            return;
2664        }
2665
2666        let mut path = PathBuilder::new();
2667        let first_line = lines.first().unwrap();
2668        let last_line = lines.last().unwrap();
2669
2670        let first_top_left = vec2f(first_line.start_x, start_y);
2671        let first_top_right = vec2f(first_line.end_x, start_y);
2672
2673        let curve_height = vec2f(0., self.corner_radius);
2674        let curve_width = |start_x: f32, end_x: f32| {
2675            let max = (end_x - start_x) / 2.;
2676            let width = if max < self.corner_radius {
2677                max
2678            } else {
2679                self.corner_radius
2680            };
2681
2682            vec2f(width, 0.)
2683        };
2684
2685        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
2686        path.reset(first_top_right - top_curve_width);
2687        path.curve_to(first_top_right + curve_height, first_top_right);
2688
2689        let mut iter = lines.iter().enumerate().peekable();
2690        while let Some((ix, line)) = iter.next() {
2691            let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
2692
2693            if let Some((_, next_line)) = iter.peek() {
2694                let next_top_right = vec2f(next_line.end_x, bottom_right.y());
2695
2696                match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
2697                    Ordering::Equal => {
2698                        path.line_to(bottom_right);
2699                    }
2700                    Ordering::Less => {
2701                        let curve_width = curve_width(next_top_right.x(), bottom_right.x());
2702                        path.line_to(bottom_right - curve_height);
2703                        if self.corner_radius > 0. {
2704                            path.curve_to(bottom_right - curve_width, bottom_right);
2705                        }
2706                        path.line_to(next_top_right + curve_width);
2707                        if self.corner_radius > 0. {
2708                            path.curve_to(next_top_right + curve_height, next_top_right);
2709                        }
2710                    }
2711                    Ordering::Greater => {
2712                        let curve_width = curve_width(bottom_right.x(), next_top_right.x());
2713                        path.line_to(bottom_right - curve_height);
2714                        if self.corner_radius > 0. {
2715                            path.curve_to(bottom_right + curve_width, bottom_right);
2716                        }
2717                        path.line_to(next_top_right - curve_width);
2718                        if self.corner_radius > 0. {
2719                            path.curve_to(next_top_right + curve_height, next_top_right);
2720                        }
2721                    }
2722                }
2723            } else {
2724                let curve_width = curve_width(line.start_x, line.end_x);
2725                path.line_to(bottom_right - curve_height);
2726                if self.corner_radius > 0. {
2727                    path.curve_to(bottom_right - curve_width, bottom_right);
2728                }
2729
2730                let bottom_left = vec2f(line.start_x, bottom_right.y());
2731                path.line_to(bottom_left + curve_width);
2732                if self.corner_radius > 0. {
2733                    path.curve_to(bottom_left - curve_height, bottom_left);
2734                }
2735            }
2736        }
2737
2738        if first_line.start_x > last_line.start_x {
2739            let curve_width = curve_width(last_line.start_x, first_line.start_x);
2740            let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
2741            path.line_to(second_top_left + curve_height);
2742            if self.corner_radius > 0. {
2743                path.curve_to(second_top_left + curve_width, second_top_left);
2744            }
2745            let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
2746            path.line_to(first_bottom_left - curve_width);
2747            if self.corner_radius > 0. {
2748                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
2749            }
2750        }
2751
2752        path.line_to(first_top_left + curve_height);
2753        if self.corner_radius > 0. {
2754            path.curve_to(first_top_left + top_curve_width, first_top_left);
2755        }
2756        path.line_to(first_top_right - top_curve_width);
2757
2758        scene.push_path(path.build(self.color, Some(bounds)));
2759    }
2760}
2761
2762fn position_to_display_point(
2763    position: Vector2F,
2764    text_bounds: RectF,
2765    position_map: &PositionMap,
2766) -> Option<DisplayPoint> {
2767    if text_bounds.contains_point(position) {
2768        let (point, target_point) = position_map.point_for_position(text_bounds, position);
2769        if point == target_point {
2770            Some(point)
2771        } else {
2772            None
2773        }
2774    } else {
2775        None
2776    }
2777}
2778
2779fn range_to_bounds(
2780    range: &Range<DisplayPoint>,
2781    content_origin: Vector2F,
2782    scroll_left: f32,
2783    scroll_top: f32,
2784    visible_row_range: &Range<u32>,
2785    line_end_overshoot: f32,
2786    position_map: &PositionMap,
2787) -> impl Iterator<Item = RectF> {
2788    let mut bounds: SmallVec<[RectF; 1]> = SmallVec::new();
2789
2790    if range.start == range.end {
2791        return bounds.into_iter();
2792    }
2793
2794    let start_row = visible_row_range.start;
2795    let end_row = visible_row_range.end;
2796
2797    let row_range = if range.end.column() == 0 {
2798        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2799    } else {
2800        cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2801    };
2802
2803    let first_y =
2804        content_origin.y() + row_range.start as f32 * position_map.line_height - scroll_top;
2805
2806    for (idx, row) in row_range.enumerate() {
2807        let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
2808
2809        let start_x = if row == range.start.row() {
2810            content_origin.x() + line_layout.x_for_index(range.start.column() as usize)
2811                - scroll_left
2812        } else {
2813            content_origin.x() - scroll_left
2814        };
2815
2816        let end_x = if row == range.end.row() {
2817            content_origin.x() + line_layout.x_for_index(range.end.column() as usize) - scroll_left
2818        } else {
2819            content_origin.x() + line_layout.width() + line_end_overshoot - scroll_left
2820        };
2821
2822        bounds.push(RectF::from_points(
2823            vec2f(start_x, first_y + position_map.line_height * idx as f32),
2824            vec2f(end_x, first_y + position_map.line_height * (idx + 1) as f32),
2825        ))
2826    }
2827
2828    bounds.into_iter()
2829}
2830
2831pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
2832    delta.powf(1.5) / 100.0
2833}
2834
2835fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
2836    delta.powf(1.2) / 300.0
2837}
2838
2839#[cfg(test)]
2840mod tests {
2841    use super::*;
2842    use crate::{
2843        display_map::{BlockDisposition, BlockProperties},
2844        editor_tests::{init_test, update_test_settings},
2845        Editor, MultiBuffer,
2846    };
2847    use gpui::TestAppContext;
2848    use language::language_settings;
2849    use log::info;
2850    use std::{num::NonZeroU32, sync::Arc};
2851    use util::test::sample_text;
2852
2853    #[gpui::test]
2854    fn test_layout_line_numbers(cx: &mut TestAppContext) {
2855        init_test(cx, |_| {});
2856
2857        let (_, editor) = cx.add_window(|cx| {
2858            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
2859            Editor::new(EditorMode::Full, buffer, None, None, cx)
2860        });
2861        let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2862
2863        let layouts = editor.update(cx, |editor, cx| {
2864            let snapshot = editor.snapshot(cx);
2865            element
2866                .layout_line_numbers(0..6, &Default::default(), false, &snapshot, cx)
2867                .0
2868        });
2869        assert_eq!(layouts.len(), 6);
2870    }
2871
2872    #[gpui::test]
2873    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
2874        init_test(cx, |_| {});
2875
2876        let (_, editor) = cx.add_window(|cx| {
2877            let buffer = MultiBuffer::build_simple("", cx);
2878            Editor::new(EditorMode::Full, buffer, None, None, cx)
2879        });
2880
2881        editor.update(cx, |editor, cx| {
2882            editor.set_placeholder_text("hello", cx);
2883            editor.insert_blocks(
2884                [BlockProperties {
2885                    style: BlockStyle::Fixed,
2886                    disposition: BlockDisposition::Above,
2887                    height: 3,
2888                    position: Anchor::min(),
2889                    render: Arc::new(|_| Empty::new().into_any()),
2890                }],
2891                cx,
2892            );
2893
2894            // Blur the editor so that it displays placeholder text.
2895            cx.blur();
2896        });
2897
2898        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
2899        let (size, mut state) = editor.update(cx, |editor, cx| {
2900            let mut new_parents = Default::default();
2901            let mut notify_views_if_parents_change = Default::default();
2902            let mut layout_cx = LayoutContext::new(
2903                cx,
2904                &mut new_parents,
2905                &mut notify_views_if_parents_change,
2906                false,
2907            );
2908            element.layout(
2909                SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2910                editor,
2911                &mut layout_cx,
2912            )
2913        });
2914
2915        assert_eq!(state.position_map.line_layouts.len(), 4);
2916        assert_eq!(
2917            state
2918                .line_number_layouts
2919                .iter()
2920                .map(Option::is_some)
2921                .collect::<Vec<_>>(),
2922            &[false, false, false, true]
2923        );
2924
2925        // Don't panic.
2926        let mut scene = SceneBuilder::new(1.0);
2927        let bounds = RectF::new(Default::default(), size);
2928        editor.update(cx, |editor, cx| {
2929            element.paint(&mut scene, bounds, bounds, &mut state, editor, cx);
2930        });
2931    }
2932
2933    #[gpui::test]
2934    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
2935        const TAB_SIZE: u32 = 4;
2936
2937        let input_text = "\t \t|\t| a b";
2938        let expected_invisibles = vec![
2939            Invisible::Tab {
2940                line_start_offset: 0,
2941            },
2942            Invisible::Whitespace {
2943                line_offset: TAB_SIZE as usize,
2944            },
2945            Invisible::Tab {
2946                line_start_offset: TAB_SIZE as usize + 1,
2947            },
2948            Invisible::Tab {
2949                line_start_offset: TAB_SIZE as usize * 2 + 1,
2950            },
2951            Invisible::Whitespace {
2952                line_offset: TAB_SIZE as usize * 3 + 1,
2953            },
2954            Invisible::Whitespace {
2955                line_offset: TAB_SIZE as usize * 3 + 3,
2956            },
2957        ];
2958        assert_eq!(
2959            expected_invisibles.len(),
2960            input_text
2961                .chars()
2962                .filter(|initial_char| initial_char.is_whitespace())
2963                .count(),
2964            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
2965        );
2966
2967        init_test(cx, |s| {
2968            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
2969            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
2970        });
2971
2972        let actual_invisibles =
2973            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
2974
2975        assert_eq!(expected_invisibles, actual_invisibles);
2976    }
2977
2978    #[gpui::test]
2979    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
2980        init_test(cx, |s| {
2981            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
2982            s.defaults.tab_size = NonZeroU32::new(4);
2983        });
2984
2985        for editor_mode_without_invisibles in [
2986            EditorMode::SingleLine,
2987            EditorMode::AutoHeight { max_lines: 100 },
2988        ] {
2989            let invisibles = collect_invisibles_from_new_editor(
2990                cx,
2991                editor_mode_without_invisibles,
2992                "\t\t\t| | a b",
2993                500.0,
2994            );
2995            assert!(invisibles.is_empty(),
2996                "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
2997        }
2998    }
2999
3000    #[gpui::test]
3001    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3002        let tab_size = 4;
3003        let input_text = "a\tbcd   ".repeat(9);
3004        let repeated_invisibles = [
3005            Invisible::Tab {
3006                line_start_offset: 1,
3007            },
3008            Invisible::Whitespace {
3009                line_offset: tab_size as usize + 3,
3010            },
3011            Invisible::Whitespace {
3012                line_offset: tab_size as usize + 4,
3013            },
3014            Invisible::Whitespace {
3015                line_offset: tab_size as usize + 5,
3016            },
3017        ];
3018        let expected_invisibles = std::iter::once(repeated_invisibles)
3019            .cycle()
3020            .take(9)
3021            .flatten()
3022            .collect::<Vec<_>>();
3023        assert_eq!(
3024            expected_invisibles.len(),
3025            input_text
3026                .chars()
3027                .filter(|initial_char| initial_char.is_whitespace())
3028                .count(),
3029            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3030        );
3031        info!("Expected invisibles: {expected_invisibles:?}");
3032
3033        init_test(cx, |_| {});
3034
3035        // Put the same string with repeating whitespace pattern into editors of various size,
3036        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3037        let resize_step = 10.0;
3038        let mut editor_width = 200.0;
3039        while editor_width <= 1000.0 {
3040            update_test_settings(cx, |s| {
3041                s.defaults.tab_size = NonZeroU32::new(tab_size);
3042                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3043                s.defaults.preferred_line_length = Some(editor_width as u32);
3044                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3045            });
3046
3047            let actual_invisibles =
3048                collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
3049
3050            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3051            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3052            let mut i = 0;
3053            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3054                i = actual_index;
3055                match expected_invisibles.get(i) {
3056                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3057                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3058                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3059                        _ => {
3060                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3061                        }
3062                    },
3063                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3064                }
3065            }
3066            let missing_expected_invisibles = &expected_invisibles[i + 1..];
3067            assert!(
3068                missing_expected_invisibles.is_empty(),
3069                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3070            );
3071
3072            editor_width += resize_step;
3073        }
3074    }
3075
3076    fn collect_invisibles_from_new_editor(
3077        cx: &mut TestAppContext,
3078        editor_mode: EditorMode,
3079        input_text: &str,
3080        editor_width: f32,
3081    ) -> Vec<Invisible> {
3082        info!(
3083            "Creating editor with mode {editor_mode:?}, witdh {editor_width} and text '{input_text}'"
3084        );
3085        let (_, editor) = cx.add_window(|cx| {
3086            let buffer = MultiBuffer::build_simple(&input_text, cx);
3087            Editor::new(editor_mode, buffer, None, None, cx)
3088        });
3089
3090        let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3091        let (_, layout_state) = editor.update(cx, |editor, cx| {
3092            editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3093            editor.set_wrap_width(Some(editor_width), cx);
3094
3095            let mut new_parents = Default::default();
3096            let mut notify_views_if_parents_change = Default::default();
3097            let mut layout_cx = LayoutContext::new(
3098                cx,
3099                &mut new_parents,
3100                &mut notify_views_if_parents_change,
3101                false,
3102            );
3103            element.layout(
3104                SizeConstraint::new(vec2f(editor_width, 500.), vec2f(editor_width, 500.)),
3105                editor,
3106                &mut layout_cx,
3107            )
3108        });
3109
3110        layout_state
3111            .position_map
3112            .line_layouts
3113            .iter()
3114            .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3115            .flatten()
3116            .cloned()
3117            .collect()
3118    }
3119}