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