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