1use crate::{
2 blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
3 display_map::{
4 BlockContext, BlockStyle, DisplaySnapshot, FoldStatus, HighlightedChunk, ToDisplayPoint,
5 TransformBlock,
6 },
7 editor_settings::{DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar},
8 git::{blame::GitBlame, diff_hunk_to_display, DisplayDiffHunk},
9 hover_popover::{
10 self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
11 },
12 items::BufferSearchHighlights,
13 mouse_context_menu::{self, MouseContextMenu},
14 scroll::scroll_amount::ScrollAmount,
15 CursorShape, DisplayPoint, DocumentHighlightRead, DocumentHighlightWrite, Editor, EditorMode,
16 EditorSettings, EditorSnapshot, EditorStyle, ExpandExcerpts, GutterDimensions, HalfPageDown,
17 HalfPageUp, HoveredCursor, LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point,
18 SelectPhase, Selection, SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
19};
20use anyhow::Result;
21use client::ParticipantIndex;
22use collections::{BTreeMap, HashMap};
23use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
24use gpui::{
25 anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
26 transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
27 ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity,
28 GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, ModifiersChangedEvent,
29 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, ParentElement, Pixels,
30 ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size, Stateful,
31 StatefulInteractiveElement, Style, Styled, TextRun, TextStyle, TextStyleRefinement, View,
32 ViewContext, WeakView, WindowContext,
33};
34use itertools::Itertools;
35use language::language_settings::ShowWhitespaceSetting;
36use lsp::DiagnosticSeverity;
37use multi_buffer::Anchor;
38use project::{
39 project_settings::{GitGutterSetting, ProjectSettings},
40 ProjectPath,
41};
42use settings::Settings;
43use smallvec::SmallVec;
44use std::{
45 any::TypeId,
46 borrow::Cow,
47 cmp::{self, max, Ordering},
48 fmt::Write,
49 iter, mem,
50 ops::{Deref, Range},
51 sync::Arc,
52};
53use sum_tree::Bias;
54use theme::{ActiveTheme, PlayerColor};
55use ui::prelude::*;
56use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
57use util::ResultExt;
58use workspace::{item::Item, Workspace};
59
60struct SelectionLayout {
61 head: DisplayPoint,
62 cursor_shape: CursorShape,
63 is_newest: bool,
64 is_local: bool,
65 range: Range<DisplayPoint>,
66 active_rows: Range<u32>,
67 user_name: Option<SharedString>,
68}
69
70impl SelectionLayout {
71 fn new<T: ToPoint + ToDisplayPoint + Clone>(
72 selection: Selection<T>,
73 line_mode: bool,
74 cursor_shape: CursorShape,
75 map: &DisplaySnapshot,
76 is_newest: bool,
77 is_local: bool,
78 user_name: Option<SharedString>,
79 ) -> Self {
80 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
81 let display_selection = point_selection.map(|p| p.to_display_point(map));
82 let mut range = display_selection.range();
83 let mut head = display_selection.head();
84 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
85 ..map.next_line_boundary(point_selection.end).1.row();
86
87 // vim visual line mode
88 if line_mode {
89 let point_range = map.expand_to_line(point_selection.range());
90 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
91 }
92
93 // any vim visual mode (including line mode)
94 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
95 && !range.is_empty()
96 && !selection.reversed
97 {
98 if head.column() > 0 {
99 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
100 } else if head.row() > 0 && head != map.max_point() {
101 head = map.clip_point(
102 DisplayPoint::new(head.row() - 1, map.line_len(head.row() - 1)),
103 Bias::Left,
104 );
105 // updating range.end is a no-op unless you're cursor is
106 // on the newline containing a multi-buffer divider
107 // in which case the clip_point may have moved the head up
108 // an additional row.
109 range.end = DisplayPoint::new(head.row() + 1, 0);
110 active_rows.end = head.row();
111 }
112 }
113
114 Self {
115 head,
116 cursor_shape,
117 is_newest,
118 is_local,
119 range,
120 active_rows,
121 user_name,
122 }
123 }
124}
125
126pub struct EditorElement {
127 editor: View<Editor>,
128 style: EditorStyle,
129}
130
131impl EditorElement {
132 pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
133 Self {
134 editor: editor.clone(),
135 style,
136 }
137 }
138
139 fn register_actions(&self, cx: &mut WindowContext) {
140 let view = &self.editor;
141 view.update(cx, |editor, cx| {
142 for action in editor.editor_actions.iter() {
143 (action)(cx)
144 }
145 });
146
147 crate::rust_analyzer_ext::apply_related_actions(view, cx);
148 register_action(view, cx, Editor::move_left);
149 register_action(view, cx, Editor::move_right);
150 register_action(view, cx, Editor::move_down);
151 register_action(view, cx, Editor::move_down_by_lines);
152 register_action(view, cx, Editor::select_down_by_lines);
153 register_action(view, cx, Editor::move_up);
154 register_action(view, cx, Editor::move_up_by_lines);
155 register_action(view, cx, Editor::select_up_by_lines);
156 register_action(view, cx, Editor::cancel);
157 register_action(view, cx, Editor::newline);
158 register_action(view, cx, Editor::newline_above);
159 register_action(view, cx, Editor::newline_below);
160 register_action(view, cx, Editor::backspace);
161 register_action(view, cx, Editor::delete);
162 register_action(view, cx, Editor::tab);
163 register_action(view, cx, Editor::tab_prev);
164 register_action(view, cx, Editor::indent);
165 register_action(view, cx, Editor::outdent);
166 register_action(view, cx, Editor::delete_line);
167 register_action(view, cx, Editor::join_lines);
168 register_action(view, cx, Editor::sort_lines_case_sensitive);
169 register_action(view, cx, Editor::sort_lines_case_insensitive);
170 register_action(view, cx, Editor::reverse_lines);
171 register_action(view, cx, Editor::shuffle_lines);
172 register_action(view, cx, Editor::convert_to_upper_case);
173 register_action(view, cx, Editor::convert_to_lower_case);
174 register_action(view, cx, Editor::convert_to_title_case);
175 register_action(view, cx, Editor::convert_to_snake_case);
176 register_action(view, cx, Editor::convert_to_kebab_case);
177 register_action(view, cx, Editor::convert_to_upper_camel_case);
178 register_action(view, cx, Editor::convert_to_lower_camel_case);
179 register_action(view, cx, Editor::delete_to_previous_word_start);
180 register_action(view, cx, Editor::delete_to_previous_subword_start);
181 register_action(view, cx, Editor::delete_to_next_word_end);
182 register_action(view, cx, Editor::delete_to_next_subword_end);
183 register_action(view, cx, Editor::delete_to_beginning_of_line);
184 register_action(view, cx, Editor::delete_to_end_of_line);
185 register_action(view, cx, Editor::cut_to_end_of_line);
186 register_action(view, cx, Editor::duplicate_line_up);
187 register_action(view, cx, Editor::duplicate_line_down);
188 register_action(view, cx, Editor::move_line_up);
189 register_action(view, cx, Editor::move_line_down);
190 register_action(view, cx, Editor::transpose);
191 register_action(view, cx, Editor::cut);
192 register_action(view, cx, Editor::copy);
193 register_action(view, cx, Editor::paste);
194 register_action(view, cx, Editor::undo);
195 register_action(view, cx, Editor::redo);
196 register_action(view, cx, Editor::move_page_up);
197 register_action(view, cx, Editor::move_page_down);
198 register_action(view, cx, Editor::next_screen);
199 register_action(view, cx, Editor::scroll_cursor_top);
200 register_action(view, cx, Editor::scroll_cursor_center);
201 register_action(view, cx, Editor::scroll_cursor_bottom);
202 register_action(view, cx, |editor, _: &LineDown, cx| {
203 editor.scroll_screen(&ScrollAmount::Line(1.), cx)
204 });
205 register_action(view, cx, |editor, _: &LineUp, cx| {
206 editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
207 });
208 register_action(view, cx, |editor, _: &HalfPageDown, cx| {
209 editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
210 });
211 register_action(view, cx, |editor, _: &HalfPageUp, cx| {
212 editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
213 });
214 register_action(view, cx, |editor, _: &PageDown, cx| {
215 editor.scroll_screen(&ScrollAmount::Page(1.), cx)
216 });
217 register_action(view, cx, |editor, _: &PageUp, cx| {
218 editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
219 });
220 register_action(view, cx, Editor::move_to_previous_word_start);
221 register_action(view, cx, Editor::move_to_previous_subword_start);
222 register_action(view, cx, Editor::move_to_next_word_end);
223 register_action(view, cx, Editor::move_to_next_subword_end);
224 register_action(view, cx, Editor::move_to_beginning_of_line);
225 register_action(view, cx, Editor::move_to_end_of_line);
226 register_action(view, cx, Editor::move_to_start_of_paragraph);
227 register_action(view, cx, Editor::move_to_end_of_paragraph);
228 register_action(view, cx, Editor::move_to_beginning);
229 register_action(view, cx, Editor::move_to_end);
230 register_action(view, cx, Editor::select_up);
231 register_action(view, cx, Editor::select_down);
232 register_action(view, cx, Editor::select_left);
233 register_action(view, cx, Editor::select_right);
234 register_action(view, cx, Editor::select_to_previous_word_start);
235 register_action(view, cx, Editor::select_to_previous_subword_start);
236 register_action(view, cx, Editor::select_to_next_word_end);
237 register_action(view, cx, Editor::select_to_next_subword_end);
238 register_action(view, cx, Editor::select_to_beginning_of_line);
239 register_action(view, cx, Editor::select_to_end_of_line);
240 register_action(view, cx, Editor::select_to_start_of_paragraph);
241 register_action(view, cx, Editor::select_to_end_of_paragraph);
242 register_action(view, cx, Editor::select_to_beginning);
243 register_action(view, cx, Editor::select_to_end);
244 register_action(view, cx, Editor::select_all);
245 register_action(view, cx, |editor, action, cx| {
246 editor.select_all_matches(action, cx).log_err();
247 });
248 register_action(view, cx, Editor::select_line);
249 register_action(view, cx, Editor::split_selection_into_lines);
250 register_action(view, cx, Editor::add_selection_above);
251 register_action(view, cx, Editor::add_selection_below);
252 register_action(view, cx, |editor, action, cx| {
253 editor.select_next(action, cx).log_err();
254 });
255 register_action(view, cx, |editor, action, cx| {
256 editor.select_previous(action, cx).log_err();
257 });
258 register_action(view, cx, Editor::toggle_comments);
259 register_action(view, cx, Editor::select_larger_syntax_node);
260 register_action(view, cx, Editor::select_smaller_syntax_node);
261 register_action(view, cx, Editor::move_to_enclosing_bracket);
262 register_action(view, cx, Editor::undo_selection);
263 register_action(view, cx, Editor::redo_selection);
264 if !view.read(cx).is_singleton(cx) {
265 register_action(view, cx, Editor::expand_excerpts);
266 }
267 register_action(view, cx, Editor::go_to_diagnostic);
268 register_action(view, cx, Editor::go_to_prev_diagnostic);
269 register_action(view, cx, Editor::go_to_hunk);
270 register_action(view, cx, Editor::go_to_prev_hunk);
271 register_action(view, cx, |editor, a, cx| {
272 editor.go_to_definition(a, cx).detach_and_log_err(cx);
273 });
274 register_action(view, cx, |editor, a, cx| {
275 editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
276 });
277 register_action(view, cx, |editor, a, cx| {
278 editor.go_to_implementation(a, cx).detach_and_log_err(cx);
279 });
280 register_action(view, cx, |editor, a, cx| {
281 editor
282 .go_to_implementation_split(a, cx)
283 .detach_and_log_err(cx);
284 });
285 register_action(view, cx, |editor, a, cx| {
286 editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
287 });
288 register_action(view, cx, |editor, a, cx| {
289 editor
290 .go_to_type_definition_split(a, cx)
291 .detach_and_log_err(cx);
292 });
293 register_action(view, cx, Editor::open_url);
294 register_action(view, cx, Editor::fold);
295 register_action(view, cx, Editor::fold_at);
296 register_action(view, cx, Editor::unfold_lines);
297 register_action(view, cx, Editor::unfold_at);
298 register_action(view, cx, Editor::fold_selected_ranges);
299 register_action(view, cx, Editor::show_completions);
300 register_action(view, cx, Editor::toggle_code_actions);
301 register_action(view, cx, Editor::open_excerpts);
302 register_action(view, cx, Editor::open_excerpts_in_split);
303 register_action(view, cx, Editor::toggle_soft_wrap);
304 register_action(view, cx, Editor::toggle_line_numbers);
305 register_action(view, cx, Editor::toggle_inlay_hints);
306 register_action(view, cx, hover_popover::hover);
307 register_action(view, cx, Editor::reveal_in_finder);
308 register_action(view, cx, Editor::copy_path);
309 register_action(view, cx, Editor::copy_relative_path);
310 register_action(view, cx, Editor::copy_highlight_json);
311 register_action(view, cx, Editor::copy_permalink_to_line);
312 register_action(view, cx, Editor::open_permalink_to_line);
313 register_action(view, cx, Editor::toggle_git_blame);
314 register_action(view, cx, Editor::toggle_git_blame_inline);
315 register_action(view, cx, |editor, action, cx| {
316 if let Some(task) = editor.format(action, cx) {
317 task.detach_and_log_err(cx);
318 } else {
319 cx.propagate();
320 }
321 });
322 register_action(view, cx, Editor::restart_language_server);
323 register_action(view, cx, Editor::show_character_palette);
324 register_action(view, cx, |editor, action, cx| {
325 if let Some(task) = editor.confirm_completion(action, cx) {
326 task.detach_and_log_err(cx);
327 } else {
328 cx.propagate();
329 }
330 });
331 register_action(view, cx, |editor, action, cx| {
332 if let Some(task) = editor.confirm_code_action(action, cx) {
333 task.detach_and_log_err(cx);
334 } else {
335 cx.propagate();
336 }
337 });
338 register_action(view, cx, |editor, action, cx| {
339 if let Some(task) = editor.rename(action, cx) {
340 task.detach_and_log_err(cx);
341 } else {
342 cx.propagate();
343 }
344 });
345 register_action(view, cx, |editor, action, cx| {
346 if let Some(task) = editor.confirm_rename(action, cx) {
347 task.detach_and_log_err(cx);
348 } else {
349 cx.propagate();
350 }
351 });
352 register_action(view, cx, |editor, action, cx| {
353 if let Some(task) = editor.find_all_references(action, cx) {
354 task.detach_and_log_err(cx);
355 } else {
356 cx.propagate();
357 }
358 });
359 register_action(view, cx, Editor::next_inline_completion);
360 register_action(view, cx, Editor::previous_inline_completion);
361 register_action(view, cx, Editor::show_inline_completion);
362 register_action(view, cx, Editor::context_menu_first);
363 register_action(view, cx, Editor::context_menu_prev);
364 register_action(view, cx, Editor::context_menu_next);
365 register_action(view, cx, Editor::context_menu_last);
366 register_action(view, cx, Editor::display_cursor_names);
367 register_action(view, cx, Editor::unique_lines_case_insensitive);
368 register_action(view, cx, Editor::unique_lines_case_sensitive);
369 register_action(view, cx, Editor::accept_partial_inline_completion);
370 register_action(view, cx, Editor::revert_selected_hunks);
371 register_action(view, cx, Editor::open_active_item_in_terminal)
372 }
373
374 fn register_key_listeners(&self, cx: &mut WindowContext, layout: &EditorLayout) {
375 let position_map = layout.position_map.clone();
376 cx.on_key_event({
377 let editor = self.editor.clone();
378 let text_hitbox = layout.text_hitbox.clone();
379 move |event: &ModifiersChangedEvent, phase, cx| {
380 if phase != DispatchPhase::Bubble {
381 return;
382 }
383
384 editor.update(cx, |editor, cx| {
385 Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
386 })
387 }
388 });
389 }
390
391 fn modifiers_changed(
392 editor: &mut Editor,
393 event: &ModifiersChangedEvent,
394 position_map: &PositionMap,
395 text_hitbox: &Hitbox,
396 cx: &mut ViewContext<Editor>,
397 ) {
398 let mouse_position = cx.mouse_position();
399 if !text_hitbox.is_hovered(cx) {
400 return;
401 }
402
403 editor.update_hovered_link(
404 position_map.point_for_position(text_hitbox.bounds, mouse_position),
405 &position_map.snapshot,
406 event.modifiers,
407 cx,
408 )
409 }
410
411 fn mouse_left_down(
412 editor: &mut Editor,
413 event: &MouseDownEvent,
414 position_map: &PositionMap,
415 text_hitbox: &Hitbox,
416 gutter_hitbox: &Hitbox,
417 cx: &mut ViewContext<Editor>,
418 ) {
419 if cx.default_prevented() {
420 return;
421 }
422
423 let mut click_count = event.click_count;
424 let mut modifiers = event.modifiers;
425
426 if gutter_hitbox.is_hovered(cx) {
427 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
428 } else if !text_hitbox.is_hovered(cx) {
429 return;
430 }
431
432 if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
433 match EditorSettings::get_global(cx).double_click_in_multibuffer {
434 DoubleClickInMultibuffer::Select => {
435 // do nothing special on double click, all selection logic is below
436 }
437 DoubleClickInMultibuffer::Open => {
438 if modifiers.alt {
439 // if double click is made with alt, pretend it's a regular double click without opening and alt,
440 // and run the selection logic.
441 modifiers.alt = false;
442 } else {
443 // if double click is made without alt, open the corresponding excerp
444 editor.open_excerpts(&OpenExcerpts, cx);
445 return;
446 }
447 }
448 }
449 }
450
451 let point_for_position =
452 position_map.point_for_position(text_hitbox.bounds, event.position);
453 let position = point_for_position.previous_valid;
454 if modifiers.shift && modifiers.alt {
455 editor.select(
456 SelectPhase::BeginColumnar {
457 position,
458 goal_column: point_for_position.exact_unclipped.column(),
459 },
460 cx,
461 );
462 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
463 {
464 editor.select(
465 SelectPhase::Extend {
466 position,
467 click_count,
468 },
469 cx,
470 );
471 } else {
472 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
473 let multi_cursor_modifier = match multi_cursor_setting {
474 MultiCursorModifier::Alt => modifiers.alt,
475 MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
476 };
477 editor.select(
478 SelectPhase::Begin {
479 position,
480 add: multi_cursor_modifier,
481 click_count,
482 },
483 cx,
484 );
485 }
486
487 cx.stop_propagation();
488 }
489
490 fn mouse_right_down(
491 editor: &mut Editor,
492 event: &MouseDownEvent,
493 position_map: &PositionMap,
494 text_hitbox: &Hitbox,
495 cx: &mut ViewContext<Editor>,
496 ) {
497 if !text_hitbox.is_hovered(cx) {
498 return;
499 }
500 let point_for_position =
501 position_map.point_for_position(text_hitbox.bounds, event.position);
502 mouse_context_menu::deploy_context_menu(
503 editor,
504 event.position,
505 point_for_position.previous_valid,
506 cx,
507 );
508 cx.stop_propagation();
509 }
510
511 fn mouse_middle_down(
512 editor: &mut Editor,
513 event: &MouseDownEvent,
514 position_map: &PositionMap,
515 text_hitbox: &Hitbox,
516 cx: &mut ViewContext<Editor>,
517 ) {
518 if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
519 return;
520 }
521
522 if let Some(item) = cx.read_from_primary() {
523 let point_for_position =
524 position_map.point_for_position(text_hitbox.bounds, event.position);
525 let position = point_for_position.previous_valid;
526
527 editor.select(
528 SelectPhase::Begin {
529 position,
530 add: false,
531 click_count: 1,
532 },
533 cx,
534 );
535 editor.insert(item.text(), cx);
536 }
537 }
538
539 fn mouse_up(
540 editor: &mut Editor,
541 event: &MouseUpEvent,
542 position_map: &PositionMap,
543 text_hitbox: &Hitbox,
544 cx: &mut ViewContext<Editor>,
545 ) {
546 let end_selection = editor.has_pending_selection();
547 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
548
549 if end_selection {
550 editor.select(SelectPhase::End, cx);
551 }
552
553 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
554 let multi_cursor_modifier = match multi_cursor_setting {
555 MultiCursorModifier::Alt => event.modifiers.secondary(),
556 MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
557 };
558
559 if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
560 let point = position_map.point_for_position(text_hitbox.bounds, event.position);
561 editor.handle_click_hovered_link(point, event.modifiers, cx);
562
563 cx.stop_propagation();
564 } else if end_selection {
565 cx.stop_propagation();
566 }
567 }
568
569 fn mouse_dragged(
570 editor: &mut Editor,
571 event: &MouseMoveEvent,
572 position_map: &PositionMap,
573 text_bounds: Bounds<Pixels>,
574 cx: &mut ViewContext<Editor>,
575 ) {
576 if !editor.has_pending_selection() {
577 return;
578 }
579
580 let point_for_position = position_map.point_for_position(text_bounds, event.position);
581 let mut scroll_delta = gpui::Point::<f32>::default();
582 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
583 let top = text_bounds.origin.y + vertical_margin;
584 let bottom = text_bounds.lower_left().y - vertical_margin;
585 if event.position.y < top {
586 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
587 }
588 if event.position.y > bottom {
589 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
590 }
591
592 let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
593 let left = text_bounds.origin.x + horizontal_margin;
594 let right = text_bounds.upper_right().x - horizontal_margin;
595 if event.position.x < left {
596 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
597 }
598 if event.position.x > right {
599 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
600 }
601
602 editor.select(
603 SelectPhase::Update {
604 position: point_for_position.previous_valid,
605 goal_column: point_for_position.exact_unclipped.column(),
606 scroll_delta,
607 },
608 cx,
609 );
610 }
611
612 fn mouse_moved(
613 editor: &mut Editor,
614 event: &MouseMoveEvent,
615 position_map: &PositionMap,
616 text_hitbox: &Hitbox,
617 gutter_hitbox: &Hitbox,
618 cx: &mut ViewContext<Editor>,
619 ) {
620 let modifiers = event.modifiers;
621 let gutter_hovered = gutter_hitbox.is_hovered(cx);
622 editor.set_gutter_hovered(gutter_hovered, cx);
623
624 // Don't trigger hover popover if mouse is hovering over context menu
625 if text_hitbox.is_hovered(cx) {
626 let point_for_position =
627 position_map.point_for_position(text_hitbox.bounds, event.position);
628
629 editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
630
631 if let Some(point) = point_for_position.as_valid() {
632 hover_at(editor, Some(point), cx);
633 Self::update_visible_cursor(editor, point, position_map, cx);
634 } else {
635 hover_at(editor, None, cx);
636 }
637 } else {
638 editor.hide_hovered_link(cx);
639 hover_at(editor, None, cx);
640 if gutter_hovered {
641 cx.stop_propagation();
642 }
643 }
644 }
645
646 fn update_visible_cursor(
647 editor: &mut Editor,
648 point: DisplayPoint,
649 position_map: &PositionMap,
650 cx: &mut ViewContext<Editor>,
651 ) {
652 let snapshot = &position_map.snapshot;
653 let Some(hub) = editor.collaboration_hub() else {
654 return;
655 };
656 let range = DisplayPoint::new(point.row(), point.column().saturating_sub(1))
657 ..DisplayPoint::new(
658 point.row(),
659 (point.column() + 1).min(snapshot.line_len(point.row())),
660 );
661
662 let range = snapshot
663 .buffer_snapshot
664 .anchor_at(range.start.to_point(&snapshot.display_snapshot), Bias::Left)
665 ..snapshot
666 .buffer_snapshot
667 .anchor_at(range.end.to_point(&snapshot.display_snapshot), Bias::Right);
668
669 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
670 return;
671 };
672 let key = crate::HoveredCursor {
673 replica_id: selection.replica_id,
674 selection_id: selection.selection.id,
675 };
676 editor.hovered_cursors.insert(
677 key.clone(),
678 cx.spawn(|editor, mut cx| async move {
679 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
680 editor
681 .update(&mut cx, |editor, cx| {
682 editor.hovered_cursors.remove(&key);
683 cx.notify();
684 })
685 .ok();
686 }),
687 );
688 cx.notify()
689 }
690
691 fn layout_selections(
692 &self,
693 start_anchor: Anchor,
694 end_anchor: Anchor,
695 snapshot: &EditorSnapshot,
696 start_row: u32,
697 end_row: u32,
698 cx: &mut WindowContext,
699 ) -> (
700 Vec<(PlayerColor, Vec<SelectionLayout>)>,
701 BTreeMap<u32, bool>,
702 Option<DisplayPoint>,
703 ) {
704 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
705 let mut active_rows = BTreeMap::new();
706 let mut newest_selection_head = None;
707 let editor = self.editor.read(cx);
708
709 if editor.show_local_selections {
710 let mut local_selections: Vec<Selection<Point>> = editor
711 .selections
712 .disjoint_in_range(start_anchor..end_anchor, cx);
713 local_selections.extend(editor.selections.pending(cx));
714 let mut layouts = Vec::new();
715 let newest = editor.selections.newest(cx);
716 for selection in local_selections.drain(..) {
717 let is_empty = selection.start == selection.end;
718 let is_newest = selection == newest;
719
720 let layout = SelectionLayout::new(
721 selection,
722 editor.selections.line_mode,
723 editor.cursor_shape,
724 &snapshot.display_snapshot,
725 is_newest,
726 editor.leader_peer_id.is_none(),
727 None,
728 );
729 if is_newest {
730 newest_selection_head = Some(layout.head);
731 }
732
733 for row in cmp::max(layout.active_rows.start, start_row)
734 ..=cmp::min(layout.active_rows.end, end_row)
735 {
736 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
737 *contains_non_empty_selection |= !is_empty;
738 }
739 layouts.push(layout);
740 }
741
742 let player = if editor.read_only(cx) {
743 cx.theme().players().read_only()
744 } else {
745 self.style.local_player
746 };
747
748 selections.push((player, layouts));
749 }
750
751 if let Some(collaboration_hub) = &editor.collaboration_hub {
752 // When following someone, render the local selections in their color.
753 if let Some(leader_id) = editor.leader_peer_id {
754 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
755 if let Some(participant_index) = collaboration_hub
756 .user_participant_indices(cx)
757 .get(&collaborator.user_id)
758 {
759 if let Some((local_selection_style, _)) = selections.first_mut() {
760 *local_selection_style = cx
761 .theme()
762 .players()
763 .color_for_participant(participant_index.0);
764 }
765 }
766 }
767 }
768
769 let mut remote_selections = HashMap::default();
770 for selection in snapshot.remote_selections_in_range(
771 &(start_anchor..end_anchor),
772 collaboration_hub.as_ref(),
773 cx,
774 ) {
775 let selection_style = Self::get_participant_color(selection.participant_index, cx);
776
777 // Don't re-render the leader's selections, since the local selections
778 // match theirs.
779 if Some(selection.peer_id) == editor.leader_peer_id {
780 continue;
781 }
782 let key = HoveredCursor {
783 replica_id: selection.replica_id,
784 selection_id: selection.selection.id,
785 };
786
787 let is_shown =
788 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
789
790 remote_selections
791 .entry(selection.replica_id)
792 .or_insert((selection_style, Vec::new()))
793 .1
794 .push(SelectionLayout::new(
795 selection.selection,
796 selection.line_mode,
797 selection.cursor_shape,
798 &snapshot.display_snapshot,
799 false,
800 false,
801 if is_shown { selection.user_name } else { None },
802 ));
803 }
804
805 selections.extend(remote_selections.into_values());
806 }
807 (selections, active_rows, newest_selection_head)
808 }
809
810 #[allow(clippy::too_many_arguments)]
811 fn layout_folds(
812 &self,
813 snapshot: &EditorSnapshot,
814 content_origin: gpui::Point<Pixels>,
815 visible_anchor_range: Range<Anchor>,
816 visible_display_row_range: Range<u32>,
817 scroll_pixel_position: gpui::Point<Pixels>,
818 line_height: Pixels,
819 line_layouts: &[LineWithInvisibles],
820 cx: &mut WindowContext,
821 ) -> Vec<FoldLayout> {
822 snapshot
823 .folds_in_range(visible_anchor_range.clone())
824 .filter_map(|fold| {
825 let fold_range = fold.range.clone();
826 let display_range = fold.range.start.to_display_point(&snapshot)
827 ..fold.range.end.to_display_point(&snapshot);
828 debug_assert_eq!(display_range.start.row(), display_range.end.row());
829 let row = display_range.start.row();
830 debug_assert!(row < visible_display_row_range.end);
831 let line_layout = line_layouts
832 .get((row - visible_display_row_range.start) as usize)
833 .map(|l| &l.line)?;
834
835 let start_x = content_origin.x
836 + line_layout.x_for_index(display_range.start.column() as usize)
837 - scroll_pixel_position.x;
838 let start_y = content_origin.y + row as f32 * line_height - scroll_pixel_position.y;
839 let end_x = content_origin.x
840 + line_layout.x_for_index(display_range.end.column() as usize)
841 - scroll_pixel_position.x;
842
843 let fold_bounds = Bounds {
844 origin: point(start_x, start_y),
845 size: size(end_x - start_x, line_height),
846 };
847
848 let mut hover_element = div()
849 .id(fold.id)
850 .size_full()
851 .cursor_pointer()
852 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
853 .on_click(
854 cx.listener_for(&self.editor, move |editor: &mut Editor, _, cx| {
855 editor.unfold_ranges(
856 [fold_range.start..fold_range.end],
857 true,
858 false,
859 cx,
860 );
861 cx.stop_propagation();
862 }),
863 )
864 .into_any();
865 hover_element.prepaint_as_root(fold_bounds.origin, fold_bounds.size.into(), cx);
866 Some(FoldLayout {
867 display_range,
868 hover_element,
869 })
870 })
871 .collect()
872 }
873
874 fn collect_cursors(
875 &self,
876 snapshot: &EditorSnapshot,
877 cx: &mut WindowContext,
878 ) -> Vec<(Anchor, Hsla)> {
879 let editor = self.editor.read(cx);
880 let mut cursors = Vec::<(Anchor, Hsla)>::new();
881 let mut skip_local = false;
882 // Remote cursors
883 if let Some(collaboration_hub) = &editor.collaboration_hub {
884 for remote_selection in snapshot.remote_selections_in_range(
885 &(Anchor::min()..Anchor::max()),
886 collaboration_hub.deref(),
887 cx,
888 ) {
889 let color = Self::get_participant_color(remote_selection.participant_index, cx);
890 cursors.push((remote_selection.selection.head(), color.cursor));
891 if Some(remote_selection.peer_id) == editor.leader_peer_id {
892 skip_local = true;
893 }
894 }
895 }
896 // Local cursors
897 if !skip_local {
898 editor.selections.disjoint.iter().for_each(|selection| {
899 cursors.push((selection.head(), cx.theme().players().local().cursor));
900 });
901 if let Some(ref selection) = editor.selections.pending_anchor() {
902 cursors.push((selection.head(), cx.theme().players().local().cursor));
903 }
904 }
905 cursors
906 }
907
908 #[allow(clippy::too_many_arguments)]
909 fn layout_visible_cursors(
910 &self,
911 snapshot: &EditorSnapshot,
912 selections: &[(PlayerColor, Vec<SelectionLayout>)],
913 visible_display_row_range: Range<u32>,
914 line_layouts: &[LineWithInvisibles],
915 text_hitbox: &Hitbox,
916 content_origin: gpui::Point<Pixels>,
917 scroll_position: gpui::Point<f32>,
918 scroll_pixel_position: gpui::Point<Pixels>,
919 line_height: Pixels,
920 em_width: Pixels,
921 autoscroll_containing_element: bool,
922 cx: &mut WindowContext,
923 ) -> (Vec<CursorLayout>, bool) {
924 let mut autoscroll_bounds = None;
925 let mut non_visible_cursors = false;
926 let cursor_layouts = self.editor.update(cx, |editor, cx| {
927 let mut cursors = Vec::new();
928 for (player_color, selections) in selections {
929 for selection in selections {
930 let cursor_position = selection.head;
931
932 let in_range = visible_display_row_range.contains(&cursor_position.row());
933 if !in_range {
934 non_visible_cursors |= true;
935 }
936
937 if (selection.is_local && !editor.show_local_cursors(cx)) || !in_range {
938 continue;
939 }
940
941 let cursor_row_layout = &line_layouts
942 [(cursor_position.row() - visible_display_row_range.start) as usize]
943 .line;
944 let cursor_column = cursor_position.column() as usize;
945
946 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
947 let mut block_width =
948 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
949 if block_width == Pixels::ZERO {
950 block_width = em_width;
951 }
952 let block_text = if let CursorShape::Block = selection.cursor_shape {
953 snapshot.display_chars_at(cursor_position).next().and_then(
954 |(character, _)| {
955 let text = if character == '\n' {
956 SharedString::from(" ")
957 } else {
958 SharedString::from(character.to_string())
959 };
960 let len = text.len();
961
962 let font = cursor_row_layout
963 .font_id_for_index(cursor_column)
964 .and_then(|cursor_font_id| {
965 cx.text_system().get_font_for_id(cursor_font_id)
966 })
967 .unwrap_or(self.style.text.font());
968
969 cx.text_system()
970 .shape_line(
971 text,
972 cursor_row_layout.font_size,
973 &[TextRun {
974 len,
975 font,
976 color: self.style.background,
977 background_color: None,
978 strikethrough: None,
979 underline: None,
980 }],
981 )
982 .log_err()
983 },
984 )
985 } else {
986 None
987 };
988
989 let x = cursor_character_x - scroll_pixel_position.x;
990 let y = (cursor_position.row() as f32 - scroll_pixel_position.y / line_height)
991 * line_height;
992 if selection.is_newest {
993 editor.pixel_position_of_newest_cursor = Some(point(
994 text_hitbox.origin.x + x + block_width / 2.,
995 text_hitbox.origin.y + y + line_height / 2.,
996 ));
997
998 if autoscroll_containing_element {
999 let top = text_hitbox.origin.y
1000 + (cursor_position.row() as f32 - scroll_position.y - 3.).max(0.)
1001 * line_height;
1002 let left = text_hitbox.origin.x
1003 + (cursor_position.column() as f32 - scroll_position.x - 3.)
1004 .max(0.)
1005 * em_width;
1006
1007 let bottom = text_hitbox.origin.y
1008 + (cursor_position.row() as f32 - scroll_position.y + 4.)
1009 * line_height;
1010 let right = text_hitbox.origin.x
1011 + (cursor_position.column() as f32 - scroll_position.x + 4.)
1012 * em_width;
1013
1014 autoscroll_bounds =
1015 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1016 }
1017 }
1018
1019 let mut cursor = CursorLayout {
1020 color: player_color.cursor,
1021 block_width,
1022 origin: point(x, y),
1023 line_height,
1024 shape: selection.cursor_shape,
1025 block_text,
1026 cursor_name: None,
1027 };
1028 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1029 string: name,
1030 color: self.style.background,
1031 is_top_row: cursor_position.row() == 0,
1032 });
1033 cursor.layout(content_origin, cursor_name, cx);
1034 cursors.push(cursor);
1035 }
1036 }
1037 cursors
1038 });
1039
1040 if let Some(bounds) = autoscroll_bounds {
1041 cx.request_autoscroll(bounds);
1042 }
1043
1044 (cursor_layouts, non_visible_cursors)
1045 }
1046
1047 fn layout_scrollbar(
1048 &self,
1049 snapshot: &EditorSnapshot,
1050 bounds: Bounds<Pixels>,
1051 scroll_position: gpui::Point<f32>,
1052 rows_per_page: f32,
1053 non_visible_cursors: bool,
1054 cx: &mut WindowContext,
1055 ) -> Option<ScrollbarLayout> {
1056 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1057 let show_scrollbars = match scrollbar_settings.show {
1058 ShowScrollbar::Auto => {
1059 let editor = self.editor.read(cx);
1060 let is_singleton = editor.is_singleton(cx);
1061 // Git
1062 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1063 ||
1064 // Buffer Search Results
1065 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1066 ||
1067 // Selected Symbol Occurrences
1068 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1069 ||
1070 // Diagnostics
1071 (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
1072 ||
1073 // Cursors out of sight
1074 non_visible_cursors
1075 ||
1076 // Scrollmanager
1077 editor.scroll_manager.scrollbars_visible()
1078 }
1079 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1080 ShowScrollbar::Always => true,
1081 ShowScrollbar::Never => false,
1082 };
1083 if snapshot.mode != EditorMode::Full {
1084 return None;
1085 }
1086
1087 let visible_row_range = scroll_position.y..scroll_position.y + rows_per_page;
1088
1089 // If a drag took place after we started dragging the scrollbar,
1090 // cancel the scrollbar drag.
1091 if cx.has_active_drag() {
1092 self.editor.update(cx, |editor, cx| {
1093 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1094 });
1095 }
1096
1097 let track_bounds = Bounds::from_corners(
1098 point(self.scrollbar_left(&bounds), bounds.origin.y),
1099 point(bounds.lower_right().x, bounds.lower_left().y),
1100 );
1101
1102 let height = bounds.size.height;
1103 let total_rows = snapshot.max_point().row() as f32 + rows_per_page;
1104 let px_per_row = height / total_rows;
1105 let thumb_height = (rows_per_page * px_per_row).max(ScrollbarLayout::MIN_THUMB_HEIGHT);
1106 let row_height = (height - thumb_height) / snapshot.max_point().row() as f32;
1107
1108 Some(ScrollbarLayout {
1109 hitbox: cx.insert_hitbox(track_bounds, false),
1110 visible_row_range,
1111 row_height,
1112 visible: show_scrollbars,
1113 thumb_height,
1114 })
1115 }
1116
1117 #[allow(clippy::too_many_arguments)]
1118 fn layout_gutter_fold_indicators(
1119 &self,
1120 fold_statuses: Vec<Option<(FoldStatus, u32, bool)>>,
1121 line_height: Pixels,
1122 gutter_dimensions: &GutterDimensions,
1123 gutter_settings: crate::editor_settings::Gutter,
1124 scroll_pixel_position: gpui::Point<Pixels>,
1125 gutter_hitbox: &Hitbox,
1126 cx: &mut WindowContext,
1127 ) -> Vec<Option<AnyElement>> {
1128 let mut indicators = self.editor.update(cx, |editor, cx| {
1129 editor.render_fold_indicators(
1130 fold_statuses,
1131 &self.style,
1132 editor.gutter_hovered,
1133 line_height,
1134 gutter_dimensions.margin,
1135 cx,
1136 )
1137 });
1138
1139 for (ix, fold_indicator) in indicators.iter_mut().enumerate() {
1140 if let Some(fold_indicator) = fold_indicator {
1141 debug_assert!(gutter_settings.folds);
1142 let available_space = size(
1143 AvailableSpace::MinContent,
1144 AvailableSpace::Definite(line_height * 0.55),
1145 );
1146 let fold_indicator_size = fold_indicator.layout_as_root(available_space, cx);
1147
1148 let position = point(
1149 gutter_dimensions.width - gutter_dimensions.right_padding,
1150 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1151 );
1152 let centering_offset = point(
1153 (gutter_dimensions.right_padding + gutter_dimensions.margin
1154 - fold_indicator_size.width)
1155 / 2.,
1156 (line_height - fold_indicator_size.height) / 2.,
1157 );
1158 let origin = gutter_hitbox.origin + position + centering_offset;
1159 fold_indicator.prepaint_as_root(origin, available_space, cx);
1160 }
1161 }
1162
1163 indicators
1164 }
1165
1166 //Folds contained in a hunk are ignored apart from shrinking visual size
1167 //If a fold contains any hunks then that fold line is marked as modified
1168 fn layout_git_gutters(
1169 &self,
1170 display_rows: Range<u32>,
1171 snapshot: &EditorSnapshot,
1172 ) -> Vec<DisplayDiffHunk> {
1173 let buffer_snapshot = &snapshot.buffer_snapshot;
1174
1175 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1176 .to_point(snapshot)
1177 .row;
1178 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1179 .to_point(snapshot)
1180 .row;
1181
1182 buffer_snapshot
1183 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1184 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1185 .dedup()
1186 .collect()
1187 }
1188
1189 #[allow(clippy::too_many_arguments)]
1190 fn layout_inline_blame(
1191 &self,
1192 display_row: u32,
1193 display_snapshot: &DisplaySnapshot,
1194 line_layout: &LineWithInvisibles,
1195 em_width: Pixels,
1196 content_origin: gpui::Point<Pixels>,
1197 scroll_pixel_position: gpui::Point<Pixels>,
1198 line_height: Pixels,
1199 cx: &mut WindowContext,
1200 ) -> Option<AnyElement> {
1201 if !self
1202 .editor
1203 .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1204 {
1205 return None;
1206 }
1207
1208 let workspace = self
1209 .editor
1210 .read(cx)
1211 .workspace
1212 .as_ref()
1213 .map(|(w, _)| w.clone());
1214
1215 let display_point = DisplayPoint::new(display_row, 0);
1216 let buffer_row = display_point.to_point(display_snapshot).row;
1217
1218 let blame = self.editor.read(cx).blame.clone()?;
1219 let blame_entry = blame
1220 .update(cx, |blame, cx| {
1221 blame.blame_for_rows([Some(buffer_row)], cx).next()
1222 })
1223 .flatten()?;
1224
1225 let mut element =
1226 render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1227
1228 let start_y = content_origin.y
1229 + line_height * (display_row as f32 - scroll_pixel_position.y / line_height);
1230
1231 let start_x = {
1232 const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1233
1234 let padded_line_width =
1235 line_layout.line.width + (em_width * INLINE_BLAME_PADDING_EM_WIDTHS);
1236
1237 let min_column = ProjectSettings::get_global(cx)
1238 .git
1239 .inline_blame
1240 .and_then(|settings| settings.min_column)
1241 .map(|col| self.column_pixels(col as usize, cx))
1242 .unwrap_or(px(0.));
1243
1244 (content_origin.x - scroll_pixel_position.x) + max(padded_line_width, min_column)
1245 };
1246
1247 let absolute_offset = point(start_x, start_y);
1248 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1249
1250 element.prepaint_as_root(absolute_offset, available_space, cx);
1251
1252 Some(element)
1253 }
1254
1255 #[allow(clippy::too_many_arguments)]
1256 fn layout_blame_entries(
1257 &self,
1258 buffer_rows: impl Iterator<Item = Option<u32>>,
1259 em_width: Pixels,
1260 scroll_position: gpui::Point<f32>,
1261 line_height: Pixels,
1262 gutter_hitbox: &Hitbox,
1263 max_width: Option<Pixels>,
1264 cx: &mut WindowContext,
1265 ) -> Option<Vec<AnyElement>> {
1266 if !self
1267 .editor
1268 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1269 {
1270 return None;
1271 }
1272
1273 let blame = self.editor.read(cx).blame.clone()?;
1274 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1275 blame.blame_for_rows(buffer_rows, cx).collect()
1276 });
1277
1278 let width = if let Some(max_width) = max_width {
1279 AvailableSpace::Definite(max_width)
1280 } else {
1281 AvailableSpace::MaxContent
1282 };
1283 let scroll_top = scroll_position.y * line_height;
1284 let start_x = em_width * 1;
1285
1286 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1287
1288 let shaped_lines = blamed_rows
1289 .into_iter()
1290 .enumerate()
1291 .flat_map(|(ix, blame_entry)| {
1292 if let Some(blame_entry) = blame_entry {
1293 let mut element = render_blame_entry(
1294 ix,
1295 &blame,
1296 blame_entry,
1297 &self.style,
1298 &mut last_used_color,
1299 self.editor.clone(),
1300 cx,
1301 );
1302
1303 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1304 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1305
1306 element.prepaint_as_root(
1307 absolute_offset,
1308 size(width, AvailableSpace::MinContent),
1309 cx,
1310 );
1311
1312 Some(element)
1313 } else {
1314 None
1315 }
1316 })
1317 .collect();
1318
1319 Some(shaped_lines)
1320 }
1321
1322 fn layout_code_actions_indicator(
1323 &self,
1324 line_height: Pixels,
1325 newest_selection_head: DisplayPoint,
1326 scroll_pixel_position: gpui::Point<Pixels>,
1327 gutter_dimensions: &GutterDimensions,
1328 gutter_hitbox: &Hitbox,
1329 cx: &mut WindowContext,
1330 ) -> Option<AnyElement> {
1331 let mut active = false;
1332 let mut button = None;
1333 self.editor.update(cx, |editor, cx| {
1334 active = matches!(
1335 editor.context_menu.read().as_ref(),
1336 Some(crate::ContextMenu::CodeActions(_))
1337 );
1338 button = editor.render_code_actions_indicator(&self.style, active, cx);
1339 });
1340
1341 let mut button = button?.into_any_element();
1342 let available_space = size(
1343 AvailableSpace::MinContent,
1344 AvailableSpace::Definite(line_height),
1345 );
1346 let indicator_size = button.layout_as_root(available_space, cx);
1347
1348 let blame_width = gutter_dimensions
1349 .git_blame_entries_width
1350 .unwrap_or(Pixels::ZERO);
1351
1352 let mut x = blame_width;
1353 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
1354 - indicator_size.width
1355 - blame_width;
1356 x += available_width / 2.;
1357
1358 let mut y = newest_selection_head.row() as f32 * line_height - scroll_pixel_position.y;
1359 y += (line_height - indicator_size.height) / 2.;
1360
1361 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
1362 Some(button)
1363 }
1364
1365 fn get_participant_color(
1366 participant_index: Option<ParticipantIndex>,
1367 cx: &WindowContext,
1368 ) -> PlayerColor {
1369 if let Some(index) = participant_index {
1370 cx.theme().players().color_for_participant(index.0)
1371 } else {
1372 cx.theme().players().absent()
1373 }
1374 }
1375
1376 fn calculate_relative_line_numbers(
1377 &self,
1378 buffer_rows: Vec<Option<u32>>,
1379 rows: &Range<u32>,
1380 relative_to: Option<u32>,
1381 ) -> HashMap<u32, u32> {
1382 let mut relative_rows: HashMap<u32, u32> = Default::default();
1383 let Some(relative_to) = relative_to else {
1384 return relative_rows;
1385 };
1386
1387 let start = rows.start.min(relative_to);
1388
1389 let head_idx = relative_to - start;
1390 let mut delta = 1;
1391 let mut i = head_idx + 1;
1392 while i < buffer_rows.len() as u32 {
1393 if buffer_rows[i as usize].is_some() {
1394 if rows.contains(&(i + start)) {
1395 relative_rows.insert(i + start, delta);
1396 }
1397 delta += 1;
1398 }
1399 i += 1;
1400 }
1401 delta = 1;
1402 i = head_idx.min(buffer_rows.len() as u32 - 1);
1403 while i > 0 && buffer_rows[i as usize].is_none() {
1404 i -= 1;
1405 }
1406
1407 while i > 0 {
1408 i -= 1;
1409 if buffer_rows[i as usize].is_some() {
1410 if rows.contains(&(i + start)) {
1411 relative_rows.insert(i + start, delta);
1412 }
1413 delta += 1;
1414 }
1415 }
1416
1417 relative_rows
1418 }
1419
1420 fn layout_line_numbers(
1421 &self,
1422 rows: Range<u32>,
1423 buffer_rows: impl Iterator<Item = Option<u32>>,
1424 active_rows: &BTreeMap<u32, bool>,
1425 newest_selection_head: Option<DisplayPoint>,
1426 snapshot: &EditorSnapshot,
1427 cx: &WindowContext,
1428 ) -> (
1429 Vec<Option<ShapedLine>>,
1430 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1431 ) {
1432 let editor = self.editor.read(cx);
1433 let is_singleton = editor.is_singleton(cx);
1434 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1435 let newest = editor.selections.newest::<Point>(cx);
1436 SelectionLayout::new(
1437 newest,
1438 editor.selections.line_mode,
1439 editor.cursor_shape,
1440 &snapshot.display_snapshot,
1441 true,
1442 true,
1443 None,
1444 )
1445 .head
1446 });
1447 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1448 let include_line_numbers =
1449 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1450 let include_fold_statuses =
1451 EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1452 let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1453 let mut fold_statuses = Vec::with_capacity(rows.len());
1454 let mut line_number = String::new();
1455 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1456 let relative_to = if is_relative {
1457 Some(newest_selection_head.row())
1458 } else {
1459 None
1460 };
1461
1462 let buffer_rows = buffer_rows.collect::<Vec<_>>();
1463 let relative_rows =
1464 self.calculate_relative_line_numbers(buffer_rows.clone(), &rows, relative_to);
1465
1466 for (ix, row) in buffer_rows.into_iter().enumerate() {
1467 let display_row = rows.start + ix as u32;
1468 let (active, color) = if active_rows.contains_key(&display_row) {
1469 (true, cx.theme().colors().editor_active_line_number)
1470 } else {
1471 (false, cx.theme().colors().editor_line_number)
1472 };
1473 if let Some(buffer_row) = row {
1474 if include_line_numbers {
1475 line_number.clear();
1476 let default_number = buffer_row + 1;
1477 let number = relative_rows
1478 .get(&(ix as u32 + rows.start))
1479 .unwrap_or(&default_number);
1480 write!(&mut line_number, "{}", number).unwrap();
1481 let run = TextRun {
1482 len: line_number.len(),
1483 font: self.style.text.font(),
1484 color,
1485 background_color: None,
1486 underline: None,
1487 strikethrough: None,
1488 };
1489 let shaped_line = cx
1490 .text_system()
1491 .shape_line(line_number.clone().into(), font_size, &[run])
1492 .unwrap();
1493 shaped_line_numbers.push(Some(shaped_line));
1494 }
1495 if include_fold_statuses {
1496 fold_statuses.push(
1497 is_singleton
1498 .then(|| {
1499 snapshot
1500 .fold_for_line(buffer_row)
1501 .map(|fold_status| (fold_status, buffer_row, active))
1502 })
1503 .flatten(),
1504 )
1505 }
1506 } else {
1507 fold_statuses.push(None);
1508 shaped_line_numbers.push(None);
1509 }
1510 }
1511
1512 (shaped_line_numbers, fold_statuses)
1513 }
1514
1515 fn layout_lines(
1516 &self,
1517 rows: Range<u32>,
1518 line_number_layouts: &[Option<ShapedLine>],
1519 snapshot: &EditorSnapshot,
1520 cx: &WindowContext,
1521 ) -> Vec<LineWithInvisibles> {
1522 if rows.start >= rows.end {
1523 return Vec::new();
1524 }
1525
1526 // Show the placeholder when the editor is empty
1527 if snapshot.is_empty() {
1528 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1529 let placeholder_color = cx.theme().colors().text_placeholder;
1530 let placeholder_text = snapshot.placeholder_text();
1531
1532 let placeholder_lines = placeholder_text
1533 .as_ref()
1534 .map_or("", AsRef::as_ref)
1535 .split('\n')
1536 .skip(rows.start as usize)
1537 .chain(iter::repeat(""))
1538 .take(rows.len());
1539 placeholder_lines
1540 .filter_map(move |line| {
1541 let run = TextRun {
1542 len: line.len(),
1543 font: self.style.text.font(),
1544 color: placeholder_color,
1545 background_color: None,
1546 underline: Default::default(),
1547 strikethrough: None,
1548 };
1549 cx.text_system()
1550 .shape_line(line.to_string().into(), font_size, &[run])
1551 .log_err()
1552 })
1553 .map(|line| LineWithInvisibles {
1554 line,
1555 invisibles: Vec::new(),
1556 })
1557 .collect()
1558 } else {
1559 let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1560 LineWithInvisibles::from_chunks(
1561 chunks,
1562 &self.style.text,
1563 MAX_LINE_LEN,
1564 rows.len(),
1565 line_number_layouts,
1566 snapshot.mode,
1567 cx,
1568 )
1569 }
1570 }
1571
1572 #[allow(clippy::too_many_arguments)]
1573 fn build_blocks(
1574 &self,
1575 rows: Range<u32>,
1576 snapshot: &EditorSnapshot,
1577 hitbox: &Hitbox,
1578 text_hitbox: &Hitbox,
1579 scroll_width: &mut Pixels,
1580 gutter_dimensions: &GutterDimensions,
1581 em_width: Pixels,
1582 text_x: Pixels,
1583 line_height: Pixels,
1584 line_layouts: &[LineWithInvisibles],
1585 cx: &mut WindowContext,
1586 ) -> Vec<BlockLayout> {
1587 let mut block_id = 0;
1588 let (fixed_blocks, non_fixed_blocks) = snapshot
1589 .blocks_in_range(rows.clone())
1590 .partition::<Vec<_>, _>(|(_, block)| match block {
1591 TransformBlock::ExcerptHeader { .. } => false,
1592 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1593 });
1594
1595 let render_block = |block: &TransformBlock,
1596 available_space: Size<AvailableSpace>,
1597 block_id: usize,
1598 block_row_start: u32,
1599 cx: &mut WindowContext| {
1600 let mut element = match block {
1601 TransformBlock::Custom(block) => {
1602 let align_to = block
1603 .position()
1604 .to_point(&snapshot.buffer_snapshot)
1605 .to_display_point(snapshot);
1606 let anchor_x = text_x
1607 + if rows.contains(&align_to.row()) {
1608 line_layouts[(align_to.row() - rows.start) as usize]
1609 .line
1610 .x_for_index(align_to.column() as usize)
1611 } else {
1612 layout_line(align_to.row(), snapshot, &self.style, cx)
1613 .unwrap()
1614 .x_for_index(align_to.column() as usize)
1615 };
1616
1617 block.render(&mut BlockContext {
1618 context: cx,
1619 anchor_x,
1620 gutter_dimensions,
1621 line_height,
1622 em_width,
1623 block_id,
1624 max_width: text_hitbox.size.width.max(*scroll_width),
1625 editor_style: &self.style,
1626 })
1627 }
1628
1629 TransformBlock::ExcerptHeader {
1630 buffer,
1631 range,
1632 starts_new_buffer,
1633 height,
1634 id,
1635 ..
1636 } => {
1637 let include_root = self
1638 .editor
1639 .read(cx)
1640 .project
1641 .as_ref()
1642 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1643 .unwrap_or_default();
1644
1645 #[derive(Clone)]
1646 struct JumpData {
1647 position: Point,
1648 anchor: text::Anchor,
1649 path: ProjectPath,
1650 line_offset_from_top: u32,
1651 }
1652
1653 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1654 let jump_path = ProjectPath {
1655 worktree_id: file.worktree_id(cx),
1656 path: file.path.clone(),
1657 };
1658 let jump_anchor = range
1659 .primary
1660 .as_ref()
1661 .map_or(range.context.start, |primary| primary.start);
1662
1663 let excerpt_start = range.context.start;
1664 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1665 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
1666 0
1667 } else {
1668 let excerpt_start_row =
1669 language::ToPoint::to_point(&jump_anchor, buffer).row;
1670 jump_position.row - excerpt_start_row
1671 };
1672
1673 let line_offset_from_top =
1674 block_row_start + *height as u32 + offset_from_excerpt_start
1675 - snapshot
1676 .scroll_anchor
1677 .scroll_position(&snapshot.display_snapshot)
1678 .y as u32;
1679
1680 JumpData {
1681 position: jump_position,
1682 anchor: jump_anchor,
1683 path: jump_path,
1684 line_offset_from_top,
1685 }
1686 });
1687
1688 let element = if *starts_new_buffer {
1689 let path = buffer.resolve_file_path(cx, include_root);
1690 let mut filename = None;
1691 let mut parent_path = None;
1692 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1693 if let Some(path) = path {
1694 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1695 parent_path = path
1696 .parent()
1697 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1698 }
1699
1700 v_flex()
1701 .id(("path header container", block_id))
1702 .size_full()
1703 .justify_center()
1704 .p(gpui::px(6.))
1705 .child(
1706 h_flex()
1707 .id("path header block")
1708 .size_full()
1709 .pl(gpui::px(12.))
1710 .pr(gpui::px(8.))
1711 .rounded_md()
1712 .shadow_md()
1713 .border()
1714 .border_color(cx.theme().colors().border)
1715 .bg(cx.theme().colors().editor_subheader_background)
1716 .justify_between()
1717 .hover(|style| style.bg(cx.theme().colors().element_hover))
1718 .child(
1719 h_flex().gap_3().child(
1720 h_flex()
1721 .gap_2()
1722 .child(
1723 filename
1724 .map(SharedString::from)
1725 .unwrap_or_else(|| "untitled".into()),
1726 )
1727 .when_some(parent_path, |then, path| {
1728 then.child(
1729 div().child(path).text_color(
1730 cx.theme().colors().text_muted,
1731 ),
1732 )
1733 }),
1734 ),
1735 )
1736 .when_some(jump_data.clone(), |this, jump_data| {
1737 this.cursor_pointer()
1738 .tooltip(|cx| {
1739 Tooltip::for_action(
1740 "Jump to File",
1741 &OpenExcerpts,
1742 cx,
1743 )
1744 })
1745 .on_mouse_down(MouseButton::Left, |_, cx| {
1746 cx.stop_propagation()
1747 })
1748 .on_click(cx.listener_for(&self.editor, {
1749 move |editor, _, cx| {
1750 editor.jump(
1751 jump_data.path.clone(),
1752 jump_data.position,
1753 jump_data.anchor,
1754 jump_data.line_offset_from_top,
1755 cx,
1756 );
1757 }
1758 }))
1759 }),
1760 )
1761 } else {
1762 v_flex()
1763 .id(("collapsed context", block_id))
1764 .size_full()
1765 .child(
1766 div()
1767 .flex()
1768 .v_flex()
1769 .justify_start()
1770 .id("jump to collapsed context")
1771 .w(relative(1.0))
1772 .h_full()
1773 .child(
1774 div()
1775 .h_px()
1776 .w_full()
1777 .bg(cx.theme().colors().border_variant)
1778 .group_hover("excerpt-jump-action", |style| {
1779 style.bg(cx.theme().colors().border)
1780 }),
1781 ),
1782 )
1783 .child(
1784 h_flex()
1785 .justify_end()
1786 .flex_none()
1787 .w(
1788 gutter_dimensions.width - (gutter_dimensions.left_padding), // + gutter_dimensions.right_padding)
1789 )
1790 .h_full()
1791 .child(
1792 ButtonLike::new("expand-icon")
1793 .style(ButtonStyle::Transparent)
1794 .child(
1795 svg()
1796 .path(IconName::ExpandVertical.path())
1797 .size(IconSize::XSmall.rems())
1798 .text_color(
1799 cx.theme().colors().editor_line_number,
1800 )
1801 .group("")
1802 .hover(|style| {
1803 style.text_color(
1804 cx.theme()
1805 .colors()
1806 .editor_active_line_number,
1807 )
1808 }),
1809 )
1810 .on_click(cx.listener_for(&self.editor, {
1811 let id = *id;
1812 move |editor, _, cx| {
1813 editor.expand_excerpt(id, cx);
1814 }
1815 }))
1816 .tooltip({
1817 move |cx| {
1818 Tooltip::for_action(
1819 "Expand Excerpt",
1820 &ExpandExcerpts { lines: 0 },
1821 cx,
1822 )
1823 }
1824 }),
1825 ),
1826 )
1827 .group("excerpt-jump-action")
1828 .cursor_pointer()
1829 .when_some(jump_data.clone(), |this, jump_data| {
1830 this.on_click(cx.listener_for(&self.editor, {
1831 let path = jump_data.path.clone();
1832 move |editor, _, cx| {
1833 cx.stop_propagation();
1834
1835 editor.jump(
1836 path.clone(),
1837 jump_data.position,
1838 jump_data.anchor,
1839 jump_data.line_offset_from_top,
1840 cx,
1841 );
1842 }
1843 }))
1844 .tooltip(move |cx| {
1845 Tooltip::for_action(
1846 format!(
1847 "Jump to {}:L{}",
1848 jump_data.path.path.display(),
1849 jump_data.position.row + 1
1850 ),
1851 &OpenExcerpts,
1852 cx,
1853 )
1854 })
1855 })
1856 };
1857 element.into_any()
1858 }
1859 };
1860
1861 let size = element.layout_as_root(available_space, cx);
1862 (element, size)
1863 };
1864
1865 let mut fixed_block_max_width = Pixels::ZERO;
1866 let mut blocks = Vec::new();
1867 for (row, block) in fixed_blocks {
1868 let available_space = size(
1869 AvailableSpace::MinContent,
1870 AvailableSpace::Definite(block.height() as f32 * line_height),
1871 );
1872 let (element, element_size) = render_block(block, available_space, block_id, row, cx);
1873 block_id += 1;
1874 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1875 blocks.push(BlockLayout {
1876 row,
1877 element,
1878 available_space,
1879 style: BlockStyle::Fixed,
1880 });
1881 }
1882 for (row, block) in non_fixed_blocks {
1883 let style = match block {
1884 TransformBlock::Custom(block) => block.style(),
1885 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1886 };
1887 let width = match style {
1888 BlockStyle::Sticky => hitbox.size.width,
1889 BlockStyle::Flex => hitbox
1890 .size
1891 .width
1892 .max(fixed_block_max_width)
1893 .max(gutter_dimensions.width + *scroll_width),
1894 BlockStyle::Fixed => unreachable!(),
1895 };
1896 let available_space = size(
1897 AvailableSpace::Definite(width),
1898 AvailableSpace::Definite(block.height() as f32 * line_height),
1899 );
1900 let (element, _) = render_block(block, available_space, block_id, row, cx);
1901 block_id += 1;
1902 blocks.push(BlockLayout {
1903 row,
1904 element,
1905 available_space,
1906 style,
1907 });
1908 }
1909
1910 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1911 blocks
1912 }
1913
1914 fn layout_blocks(
1915 &self,
1916 blocks: &mut Vec<BlockLayout>,
1917 hitbox: &Hitbox,
1918 line_height: Pixels,
1919 scroll_pixel_position: gpui::Point<Pixels>,
1920 cx: &mut WindowContext,
1921 ) {
1922 for block in blocks {
1923 let mut origin = hitbox.origin
1924 + point(
1925 Pixels::ZERO,
1926 block.row as f32 * line_height - scroll_pixel_position.y,
1927 );
1928 if !matches!(block.style, BlockStyle::Sticky) {
1929 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1930 }
1931 block
1932 .element
1933 .prepaint_as_root(origin, block.available_space, cx);
1934 }
1935 }
1936
1937 #[allow(clippy::too_many_arguments)]
1938 fn layout_context_menu(
1939 &self,
1940 line_height: Pixels,
1941 hitbox: &Hitbox,
1942 text_hitbox: &Hitbox,
1943 content_origin: gpui::Point<Pixels>,
1944 start_row: u32,
1945 scroll_pixel_position: gpui::Point<Pixels>,
1946 line_layouts: &[LineWithInvisibles],
1947 newest_selection_head: DisplayPoint,
1948 cx: &mut WindowContext,
1949 ) -> bool {
1950 let max_height = cmp::min(
1951 12. * line_height,
1952 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1953 );
1954 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1955 if editor.context_menu_visible() {
1956 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1957 } else {
1958 None
1959 }
1960 }) else {
1961 return false;
1962 };
1963
1964 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1965 let context_menu_size = context_menu.layout_as_root(available_space, cx);
1966
1967 let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1968 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1969 let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1970 let mut list_origin = content_origin + point(x, y);
1971 let list_width = context_menu_size.width;
1972 let list_height = context_menu_size.height;
1973
1974 // Snap the right edge of the list to the right edge of the window if
1975 // its horizontal bounds overflow.
1976 if list_origin.x + list_width > cx.viewport_size().width {
1977 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1978 }
1979
1980 if list_origin.y + list_height > text_hitbox.lower_right().y {
1981 list_origin.y -= line_height + list_height;
1982 }
1983
1984 cx.defer_draw(context_menu, list_origin, 1);
1985 true
1986 }
1987
1988 fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
1989 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1990 let mut element = deferred(
1991 anchored()
1992 .position(mouse_context_menu.position)
1993 .child(mouse_context_menu.context_menu.clone())
1994 .anchor(AnchorCorner::TopLeft)
1995 .snap_to_window(),
1996 )
1997 .with_priority(1)
1998 .into_any();
1999
2000 element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2001 Some(element)
2002 }
2003
2004 #[allow(clippy::too_many_arguments)]
2005 fn layout_hover_popovers(
2006 &self,
2007 snapshot: &EditorSnapshot,
2008 hitbox: &Hitbox,
2009 text_hitbox: &Hitbox,
2010 visible_display_row_range: Range<u32>,
2011 content_origin: gpui::Point<Pixels>,
2012 scroll_pixel_position: gpui::Point<Pixels>,
2013 line_layouts: &[LineWithInvisibles],
2014 line_height: Pixels,
2015 em_width: Pixels,
2016 cx: &mut WindowContext,
2017 ) {
2018 struct MeasuredHoverPopover {
2019 element: AnyElement,
2020 size: Size<Pixels>,
2021 horizontal_offset: Pixels,
2022 }
2023
2024 let max_size = size(
2025 (120. * em_width) // Default size
2026 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2027 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2028 (16. * line_height) // Default size
2029 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2030 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2031 );
2032
2033 let hover_popovers = self.editor.update(cx, |editor, cx| {
2034 editor.hover_state.render(
2035 &snapshot,
2036 &self.style,
2037 visible_display_row_range.clone(),
2038 max_size,
2039 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2040 cx,
2041 )
2042 });
2043 let Some((position, hover_popovers)) = hover_popovers else {
2044 return;
2045 };
2046
2047 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2048
2049 // This is safe because we check on layout whether the required row is available
2050 let hovered_row_layout =
2051 &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
2052
2053 // Compute Hovered Point
2054 let x =
2055 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2056 let y = position.row() as f32 * line_height - scroll_pixel_position.y;
2057 let hovered_point = content_origin + point(x, y);
2058
2059 let mut overall_height = Pixels::ZERO;
2060 let mut measured_hover_popovers = Vec::new();
2061 for mut hover_popover in hover_popovers {
2062 let size = hover_popover.layout_as_root(available_space, cx);
2063 let horizontal_offset =
2064 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2065
2066 overall_height += HOVER_POPOVER_GAP + size.height;
2067
2068 measured_hover_popovers.push(MeasuredHoverPopover {
2069 element: hover_popover,
2070 size,
2071 horizontal_offset,
2072 });
2073 }
2074 overall_height += HOVER_POPOVER_GAP;
2075
2076 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2077 let mut occlusion = div()
2078 .size_full()
2079 .occlude()
2080 .on_mouse_move(|_, cx| cx.stop_propagation())
2081 .into_any_element();
2082 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2083 cx.defer_draw(occlusion, origin, 2);
2084 }
2085
2086 if hovered_point.y > overall_height {
2087 // There is enough space above. Render popovers above the hovered point
2088 let mut current_y = hovered_point.y;
2089 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2090 let size = popover.size;
2091 let popover_origin = point(
2092 hovered_point.x + popover.horizontal_offset,
2093 current_y - size.height,
2094 );
2095
2096 cx.defer_draw(popover.element, popover_origin, 2);
2097 if position != itertools::Position::Last {
2098 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2099 draw_occluder(size.width, origin, cx);
2100 }
2101
2102 current_y = popover_origin.y - HOVER_POPOVER_GAP;
2103 }
2104 } else {
2105 // There is not enough space above. Render popovers below the hovered point
2106 let mut current_y = hovered_point.y + line_height;
2107 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2108 let size = popover.size;
2109 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2110
2111 cx.defer_draw(popover.element, popover_origin, 2);
2112 if position != itertools::Position::Last {
2113 let origin = point(popover_origin.x, popover_origin.y + size.height);
2114 draw_occluder(size.width, origin, cx);
2115 }
2116
2117 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2118 }
2119 }
2120 }
2121
2122 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2123 cx.paint_layer(layout.hitbox.bounds, |cx| {
2124 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2125 let gutter_bg = cx.theme().colors().editor_gutter_background;
2126 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2127 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2128
2129 if let EditorMode::Full = layout.mode {
2130 let mut active_rows = layout.active_rows.iter().peekable();
2131 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2132 let mut end_row = *start_row;
2133 while active_rows.peek().map_or(false, |r| {
2134 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
2135 }) {
2136 active_rows.next().unwrap();
2137 end_row += 1;
2138 }
2139
2140 if !contains_non_empty_selection {
2141 let origin = point(
2142 layout.hitbox.origin.x,
2143 layout.hitbox.origin.y
2144 + (*start_row as f32 - scroll_top)
2145 * layout.position_map.line_height,
2146 );
2147 let size = size(
2148 layout.hitbox.size.width,
2149 layout.position_map.line_height * (end_row - start_row + 1) as f32,
2150 );
2151 let active_line_bg = cx.theme().colors().editor_active_line_background;
2152 cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
2153 }
2154 }
2155
2156 let mut paint_highlight =
2157 |highlight_row_start: u32, highlight_row_end: u32, color| {
2158 let origin = point(
2159 layout.hitbox.origin.x,
2160 layout.hitbox.origin.y
2161 + (highlight_row_start as f32 - scroll_top)
2162 * layout.position_map.line_height,
2163 );
2164 let size = size(
2165 layout.hitbox.size.width,
2166 layout.position_map.line_height
2167 * (highlight_row_end + 1 - highlight_row_start) as f32,
2168 );
2169 cx.paint_quad(fill(Bounds { origin, size }, color));
2170 };
2171
2172 let mut last_row = None;
2173 let mut highlight_row_start = 0u32;
2174 let mut highlight_row_end = 0u32;
2175 for (&row, &color) in &layout.highlighted_rows {
2176 let paint = last_row.map_or(false, |(last_row, last_color)| {
2177 last_color != color || last_row + 1 < row
2178 });
2179
2180 if paint {
2181 let paint_range_is_unfinished = highlight_row_end == 0;
2182 if paint_range_is_unfinished {
2183 highlight_row_end = row;
2184 last_row = None;
2185 }
2186 paint_highlight(highlight_row_start, highlight_row_end, color);
2187 highlight_row_start = 0;
2188 highlight_row_end = 0;
2189 if !paint_range_is_unfinished {
2190 highlight_row_start = row;
2191 last_row = Some((row, color));
2192 }
2193 } else {
2194 if last_row.is_none() {
2195 highlight_row_start = row;
2196 } else {
2197 highlight_row_end = row;
2198 }
2199 last_row = Some((row, color));
2200 }
2201 }
2202 if let Some((row, hsla)) = last_row {
2203 highlight_row_end = row;
2204 paint_highlight(highlight_row_start, highlight_row_end, hsla);
2205 }
2206
2207 let scroll_left =
2208 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2209
2210 for (wrap_position, active) in layout.wrap_guides.iter() {
2211 let x = (layout.text_hitbox.origin.x
2212 + *wrap_position
2213 + layout.position_map.em_width / 2.)
2214 - scroll_left;
2215
2216 let show_scrollbars = layout
2217 .scrollbar_layout
2218 .as_ref()
2219 .map_or(false, |scrollbar| scrollbar.visible);
2220 if x < layout.text_hitbox.origin.x
2221 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2222 {
2223 continue;
2224 }
2225
2226 let color = if *active {
2227 cx.theme().colors().editor_active_wrap_guide
2228 } else {
2229 cx.theme().colors().editor_wrap_guide
2230 };
2231 cx.paint_quad(fill(
2232 Bounds {
2233 origin: point(x, layout.text_hitbox.origin.y),
2234 size: size(px(1.), layout.text_hitbox.size.height),
2235 },
2236 color,
2237 ));
2238 }
2239 }
2240 })
2241 }
2242
2243 fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2244 let line_height = layout.position_map.line_height;
2245
2246 let scroll_position = layout.position_map.snapshot.scroll_position();
2247 let scroll_top = scroll_position.y * line_height;
2248
2249 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2250
2251 let show_git_gutter = matches!(
2252 ProjectSettings::get_global(cx).git.git_gutter,
2253 Some(GitGutterSetting::TrackedFiles)
2254 );
2255
2256 if show_git_gutter {
2257 Self::paint_diff_hunks(layout, cx);
2258 }
2259
2260 if layout.blamed_display_rows.is_some() {
2261 self.paint_blamed_display_rows(layout, cx);
2262 }
2263
2264 for (ix, line) in layout.line_numbers.iter().enumerate() {
2265 if let Some(line) = line {
2266 let line_origin = layout.gutter_hitbox.origin
2267 + point(
2268 layout.gutter_hitbox.size.width
2269 - line.width
2270 - layout.gutter_dimensions.right_padding,
2271 ix as f32 * line_height - (scroll_top % line_height),
2272 );
2273
2274 line.paint(line_origin, line_height, cx).log_err();
2275 }
2276 }
2277
2278 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2279 cx.with_element_namespace("gutter_fold_indicators", |cx| {
2280 for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2281 fold_indicator.paint(cx);
2282 }
2283 });
2284
2285 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2286 indicator.paint(cx);
2287 }
2288 })
2289 }
2290
2291 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2292 if layout.display_hunks.is_empty() {
2293 return;
2294 }
2295
2296 let line_height = layout.position_map.line_height;
2297
2298 let scroll_position = layout.position_map.snapshot.scroll_position();
2299 let scroll_top = scroll_position.y * line_height;
2300
2301 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2302 for hunk in &layout.display_hunks {
2303 let (display_row_range, status) = match hunk {
2304 //TODO: This rendering is entirely a horrible hack
2305 &DisplayDiffHunk::Folded { display_row: row } => {
2306 let start_y = row as f32 * line_height - scroll_top;
2307 let end_y = start_y + line_height;
2308
2309 let width = 0.275 * line_height;
2310 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2311 let highlight_size = size(width * 2., end_y - start_y);
2312 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2313 cx.paint_quad(quad(
2314 highlight_bounds,
2315 Corners::all(1. * line_height),
2316 cx.theme().status().modified,
2317 Edges::default(),
2318 transparent_black(),
2319 ));
2320
2321 continue;
2322 }
2323
2324 DisplayDiffHunk::Unfolded {
2325 display_row_range,
2326 status,
2327 } => (display_row_range, status),
2328 };
2329
2330 let color = match status {
2331 DiffHunkStatus::Added => cx.theme().status().created,
2332 DiffHunkStatus::Modified => cx.theme().status().modified,
2333
2334 //TODO: This rendering is entirely a horrible hack
2335 DiffHunkStatus::Removed => {
2336 let row = display_row_range.start;
2337
2338 let offset = line_height / 2.;
2339 let start_y = row as f32 * line_height - offset - scroll_top;
2340 let end_y = start_y + line_height;
2341
2342 let width = 0.275 * line_height;
2343 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2344 let highlight_size = size(width * 2., end_y - start_y);
2345 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2346 cx.paint_quad(quad(
2347 highlight_bounds,
2348 Corners::all(1. * line_height),
2349 cx.theme().status().deleted,
2350 Edges::default(),
2351 transparent_black(),
2352 ));
2353
2354 continue;
2355 }
2356 };
2357
2358 let start_row = display_row_range.start;
2359 let end_row = display_row_range.end;
2360 // If we're in a multibuffer, row range span might include an
2361 // excerpt header, so if we were to draw the marker straight away,
2362 // the hunk might include the rows of that header.
2363 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2364 // Instead, we simply check whether the range we're dealing with includes
2365 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2366 let end_row_in_current_excerpt = layout
2367 .position_map
2368 .snapshot
2369 .blocks_in_range(start_row..end_row)
2370 .find_map(|(start_row, block)| {
2371 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2372 Some(start_row)
2373 } else {
2374 None
2375 }
2376 })
2377 .unwrap_or(end_row);
2378
2379 let start_y = start_row as f32 * line_height - scroll_top;
2380 let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2381
2382 let width = 0.275 * line_height;
2383 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2384 let highlight_size = size(width * 2., end_y - start_y);
2385 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2386 cx.paint_quad(quad(
2387 highlight_bounds,
2388 Corners::all(0.05 * line_height),
2389 color,
2390 Edges::default(),
2391 transparent_black(),
2392 ));
2393 }
2394 })
2395 }
2396
2397 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2398 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2399 return;
2400 };
2401
2402 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2403 for mut blame_element in blamed_display_rows.into_iter() {
2404 blame_element.paint(cx);
2405 }
2406 })
2407 }
2408
2409 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2410 cx.with_content_mask(
2411 Some(ContentMask {
2412 bounds: layout.text_hitbox.bounds,
2413 }),
2414 |cx| {
2415 let cursor_style = if self
2416 .editor
2417 .read(cx)
2418 .hovered_link_state
2419 .as_ref()
2420 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2421 {
2422 CursorStyle::PointingHand
2423 } else {
2424 CursorStyle::IBeam
2425 };
2426 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2427
2428 cx.with_element_namespace("folds", |cx| self.paint_folds(layout, cx));
2429 let invisible_display_ranges = self.paint_highlights(layout, cx);
2430 self.paint_lines(&invisible_display_ranges, layout, cx);
2431 self.paint_redactions(layout, cx);
2432 self.paint_cursors(layout, cx);
2433 self.paint_inline_blame(layout, cx);
2434 },
2435 )
2436 }
2437
2438 fn paint_highlights(
2439 &mut self,
2440 layout: &mut EditorLayout,
2441 cx: &mut WindowContext,
2442 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2443 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2444 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2445 let line_end_overshoot = 0.15 * layout.position_map.line_height;
2446 for (range, color) in &layout.highlighted_ranges {
2447 self.paint_highlighted_range(
2448 range.clone(),
2449 *color,
2450 Pixels::ZERO,
2451 line_end_overshoot,
2452 layout,
2453 cx,
2454 );
2455 }
2456
2457 let corner_radius = 0.15 * layout.position_map.line_height;
2458
2459 for (player_color, selections) in &layout.selections {
2460 for selection in selections.into_iter() {
2461 self.paint_highlighted_range(
2462 selection.range.clone(),
2463 player_color.selection,
2464 corner_radius,
2465 corner_radius * 2.,
2466 layout,
2467 cx,
2468 );
2469
2470 if selection.is_local && !selection.range.is_empty() {
2471 invisible_display_ranges.push(selection.range.clone());
2472 }
2473 }
2474 }
2475 invisible_display_ranges
2476 })
2477 }
2478
2479 fn paint_lines(
2480 &mut self,
2481 invisible_display_ranges: &[Range<DisplayPoint>],
2482 layout: &EditorLayout,
2483 cx: &mut WindowContext,
2484 ) {
2485 let whitespace_setting = self
2486 .editor
2487 .read(cx)
2488 .buffer
2489 .read(cx)
2490 .settings_at(0, cx)
2491 .show_whitespaces;
2492
2493 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2494 let row = layout.visible_display_row_range.start + ix as u32;
2495 line_with_invisibles.draw(
2496 layout,
2497 row,
2498 layout.content_origin,
2499 whitespace_setting,
2500 invisible_display_ranges,
2501 cx,
2502 )
2503 }
2504 }
2505
2506 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
2507 if layout.redacted_ranges.is_empty() {
2508 return;
2509 }
2510
2511 let line_end_overshoot = layout.line_end_overshoot();
2512
2513 // A softer than perfect black
2514 let redaction_color = gpui::rgb(0x0e1111);
2515
2516 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2517 for range in layout.redacted_ranges.iter() {
2518 self.paint_highlighted_range(
2519 range.clone(),
2520 redaction_color.into(),
2521 Pixels::ZERO,
2522 line_end_overshoot,
2523 layout,
2524 cx,
2525 );
2526 }
2527 });
2528 }
2529
2530 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2531 for cursor in &mut layout.visible_cursors {
2532 cursor.paint(layout.content_origin, cx);
2533 }
2534 }
2535
2536 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2537 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2538 return;
2539 };
2540
2541 let thumb_bounds = scrollbar_layout.thumb_bounds();
2542 if scrollbar_layout.visible {
2543 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2544 cx.paint_quad(quad(
2545 scrollbar_layout.hitbox.bounds,
2546 Corners::default(),
2547 cx.theme().colors().scrollbar_track_background,
2548 Edges {
2549 top: Pixels::ZERO,
2550 right: Pixels::ZERO,
2551 bottom: Pixels::ZERO,
2552 left: ScrollbarLayout::BORDER_WIDTH,
2553 },
2554 cx.theme().colors().scrollbar_track_border,
2555 ));
2556
2557 let fast_markers =
2558 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
2559 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2560 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
2561
2562 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2563 for marker in markers.iter().chain(&fast_markers) {
2564 let mut marker = marker.clone();
2565 marker.bounds.origin += scrollbar_layout.hitbox.origin;
2566 cx.paint_quad(marker);
2567 }
2568
2569 cx.paint_quad(quad(
2570 thumb_bounds,
2571 Corners::default(),
2572 cx.theme().colors().scrollbar_thumb_background,
2573 Edges {
2574 top: Pixels::ZERO,
2575 right: Pixels::ZERO,
2576 bottom: Pixels::ZERO,
2577 left: ScrollbarLayout::BORDER_WIDTH,
2578 },
2579 cx.theme().colors().scrollbar_thumb_border,
2580 ));
2581 });
2582 }
2583
2584 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2585
2586 let row_height = scrollbar_layout.row_height;
2587 let row_range = scrollbar_layout.visible_row_range.clone();
2588
2589 cx.on_mouse_event({
2590 let editor = self.editor.clone();
2591 let hitbox = scrollbar_layout.hitbox.clone();
2592 let mut mouse_position = cx.mouse_position();
2593 move |event: &MouseMoveEvent, phase, cx| {
2594 if phase == DispatchPhase::Capture {
2595 return;
2596 }
2597
2598 editor.update(cx, |editor, cx| {
2599 if event.pressed_button == Some(MouseButton::Left)
2600 && editor.scroll_manager.is_dragging_scrollbar()
2601 {
2602 let y = mouse_position.y;
2603 let new_y = event.position.y;
2604 if (hitbox.top()..hitbox.bottom()).contains(&y) {
2605 let mut position = editor.scroll_position(cx);
2606 position.y += (new_y - y) / row_height;
2607 if position.y < 0.0 {
2608 position.y = 0.0;
2609 }
2610 editor.set_scroll_position(position, cx);
2611 }
2612
2613 cx.stop_propagation();
2614 } else {
2615 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2616 if hitbox.is_hovered(cx) {
2617 editor.scroll_manager.show_scrollbar(cx);
2618 }
2619 }
2620 mouse_position = event.position;
2621 })
2622 }
2623 });
2624
2625 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2626 cx.on_mouse_event({
2627 let editor = self.editor.clone();
2628 move |_: &MouseUpEvent, phase, cx| {
2629 if phase == DispatchPhase::Capture {
2630 return;
2631 }
2632
2633 editor.update(cx, |editor, cx| {
2634 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2635 cx.stop_propagation();
2636 });
2637 }
2638 });
2639 } else {
2640 cx.on_mouse_event({
2641 let editor = self.editor.clone();
2642 let hitbox = scrollbar_layout.hitbox.clone();
2643 move |event: &MouseDownEvent, phase, cx| {
2644 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2645 return;
2646 }
2647
2648 editor.update(cx, |editor, cx| {
2649 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2650
2651 let y = event.position.y;
2652 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2653 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
2654 let top_row = center_row
2655 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2656 let mut position = editor.scroll_position(cx);
2657 position.y = top_row as f32;
2658 editor.set_scroll_position(position, cx);
2659 } else {
2660 editor.scroll_manager.show_scrollbar(cx);
2661 }
2662
2663 cx.stop_propagation();
2664 });
2665 }
2666 });
2667 }
2668 }
2669
2670 fn collect_fast_scrollbar_markers(
2671 &self,
2672 layout: &EditorLayout,
2673 scrollbar_layout: &ScrollbarLayout,
2674 cx: &mut WindowContext,
2675 ) -> Vec<PaintQuad> {
2676 const LIMIT: usize = 100;
2677 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
2678 return vec![];
2679 }
2680 let cursor_ranges = layout
2681 .cursors
2682 .iter()
2683 .map(|cursor| {
2684 let point = cursor
2685 .0
2686 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2687 ColoredRange {
2688 start: point.row(),
2689 end: point.row(),
2690 color: cursor.1,
2691 }
2692 })
2693 .collect_vec();
2694 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
2695 }
2696
2697 fn refresh_slow_scrollbar_markers(
2698 &self,
2699 layout: &EditorLayout,
2700 scrollbar_layout: &ScrollbarLayout,
2701 cx: &mut WindowContext,
2702 ) {
2703 self.editor.update(cx, |editor, cx| {
2704 if !editor.is_singleton(cx)
2705 || !editor
2706 .scrollbar_marker_state
2707 .should_refresh(scrollbar_layout.hitbox.size)
2708 {
2709 return;
2710 }
2711
2712 let scrollbar_layout = scrollbar_layout.clone();
2713 let background_highlights = editor.background_highlights.clone();
2714 let snapshot = layout.position_map.snapshot.clone();
2715 let theme = cx.theme().clone();
2716 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2717 let max_row = layout.max_row;
2718
2719 editor.scrollbar_marker_state.dirty = false;
2720 editor.scrollbar_marker_state.pending_refresh =
2721 Some(cx.spawn(|editor, mut cx| async move {
2722 let scrollbar_size = scrollbar_layout.hitbox.size;
2723 let scrollbar_markers = cx
2724 .background_executor()
2725 .spawn(async move {
2726 let mut marker_quads = Vec::new();
2727
2728 if scrollbar_settings.git_diff {
2729 let marker_row_ranges = snapshot
2730 .buffer_snapshot
2731 .git_diff_hunks_in_range(0..max_row)
2732 .map(|hunk| {
2733 let start_display_row =
2734 Point::new(hunk.associated_range.start, 0)
2735 .to_display_point(&snapshot.display_snapshot)
2736 .row();
2737 let mut end_display_row =
2738 Point::new(hunk.associated_range.end, 0)
2739 .to_display_point(&snapshot.display_snapshot)
2740 .row();
2741 if end_display_row != start_display_row {
2742 end_display_row -= 1;
2743 }
2744 let color = match hunk.status() {
2745 DiffHunkStatus::Added => theme.status().created,
2746 DiffHunkStatus::Modified => theme.status().modified,
2747 DiffHunkStatus::Removed => theme.status().deleted,
2748 };
2749 ColoredRange {
2750 start: start_display_row,
2751 end: end_display_row,
2752 color,
2753 }
2754 });
2755
2756 marker_quads.extend(
2757 scrollbar_layout
2758 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
2759 );
2760 }
2761
2762 for (background_highlight_id, (_, background_ranges)) in
2763 background_highlights.iter()
2764 {
2765 let is_search_highlights = *background_highlight_id
2766 == TypeId::of::<BufferSearchHighlights>();
2767 let is_symbol_occurrences = *background_highlight_id
2768 == TypeId::of::<DocumentHighlightRead>()
2769 || *background_highlight_id
2770 == TypeId::of::<DocumentHighlightWrite>();
2771 if (is_search_highlights && scrollbar_settings.search_results)
2772 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
2773 {
2774 let mut color = theme.status().info;
2775 if is_symbol_occurrences {
2776 color.fade_out(0.5);
2777 }
2778 let marker_row_ranges =
2779 background_ranges.into_iter().map(|range| {
2780 let display_start = range
2781 .start
2782 .to_display_point(&snapshot.display_snapshot);
2783 let display_end = range
2784 .end
2785 .to_display_point(&snapshot.display_snapshot);
2786 ColoredRange {
2787 start: display_start.row(),
2788 end: display_end.row(),
2789 color,
2790 }
2791 });
2792 marker_quads.extend(
2793 scrollbar_layout
2794 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
2795 );
2796 }
2797 }
2798
2799 if scrollbar_settings.diagnostics {
2800 let max_point =
2801 snapshot.display_snapshot.buffer_snapshot.max_point();
2802
2803 let diagnostics = snapshot
2804 .buffer_snapshot
2805 .diagnostics_in_range::<_, Point>(
2806 Point::zero()..max_point,
2807 false,
2808 )
2809 // We want to sort by severity, in order to paint the most severe diagnostics last.
2810 .sorted_by_key(|diagnostic| {
2811 std::cmp::Reverse(diagnostic.diagnostic.severity)
2812 });
2813
2814 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2815 let start_display = diagnostic
2816 .range
2817 .start
2818 .to_display_point(&snapshot.display_snapshot);
2819 let end_display = diagnostic
2820 .range
2821 .end
2822 .to_display_point(&snapshot.display_snapshot);
2823 let color = match diagnostic.diagnostic.severity {
2824 DiagnosticSeverity::ERROR => theme.status().error,
2825 DiagnosticSeverity::WARNING => theme.status().warning,
2826 DiagnosticSeverity::INFORMATION => theme.status().info,
2827 _ => theme.status().hint,
2828 };
2829 ColoredRange {
2830 start: start_display.row(),
2831 end: end_display.row(),
2832 color,
2833 }
2834 });
2835 marker_quads.extend(
2836 scrollbar_layout
2837 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
2838 );
2839 }
2840
2841 Arc::from(marker_quads)
2842 })
2843 .await;
2844
2845 editor.update(&mut cx, |editor, cx| {
2846 editor.scrollbar_marker_state.markers = scrollbar_markers;
2847 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2848 editor.scrollbar_marker_state.pending_refresh = None;
2849 cx.notify();
2850 })?;
2851
2852 Ok(())
2853 }));
2854 });
2855 }
2856
2857 #[allow(clippy::too_many_arguments)]
2858 fn paint_highlighted_range(
2859 &self,
2860 range: Range<DisplayPoint>,
2861 color: Hsla,
2862 corner_radius: Pixels,
2863 line_end_overshoot: Pixels,
2864 layout: &EditorLayout,
2865 cx: &mut WindowContext,
2866 ) {
2867 let start_row = layout.visible_display_row_range.start;
2868 let end_row = layout.visible_display_row_range.end;
2869 if range.start != range.end {
2870 let row_range = if range.end.column() == 0 {
2871 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2872 } else {
2873 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2874 };
2875
2876 let highlighted_range = HighlightedRange {
2877 color,
2878 line_height: layout.position_map.line_height,
2879 corner_radius,
2880 start_y: layout.content_origin.y
2881 + row_range.start as f32 * layout.position_map.line_height
2882 - layout.position_map.scroll_pixel_position.y,
2883 lines: row_range
2884 .into_iter()
2885 .map(|row| {
2886 let line_layout =
2887 &layout.position_map.line_layouts[(row - start_row) as usize].line;
2888 HighlightedRangeLine {
2889 start_x: if row == range.start.row() {
2890 layout.content_origin.x
2891 + line_layout.x_for_index(range.start.column() as usize)
2892 - layout.position_map.scroll_pixel_position.x
2893 } else {
2894 layout.content_origin.x
2895 - layout.position_map.scroll_pixel_position.x
2896 },
2897 end_x: if row == range.end.row() {
2898 layout.content_origin.x
2899 + line_layout.x_for_index(range.end.column() as usize)
2900 - layout.position_map.scroll_pixel_position.x
2901 } else {
2902 layout.content_origin.x + line_layout.width + line_end_overshoot
2903 - layout.position_map.scroll_pixel_position.x
2904 },
2905 }
2906 })
2907 .collect(),
2908 };
2909
2910 highlighted_range.paint(layout.text_hitbox.bounds, cx);
2911 }
2912 }
2913
2914 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2915 if layout.folds.is_empty() {
2916 return;
2917 }
2918
2919 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2920 let fold_corner_radius = 0.15 * layout.position_map.line_height;
2921 for mut fold in mem::take(&mut layout.folds) {
2922 fold.hover_element.paint(cx);
2923
2924 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2925 let fold_background = if hover_element.interactivity().active.unwrap() {
2926 cx.theme().colors().ghost_element_active
2927 } else if hover_element.interactivity().hovered.unwrap() {
2928 cx.theme().colors().ghost_element_hover
2929 } else {
2930 cx.theme().colors().ghost_element_background
2931 };
2932
2933 self.paint_highlighted_range(
2934 fold.display_range.clone(),
2935 fold_background,
2936 fold_corner_radius,
2937 fold_corner_radius * 2.,
2938 layout,
2939 cx,
2940 );
2941 }
2942 })
2943 }
2944
2945 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2946 if let Some(mut inline_blame) = layout.inline_blame.take() {
2947 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2948 inline_blame.paint(cx);
2949 })
2950 }
2951 }
2952
2953 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2954 for mut block in layout.blocks.drain(..) {
2955 block.element.paint(cx);
2956 }
2957 }
2958
2959 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2960 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2961 mouse_context_menu.paint(cx);
2962 }
2963 }
2964
2965 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
2966 cx.on_mouse_event({
2967 let position_map = layout.position_map.clone();
2968 let editor = self.editor.clone();
2969 let hitbox = layout.hitbox.clone();
2970 let mut delta = ScrollDelta::default();
2971
2972 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
2973 // accidentally turn off their scrolling.
2974 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
2975
2976 move |event: &ScrollWheelEvent, phase, cx| {
2977 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2978 delta = delta.coalesce(event.delta);
2979 editor.update(cx, |editor, cx| {
2980 let position_map: &PositionMap = &position_map;
2981
2982 let line_height = position_map.line_height;
2983 let max_glyph_width = position_map.em_width;
2984 let (delta, axis) = match delta {
2985 gpui::ScrollDelta::Pixels(mut pixels) => {
2986 //Trackpad
2987 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2988 (pixels, axis)
2989 }
2990
2991 gpui::ScrollDelta::Lines(lines) => {
2992 //Not trackpad
2993 let pixels =
2994 point(lines.x * max_glyph_width, lines.y * line_height);
2995 (pixels, None)
2996 }
2997 };
2998
2999 let scroll_position = position_map.snapshot.scroll_position();
3000 let x = (scroll_position.x * max_glyph_width
3001 - (delta.x * scroll_sensitivity))
3002 / max_glyph_width;
3003 let y = (scroll_position.y * line_height - (delta.y * scroll_sensitivity))
3004 / line_height;
3005 let scroll_position =
3006 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3007 editor.scroll(scroll_position, axis, cx);
3008 cx.stop_propagation();
3009 });
3010 }
3011 }
3012 });
3013 }
3014
3015 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3016 self.paint_scroll_wheel_listener(layout, cx);
3017
3018 cx.on_mouse_event({
3019 let position_map = layout.position_map.clone();
3020 let editor = self.editor.clone();
3021 let text_hitbox = layout.text_hitbox.clone();
3022 let gutter_hitbox = layout.gutter_hitbox.clone();
3023
3024 move |event: &MouseDownEvent, phase, cx| {
3025 if phase == DispatchPhase::Bubble {
3026 match event.button {
3027 MouseButton::Left => editor.update(cx, |editor, cx| {
3028 Self::mouse_left_down(
3029 editor,
3030 event,
3031 &position_map,
3032 &text_hitbox,
3033 &gutter_hitbox,
3034 cx,
3035 );
3036 }),
3037 MouseButton::Right => editor.update(cx, |editor, cx| {
3038 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3039 }),
3040 MouseButton::Middle => editor.update(cx, |editor, cx| {
3041 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3042 }),
3043 _ => {}
3044 };
3045 }
3046 }
3047 });
3048
3049 cx.on_mouse_event({
3050 let editor = self.editor.clone();
3051 let position_map = layout.position_map.clone();
3052 let text_hitbox = layout.text_hitbox.clone();
3053
3054 move |event: &MouseUpEvent, phase, cx| {
3055 if phase == DispatchPhase::Bubble {
3056 editor.update(cx, |editor, cx| {
3057 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3058 });
3059 }
3060 }
3061 });
3062 cx.on_mouse_event({
3063 let position_map = layout.position_map.clone();
3064 let editor = self.editor.clone();
3065 let text_hitbox = layout.text_hitbox.clone();
3066 let gutter_hitbox = layout.gutter_hitbox.clone();
3067
3068 move |event: &MouseMoveEvent, phase, cx| {
3069 if phase == DispatchPhase::Bubble {
3070 editor.update(cx, |editor, cx| {
3071 if event.pressed_button == Some(MouseButton::Left) {
3072 Self::mouse_dragged(
3073 editor,
3074 event,
3075 &position_map,
3076 text_hitbox.bounds,
3077 cx,
3078 )
3079 }
3080
3081 Self::mouse_moved(
3082 editor,
3083 event,
3084 &position_map,
3085 &text_hitbox,
3086 &gutter_hitbox,
3087 cx,
3088 )
3089 });
3090 }
3091 }
3092 });
3093 }
3094
3095 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3096 bounds.upper_right().x - self.style.scrollbar_width
3097 }
3098
3099 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3100 let style = &self.style;
3101 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3102 let layout = cx
3103 .text_system()
3104 .shape_line(
3105 SharedString::from(" ".repeat(column)),
3106 font_size,
3107 &[TextRun {
3108 len: column,
3109 font: style.text.font(),
3110 color: Hsla::default(),
3111 background_color: None,
3112 underline: None,
3113 strikethrough: None,
3114 }],
3115 )
3116 .unwrap();
3117
3118 layout.width
3119 }
3120
3121 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3122 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
3123 self.column_pixels(digit_count, cx)
3124 }
3125}
3126
3127fn render_inline_blame_entry(
3128 blame: &gpui::Model<GitBlame>,
3129 blame_entry: BlameEntry,
3130 style: &EditorStyle,
3131 workspace: Option<WeakView<Workspace>>,
3132 cx: &mut WindowContext<'_>,
3133) -> AnyElement {
3134 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3135
3136 let author = blame_entry.author.as_deref().unwrap_or_default();
3137 let text = format!("{}, {}", author, relative_timestamp);
3138
3139 let details = blame.read(cx).details_for_entry(&blame_entry);
3140
3141 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3142
3143 h_flex()
3144 .id("inline-blame")
3145 .w_full()
3146 .font_family(style.text.font().family)
3147 .text_color(cx.theme().status().hint)
3148 .line_height(style.text.line_height)
3149 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3150 .child(text)
3151 .gap_2()
3152 .hoverable_tooltip(move |_| tooltip.clone().into())
3153 .into_any()
3154}
3155
3156fn render_blame_entry(
3157 ix: usize,
3158 blame: &gpui::Model<GitBlame>,
3159 blame_entry: BlameEntry,
3160 style: &EditorStyle,
3161 last_used_color: &mut Option<(PlayerColor, Oid)>,
3162 editor: View<Editor>,
3163 cx: &mut WindowContext<'_>,
3164) -> AnyElement {
3165 let mut sha_color = cx
3166 .theme()
3167 .players()
3168 .color_for_participant(blame_entry.sha.into());
3169 // If the last color we used is the same as the one we get for this line, but
3170 // the commit SHAs are different, then we try again to get a different color.
3171 match *last_used_color {
3172 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3173 let index: u32 = blame_entry.sha.into();
3174 sha_color = cx.theme().players().color_for_participant(index + 1);
3175 }
3176 _ => {}
3177 };
3178 last_used_color.replace((sha_color, blame_entry.sha));
3179
3180 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3181
3182 let pretty_commit_id = format!("{}", blame_entry.sha);
3183 let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3184
3185 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3186 let name = util::truncate_and_trailoff(author_name, 20);
3187
3188 let details = blame.read(cx).details_for_entry(&blame_entry);
3189
3190 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3191
3192 let tooltip = cx.new_view(|_| {
3193 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3194 });
3195
3196 h_flex()
3197 .w_full()
3198 .font_family(style.text.font().family)
3199 .line_height(style.text.line_height)
3200 .id(("blame", ix))
3201 .children([
3202 div()
3203 .text_color(sha_color.cursor)
3204 .child(short_commit_id)
3205 .mr_2(),
3206 div()
3207 .w_full()
3208 .h_flex()
3209 .justify_between()
3210 .text_color(cx.theme().status().hint)
3211 .child(name)
3212 .child(relative_timestamp),
3213 ])
3214 .on_mouse_down(MouseButton::Right, {
3215 let blame_entry = blame_entry.clone();
3216 move |event, cx| {
3217 deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3218 }
3219 })
3220 .hover(|style| style.bg(cx.theme().colors().element_hover))
3221 .when_some(
3222 details.and_then(|details| details.permalink),
3223 |this, url| {
3224 let url = url.clone();
3225 this.cursor_pointer().on_click(move |_, cx| {
3226 cx.stop_propagation();
3227 cx.open_url(url.as_str())
3228 })
3229 },
3230 )
3231 .hoverable_tooltip(move |_| tooltip.clone().into())
3232 .into_any()
3233}
3234
3235fn deploy_blame_entry_context_menu(
3236 blame_entry: &BlameEntry,
3237 editor: View<Editor>,
3238 position: gpui::Point<Pixels>,
3239 cx: &mut WindowContext<'_>,
3240) {
3241 let context_menu = ContextMenu::build(cx, move |this, _| {
3242 let sha = format!("{}", blame_entry.sha);
3243 this.entry("Copy commit SHA", None, move |cx| {
3244 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3245 })
3246 });
3247
3248 editor.update(cx, move |editor, cx| {
3249 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3250 cx.notify();
3251 });
3252}
3253
3254#[derive(Debug)]
3255pub(crate) struct LineWithInvisibles {
3256 pub line: ShapedLine,
3257 invisibles: Vec<Invisible>,
3258}
3259
3260impl LineWithInvisibles {
3261 fn from_chunks<'a>(
3262 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3263 text_style: &TextStyle,
3264 max_line_len: usize,
3265 max_line_count: usize,
3266 line_number_layouts: &[Option<ShapedLine>],
3267 editor_mode: EditorMode,
3268 cx: &WindowContext,
3269 ) -> Vec<Self> {
3270 let mut layouts = Vec::with_capacity(max_line_count);
3271 let mut line = String::new();
3272 let mut invisibles = Vec::new();
3273 let mut styles = Vec::new();
3274 let mut non_whitespace_added = false;
3275 let mut row = 0;
3276 let mut line_exceeded_max_len = false;
3277 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3278
3279 for highlighted_chunk in chunks.chain([HighlightedChunk {
3280 chunk: "\n",
3281 style: None,
3282 is_tab: false,
3283 }]) {
3284 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3285 if ix > 0 {
3286 let shaped_line = cx
3287 .text_system()
3288 .shape_line(line.clone().into(), font_size, &styles)
3289 .unwrap();
3290 layouts.push(Self {
3291 line: shaped_line,
3292 invisibles: std::mem::take(&mut invisibles),
3293 });
3294
3295 line.clear();
3296 styles.clear();
3297 row += 1;
3298 line_exceeded_max_len = false;
3299 non_whitespace_added = false;
3300 if row == max_line_count {
3301 return layouts;
3302 }
3303 }
3304
3305 if !line_chunk.is_empty() && !line_exceeded_max_len {
3306 let text_style = if let Some(style) = highlighted_chunk.style {
3307 Cow::Owned(text_style.clone().highlight(style))
3308 } else {
3309 Cow::Borrowed(text_style)
3310 };
3311
3312 if line.len() + line_chunk.len() > max_line_len {
3313 let mut chunk_len = max_line_len - line.len();
3314 while !line_chunk.is_char_boundary(chunk_len) {
3315 chunk_len -= 1;
3316 }
3317 line_chunk = &line_chunk[..chunk_len];
3318 line_exceeded_max_len = true;
3319 }
3320
3321 styles.push(TextRun {
3322 len: line_chunk.len(),
3323 font: text_style.font(),
3324 color: text_style.color,
3325 background_color: text_style.background_color,
3326 underline: text_style.underline,
3327 strikethrough: text_style.strikethrough,
3328 });
3329
3330 if editor_mode == EditorMode::Full {
3331 // Line wrap pads its contents with fake whitespaces,
3332 // avoid printing them
3333 let inside_wrapped_string = line_number_layouts
3334 .get(row)
3335 .and_then(|layout| layout.as_ref())
3336 .is_none();
3337 if highlighted_chunk.is_tab {
3338 if non_whitespace_added || !inside_wrapped_string {
3339 invisibles.push(Invisible::Tab {
3340 line_start_offset: line.len(),
3341 });
3342 }
3343 } else {
3344 invisibles.extend(
3345 line_chunk
3346 .chars()
3347 .enumerate()
3348 .filter(|(_, line_char)| {
3349 let is_whitespace = line_char.is_whitespace();
3350 non_whitespace_added |= !is_whitespace;
3351 is_whitespace
3352 && (non_whitespace_added || !inside_wrapped_string)
3353 })
3354 .map(|(whitespace_index, _)| Invisible::Whitespace {
3355 line_offset: line.len() + whitespace_index,
3356 }),
3357 )
3358 }
3359 }
3360
3361 line.push_str(line_chunk);
3362 }
3363 }
3364 }
3365
3366 layouts
3367 }
3368
3369 fn draw(
3370 &self,
3371 layout: &EditorLayout,
3372 row: u32,
3373 content_origin: gpui::Point<Pixels>,
3374 whitespace_setting: ShowWhitespaceSetting,
3375 selection_ranges: &[Range<DisplayPoint>],
3376 cx: &mut WindowContext,
3377 ) {
3378 let line_height = layout.position_map.line_height;
3379 let line_y =
3380 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3381
3382 let line_origin =
3383 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3384 self.line.paint(line_origin, line_height, cx).log_err();
3385
3386 self.draw_invisibles(
3387 &selection_ranges,
3388 layout,
3389 content_origin,
3390 line_y,
3391 row,
3392 line_height,
3393 whitespace_setting,
3394 cx,
3395 );
3396 }
3397
3398 #[allow(clippy::too_many_arguments)]
3399 fn draw_invisibles(
3400 &self,
3401 selection_ranges: &[Range<DisplayPoint>],
3402 layout: &EditorLayout,
3403 content_origin: gpui::Point<Pixels>,
3404 line_y: Pixels,
3405 row: u32,
3406 line_height: Pixels,
3407 whitespace_setting: ShowWhitespaceSetting,
3408 cx: &mut WindowContext,
3409 ) {
3410 let allowed_invisibles_regions = match whitespace_setting {
3411 ShowWhitespaceSetting::None => return,
3412 ShowWhitespaceSetting::Selection => Some(selection_ranges),
3413 ShowWhitespaceSetting::All => None,
3414 };
3415
3416 for invisible in &self.invisibles {
3417 let (&token_offset, invisible_symbol) = match invisible {
3418 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3419 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3420 };
3421
3422 let x_offset = self.line.x_for_index(token_offset);
3423 let invisible_offset =
3424 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3425 let origin = content_origin
3426 + gpui::point(
3427 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3428 line_y,
3429 );
3430
3431 if let Some(allowed_regions) = allowed_invisibles_regions {
3432 let invisible_point = DisplayPoint::new(row, token_offset as u32);
3433 if !allowed_regions
3434 .iter()
3435 .any(|region| region.start <= invisible_point && invisible_point < region.end)
3436 {
3437 continue;
3438 }
3439 }
3440 invisible_symbol.paint(origin, line_height, cx).log_err();
3441 }
3442 }
3443}
3444
3445#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3446enum Invisible {
3447 Tab { line_start_offset: usize },
3448 Whitespace { line_offset: usize },
3449}
3450
3451impl Element for EditorElement {
3452 type RequestLayoutState = ();
3453 type PrepaintState = EditorLayout;
3454
3455 fn id(&self) -> Option<ElementId> {
3456 None
3457 }
3458
3459 fn request_layout(
3460 &mut self,
3461 _: Option<&GlobalElementId>,
3462 cx: &mut WindowContext,
3463 ) -> (gpui::LayoutId, ()) {
3464 self.editor.update(cx, |editor, cx| {
3465 editor.set_style(self.style.clone(), cx);
3466
3467 let layout_id = match editor.mode {
3468 EditorMode::SingleLine => {
3469 let rem_size = cx.rem_size();
3470 let mut style = Style::default();
3471 style.size.width = relative(1.).into();
3472 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3473 cx.request_layout(&style, None)
3474 }
3475 EditorMode::AutoHeight { max_lines } => {
3476 let editor_handle = cx.view().clone();
3477 let max_line_number_width =
3478 self.max_line_number_width(&editor.snapshot(cx), cx);
3479 cx.request_measured_layout(Style::default(), move |known_dimensions, _, cx| {
3480 editor_handle
3481 .update(cx, |editor, cx| {
3482 compute_auto_height_layout(
3483 editor,
3484 max_lines,
3485 max_line_number_width,
3486 known_dimensions,
3487 cx,
3488 )
3489 })
3490 .unwrap_or_default()
3491 })
3492 }
3493 EditorMode::Full => {
3494 let mut style = Style::default();
3495 style.size.width = relative(1.).into();
3496 style.size.height = relative(1.).into();
3497 cx.request_layout(&style, None)
3498 }
3499 };
3500
3501 (layout_id, ())
3502 })
3503 }
3504
3505 fn prepaint(
3506 &mut self,
3507 _: Option<&GlobalElementId>,
3508 bounds: Bounds<Pixels>,
3509 _: &mut Self::RequestLayoutState,
3510 cx: &mut WindowContext,
3511 ) -> Self::PrepaintState {
3512 let text_style = TextStyleRefinement {
3513 font_size: Some(self.style.text.font_size),
3514 line_height: Some(self.style.text.line_height),
3515 ..Default::default()
3516 };
3517 cx.set_view_id(self.editor.entity_id());
3518 cx.with_text_style(Some(text_style), |cx| {
3519 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3520 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3521 let style = self.style.clone();
3522
3523 let font_id = cx.text_system().resolve_font(&style.text.font());
3524 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3525 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3526 let em_width = cx
3527 .text_system()
3528 .typographic_bounds(font_id, font_size, 'm')
3529 .unwrap()
3530 .size
3531 .width;
3532 let em_advance = cx
3533 .text_system()
3534 .advance(font_id, font_size, 'm')
3535 .unwrap()
3536 .width;
3537
3538 let gutter_dimensions = snapshot.gutter_dimensions(
3539 font_id,
3540 font_size,
3541 em_width,
3542 self.max_line_number_width(&snapshot, cx),
3543 cx,
3544 );
3545 let text_width = bounds.size.width - gutter_dimensions.width;
3546 let overscroll = size(em_width, px(0.));
3547
3548 snapshot = self.editor.update(cx, |editor, cx| {
3549 editor.last_bounds = Some(bounds);
3550 editor.gutter_width = gutter_dimensions.width;
3551 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3552
3553 let editor_width =
3554 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3555 let wrap_width = match editor.soft_wrap_mode(cx) {
3556 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3557 SoftWrap::EditorWidth => editor_width,
3558 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3559 };
3560
3561 if editor.set_wrap_width(Some(wrap_width), cx) {
3562 editor.snapshot(cx)
3563 } else {
3564 snapshot
3565 }
3566 });
3567
3568 let wrap_guides = self
3569 .editor
3570 .read(cx)
3571 .wrap_guides(cx)
3572 .iter()
3573 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3574 .collect::<SmallVec<[_; 2]>>();
3575
3576 let hitbox = cx.insert_hitbox(bounds, false);
3577 let gutter_hitbox = cx.insert_hitbox(
3578 Bounds {
3579 origin: bounds.origin,
3580 size: size(gutter_dimensions.width, bounds.size.height),
3581 },
3582 false,
3583 );
3584 let text_hitbox = cx.insert_hitbox(
3585 Bounds {
3586 origin: gutter_hitbox.upper_right(),
3587 size: size(text_width, bounds.size.height),
3588 },
3589 false,
3590 );
3591 // Offset the content_bounds from the text_bounds by the gutter margin (which
3592 // is roughly half a character wide) to make hit testing work more like how we want.
3593 let content_origin =
3594 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3595
3596 let mut autoscroll_containing_element = false;
3597 let mut autoscroll_horizontally = false;
3598 self.editor.update(cx, |editor, cx| {
3599 autoscroll_containing_element =
3600 editor.autoscroll_requested() || editor.has_pending_selection();
3601 autoscroll_horizontally = editor.autoscroll_vertically(bounds, line_height, cx);
3602 snapshot = editor.snapshot(cx);
3603 });
3604
3605 let mut scroll_position = snapshot.scroll_position();
3606 // The scroll position is a fractional point, the whole number of which represents
3607 // the top of the window in terms of display rows.
3608 let start_row = scroll_position.y as u32;
3609 let height_in_lines = bounds.size.height / line_height;
3610 let max_row = snapshot.max_point().row();
3611 let end_row = cmp::min(
3612 (scroll_position.y + height_in_lines).ceil() as u32,
3613 max_row + 1,
3614 );
3615
3616 let buffer_rows = snapshot
3617 .buffer_rows(start_row)
3618 .take((start_row..end_row).len());
3619
3620 let start_anchor = if start_row == 0 {
3621 Anchor::min()
3622 } else {
3623 snapshot.buffer_snapshot.anchor_before(
3624 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3625 )
3626 };
3627 let end_anchor = if end_row > max_row {
3628 Anchor::max()
3629 } else {
3630 snapshot.buffer_snapshot.anchor_before(
3631 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3632 )
3633 };
3634
3635 let highlighted_rows = self
3636 .editor
3637 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3638 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3639 start_anchor..end_anchor,
3640 &snapshot.display_snapshot,
3641 cx.theme().colors(),
3642 );
3643
3644 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3645 start_anchor..end_anchor,
3646 &snapshot.display_snapshot,
3647 cx,
3648 );
3649
3650 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3651 start_anchor,
3652 end_anchor,
3653 &snapshot,
3654 start_row,
3655 end_row,
3656 cx,
3657 );
3658
3659 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3660 start_row..end_row,
3661 buffer_rows.clone(),
3662 &active_rows,
3663 newest_selection_head,
3664 &snapshot,
3665 cx,
3666 );
3667
3668 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3669
3670 let mut max_visible_line_width = Pixels::ZERO;
3671 let line_layouts =
3672 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3673 for line_with_invisibles in &line_layouts {
3674 if line_with_invisibles.line.width > max_visible_line_width {
3675 max_visible_line_width = line_with_invisibles.line.width;
3676 }
3677 }
3678
3679 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3680 .unwrap()
3681 .width;
3682 let mut scroll_width =
3683 longest_line_width.max(max_visible_line_width) + overscroll.width;
3684
3685 let mut blocks = cx.with_element_namespace("blocks", |cx| {
3686 self.build_blocks(
3687 start_row..end_row,
3688 &snapshot,
3689 &hitbox,
3690 &text_hitbox,
3691 &mut scroll_width,
3692 &gutter_dimensions,
3693 em_width,
3694 gutter_dimensions.width + gutter_dimensions.margin,
3695 line_height,
3696 &line_layouts,
3697 cx,
3698 )
3699 });
3700
3701 let scroll_pixel_position = point(
3702 scroll_position.x * em_width,
3703 scroll_position.y * line_height,
3704 );
3705
3706 let mut inline_blame = None;
3707 if let Some(newest_selection_head) = newest_selection_head {
3708 let display_row = newest_selection_head.row();
3709 if (start_row..end_row).contains(&display_row) {
3710 let line_layout = &line_layouts[(display_row - start_row) as usize];
3711 inline_blame = self.layout_inline_blame(
3712 display_row,
3713 &snapshot.display_snapshot,
3714 line_layout,
3715 em_width,
3716 content_origin,
3717 scroll_pixel_position,
3718 line_height,
3719 cx,
3720 );
3721 }
3722 }
3723
3724 let blamed_display_rows = self.layout_blame_entries(
3725 buffer_rows,
3726 em_width,
3727 scroll_position,
3728 line_height,
3729 &gutter_hitbox,
3730 gutter_dimensions.git_blame_entries_width,
3731 cx,
3732 );
3733
3734 let scroll_max = point(
3735 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3736 max_row as f32,
3737 );
3738
3739 self.editor.update(cx, |editor, cx| {
3740 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3741
3742 let autoscrolled = if autoscroll_horizontally {
3743 editor.autoscroll_horizontally(
3744 start_row,
3745 text_hitbox.size.width,
3746 scroll_width,
3747 em_width,
3748 &line_layouts,
3749 cx,
3750 )
3751 } else {
3752 false
3753 };
3754
3755 if clamped || autoscrolled {
3756 snapshot = editor.snapshot(cx);
3757 scroll_position = snapshot.scroll_position();
3758 }
3759 });
3760
3761 cx.with_element_namespace("blocks", |cx| {
3762 self.layout_blocks(
3763 &mut blocks,
3764 &hitbox,
3765 line_height,
3766 scroll_pixel_position,
3767 cx,
3768 );
3769 });
3770
3771 let cursors = self.collect_cursors(&snapshot, cx);
3772
3773 let (visible_cursors, non_visible_cursors) = self.layout_visible_cursors(
3774 &snapshot,
3775 &selections,
3776 start_row..end_row,
3777 &line_layouts,
3778 &text_hitbox,
3779 content_origin,
3780 scroll_position,
3781 scroll_pixel_position,
3782 line_height,
3783 em_width,
3784 autoscroll_containing_element,
3785 cx,
3786 );
3787
3788 let scrollbar_layout = self.layout_scrollbar(
3789 &snapshot,
3790 bounds,
3791 scroll_position,
3792 height_in_lines,
3793 non_visible_cursors,
3794 cx,
3795 );
3796
3797 let folds = cx.with_element_namespace("folds", |cx| {
3798 self.layout_folds(
3799 &snapshot,
3800 content_origin,
3801 start_anchor..end_anchor,
3802 start_row..end_row,
3803 scroll_pixel_position,
3804 line_height,
3805 &line_layouts,
3806 cx,
3807 )
3808 });
3809
3810 let gutter_settings = EditorSettings::get_global(cx).gutter;
3811
3812 let mut context_menu_visible = false;
3813 let mut code_actions_indicator = None;
3814 if let Some(newest_selection_head) = newest_selection_head {
3815 if (start_row..end_row).contains(&newest_selection_head.row()) {
3816 context_menu_visible = self.layout_context_menu(
3817 line_height,
3818 &hitbox,
3819 &text_hitbox,
3820 content_origin,
3821 start_row,
3822 scroll_pixel_position,
3823 &line_layouts,
3824 newest_selection_head,
3825 cx,
3826 );
3827 if gutter_settings.code_actions {
3828 code_actions_indicator = self.layout_code_actions_indicator(
3829 line_height,
3830 newest_selection_head,
3831 scroll_pixel_position,
3832 &gutter_dimensions,
3833 &gutter_hitbox,
3834 cx,
3835 );
3836 }
3837 }
3838 }
3839
3840 if !context_menu_visible && !cx.has_active_drag() {
3841 self.layout_hover_popovers(
3842 &snapshot,
3843 &hitbox,
3844 &text_hitbox,
3845 start_row..end_row,
3846 content_origin,
3847 scroll_pixel_position,
3848 &line_layouts,
3849 line_height,
3850 em_width,
3851 cx,
3852 );
3853 }
3854
3855 let mouse_context_menu = self.layout_mouse_context_menu(cx);
3856
3857 let fold_indicators = if gutter_settings.folds {
3858 cx.with_element_namespace("gutter_fold_indicators", |cx| {
3859 self.layout_gutter_fold_indicators(
3860 fold_statuses,
3861 line_height,
3862 &gutter_dimensions,
3863 gutter_settings,
3864 scroll_pixel_position,
3865 &gutter_hitbox,
3866 cx,
3867 )
3868 })
3869 } else {
3870 Vec::new()
3871 };
3872
3873 let invisible_symbol_font_size = font_size / 2.;
3874 let tab_invisible = cx
3875 .text_system()
3876 .shape_line(
3877 "→".into(),
3878 invisible_symbol_font_size,
3879 &[TextRun {
3880 len: "→".len(),
3881 font: self.style.text.font(),
3882 color: cx.theme().colors().editor_invisible,
3883 background_color: None,
3884 underline: None,
3885 strikethrough: None,
3886 }],
3887 )
3888 .unwrap();
3889 let space_invisible = cx
3890 .text_system()
3891 .shape_line(
3892 "•".into(),
3893 invisible_symbol_font_size,
3894 &[TextRun {
3895 len: "•".len(),
3896 font: self.style.text.font(),
3897 color: cx.theme().colors().editor_invisible,
3898 background_color: None,
3899 underline: None,
3900 strikethrough: None,
3901 }],
3902 )
3903 .unwrap();
3904
3905 EditorLayout {
3906 mode: snapshot.mode,
3907 position_map: Arc::new(PositionMap {
3908 size: bounds.size,
3909 scroll_pixel_position,
3910 scroll_max,
3911 line_layouts,
3912 line_height,
3913 em_width,
3914 em_advance,
3915 snapshot,
3916 }),
3917 visible_display_row_range: start_row..end_row,
3918 wrap_guides,
3919 hitbox,
3920 text_hitbox,
3921 gutter_hitbox,
3922 gutter_dimensions,
3923 content_origin,
3924 scrollbar_layout,
3925 max_row,
3926 active_rows,
3927 highlighted_rows,
3928 highlighted_ranges,
3929 redacted_ranges,
3930 line_numbers,
3931 display_hunks,
3932 blamed_display_rows,
3933 inline_blame,
3934 folds,
3935 blocks,
3936 cursors,
3937 visible_cursors,
3938 selections,
3939 mouse_context_menu,
3940 code_actions_indicator,
3941 fold_indicators,
3942 tab_invisible,
3943 space_invisible,
3944 }
3945 })
3946 })
3947 }
3948
3949 fn paint(
3950 &mut self,
3951 _: Option<&GlobalElementId>,
3952 bounds: Bounds<gpui::Pixels>,
3953 _: &mut Self::RequestLayoutState,
3954 layout: &mut Self::PrepaintState,
3955 cx: &mut WindowContext,
3956 ) {
3957 let focus_handle = self.editor.focus_handle(cx);
3958 let key_context = self.editor.read(cx).key_context(cx);
3959 cx.set_focus_handle(&focus_handle);
3960 cx.set_key_context(key_context);
3961 cx.handle_input(
3962 &focus_handle,
3963 ElementInputHandler::new(bounds, self.editor.clone()),
3964 );
3965 self.register_actions(cx);
3966 self.register_key_listeners(cx, layout);
3967
3968 let text_style = TextStyleRefinement {
3969 font_size: Some(self.style.text.font_size),
3970 line_height: Some(self.style.text.line_height),
3971 ..Default::default()
3972 };
3973 cx.with_text_style(Some(text_style), |cx| {
3974 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3975 self.paint_mouse_listeners(layout, cx);
3976
3977 self.paint_background(layout, cx);
3978 if layout.gutter_hitbox.size.width > Pixels::ZERO {
3979 self.paint_gutter(layout, cx);
3980 }
3981 self.paint_text(layout, cx);
3982
3983 if !layout.blocks.is_empty() {
3984 cx.with_element_namespace("blocks", |cx| {
3985 self.paint_blocks(layout, cx);
3986 });
3987 }
3988
3989 self.paint_scrollbar(layout, cx);
3990 self.paint_mouse_context_menu(layout, cx);
3991 });
3992 })
3993 }
3994}
3995
3996impl IntoElement for EditorElement {
3997 type Element = Self;
3998
3999 fn into_element(self) -> Self::Element {
4000 self
4001 }
4002}
4003
4004type BufferRow = u32;
4005
4006pub struct EditorLayout {
4007 position_map: Arc<PositionMap>,
4008 hitbox: Hitbox,
4009 text_hitbox: Hitbox,
4010 gutter_hitbox: Hitbox,
4011 gutter_dimensions: GutterDimensions,
4012 content_origin: gpui::Point<Pixels>,
4013 scrollbar_layout: Option<ScrollbarLayout>,
4014 mode: EditorMode,
4015 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
4016 visible_display_row_range: Range<u32>,
4017 active_rows: BTreeMap<u32, bool>,
4018 highlighted_rows: BTreeMap<u32, Hsla>,
4019 line_numbers: Vec<Option<ShapedLine>>,
4020 display_hunks: Vec<DisplayDiffHunk>,
4021 blamed_display_rows: Option<Vec<AnyElement>>,
4022 inline_blame: Option<AnyElement>,
4023 folds: Vec<FoldLayout>,
4024 blocks: Vec<BlockLayout>,
4025 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4026 redacted_ranges: Vec<Range<DisplayPoint>>,
4027 cursors: Vec<(Anchor, Hsla)>,
4028 visible_cursors: Vec<CursorLayout>,
4029 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4030 max_row: u32,
4031 code_actions_indicator: Option<AnyElement>,
4032 fold_indicators: Vec<Option<AnyElement>>,
4033 mouse_context_menu: Option<AnyElement>,
4034 tab_invisible: ShapedLine,
4035 space_invisible: ShapedLine,
4036}
4037
4038impl EditorLayout {
4039 fn line_end_overshoot(&self) -> Pixels {
4040 0.15 * self.position_map.line_height
4041 }
4042}
4043
4044struct ColoredRange<T> {
4045 start: T,
4046 end: T,
4047 color: Hsla,
4048}
4049
4050#[derive(Clone)]
4051struct ScrollbarLayout {
4052 hitbox: Hitbox,
4053 visible_row_range: Range<f32>,
4054 visible: bool,
4055 row_height: Pixels,
4056 thumb_height: Pixels,
4057}
4058
4059impl ScrollbarLayout {
4060 const BORDER_WIDTH: Pixels = px(1.0);
4061 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
4062 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
4063 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
4064
4065 fn thumb_bounds(&self) -> Bounds<Pixels> {
4066 let thumb_top = self.y_for_row(self.visible_row_range.start);
4067 let thumb_bottom = thumb_top + self.thumb_height;
4068 Bounds::from_corners(
4069 point(self.hitbox.left(), thumb_top),
4070 point(self.hitbox.right(), thumb_bottom),
4071 )
4072 }
4073
4074 fn y_for_row(&self, row: f32) -> Pixels {
4075 self.hitbox.top() + row * self.row_height
4076 }
4077
4078 fn marker_quads_for_ranges(
4079 &self,
4080 row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4081 column: Option<usize>,
4082 ) -> Vec<PaintQuad> {
4083 struct MinMax {
4084 min: Pixels,
4085 max: Pixels,
4086 }
4087 let (x_range, height_limit) = if let Some(column) = column {
4088 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
4089 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
4090 let end = start + column_width;
4091 (
4092 Range { start, end },
4093 MinMax {
4094 min: Self::MIN_MARKER_HEIGHT,
4095 max: px(f32::MAX),
4096 },
4097 )
4098 } else {
4099 (
4100 Range {
4101 start: Self::BORDER_WIDTH,
4102 end: self.hitbox.size.width,
4103 },
4104 MinMax {
4105 min: Self::LINE_MARKER_HEIGHT,
4106 max: Self::LINE_MARKER_HEIGHT,
4107 },
4108 )
4109 };
4110
4111 let row_to_y = |row: u32| row as f32 * self.row_height;
4112 let mut pixel_ranges = row_ranges
4113 .into_iter()
4114 .map(|range| {
4115 let start_y = row_to_y(range.start);
4116 let end_y = row_to_y(range.end)
4117 + self.row_height.max(height_limit.min).min(height_limit.max);
4118 ColoredRange {
4119 start: start_y,
4120 end: end_y,
4121 color: range.color,
4122 }
4123 })
4124 .peekable();
4125
4126 let mut quads = Vec::new();
4127 while let Some(mut pixel_range) = pixel_ranges.next() {
4128 while let Some(next_pixel_range) = pixel_ranges.peek() {
4129 if pixel_range.end >= next_pixel_range.start - px(1.0)
4130 && pixel_range.color == next_pixel_range.color
4131 {
4132 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4133 pixel_ranges.next();
4134 } else {
4135 break;
4136 }
4137 }
4138
4139 let bounds = Bounds::from_corners(
4140 point(x_range.start, pixel_range.start),
4141 point(x_range.end, pixel_range.end),
4142 );
4143 quads.push(quad(
4144 bounds,
4145 Corners::default(),
4146 pixel_range.color,
4147 Edges::default(),
4148 Hsla::transparent_black(),
4149 ));
4150 }
4151
4152 quads
4153 }
4154}
4155
4156struct FoldLayout {
4157 display_range: Range<DisplayPoint>,
4158 hover_element: AnyElement,
4159}
4160
4161struct PositionMap {
4162 size: Size<Pixels>,
4163 line_height: Pixels,
4164 scroll_pixel_position: gpui::Point<Pixels>,
4165 scroll_max: gpui::Point<f32>,
4166 em_width: Pixels,
4167 em_advance: Pixels,
4168 line_layouts: Vec<LineWithInvisibles>,
4169 snapshot: EditorSnapshot,
4170}
4171
4172#[derive(Debug, Copy, Clone)]
4173pub struct PointForPosition {
4174 pub previous_valid: DisplayPoint,
4175 pub next_valid: DisplayPoint,
4176 pub exact_unclipped: DisplayPoint,
4177 pub column_overshoot_after_line_end: u32,
4178}
4179
4180impl PointForPosition {
4181 pub fn as_valid(&self) -> Option<DisplayPoint> {
4182 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4183 Some(self.previous_valid)
4184 } else {
4185 None
4186 }
4187 }
4188}
4189
4190impl PositionMap {
4191 fn point_for_position(
4192 &self,
4193 text_bounds: Bounds<Pixels>,
4194 position: gpui::Point<Pixels>,
4195 ) -> PointForPosition {
4196 let scroll_position = self.snapshot.scroll_position();
4197 let position = position - text_bounds.origin;
4198 let y = position.y.max(px(0.)).min(self.size.height);
4199 let x = position.x + (scroll_position.x * self.em_width);
4200 let row = ((y / self.line_height) + scroll_position.y) as u32;
4201
4202 let (column, x_overshoot_after_line_end) = if let Some(line) = self
4203 .line_layouts
4204 .get(row as usize - scroll_position.y as usize)
4205 .map(|LineWithInvisibles { line, .. }| line)
4206 {
4207 if let Some(ix) = line.index_for_x(x) {
4208 (ix as u32, px(0.))
4209 } else {
4210 (line.len as u32, px(0.).max(x - line.width))
4211 }
4212 } else {
4213 (0, x)
4214 };
4215
4216 let mut exact_unclipped = DisplayPoint::new(row, column);
4217 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4218 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4219
4220 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4221 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4222 PointForPosition {
4223 previous_valid,
4224 next_valid,
4225 exact_unclipped,
4226 column_overshoot_after_line_end,
4227 }
4228 }
4229}
4230
4231struct BlockLayout {
4232 row: u32,
4233 element: AnyElement,
4234 available_space: Size<AvailableSpace>,
4235 style: BlockStyle,
4236}
4237
4238fn layout_line(
4239 row: u32,
4240 snapshot: &EditorSnapshot,
4241 style: &EditorStyle,
4242 cx: &WindowContext,
4243) -> Result<ShapedLine> {
4244 let mut line = snapshot.line(row);
4245
4246 if line.len() > MAX_LINE_LEN {
4247 let mut len = MAX_LINE_LEN;
4248 while !line.is_char_boundary(len) {
4249 len -= 1;
4250 }
4251
4252 line.truncate(len);
4253 }
4254
4255 cx.text_system().shape_line(
4256 line.into(),
4257 style.text.font_size.to_pixels(cx.rem_size()),
4258 &[TextRun {
4259 len: snapshot.line_len(row) as usize,
4260 font: style.text.font(),
4261 color: Hsla::default(),
4262 background_color: None,
4263 underline: None,
4264 strikethrough: None,
4265 }],
4266 )
4267}
4268
4269pub struct CursorLayout {
4270 origin: gpui::Point<Pixels>,
4271 block_width: Pixels,
4272 line_height: Pixels,
4273 color: Hsla,
4274 shape: CursorShape,
4275 block_text: Option<ShapedLine>,
4276 cursor_name: Option<AnyElement>,
4277}
4278
4279#[derive(Debug)]
4280pub struct CursorName {
4281 string: SharedString,
4282 color: Hsla,
4283 is_top_row: bool,
4284}
4285
4286impl CursorLayout {
4287 pub fn new(
4288 origin: gpui::Point<Pixels>,
4289 block_width: Pixels,
4290 line_height: Pixels,
4291 color: Hsla,
4292 shape: CursorShape,
4293 block_text: Option<ShapedLine>,
4294 ) -> CursorLayout {
4295 CursorLayout {
4296 origin,
4297 block_width,
4298 line_height,
4299 color,
4300 shape,
4301 block_text,
4302 cursor_name: None,
4303 }
4304 }
4305
4306 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4307 Bounds {
4308 origin: self.origin + origin,
4309 size: size(self.block_width, self.line_height),
4310 }
4311 }
4312
4313 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4314 match self.shape {
4315 CursorShape::Bar => Bounds {
4316 origin: self.origin + origin,
4317 size: size(px(2.0), self.line_height),
4318 },
4319 CursorShape::Block | CursorShape::Hollow => Bounds {
4320 origin: self.origin + origin,
4321 size: size(self.block_width, self.line_height),
4322 },
4323 CursorShape::Underscore => Bounds {
4324 origin: self.origin
4325 + origin
4326 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4327 size: size(self.block_width, px(2.0)),
4328 },
4329 }
4330 }
4331
4332 pub fn layout(
4333 &mut self,
4334 origin: gpui::Point<Pixels>,
4335 cursor_name: Option<CursorName>,
4336 cx: &mut WindowContext,
4337 ) {
4338 if let Some(cursor_name) = cursor_name {
4339 let bounds = self.bounds(origin);
4340 let text_size = self.line_height / 1.5;
4341
4342 let name_origin = if cursor_name.is_top_row {
4343 point(bounds.right() - px(1.), bounds.top())
4344 } else {
4345 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4346 };
4347 let mut name_element = div()
4348 .bg(self.color)
4349 .text_size(text_size)
4350 .px_0p5()
4351 .line_height(text_size + px(2.))
4352 .text_color(cursor_name.color)
4353 .child(cursor_name.string.clone())
4354 .into_any_element();
4355
4356 name_element.prepaint_as_root(
4357 name_origin,
4358 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4359 cx,
4360 );
4361
4362 self.cursor_name = Some(name_element);
4363 }
4364 }
4365
4366 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
4367 let bounds = self.bounds(origin);
4368
4369 //Draw background or border quad
4370 let cursor = if matches!(self.shape, CursorShape::Hollow) {
4371 outline(bounds, self.color)
4372 } else {
4373 fill(bounds, self.color)
4374 };
4375
4376 if let Some(name) = &mut self.cursor_name {
4377 name.paint(cx);
4378 }
4379
4380 cx.paint_quad(cursor);
4381
4382 if let Some(block_text) = &self.block_text {
4383 block_text
4384 .paint(self.origin + origin, self.line_height, cx)
4385 .log_err();
4386 }
4387 }
4388
4389 pub fn shape(&self) -> CursorShape {
4390 self.shape
4391 }
4392}
4393
4394#[derive(Debug)]
4395pub struct HighlightedRange {
4396 pub start_y: Pixels,
4397 pub line_height: Pixels,
4398 pub lines: Vec<HighlightedRangeLine>,
4399 pub color: Hsla,
4400 pub corner_radius: Pixels,
4401}
4402
4403#[derive(Debug)]
4404pub struct HighlightedRangeLine {
4405 pub start_x: Pixels,
4406 pub end_x: Pixels,
4407}
4408
4409impl HighlightedRange {
4410 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
4411 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4412 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4413 self.paint_lines(
4414 self.start_y + self.line_height,
4415 &self.lines[1..],
4416 bounds,
4417 cx,
4418 );
4419 } else {
4420 self.paint_lines(self.start_y, &self.lines, bounds, cx);
4421 }
4422 }
4423
4424 fn paint_lines(
4425 &self,
4426 start_y: Pixels,
4427 lines: &[HighlightedRangeLine],
4428 _bounds: Bounds<Pixels>,
4429 cx: &mut WindowContext,
4430 ) {
4431 if lines.is_empty() {
4432 return;
4433 }
4434
4435 let first_line = lines.first().unwrap();
4436 let last_line = lines.last().unwrap();
4437
4438 let first_top_left = point(first_line.start_x, start_y);
4439 let first_top_right = point(first_line.end_x, start_y);
4440
4441 let curve_height = point(Pixels::ZERO, self.corner_radius);
4442 let curve_width = |start_x: Pixels, end_x: Pixels| {
4443 let max = (end_x - start_x) / 2.;
4444 let width = if max < self.corner_radius {
4445 max
4446 } else {
4447 self.corner_radius
4448 };
4449
4450 point(width, Pixels::ZERO)
4451 };
4452
4453 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4454 let mut path = gpui::Path::new(first_top_right - top_curve_width);
4455 path.curve_to(first_top_right + curve_height, first_top_right);
4456
4457 let mut iter = lines.iter().enumerate().peekable();
4458 while let Some((ix, line)) = iter.next() {
4459 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4460
4461 if let Some((_, next_line)) = iter.peek() {
4462 let next_top_right = point(next_line.end_x, bottom_right.y);
4463
4464 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4465 Ordering::Equal => {
4466 path.line_to(bottom_right);
4467 }
4468 Ordering::Less => {
4469 let curve_width = curve_width(next_top_right.x, bottom_right.x);
4470 path.line_to(bottom_right - curve_height);
4471 if self.corner_radius > Pixels::ZERO {
4472 path.curve_to(bottom_right - curve_width, bottom_right);
4473 }
4474 path.line_to(next_top_right + curve_width);
4475 if self.corner_radius > Pixels::ZERO {
4476 path.curve_to(next_top_right + curve_height, next_top_right);
4477 }
4478 }
4479 Ordering::Greater => {
4480 let curve_width = curve_width(bottom_right.x, next_top_right.x);
4481 path.line_to(bottom_right - curve_height);
4482 if self.corner_radius > Pixels::ZERO {
4483 path.curve_to(bottom_right + curve_width, bottom_right);
4484 }
4485 path.line_to(next_top_right - curve_width);
4486 if self.corner_radius > Pixels::ZERO {
4487 path.curve_to(next_top_right + curve_height, next_top_right);
4488 }
4489 }
4490 }
4491 } else {
4492 let curve_width = curve_width(line.start_x, line.end_x);
4493 path.line_to(bottom_right - curve_height);
4494 if self.corner_radius > Pixels::ZERO {
4495 path.curve_to(bottom_right - curve_width, bottom_right);
4496 }
4497
4498 let bottom_left = point(line.start_x, bottom_right.y);
4499 path.line_to(bottom_left + curve_width);
4500 if self.corner_radius > Pixels::ZERO {
4501 path.curve_to(bottom_left - curve_height, bottom_left);
4502 }
4503 }
4504 }
4505
4506 if first_line.start_x > last_line.start_x {
4507 let curve_width = curve_width(last_line.start_x, first_line.start_x);
4508 let second_top_left = point(last_line.start_x, start_y + self.line_height);
4509 path.line_to(second_top_left + curve_height);
4510 if self.corner_radius > Pixels::ZERO {
4511 path.curve_to(second_top_left + curve_width, second_top_left);
4512 }
4513 let first_bottom_left = point(first_line.start_x, second_top_left.y);
4514 path.line_to(first_bottom_left - curve_width);
4515 if self.corner_radius > Pixels::ZERO {
4516 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4517 }
4518 }
4519
4520 path.line_to(first_top_left + curve_height);
4521 if self.corner_radius > Pixels::ZERO {
4522 path.curve_to(first_top_left + top_curve_width, first_top_left);
4523 }
4524 path.line_to(first_top_right - top_curve_width);
4525
4526 cx.paint_path(path, self.color);
4527 }
4528}
4529
4530pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4531 (delta.pow(1.5) / 100.0).into()
4532}
4533
4534fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4535 (delta.pow(1.2) / 300.0).into()
4536}
4537
4538#[cfg(test)]
4539mod tests {
4540 use super::*;
4541 use crate::{
4542 display_map::{BlockDisposition, BlockProperties},
4543 editor_tests::{init_test, update_test_language_settings},
4544 Editor, MultiBuffer,
4545 };
4546 use gpui::{TestAppContext, VisualTestContext};
4547 use language::language_settings;
4548 use log::info;
4549 use std::num::NonZeroU32;
4550 use util::test::sample_text;
4551
4552 #[gpui::test]
4553 fn test_shape_line_numbers(cx: &mut TestAppContext) {
4554 init_test(cx, |_| {});
4555 let window = cx.add_window(|cx| {
4556 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4557 Editor::new(EditorMode::Full, buffer, None, cx)
4558 });
4559
4560 let editor = window.root(cx).unwrap();
4561 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4562 let element = EditorElement::new(&editor, style);
4563 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4564
4565 let layouts = cx
4566 .update_window(*window, |_, cx| {
4567 element
4568 .layout_line_numbers(
4569 0..6,
4570 (0..6).map(Some),
4571 &Default::default(),
4572 Some(DisplayPoint::new(0, 0)),
4573 &snapshot,
4574 cx,
4575 )
4576 .0
4577 })
4578 .unwrap();
4579 assert_eq!(layouts.len(), 6);
4580
4581 let relative_rows =
4582 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..6), Some(3));
4583 assert_eq!(relative_rows[&0], 3);
4584 assert_eq!(relative_rows[&1], 2);
4585 assert_eq!(relative_rows[&2], 1);
4586 // current line has no relative number
4587 assert_eq!(relative_rows[&4], 1);
4588 assert_eq!(relative_rows[&5], 2);
4589
4590 // works if cursor is before screen
4591 let relative_rows =
4592 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(3..6), Some(1));
4593 assert_eq!(relative_rows.len(), 3);
4594 assert_eq!(relative_rows[&3], 2);
4595 assert_eq!(relative_rows[&4], 3);
4596 assert_eq!(relative_rows[&5], 4);
4597
4598 // works if cursor is after screen
4599 let relative_rows =
4600 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..3), Some(6));
4601 assert_eq!(relative_rows.len(), 3);
4602 assert_eq!(relative_rows[&0], 5);
4603 assert_eq!(relative_rows[&1], 4);
4604 assert_eq!(relative_rows[&2], 3);
4605 }
4606
4607 #[gpui::test]
4608 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4609 init_test(cx, |_| {});
4610
4611 let window = cx.add_window(|cx| {
4612 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4613 Editor::new(EditorMode::Full, buffer, None, cx)
4614 });
4615 let cx = &mut VisualTestContext::from_window(*window, cx);
4616 let editor = window.root(cx).unwrap();
4617 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4618
4619 window
4620 .update(cx, |editor, cx| {
4621 editor.cursor_shape = CursorShape::Block;
4622 editor.change_selections(None, cx, |s| {
4623 s.select_ranges([
4624 Point::new(0, 0)..Point::new(1, 0),
4625 Point::new(3, 2)..Point::new(3, 3),
4626 Point::new(5, 6)..Point::new(6, 0),
4627 ]);
4628 });
4629 })
4630 .unwrap();
4631
4632 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4633 EditorElement::new(&editor, style)
4634 });
4635
4636 assert_eq!(state.selections.len(), 1);
4637 let local_selections = &state.selections[0].1;
4638 assert_eq!(local_selections.len(), 3);
4639 // moves cursor back one line
4640 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4641 assert_eq!(
4642 local_selections[0].range,
4643 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4644 );
4645
4646 // moves cursor back one column
4647 assert_eq!(
4648 local_selections[1].range,
4649 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4650 );
4651 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4652
4653 // leaves cursor on the max point
4654 assert_eq!(
4655 local_selections[2].range,
4656 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4657 );
4658 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4659
4660 // active lines does not include 1 (even though the range of the selection does)
4661 assert_eq!(
4662 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4663 vec![0, 3, 5, 6]
4664 );
4665
4666 // multi-buffer support
4667 // in DisplayPoint coordinates, this is what we're dealing with:
4668 // 0: [[file
4669 // 1: header]]
4670 // 2: aaaaaa
4671 // 3: bbbbbb
4672 // 4: cccccc
4673 // 5:
4674 // 6: ...
4675 // 7: ffffff
4676 // 8: gggggg
4677 // 9: hhhhhh
4678 // 10:
4679 // 11: [[file
4680 // 12: header]]
4681 // 13: bbbbbb
4682 // 14: cccccc
4683 // 15: dddddd
4684 let window = cx.add_window(|cx| {
4685 let buffer = MultiBuffer::build_multi(
4686 [
4687 (
4688 &(sample_text(8, 6, 'a') + "\n"),
4689 vec![
4690 Point::new(0, 0)..Point::new(3, 0),
4691 Point::new(4, 0)..Point::new(7, 0),
4692 ],
4693 ),
4694 (
4695 &(sample_text(8, 6, 'a') + "\n"),
4696 vec![Point::new(1, 0)..Point::new(3, 0)],
4697 ),
4698 ],
4699 cx,
4700 );
4701 Editor::new(EditorMode::Full, buffer, None, cx)
4702 });
4703 let editor = window.root(cx).unwrap();
4704 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4705 let _state = window.update(cx, |editor, cx| {
4706 editor.cursor_shape = CursorShape::Block;
4707 editor.change_selections(None, cx, |s| {
4708 s.select_display_ranges([
4709 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4710 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4711 ]);
4712 });
4713 });
4714
4715 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4716 EditorElement::new(&editor, style)
4717 });
4718 assert_eq!(state.selections.len(), 1);
4719 let local_selections = &state.selections[0].1;
4720 assert_eq!(local_selections.len(), 2);
4721
4722 // moves cursor on excerpt boundary back a line
4723 // and doesn't allow selection to bleed through
4724 assert_eq!(
4725 local_selections[0].range,
4726 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4727 );
4728 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4729 // moves cursor on buffer boundary back two lines
4730 // and doesn't allow selection to bleed through
4731 assert_eq!(
4732 local_selections[1].range,
4733 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4734 );
4735 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4736 }
4737
4738 #[gpui::test]
4739 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4740 init_test(cx, |_| {});
4741
4742 let window = cx.add_window(|cx| {
4743 let buffer = MultiBuffer::build_simple("", cx);
4744 Editor::new(EditorMode::Full, buffer, None, cx)
4745 });
4746 let cx = &mut VisualTestContext::from_window(*window, cx);
4747 let editor = window.root(cx).unwrap();
4748 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4749 window
4750 .update(cx, |editor, cx| {
4751 editor.set_placeholder_text("hello", cx);
4752 editor.insert_blocks(
4753 [BlockProperties {
4754 style: BlockStyle::Fixed,
4755 disposition: BlockDisposition::Above,
4756 height: 3,
4757 position: Anchor::min(),
4758 render: Box::new(|_| div().into_any()),
4759 }],
4760 None,
4761 cx,
4762 );
4763
4764 // Blur the editor so that it displays placeholder text.
4765 cx.blur();
4766 })
4767 .unwrap();
4768
4769 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4770 EditorElement::new(&editor, style)
4771 });
4772 assert_eq!(state.position_map.line_layouts.len(), 4);
4773 assert_eq!(
4774 state
4775 .line_numbers
4776 .iter()
4777 .map(Option::is_some)
4778 .collect::<Vec<_>>(),
4779 &[false, false, false, true]
4780 );
4781 }
4782
4783 #[gpui::test]
4784 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4785 const TAB_SIZE: u32 = 4;
4786
4787 let input_text = "\t \t|\t| a b";
4788 let expected_invisibles = vec![
4789 Invisible::Tab {
4790 line_start_offset: 0,
4791 },
4792 Invisible::Whitespace {
4793 line_offset: TAB_SIZE as usize,
4794 },
4795 Invisible::Tab {
4796 line_start_offset: TAB_SIZE as usize + 1,
4797 },
4798 Invisible::Tab {
4799 line_start_offset: TAB_SIZE as usize * 2 + 1,
4800 },
4801 Invisible::Whitespace {
4802 line_offset: TAB_SIZE as usize * 3 + 1,
4803 },
4804 Invisible::Whitespace {
4805 line_offset: TAB_SIZE as usize * 3 + 3,
4806 },
4807 ];
4808 assert_eq!(
4809 expected_invisibles.len(),
4810 input_text
4811 .chars()
4812 .filter(|initial_char| initial_char.is_whitespace())
4813 .count(),
4814 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4815 );
4816
4817 init_test(cx, |s| {
4818 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4819 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4820 });
4821
4822 let actual_invisibles =
4823 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4824
4825 assert_eq!(expected_invisibles, actual_invisibles);
4826 }
4827
4828 #[gpui::test]
4829 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4830 init_test(cx, |s| {
4831 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4832 s.defaults.tab_size = NonZeroU32::new(4);
4833 });
4834
4835 for editor_mode_without_invisibles in [
4836 EditorMode::SingleLine,
4837 EditorMode::AutoHeight { max_lines: 100 },
4838 ] {
4839 let invisibles = collect_invisibles_from_new_editor(
4840 cx,
4841 editor_mode_without_invisibles,
4842 "\t\t\t| | a b",
4843 px(500.0),
4844 );
4845 assert!(invisibles.is_empty(),
4846 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4847 }
4848 }
4849
4850 #[gpui::test]
4851 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4852 let tab_size = 4;
4853 let input_text = "a\tbcd ".repeat(9);
4854 let repeated_invisibles = [
4855 Invisible::Tab {
4856 line_start_offset: 1,
4857 },
4858 Invisible::Whitespace {
4859 line_offset: tab_size as usize + 3,
4860 },
4861 Invisible::Whitespace {
4862 line_offset: tab_size as usize + 4,
4863 },
4864 Invisible::Whitespace {
4865 line_offset: tab_size as usize + 5,
4866 },
4867 ];
4868 let expected_invisibles = std::iter::once(repeated_invisibles)
4869 .cycle()
4870 .take(9)
4871 .flatten()
4872 .collect::<Vec<_>>();
4873 assert_eq!(
4874 expected_invisibles.len(),
4875 input_text
4876 .chars()
4877 .filter(|initial_char| initial_char.is_whitespace())
4878 .count(),
4879 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4880 );
4881 info!("Expected invisibles: {expected_invisibles:?}");
4882
4883 init_test(cx, |_| {});
4884
4885 // Put the same string with repeating whitespace pattern into editors of various size,
4886 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4887 let resize_step = 10.0;
4888 let mut editor_width = 200.0;
4889 while editor_width <= 1000.0 {
4890 update_test_language_settings(cx, |s| {
4891 s.defaults.tab_size = NonZeroU32::new(tab_size);
4892 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4893 s.defaults.preferred_line_length = Some(editor_width as u32);
4894 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4895 });
4896
4897 let actual_invisibles = collect_invisibles_from_new_editor(
4898 cx,
4899 EditorMode::Full,
4900 &input_text,
4901 px(editor_width),
4902 );
4903
4904 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4905 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4906 let mut i = 0;
4907 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4908 i = actual_index;
4909 match expected_invisibles.get(i) {
4910 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4911 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4912 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4913 _ => {
4914 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4915 }
4916 },
4917 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4918 }
4919 }
4920 let missing_expected_invisibles = &expected_invisibles[i + 1..];
4921 assert!(
4922 missing_expected_invisibles.is_empty(),
4923 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4924 );
4925
4926 editor_width += resize_step;
4927 }
4928 }
4929
4930 fn collect_invisibles_from_new_editor(
4931 cx: &mut TestAppContext,
4932 editor_mode: EditorMode,
4933 input_text: &str,
4934 editor_width: Pixels,
4935 ) -> Vec<Invisible> {
4936 info!(
4937 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4938 editor_width.0
4939 );
4940 let window = cx.add_window(|cx| {
4941 let buffer = MultiBuffer::build_simple(&input_text, cx);
4942 Editor::new(editor_mode, buffer, None, cx)
4943 });
4944 let cx = &mut VisualTestContext::from_window(*window, cx);
4945 let editor = window.root(cx).unwrap();
4946 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4947 window
4948 .update(cx, |editor, cx| {
4949 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4950 editor.set_wrap_width(Some(editor_width), cx);
4951 })
4952 .unwrap();
4953 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4954 EditorElement::new(&editor, style)
4955 });
4956 state
4957 .position_map
4958 .line_layouts
4959 .iter()
4960 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4961 .cloned()
4962 .collect()
4963 }
4964}
4965
4966pub fn register_action<T: Action>(
4967 view: &View<Editor>,
4968 cx: &mut WindowContext,
4969 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4970) {
4971 let view = view.clone();
4972 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4973 let action = action.downcast_ref().unwrap();
4974 if phase == DispatchPhase::Bubble {
4975 view.update(cx, |editor, cx| {
4976 listener(editor, action, cx);
4977 })
4978 }
4979 })
4980}
4981
4982fn compute_auto_height_layout(
4983 editor: &mut Editor,
4984 max_lines: usize,
4985 max_line_number_width: Pixels,
4986 known_dimensions: Size<Option<Pixels>>,
4987 cx: &mut ViewContext<Editor>,
4988) -> Option<Size<Pixels>> {
4989 let width = known_dimensions.width?;
4990 if let Some(height) = known_dimensions.height {
4991 return Some(size(width, height));
4992 }
4993
4994 let style = editor.style.as_ref().unwrap();
4995 let font_id = cx.text_system().resolve_font(&style.text.font());
4996 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4997 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4998 let em_width = cx
4999 .text_system()
5000 .typographic_bounds(font_id, font_size, 'm')
5001 .unwrap()
5002 .size
5003 .width;
5004
5005 let mut snapshot = editor.snapshot(cx);
5006 let gutter_dimensions =
5007 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5008
5009 editor.gutter_width = gutter_dimensions.width;
5010 let text_width = width - gutter_dimensions.width;
5011 let overscroll = size(em_width, px(0.));
5012
5013 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5014 if editor.set_wrap_width(Some(editor_width), cx) {
5015 snapshot = editor.snapshot(cx);
5016 }
5017
5018 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5019 let height = scroll_height
5020 .max(line_height)
5021 .min(line_height * max_lines as f32);
5022
5023 Some(size(width, height))
5024}