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 display_point: 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(display_point) = display_point else {
2653 return;
2654 };
2655
2656 let Some(cursor_row_layout) =
2657 line_layouts.get(display_point.row().minus(start_row) as usize)
2658 else {
2659 return;
2660 };
2661
2662 let start_x = cursor_row_layout.x_for_index(display_point.column() as usize)
2663 - scroll_pixel_position.x
2664 + content_origin.x;
2665 let start_y =
2666 display_point.row().as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
2667
2668 let max_size = size(
2669 (120. * em_width) // Default size
2670 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2671 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2672 (16. * line_height) // Default size
2673 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2674 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2675 );
2676
2677 let maybe_element = self.editor.update(cx, |editor, cx| {
2678 if let Some(popover) = editor.signature_help_state.popover_mut() {
2679 let element = popover.render(
2680 &self.style,
2681 max_size,
2682 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2683 cx,
2684 );
2685 Some(element)
2686 } else {
2687 None
2688 }
2689 });
2690 if let Some(mut element) = maybe_element {
2691 let window_size = cx.viewport_size();
2692 let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
2693 let mut point = point(start_x, start_y - size.height);
2694
2695 // Adjusting to ensure the popover does not overflow in the X-axis direction.
2696 if point.x + size.width >= window_size.width {
2697 point.x = window_size.width - size.width;
2698 }
2699
2700 cx.defer_draw(element, point, 1)
2701 }
2702 }
2703
2704 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2705 cx.paint_layer(layout.hitbox.bounds, |cx| {
2706 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2707 let gutter_bg = cx.theme().colors().editor_gutter_background;
2708 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2709 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2710
2711 if let EditorMode::Full = layout.mode {
2712 let mut active_rows = layout.active_rows.iter().peekable();
2713 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2714 let mut end_row = start_row.0;
2715 while active_rows
2716 .peek()
2717 .map_or(false, |(active_row, has_selection)| {
2718 active_row.0 == end_row + 1
2719 && *has_selection == contains_non_empty_selection
2720 })
2721 {
2722 active_rows.next().unwrap();
2723 end_row += 1;
2724 }
2725
2726 if !contains_non_empty_selection {
2727 let highlight_h_range =
2728 match layout.position_map.snapshot.current_line_highlight {
2729 CurrentLineHighlight::Gutter => Some(Range {
2730 start: layout.hitbox.left(),
2731 end: layout.gutter_hitbox.right(),
2732 }),
2733 CurrentLineHighlight::Line => Some(Range {
2734 start: layout.text_hitbox.bounds.left(),
2735 end: layout.text_hitbox.bounds.right(),
2736 }),
2737 CurrentLineHighlight::All => Some(Range {
2738 start: layout.hitbox.left(),
2739 end: layout.hitbox.right(),
2740 }),
2741 CurrentLineHighlight::None => None,
2742 };
2743 if let Some(range) = highlight_h_range {
2744 let active_line_bg = cx.theme().colors().editor_active_line_background;
2745 let bounds = Bounds {
2746 origin: point(
2747 range.start,
2748 layout.hitbox.origin.y
2749 + (start_row.as_f32() - scroll_top)
2750 * layout.position_map.line_height,
2751 ),
2752 size: size(
2753 range.end - range.start,
2754 layout.position_map.line_height
2755 * (end_row - start_row.0 + 1) as f32,
2756 ),
2757 };
2758 cx.paint_quad(fill(bounds, active_line_bg));
2759 }
2760 }
2761 }
2762
2763 let mut paint_highlight =
2764 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
2765 let origin = point(
2766 layout.hitbox.origin.x,
2767 layout.hitbox.origin.y
2768 + (highlight_row_start.as_f32() - scroll_top)
2769 * layout.position_map.line_height,
2770 );
2771 let size = size(
2772 layout.hitbox.size.width,
2773 layout.position_map.line_height
2774 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
2775 );
2776 cx.paint_quad(fill(Bounds { origin, size }, color));
2777 };
2778
2779 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
2780 for (&new_row, &new_color) in &layout.highlighted_rows {
2781 match &mut current_paint {
2782 Some((current_color, current_range)) => {
2783 let current_color = *current_color;
2784 let new_range_started = current_color != new_color
2785 || current_range.end.next_row() != new_row;
2786 if new_range_started {
2787 paint_highlight(
2788 current_range.start,
2789 current_range.end,
2790 current_color,
2791 );
2792 current_paint = Some((new_color, new_row..new_row));
2793 continue;
2794 } else {
2795 current_range.end = current_range.end.next_row();
2796 }
2797 }
2798 None => current_paint = Some((new_color, new_row..new_row)),
2799 };
2800 }
2801 if let Some((color, range)) = current_paint {
2802 paint_highlight(range.start, range.end, color);
2803 }
2804
2805 let scroll_left =
2806 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2807
2808 for (wrap_position, active) in layout.wrap_guides.iter() {
2809 let x = (layout.text_hitbox.origin.x
2810 + *wrap_position
2811 + layout.position_map.em_width / 2.)
2812 - scroll_left;
2813
2814 let show_scrollbars = layout
2815 .scrollbar_layout
2816 .as_ref()
2817 .map_or(false, |scrollbar| scrollbar.visible);
2818 if x < layout.text_hitbox.origin.x
2819 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2820 {
2821 continue;
2822 }
2823
2824 let color = if *active {
2825 cx.theme().colors().editor_active_wrap_guide
2826 } else {
2827 cx.theme().colors().editor_wrap_guide
2828 };
2829 cx.paint_quad(fill(
2830 Bounds {
2831 origin: point(x, layout.text_hitbox.origin.y),
2832 size: size(px(1.), layout.text_hitbox.size.height),
2833 },
2834 color,
2835 ));
2836 }
2837 }
2838 })
2839 }
2840
2841 fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2842 let Some(indent_guides) = &layout.indent_guides else {
2843 return;
2844 };
2845
2846 let faded_color = |color: Hsla, alpha: f32| {
2847 let mut faded = color;
2848 faded.a = alpha;
2849 faded
2850 };
2851
2852 for indent_guide in indent_guides {
2853 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
2854 let settings = indent_guide.settings;
2855
2856 // TODO fixed for now, expose them through themes later
2857 const INDENT_AWARE_ALPHA: f32 = 0.2;
2858 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
2859 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
2860 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
2861
2862 let line_color = match (settings.coloring, indent_guide.active) {
2863 (IndentGuideColoring::Disabled, _) => None,
2864 (IndentGuideColoring::Fixed, false) => {
2865 Some(cx.theme().colors().editor_indent_guide)
2866 }
2867 (IndentGuideColoring::Fixed, true) => {
2868 Some(cx.theme().colors().editor_indent_guide_active)
2869 }
2870 (IndentGuideColoring::IndentAware, false) => {
2871 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
2872 }
2873 (IndentGuideColoring::IndentAware, true) => {
2874 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
2875 }
2876 };
2877
2878 let background_color = match (settings.background_coloring, indent_guide.active) {
2879 (IndentGuideBackgroundColoring::Disabled, _) => None,
2880 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
2881 indent_accent_colors,
2882 INDENT_AWARE_BACKGROUND_ALPHA,
2883 )),
2884 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
2885 indent_accent_colors,
2886 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
2887 )),
2888 };
2889
2890 let requested_line_width = if indent_guide.active {
2891 settings.active_line_width
2892 } else {
2893 settings.line_width
2894 }
2895 .clamp(1, 10);
2896 let mut line_indicator_width = 0.;
2897 if let Some(color) = line_color {
2898 cx.paint_quad(fill(
2899 Bounds {
2900 origin: indent_guide.origin,
2901 size: size(px(requested_line_width as f32), indent_guide.length),
2902 },
2903 color,
2904 ));
2905 line_indicator_width = requested_line_width as f32;
2906 }
2907
2908 if let Some(color) = background_color {
2909 let width = indent_guide.single_indent_width - px(line_indicator_width);
2910 cx.paint_quad(fill(
2911 Bounds {
2912 origin: point(
2913 indent_guide.origin.x + px(line_indicator_width),
2914 indent_guide.origin.y,
2915 ),
2916 size: size(width, indent_guide.length),
2917 },
2918 color,
2919 ));
2920 }
2921 }
2922 }
2923
2924 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2925 let line_height = layout.position_map.line_height;
2926 let scroll_position = layout.position_map.snapshot.scroll_position();
2927 let scroll_top = scroll_position.y * line_height;
2928
2929 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2930
2931 for (ix, line) in layout.line_numbers.iter().enumerate() {
2932 if let Some(line) = line {
2933 let line_origin = layout.gutter_hitbox.origin
2934 + point(
2935 layout.gutter_hitbox.size.width
2936 - line.width
2937 - layout.gutter_dimensions.right_padding,
2938 ix as f32 * line_height - (scroll_top % line_height),
2939 );
2940
2941 line.paint(line_origin, line_height, cx).log_err();
2942 }
2943 }
2944 }
2945
2946 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2947 if layout.display_hunks.is_empty() {
2948 return;
2949 }
2950
2951 let line_height = layout.position_map.line_height;
2952 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2953 for (hunk, hitbox) in &layout.display_hunks {
2954 let hunk_to_paint = match hunk {
2955 DisplayDiffHunk::Folded { .. } => {
2956 let hunk_bounds = Self::diff_hunk_bounds(
2957 &layout.position_map.snapshot,
2958 line_height,
2959 layout.gutter_hitbox.bounds,
2960 &hunk,
2961 );
2962 Some((
2963 hunk_bounds,
2964 cx.theme().status().modified,
2965 Corners::all(1. * line_height),
2966 ))
2967 }
2968 DisplayDiffHunk::Unfolded { status, .. } => {
2969 hitbox.as_ref().map(|hunk_hitbox| match status {
2970 DiffHunkStatus::Added => (
2971 hunk_hitbox.bounds,
2972 cx.theme().status().created,
2973 Corners::all(0.05 * line_height),
2974 ),
2975 DiffHunkStatus::Modified => (
2976 hunk_hitbox.bounds,
2977 cx.theme().status().modified,
2978 Corners::all(0.05 * line_height),
2979 ),
2980 DiffHunkStatus::Removed => (
2981 Bounds::new(
2982 point(
2983 hunk_hitbox.origin.x - hunk_hitbox.size.width,
2984 hunk_hitbox.origin.y,
2985 ),
2986 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
2987 ),
2988 cx.theme().status().deleted,
2989 Corners::all(1. * line_height),
2990 ),
2991 })
2992 }
2993 };
2994
2995 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2996 cx.paint_quad(quad(
2997 hunk_bounds,
2998 corner_radii,
2999 background_color,
3000 Edges::default(),
3001 transparent_black(),
3002 ));
3003 }
3004 }
3005 });
3006 }
3007
3008 fn diff_hunk_bounds(
3009 snapshot: &EditorSnapshot,
3010 line_height: Pixels,
3011 bounds: Bounds<Pixels>,
3012 hunk: &DisplayDiffHunk,
3013 ) -> Bounds<Pixels> {
3014 let scroll_position = snapshot.scroll_position();
3015 let scroll_top = scroll_position.y * line_height;
3016
3017 match hunk {
3018 DisplayDiffHunk::Folded { display_row, .. } => {
3019 let start_y = display_row.as_f32() * line_height - scroll_top;
3020 let end_y = start_y + line_height;
3021
3022 let width = 0.275 * line_height;
3023 let highlight_origin = bounds.origin + point(px(0.), start_y);
3024 let highlight_size = size(width, end_y - start_y);
3025 Bounds::new(highlight_origin, highlight_size)
3026 }
3027 DisplayDiffHunk::Unfolded {
3028 display_row_range,
3029 status,
3030 ..
3031 } => match status {
3032 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3033 let start_row = display_row_range.start;
3034 let end_row = display_row_range.end;
3035 // If we're in a multibuffer, row range span might include an
3036 // excerpt header, so if we were to draw the marker straight away,
3037 // the hunk might include the rows of that header.
3038 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3039 // Instead, we simply check whether the range we're dealing with includes
3040 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3041 let end_row_in_current_excerpt = snapshot
3042 .blocks_in_range(start_row..end_row)
3043 .find_map(|(start_row, block)| {
3044 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
3045 Some(start_row)
3046 } else {
3047 None
3048 }
3049 })
3050 .unwrap_or(end_row);
3051
3052 let start_y = start_row.as_f32() * line_height - scroll_top;
3053 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3054
3055 let width = 0.275 * line_height;
3056 let highlight_origin = bounds.origin + point(px(0.), start_y);
3057 let highlight_size = size(width, end_y - start_y);
3058 Bounds::new(highlight_origin, highlight_size)
3059 }
3060 DiffHunkStatus::Removed => {
3061 let row = display_row_range.start;
3062
3063 let offset = line_height / 2.;
3064 let start_y = row.as_f32() * line_height - offset - scroll_top;
3065 let end_y = start_y + line_height;
3066
3067 let width = 0.35 * line_height;
3068 let highlight_origin = bounds.origin + point(px(0.), start_y);
3069 let highlight_size = size(width, end_y - start_y);
3070 Bounds::new(highlight_origin, highlight_size)
3071 }
3072 },
3073 }
3074 }
3075
3076 fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3077 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3078 cx.with_element_namespace("gutter_fold_toggles", |cx| {
3079 for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
3080 fold_indicator.paint(cx);
3081 }
3082 });
3083
3084 for test_indicators in layout.test_indicators.iter_mut() {
3085 test_indicators.paint(cx);
3086 }
3087
3088 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3089 indicator.paint(cx);
3090 }
3091 });
3092 }
3093
3094 fn paint_gutter_highlights(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3095 for (_, hunk_hitbox) in &layout.display_hunks {
3096 if let Some(hunk_hitbox) = hunk_hitbox {
3097 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3098 }
3099 }
3100
3101 let show_git_gutter = layout
3102 .position_map
3103 .snapshot
3104 .show_git_diff_gutter
3105 .unwrap_or_else(|| {
3106 matches!(
3107 ProjectSettings::get_global(cx).git.git_gutter,
3108 Some(GitGutterSetting::TrackedFiles)
3109 )
3110 });
3111 if show_git_gutter {
3112 Self::paint_diff_hunks(layout, cx)
3113 }
3114
3115 let highlight_width = 0.275 * layout.position_map.line_height;
3116 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3117 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3118 for (range, color) in &layout.highlighted_gutter_ranges {
3119 let start_row = if range.start.row() < layout.visible_display_row_range.start {
3120 layout.visible_display_row_range.start - DisplayRow(1)
3121 } else {
3122 range.start.row()
3123 };
3124 let end_row = if range.end.row() > layout.visible_display_row_range.end {
3125 layout.visible_display_row_range.end + DisplayRow(1)
3126 } else {
3127 range.end.row()
3128 };
3129
3130 let start_y = layout.gutter_hitbox.top()
3131 + start_row.0 as f32 * layout.position_map.line_height
3132 - layout.position_map.scroll_pixel_position.y;
3133 let end_y = layout.gutter_hitbox.top()
3134 + (end_row.0 + 1) as f32 * layout.position_map.line_height
3135 - layout.position_map.scroll_pixel_position.y;
3136 let bounds = Bounds::from_corners(
3137 point(layout.gutter_hitbox.left(), start_y),
3138 point(layout.gutter_hitbox.left() + highlight_width, end_y),
3139 );
3140 cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3141 }
3142 });
3143 }
3144
3145 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3146 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3147 return;
3148 };
3149
3150 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3151 for mut blame_element in blamed_display_rows.into_iter() {
3152 blame_element.paint(cx);
3153 }
3154 })
3155 }
3156
3157 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3158 cx.with_content_mask(
3159 Some(ContentMask {
3160 bounds: layout.text_hitbox.bounds,
3161 }),
3162 |cx| {
3163 let cursor_style = if self
3164 .editor
3165 .read(cx)
3166 .hovered_link_state
3167 .as_ref()
3168 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3169 {
3170 CursorStyle::PointingHand
3171 } else {
3172 CursorStyle::IBeam
3173 };
3174 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3175
3176 let invisible_display_ranges = self.paint_highlights(layout, cx);
3177 self.paint_lines(&invisible_display_ranges, layout, cx);
3178 self.paint_redactions(layout, cx);
3179 self.paint_cursors(layout, cx);
3180 self.paint_inline_blame(layout, cx);
3181 cx.with_element_namespace("crease_trailers", |cx| {
3182 for trailer in layout.crease_trailers.iter_mut().flatten() {
3183 trailer.element.paint(cx);
3184 }
3185 });
3186 },
3187 )
3188 }
3189
3190 fn paint_highlights(
3191 &mut self,
3192 layout: &mut EditorLayout,
3193 cx: &mut WindowContext,
3194 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3195 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3196 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3197 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3198 for (range, color) in &layout.highlighted_ranges {
3199 self.paint_highlighted_range(
3200 range.clone(),
3201 *color,
3202 Pixels::ZERO,
3203 line_end_overshoot,
3204 layout,
3205 cx,
3206 );
3207 }
3208
3209 let corner_radius = 0.15 * layout.position_map.line_height;
3210
3211 for (player_color, selections) in &layout.selections {
3212 for selection in selections.into_iter() {
3213 self.paint_highlighted_range(
3214 selection.range.clone(),
3215 player_color.selection,
3216 corner_radius,
3217 corner_radius * 2.,
3218 layout,
3219 cx,
3220 );
3221
3222 if selection.is_local && !selection.range.is_empty() {
3223 invisible_display_ranges.push(selection.range.clone());
3224 }
3225 }
3226 }
3227 invisible_display_ranges
3228 })
3229 }
3230
3231 fn paint_lines(
3232 &mut self,
3233 invisible_display_ranges: &[Range<DisplayPoint>],
3234 layout: &mut EditorLayout,
3235 cx: &mut WindowContext,
3236 ) {
3237 let whitespace_setting = self
3238 .editor
3239 .read(cx)
3240 .buffer
3241 .read(cx)
3242 .settings_at(0, cx)
3243 .show_whitespaces;
3244
3245 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3246 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3247 line_with_invisibles.draw(
3248 layout,
3249 row,
3250 layout.content_origin,
3251 whitespace_setting,
3252 invisible_display_ranges,
3253 cx,
3254 )
3255 }
3256
3257 for line_element in &mut layout.line_elements {
3258 line_element.paint(cx);
3259 }
3260 }
3261
3262 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3263 if layout.redacted_ranges.is_empty() {
3264 return;
3265 }
3266
3267 let line_end_overshoot = layout.line_end_overshoot();
3268
3269 // A softer than perfect black
3270 let redaction_color = gpui::rgb(0x0e1111);
3271
3272 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3273 for range in layout.redacted_ranges.iter() {
3274 self.paint_highlighted_range(
3275 range.clone(),
3276 redaction_color.into(),
3277 Pixels::ZERO,
3278 line_end_overshoot,
3279 layout,
3280 cx,
3281 );
3282 }
3283 });
3284 }
3285
3286 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3287 for cursor in &mut layout.visible_cursors {
3288 cursor.paint(layout.content_origin, cx);
3289 }
3290 }
3291
3292 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3293 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3294 return;
3295 };
3296
3297 let thumb_bounds = scrollbar_layout.thumb_bounds();
3298 if scrollbar_layout.visible {
3299 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3300 cx.paint_quad(quad(
3301 scrollbar_layout.hitbox.bounds,
3302 Corners::default(),
3303 cx.theme().colors().scrollbar_track_background,
3304 Edges {
3305 top: Pixels::ZERO,
3306 right: Pixels::ZERO,
3307 bottom: Pixels::ZERO,
3308 left: ScrollbarLayout::BORDER_WIDTH,
3309 },
3310 cx.theme().colors().scrollbar_track_border,
3311 ));
3312
3313 let fast_markers =
3314 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3315 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3316 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3317
3318 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3319 for marker in markers.iter().chain(&fast_markers) {
3320 let mut marker = marker.clone();
3321 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3322 cx.paint_quad(marker);
3323 }
3324
3325 cx.paint_quad(quad(
3326 thumb_bounds,
3327 Corners::default(),
3328 cx.theme().colors().scrollbar_thumb_background,
3329 Edges {
3330 top: Pixels::ZERO,
3331 right: Pixels::ZERO,
3332 bottom: Pixels::ZERO,
3333 left: ScrollbarLayout::BORDER_WIDTH,
3334 },
3335 cx.theme().colors().scrollbar_thumb_border,
3336 ));
3337 });
3338 }
3339
3340 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3341
3342 let row_height = scrollbar_layout.row_height;
3343 let row_range = scrollbar_layout.visible_row_range.clone();
3344
3345 cx.on_mouse_event({
3346 let editor = self.editor.clone();
3347 let hitbox = scrollbar_layout.hitbox.clone();
3348 let mut mouse_position = cx.mouse_position();
3349 move |event: &MouseMoveEvent, phase, cx| {
3350 if phase == DispatchPhase::Capture {
3351 return;
3352 }
3353
3354 editor.update(cx, |editor, cx| {
3355 if event.pressed_button == Some(MouseButton::Left)
3356 && editor.scroll_manager.is_dragging_scrollbar()
3357 {
3358 let y = mouse_position.y;
3359 let new_y = event.position.y;
3360 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3361 let mut position = editor.scroll_position(cx);
3362 position.y += (new_y - y) / row_height;
3363 if position.y < 0.0 {
3364 position.y = 0.0;
3365 }
3366 editor.set_scroll_position(position, cx);
3367 }
3368
3369 cx.stop_propagation();
3370 } else {
3371 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3372 if hitbox.is_hovered(cx) {
3373 editor.scroll_manager.show_scrollbar(cx);
3374 }
3375 }
3376 mouse_position = event.position;
3377 })
3378 }
3379 });
3380
3381 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3382 cx.on_mouse_event({
3383 let editor = self.editor.clone();
3384 move |_: &MouseUpEvent, phase, cx| {
3385 if phase == DispatchPhase::Capture {
3386 return;
3387 }
3388
3389 editor.update(cx, |editor, cx| {
3390 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3391 cx.stop_propagation();
3392 });
3393 }
3394 });
3395 } else {
3396 cx.on_mouse_event({
3397 let editor = self.editor.clone();
3398 let hitbox = scrollbar_layout.hitbox.clone();
3399 move |event: &MouseDownEvent, phase, cx| {
3400 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3401 return;
3402 }
3403
3404 editor.update(cx, |editor, cx| {
3405 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3406
3407 let y = event.position.y;
3408 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3409 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3410 let top_row = center_row
3411 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3412 let mut position = editor.scroll_position(cx);
3413 position.y = top_row as f32;
3414 editor.set_scroll_position(position, cx);
3415 } else {
3416 editor.scroll_manager.show_scrollbar(cx);
3417 }
3418
3419 cx.stop_propagation();
3420 });
3421 }
3422 });
3423 }
3424 }
3425
3426 fn collect_fast_scrollbar_markers(
3427 &self,
3428 layout: &EditorLayout,
3429 scrollbar_layout: &ScrollbarLayout,
3430 cx: &mut WindowContext,
3431 ) -> Vec<PaintQuad> {
3432 const LIMIT: usize = 100;
3433 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3434 return vec![];
3435 }
3436 let cursor_ranges = layout
3437 .cursors
3438 .iter()
3439 .map(|(point, color)| ColoredRange {
3440 start: point.row(),
3441 end: point.row(),
3442 color: *color,
3443 })
3444 .collect_vec();
3445 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3446 }
3447
3448 fn refresh_slow_scrollbar_markers(
3449 &self,
3450 layout: &EditorLayout,
3451 scrollbar_layout: &ScrollbarLayout,
3452 cx: &mut WindowContext,
3453 ) {
3454 self.editor.update(cx, |editor, cx| {
3455 if !editor.is_singleton(cx)
3456 || !editor
3457 .scrollbar_marker_state
3458 .should_refresh(scrollbar_layout.hitbox.size)
3459 {
3460 return;
3461 }
3462
3463 let scrollbar_layout = scrollbar_layout.clone();
3464 let background_highlights = editor.background_highlights.clone();
3465 let snapshot = layout.position_map.snapshot.clone();
3466 let theme = cx.theme().clone();
3467 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3468
3469 editor.scrollbar_marker_state.dirty = false;
3470 editor.scrollbar_marker_state.pending_refresh =
3471 Some(cx.spawn(|editor, mut cx| async move {
3472 let scrollbar_size = scrollbar_layout.hitbox.size;
3473 let scrollbar_markers = cx
3474 .background_executor()
3475 .spawn(async move {
3476 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3477 let mut marker_quads = Vec::new();
3478 if scrollbar_settings.git_diff {
3479 let marker_row_ranges = snapshot
3480 .buffer_snapshot
3481 .git_diff_hunks_in_range(
3482 MultiBufferRow::MIN..MultiBufferRow::MAX,
3483 )
3484 .map(|hunk| {
3485 let start_display_row =
3486 MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3487 .to_display_point(&snapshot.display_snapshot)
3488 .row();
3489 let mut end_display_row =
3490 MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3491 .to_display_point(&snapshot.display_snapshot)
3492 .row();
3493 if end_display_row != start_display_row {
3494 end_display_row.0 -= 1;
3495 }
3496 let color = match hunk_status(&hunk) {
3497 DiffHunkStatus::Added => theme.status().created,
3498 DiffHunkStatus::Modified => theme.status().modified,
3499 DiffHunkStatus::Removed => theme.status().deleted,
3500 };
3501 ColoredRange {
3502 start: start_display_row,
3503 end: end_display_row,
3504 color,
3505 }
3506 });
3507
3508 marker_quads.extend(
3509 scrollbar_layout
3510 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3511 );
3512 }
3513
3514 for (background_highlight_id, (_, background_ranges)) in
3515 background_highlights.iter()
3516 {
3517 let is_search_highlights = *background_highlight_id
3518 == TypeId::of::<BufferSearchHighlights>();
3519 let is_symbol_occurrences = *background_highlight_id
3520 == TypeId::of::<DocumentHighlightRead>()
3521 || *background_highlight_id
3522 == TypeId::of::<DocumentHighlightWrite>();
3523 if (is_search_highlights && scrollbar_settings.search_results)
3524 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3525 {
3526 let mut color = theme.status().info;
3527 if is_symbol_occurrences {
3528 color.fade_out(0.5);
3529 }
3530 let marker_row_ranges =
3531 background_ranges.into_iter().map(|range| {
3532 let display_start = range
3533 .start
3534 .to_display_point(&snapshot.display_snapshot);
3535 let display_end = range
3536 .end
3537 .to_display_point(&snapshot.display_snapshot);
3538 ColoredRange {
3539 start: display_start.row(),
3540 end: display_end.row(),
3541 color,
3542 }
3543 });
3544 marker_quads.extend(
3545 scrollbar_layout
3546 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3547 );
3548 }
3549 }
3550
3551 if scrollbar_settings.diagnostics {
3552 let diagnostics = snapshot
3553 .buffer_snapshot
3554 .diagnostics_in_range::<_, Point>(
3555 Point::zero()..max_point,
3556 false,
3557 )
3558 // We want to sort by severity, in order to paint the most severe diagnostics last.
3559 .sorted_by_key(|diagnostic| {
3560 std::cmp::Reverse(diagnostic.diagnostic.severity)
3561 });
3562
3563 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3564 let start_display = diagnostic
3565 .range
3566 .start
3567 .to_display_point(&snapshot.display_snapshot);
3568 let end_display = diagnostic
3569 .range
3570 .end
3571 .to_display_point(&snapshot.display_snapshot);
3572 let color = match diagnostic.diagnostic.severity {
3573 DiagnosticSeverity::ERROR => theme.status().error,
3574 DiagnosticSeverity::WARNING => theme.status().warning,
3575 DiagnosticSeverity::INFORMATION => theme.status().info,
3576 _ => theme.status().hint,
3577 };
3578 ColoredRange {
3579 start: start_display.row(),
3580 end: end_display.row(),
3581 color,
3582 }
3583 });
3584 marker_quads.extend(
3585 scrollbar_layout
3586 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3587 );
3588 }
3589
3590 Arc::from(marker_quads)
3591 })
3592 .await;
3593
3594 editor.update(&mut cx, |editor, cx| {
3595 editor.scrollbar_marker_state.markers = scrollbar_markers;
3596 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3597 editor.scrollbar_marker_state.pending_refresh = None;
3598 cx.notify();
3599 })?;
3600
3601 Ok(())
3602 }));
3603 });
3604 }
3605
3606 #[allow(clippy::too_many_arguments)]
3607 fn paint_highlighted_range(
3608 &self,
3609 range: Range<DisplayPoint>,
3610 color: Hsla,
3611 corner_radius: Pixels,
3612 line_end_overshoot: Pixels,
3613 layout: &EditorLayout,
3614 cx: &mut WindowContext,
3615 ) {
3616 let start_row = layout.visible_display_row_range.start;
3617 let end_row = layout.visible_display_row_range.end;
3618 if range.start != range.end {
3619 let row_range = if range.end.column() == 0 {
3620 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3621 } else {
3622 cmp::max(range.start.row(), start_row)
3623 ..cmp::min(range.end.row().next_row(), end_row)
3624 };
3625
3626 let highlighted_range = HighlightedRange {
3627 color,
3628 line_height: layout.position_map.line_height,
3629 corner_radius,
3630 start_y: layout.content_origin.y
3631 + row_range.start.as_f32() * layout.position_map.line_height
3632 - layout.position_map.scroll_pixel_position.y,
3633 lines: row_range
3634 .iter_rows()
3635 .map(|row| {
3636 let line_layout =
3637 &layout.position_map.line_layouts[row.minus(start_row) as usize];
3638 HighlightedRangeLine {
3639 start_x: if row == range.start.row() {
3640 layout.content_origin.x
3641 + line_layout.x_for_index(range.start.column() as usize)
3642 - layout.position_map.scroll_pixel_position.x
3643 } else {
3644 layout.content_origin.x
3645 - layout.position_map.scroll_pixel_position.x
3646 },
3647 end_x: if row == range.end.row() {
3648 layout.content_origin.x
3649 + line_layout.x_for_index(range.end.column() as usize)
3650 - layout.position_map.scroll_pixel_position.x
3651 } else {
3652 layout.content_origin.x + line_layout.width + line_end_overshoot
3653 - layout.position_map.scroll_pixel_position.x
3654 },
3655 }
3656 })
3657 .collect(),
3658 };
3659
3660 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3661 }
3662 }
3663
3664 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3665 if let Some(mut inline_blame) = layout.inline_blame.take() {
3666 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3667 inline_blame.paint(cx);
3668 })
3669 }
3670 }
3671
3672 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3673 for mut block in layout.blocks.drain(..) {
3674 block.element.paint(cx);
3675 }
3676 }
3677
3678 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3679 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3680 mouse_context_menu.paint(cx);
3681 }
3682 }
3683
3684 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3685 cx.on_mouse_event({
3686 let position_map = layout.position_map.clone();
3687 let editor = self.editor.clone();
3688 let hitbox = layout.hitbox.clone();
3689 let mut delta = ScrollDelta::default();
3690
3691 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3692 // accidentally turn off their scrolling.
3693 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3694
3695 move |event: &ScrollWheelEvent, phase, cx| {
3696 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3697 delta = delta.coalesce(event.delta);
3698 editor.update(cx, |editor, cx| {
3699 let position_map: &PositionMap = &position_map;
3700
3701 let line_height = position_map.line_height;
3702 let max_glyph_width = position_map.em_width;
3703 let (delta, axis) = match delta {
3704 gpui::ScrollDelta::Pixels(mut pixels) => {
3705 //Trackpad
3706 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3707 (pixels, axis)
3708 }
3709
3710 gpui::ScrollDelta::Lines(lines) => {
3711 //Not trackpad
3712 let pixels =
3713 point(lines.x * max_glyph_width, lines.y * line_height);
3714 (pixels, None)
3715 }
3716 };
3717
3718 let current_scroll_position = position_map.snapshot.scroll_position();
3719 let x = (current_scroll_position.x * max_glyph_width
3720 - (delta.x * scroll_sensitivity))
3721 / max_glyph_width;
3722 let y = (current_scroll_position.y * line_height
3723 - (delta.y * scroll_sensitivity))
3724 / line_height;
3725 let mut scroll_position =
3726 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3727 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3728 if forbid_vertical_scroll {
3729 scroll_position.y = current_scroll_position.y;
3730 }
3731
3732 if scroll_position != current_scroll_position {
3733 editor.scroll(scroll_position, axis, cx);
3734 cx.stop_propagation();
3735 } else if y < 0. {
3736 // Due to clamping, we may fail to detect cases of overscroll to the top;
3737 // We want the scroll manager to get an update in such cases and detect the change of direction
3738 // on the next frame.
3739 cx.notify();
3740 }
3741 });
3742 }
3743 }
3744 });
3745 }
3746
3747 fn paint_mouse_listeners(
3748 &mut self,
3749 layout: &EditorLayout,
3750 hovered_hunk: Option<HunkToExpand>,
3751 cx: &mut WindowContext,
3752 ) {
3753 self.paint_scroll_wheel_listener(layout, cx);
3754
3755 cx.on_mouse_event({
3756 let position_map = layout.position_map.clone();
3757 let editor = self.editor.clone();
3758 let text_hitbox = layout.text_hitbox.clone();
3759 let gutter_hitbox = layout.gutter_hitbox.clone();
3760
3761 move |event: &MouseDownEvent, phase, cx| {
3762 if phase == DispatchPhase::Bubble {
3763 match event.button {
3764 MouseButton::Left => editor.update(cx, |editor, cx| {
3765 Self::mouse_left_down(
3766 editor,
3767 event,
3768 hovered_hunk.as_ref(),
3769 &position_map,
3770 &text_hitbox,
3771 &gutter_hitbox,
3772 cx,
3773 );
3774 }),
3775 MouseButton::Right => editor.update(cx, |editor, cx| {
3776 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3777 }),
3778 MouseButton::Middle => editor.update(cx, |editor, cx| {
3779 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3780 }),
3781 _ => {}
3782 };
3783 }
3784 }
3785 });
3786
3787 cx.on_mouse_event({
3788 let editor = self.editor.clone();
3789 let position_map = layout.position_map.clone();
3790 let text_hitbox = layout.text_hitbox.clone();
3791
3792 move |event: &MouseUpEvent, phase, cx| {
3793 if phase == DispatchPhase::Bubble {
3794 editor.update(cx, |editor, cx| {
3795 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3796 });
3797 }
3798 }
3799 });
3800 cx.on_mouse_event({
3801 let position_map = layout.position_map.clone();
3802 let editor = self.editor.clone();
3803 let text_hitbox = layout.text_hitbox.clone();
3804 let gutter_hitbox = layout.gutter_hitbox.clone();
3805
3806 move |event: &MouseMoveEvent, phase, cx| {
3807 if phase == DispatchPhase::Bubble {
3808 editor.update(cx, |editor, cx| {
3809 if editor.hover_state.focused(cx) {
3810 return;
3811 }
3812 if event.pressed_button == Some(MouseButton::Left)
3813 || event.pressed_button == Some(MouseButton::Middle)
3814 {
3815 Self::mouse_dragged(
3816 editor,
3817 event,
3818 &position_map,
3819 text_hitbox.bounds,
3820 cx,
3821 )
3822 }
3823
3824 Self::mouse_moved(
3825 editor,
3826 event,
3827 &position_map,
3828 &text_hitbox,
3829 &gutter_hitbox,
3830 cx,
3831 )
3832 });
3833 }
3834 }
3835 });
3836 }
3837
3838 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3839 bounds.upper_right().x - self.style.scrollbar_width
3840 }
3841
3842 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3843 let style = &self.style;
3844 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3845 let layout = cx
3846 .text_system()
3847 .shape_line(
3848 SharedString::from(" ".repeat(column)),
3849 font_size,
3850 &[TextRun {
3851 len: column,
3852 font: style.text.font(),
3853 color: Hsla::default(),
3854 background_color: None,
3855 underline: None,
3856 strikethrough: None,
3857 }],
3858 )
3859 .unwrap();
3860
3861 layout.width
3862 }
3863
3864 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3865 let digit_count = snapshot
3866 .max_buffer_row()
3867 .next_row()
3868 .as_f32()
3869 .log10()
3870 .floor() as usize
3871 + 1;
3872 self.column_pixels(digit_count, cx)
3873 }
3874}
3875
3876fn prepaint_gutter_button(
3877 button: IconButton,
3878 row: DisplayRow,
3879 line_height: Pixels,
3880 gutter_dimensions: &GutterDimensions,
3881 scroll_pixel_position: gpui::Point<Pixels>,
3882 gutter_hitbox: &Hitbox,
3883 cx: &mut WindowContext<'_>,
3884) -> AnyElement {
3885 let mut button = button.into_any_element();
3886 let available_space = size(
3887 AvailableSpace::MinContent,
3888 AvailableSpace::Definite(line_height),
3889 );
3890 let indicator_size = button.layout_as_root(available_space, cx);
3891
3892 let blame_width = gutter_dimensions
3893 .git_blame_entries_width
3894 .unwrap_or(Pixels::ZERO);
3895
3896 let mut x = blame_width;
3897 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3898 - indicator_size.width
3899 - blame_width;
3900 x += available_width / 2.;
3901
3902 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3903 y += (line_height - indicator_size.height) / 2.;
3904
3905 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3906 button
3907}
3908
3909fn render_inline_blame_entry(
3910 blame: &gpui::Model<GitBlame>,
3911 blame_entry: BlameEntry,
3912 style: &EditorStyle,
3913 workspace: Option<WeakView<Workspace>>,
3914 cx: &mut WindowContext<'_>,
3915) -> AnyElement {
3916 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3917
3918 let author = blame_entry.author.as_deref().unwrap_or_default();
3919 let text = format!("{}, {}", author, relative_timestamp);
3920
3921 let details = blame.read(cx).details_for_entry(&blame_entry);
3922
3923 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3924
3925 h_flex()
3926 .id("inline-blame")
3927 .w_full()
3928 .font_family(style.text.font().family)
3929 .text_color(cx.theme().status().hint)
3930 .line_height(style.text.line_height)
3931 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3932 .child(text)
3933 .gap_2()
3934 .hoverable_tooltip(move |_| tooltip.clone().into())
3935 .into_any()
3936}
3937
3938fn render_blame_entry(
3939 ix: usize,
3940 blame: &gpui::Model<GitBlame>,
3941 blame_entry: BlameEntry,
3942 style: &EditorStyle,
3943 last_used_color: &mut Option<(PlayerColor, Oid)>,
3944 editor: View<Editor>,
3945 cx: &mut WindowContext<'_>,
3946) -> AnyElement {
3947 let mut sha_color = cx
3948 .theme()
3949 .players()
3950 .color_for_participant(blame_entry.sha.into());
3951 // If the last color we used is the same as the one we get for this line, but
3952 // the commit SHAs are different, then we try again to get a different color.
3953 match *last_used_color {
3954 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3955 let index: u32 = blame_entry.sha.into();
3956 sha_color = cx.theme().players().color_for_participant(index + 1);
3957 }
3958 _ => {}
3959 };
3960 last_used_color.replace((sha_color, blame_entry.sha));
3961
3962 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3963
3964 let short_commit_id = blame_entry.sha.display_short();
3965
3966 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3967 let name = util::truncate_and_trailoff(author_name, 20);
3968
3969 let details = blame.read(cx).details_for_entry(&blame_entry);
3970
3971 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3972
3973 let tooltip = cx.new_view(|_| {
3974 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3975 });
3976
3977 h_flex()
3978 .w_full()
3979 .font_family(style.text.font().family)
3980 .line_height(style.text.line_height)
3981 .id(("blame", ix))
3982 .children([
3983 div()
3984 .text_color(sha_color.cursor)
3985 .child(short_commit_id)
3986 .mr_2(),
3987 div()
3988 .w_full()
3989 .h_flex()
3990 .justify_between()
3991 .text_color(cx.theme().status().hint)
3992 .child(name)
3993 .child(relative_timestamp),
3994 ])
3995 .on_mouse_down(MouseButton::Right, {
3996 let blame_entry = blame_entry.clone();
3997 let details = details.clone();
3998 move |event, cx| {
3999 deploy_blame_entry_context_menu(
4000 &blame_entry,
4001 details.as_ref(),
4002 editor.clone(),
4003 event.position,
4004 cx,
4005 );
4006 }
4007 })
4008 .hover(|style| style.bg(cx.theme().colors().element_hover))
4009 .when_some(
4010 details.and_then(|details| details.permalink),
4011 |this, url| {
4012 let url = url.clone();
4013 this.cursor_pointer().on_click(move |_, cx| {
4014 cx.stop_propagation();
4015 cx.open_url(url.as_str())
4016 })
4017 },
4018 )
4019 .hoverable_tooltip(move |_| tooltip.clone().into())
4020 .into_any()
4021}
4022
4023fn deploy_blame_entry_context_menu(
4024 blame_entry: &BlameEntry,
4025 details: Option<&CommitDetails>,
4026 editor: View<Editor>,
4027 position: gpui::Point<Pixels>,
4028 cx: &mut WindowContext<'_>,
4029) {
4030 let context_menu = ContextMenu::build(cx, move |this, _| {
4031 let sha = format!("{}", blame_entry.sha);
4032 this.entry("Copy commit SHA", None, move |cx| {
4033 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
4034 })
4035 .when_some(
4036 details.and_then(|details| details.permalink.clone()),
4037 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4038 )
4039 });
4040
4041 editor.update(cx, move |editor, cx| {
4042 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
4043 cx.notify();
4044 });
4045}
4046
4047#[derive(Debug)]
4048pub(crate) struct LineWithInvisibles {
4049 fragments: SmallVec<[LineFragment; 1]>,
4050 invisibles: Vec<Invisible>,
4051 len: usize,
4052 width: Pixels,
4053 font_size: Pixels,
4054}
4055
4056#[allow(clippy::large_enum_variant)]
4057enum LineFragment {
4058 Text(ShapedLine),
4059 Element {
4060 element: Option<AnyElement>,
4061 size: Size<Pixels>,
4062 len: usize,
4063 },
4064}
4065
4066impl fmt::Debug for LineFragment {
4067 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4068 match self {
4069 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4070 LineFragment::Element { size, len, .. } => f
4071 .debug_struct("Element")
4072 .field("size", size)
4073 .field("len", len)
4074 .finish(),
4075 }
4076 }
4077}
4078
4079impl LineWithInvisibles {
4080 fn from_chunks<'a>(
4081 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4082 text_style: &TextStyle,
4083 max_line_len: usize,
4084 max_line_count: usize,
4085 line_number_layouts: &[Option<ShapedLine>],
4086 editor_mode: EditorMode,
4087 cx: &mut WindowContext,
4088 ) -> Vec<Self> {
4089 let mut layouts = Vec::with_capacity(max_line_count);
4090 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4091 let mut line = String::new();
4092 let mut invisibles = Vec::new();
4093 let mut width = Pixels::ZERO;
4094 let mut len = 0;
4095 let mut styles = Vec::new();
4096 let mut non_whitespace_added = false;
4097 let mut row = 0;
4098 let mut line_exceeded_max_len = false;
4099 let font_size = text_style.font_size.to_pixels(cx.rem_size());
4100
4101 let ellipsis = SharedString::from("⋯");
4102
4103 for highlighted_chunk in chunks.chain([HighlightedChunk {
4104 text: "\n",
4105 style: None,
4106 is_tab: false,
4107 renderer: None,
4108 }]) {
4109 if let Some(renderer) = highlighted_chunk.renderer {
4110 if !line.is_empty() {
4111 let shaped_line = cx
4112 .text_system()
4113 .shape_line(line.clone().into(), font_size, &styles)
4114 .unwrap();
4115 width += shaped_line.width;
4116 len += shaped_line.len;
4117 fragments.push(LineFragment::Text(shaped_line));
4118 line.clear();
4119 styles.clear();
4120 }
4121
4122 let available_width = if renderer.constrain_width {
4123 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4124 ellipsis.clone()
4125 } else {
4126 SharedString::from(Arc::from(highlighted_chunk.text))
4127 };
4128 let shaped_line = cx
4129 .text_system()
4130 .shape_line(
4131 chunk,
4132 font_size,
4133 &[text_style.to_run(highlighted_chunk.text.len())],
4134 )
4135 .unwrap();
4136 AvailableSpace::Definite(shaped_line.width)
4137 } else {
4138 AvailableSpace::MinContent
4139 };
4140
4141 let mut element = (renderer.render)(cx);
4142 let line_height = text_style.line_height_in_pixels(cx.rem_size());
4143 let size = element.layout_as_root(
4144 size(available_width, AvailableSpace::Definite(line_height)),
4145 cx,
4146 );
4147
4148 width += size.width;
4149 len += highlighted_chunk.text.len();
4150 fragments.push(LineFragment::Element {
4151 element: Some(element),
4152 size,
4153 len: highlighted_chunk.text.len(),
4154 });
4155 } else {
4156 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4157 if ix > 0 {
4158 let shaped_line = cx
4159 .text_system()
4160 .shape_line(line.clone().into(), font_size, &styles)
4161 .unwrap();
4162 width += shaped_line.width;
4163 len += shaped_line.len;
4164 fragments.push(LineFragment::Text(shaped_line));
4165 layouts.push(Self {
4166 width: mem::take(&mut width),
4167 len: mem::take(&mut len),
4168 fragments: mem::take(&mut fragments),
4169 invisibles: std::mem::take(&mut invisibles),
4170 font_size,
4171 });
4172
4173 line.clear();
4174 styles.clear();
4175 row += 1;
4176 line_exceeded_max_len = false;
4177 non_whitespace_added = false;
4178 if row == max_line_count {
4179 return layouts;
4180 }
4181 }
4182
4183 if !line_chunk.is_empty() && !line_exceeded_max_len {
4184 let text_style = if let Some(style) = highlighted_chunk.style {
4185 Cow::Owned(text_style.clone().highlight(style))
4186 } else {
4187 Cow::Borrowed(text_style)
4188 };
4189
4190 if line.len() + line_chunk.len() > max_line_len {
4191 let mut chunk_len = max_line_len - line.len();
4192 while !line_chunk.is_char_boundary(chunk_len) {
4193 chunk_len -= 1;
4194 }
4195 line_chunk = &line_chunk[..chunk_len];
4196 line_exceeded_max_len = true;
4197 }
4198
4199 styles.push(TextRun {
4200 len: line_chunk.len(),
4201 font: text_style.font(),
4202 color: text_style.color,
4203 background_color: text_style.background_color,
4204 underline: text_style.underline,
4205 strikethrough: text_style.strikethrough,
4206 });
4207
4208 if editor_mode == EditorMode::Full {
4209 // Line wrap pads its contents with fake whitespaces,
4210 // avoid printing them
4211 let inside_wrapped_string = line_number_layouts
4212 .get(row)
4213 .and_then(|layout| layout.as_ref())
4214 .is_none();
4215 if highlighted_chunk.is_tab {
4216 if non_whitespace_added || !inside_wrapped_string {
4217 invisibles.push(Invisible::Tab {
4218 line_start_offset: line.len(),
4219 line_end_offset: line.len() + line_chunk.len(),
4220 });
4221 }
4222 } else {
4223 invisibles.extend(
4224 line_chunk
4225 .bytes()
4226 .enumerate()
4227 .filter(|(_, line_byte)| {
4228 let is_whitespace =
4229 (*line_byte as char).is_whitespace();
4230 non_whitespace_added |= !is_whitespace;
4231 is_whitespace
4232 && (non_whitespace_added || !inside_wrapped_string)
4233 })
4234 .map(|(whitespace_index, _)| Invisible::Whitespace {
4235 line_offset: line.len() + whitespace_index,
4236 }),
4237 )
4238 }
4239 }
4240
4241 line.push_str(line_chunk);
4242 }
4243 }
4244 }
4245 }
4246
4247 layouts
4248 }
4249
4250 fn prepaint(
4251 &mut self,
4252 line_height: Pixels,
4253 scroll_pixel_position: gpui::Point<Pixels>,
4254 row: DisplayRow,
4255 content_origin: gpui::Point<Pixels>,
4256 line_elements: &mut SmallVec<[AnyElement; 1]>,
4257 cx: &mut WindowContext,
4258 ) {
4259 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4260 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4261 for fragment in &mut self.fragments {
4262 match fragment {
4263 LineFragment::Text(line) => {
4264 fragment_origin.x += line.width;
4265 }
4266 LineFragment::Element { element, size, .. } => {
4267 let mut element = element
4268 .take()
4269 .expect("you can't prepaint LineWithInvisibles twice");
4270
4271 // Center the element vertically within the line.
4272 let mut element_origin = fragment_origin;
4273 element_origin.y += (line_height - size.height) / 2.;
4274 element.prepaint_at(element_origin, cx);
4275 line_elements.push(element);
4276
4277 fragment_origin.x += size.width;
4278 }
4279 }
4280 }
4281 }
4282
4283 fn draw(
4284 &self,
4285 layout: &EditorLayout,
4286 row: DisplayRow,
4287 content_origin: gpui::Point<Pixels>,
4288 whitespace_setting: ShowWhitespaceSetting,
4289 selection_ranges: &[Range<DisplayPoint>],
4290 cx: &mut WindowContext,
4291 ) {
4292 let line_height = layout.position_map.line_height;
4293 let line_y = line_height
4294 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4295
4296 let mut fragment_origin =
4297 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4298
4299 for fragment in &self.fragments {
4300 match fragment {
4301 LineFragment::Text(line) => {
4302 line.paint(fragment_origin, line_height, cx).log_err();
4303 fragment_origin.x += line.width;
4304 }
4305 LineFragment::Element { size, .. } => {
4306 fragment_origin.x += size.width;
4307 }
4308 }
4309 }
4310
4311 self.draw_invisibles(
4312 &selection_ranges,
4313 layout,
4314 content_origin,
4315 line_y,
4316 row,
4317 line_height,
4318 whitespace_setting,
4319 cx,
4320 );
4321 }
4322
4323 #[allow(clippy::too_many_arguments)]
4324 fn draw_invisibles(
4325 &self,
4326 selection_ranges: &[Range<DisplayPoint>],
4327 layout: &EditorLayout,
4328 content_origin: gpui::Point<Pixels>,
4329 line_y: Pixels,
4330 row: DisplayRow,
4331 line_height: Pixels,
4332 whitespace_setting: ShowWhitespaceSetting,
4333 cx: &mut WindowContext,
4334 ) {
4335 let extract_whitespace_info = |invisible: &Invisible| {
4336 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4337 Invisible::Tab {
4338 line_start_offset,
4339 line_end_offset,
4340 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4341 Invisible::Whitespace { line_offset } => {
4342 (*line_offset, line_offset + 1, &layout.space_invisible)
4343 }
4344 };
4345
4346 let x_offset = self.x_for_index(token_offset);
4347 let invisible_offset =
4348 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4349 let origin = content_origin
4350 + gpui::point(
4351 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4352 line_y,
4353 );
4354
4355 (
4356 [token_offset, token_end_offset],
4357 Box::new(move |cx: &mut WindowContext| {
4358 invisible_symbol.paint(origin, line_height, cx).log_err();
4359 }),
4360 )
4361 };
4362
4363 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4364 match whitespace_setting {
4365 ShowWhitespaceSetting::None => return,
4366 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4367 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4368 let invisible_point = DisplayPoint::new(row, start as u32);
4369 if !selection_ranges
4370 .iter()
4371 .any(|region| region.start <= invisible_point && invisible_point < region.end)
4372 {
4373 return;
4374 }
4375
4376 paint(cx);
4377 }),
4378
4379 // For a whitespace to be on a boundary, any of the following conditions need to be met:
4380 // - It is a tab
4381 // - It is adjacent to an edge (start or end)
4382 // - It is adjacent to a whitespace (left or right)
4383 ShowWhitespaceSetting::Boundary => {
4384 // 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
4385 // the above cases.
4386 // Note: We zip in the original `invisibles` to check for tab equality
4387 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4388 for (([start, end], paint), invisible) in
4389 invisible_iter.zip_eq(self.invisibles.iter())
4390 {
4391 let should_render = match (&last_seen, invisible) {
4392 (_, Invisible::Tab { .. }) => true,
4393 (Some((_, last_end, _)), _) => *last_end == start,
4394 _ => false,
4395 };
4396
4397 if should_render || start == 0 || end == self.len {
4398 paint(cx);
4399
4400 // Since we are scanning from the left, we will skip over the first available whitespace that is part
4401 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4402 if let Some((should_render_last, last_end, paint_last)) = last_seen {
4403 // Note that we need to make sure that the last one is actually adjacent
4404 if !should_render_last && last_end == start {
4405 paint_last(cx);
4406 }
4407 }
4408 }
4409
4410 // Manually render anything within a selection
4411 let invisible_point = DisplayPoint::new(row, start as u32);
4412 if selection_ranges.iter().any(|region| {
4413 region.start <= invisible_point && invisible_point < region.end
4414 }) {
4415 paint(cx);
4416 }
4417
4418 last_seen = Some((should_render, end, paint));
4419 }
4420 }
4421 };
4422 }
4423
4424 pub fn x_for_index(&self, index: usize) -> Pixels {
4425 let mut fragment_start_x = Pixels::ZERO;
4426 let mut fragment_start_index = 0;
4427
4428 for fragment in &self.fragments {
4429 match fragment {
4430 LineFragment::Text(shaped_line) => {
4431 let fragment_end_index = fragment_start_index + shaped_line.len;
4432 if index < fragment_end_index {
4433 return fragment_start_x
4434 + shaped_line.x_for_index(index - fragment_start_index);
4435 }
4436 fragment_start_x += shaped_line.width;
4437 fragment_start_index = fragment_end_index;
4438 }
4439 LineFragment::Element { len, size, .. } => {
4440 let fragment_end_index = fragment_start_index + len;
4441 if index < fragment_end_index {
4442 return fragment_start_x;
4443 }
4444 fragment_start_x += size.width;
4445 fragment_start_index = fragment_end_index;
4446 }
4447 }
4448 }
4449
4450 fragment_start_x
4451 }
4452
4453 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4454 let mut fragment_start_x = Pixels::ZERO;
4455 let mut fragment_start_index = 0;
4456
4457 for fragment in &self.fragments {
4458 match fragment {
4459 LineFragment::Text(shaped_line) => {
4460 let fragment_end_x = fragment_start_x + shaped_line.width;
4461 if x < fragment_end_x {
4462 return Some(
4463 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4464 );
4465 }
4466 fragment_start_x = fragment_end_x;
4467 fragment_start_index += shaped_line.len;
4468 }
4469 LineFragment::Element { len, size, .. } => {
4470 let fragment_end_x = fragment_start_x + size.width;
4471 if x < fragment_end_x {
4472 return Some(fragment_start_index);
4473 }
4474 fragment_start_index += len;
4475 fragment_start_x = fragment_end_x;
4476 }
4477 }
4478 }
4479
4480 None
4481 }
4482
4483 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4484 let mut fragment_start_index = 0;
4485
4486 for fragment in &self.fragments {
4487 match fragment {
4488 LineFragment::Text(shaped_line) => {
4489 let fragment_end_index = fragment_start_index + shaped_line.len;
4490 if index < fragment_end_index {
4491 return shaped_line.font_id_for_index(index - fragment_start_index);
4492 }
4493 fragment_start_index = fragment_end_index;
4494 }
4495 LineFragment::Element { len, .. } => {
4496 let fragment_end_index = fragment_start_index + len;
4497 if index < fragment_end_index {
4498 return None;
4499 }
4500 fragment_start_index = fragment_end_index;
4501 }
4502 }
4503 }
4504
4505 None
4506 }
4507}
4508
4509#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4510enum Invisible {
4511 /// A tab character
4512 ///
4513 /// A tab character is internally represented by spaces (configured by the user's tab width)
4514 /// aligned to the nearest column, so it's necessary to store the start and end offset for
4515 /// adjacency checks.
4516 Tab {
4517 line_start_offset: usize,
4518 line_end_offset: usize,
4519 },
4520 Whitespace {
4521 line_offset: usize,
4522 },
4523}
4524
4525impl EditorElement {
4526 /// Returns the rem size to use when rendering the [`EditorElement`].
4527 ///
4528 /// This allows UI elements to scale based on the `buffer_font_size`.
4529 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4530 match self.editor.read(cx).mode {
4531 EditorMode::Full => {
4532 let buffer_font_size = self.style.text.font_size;
4533 match buffer_font_size {
4534 AbsoluteLength::Pixels(pixels) => {
4535 let rem_size_scale = {
4536 // Our default UI font size is 14px on a 16px base scale.
4537 // This means the default UI font size is 0.875rems.
4538 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4539
4540 // We then determine the delta between a single rem and the default font
4541 // size scale.
4542 let default_font_size_delta = 1. - default_font_size_scale;
4543
4544 // Finally, we add this delta to 1rem to get the scale factor that
4545 // should be used to scale up the UI.
4546 1. + default_font_size_delta
4547 };
4548
4549 Some(pixels * rem_size_scale)
4550 }
4551 AbsoluteLength::Rems(rems) => {
4552 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4553 }
4554 }
4555 }
4556 // We currently use single-line and auto-height editors in UI contexts,
4557 // so we don't want to scale everything with the buffer font size, as it
4558 // ends up looking off.
4559 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
4560 }
4561 }
4562}
4563
4564impl Element for EditorElement {
4565 type RequestLayoutState = ();
4566 type PrepaintState = EditorLayout;
4567
4568 fn id(&self) -> Option<ElementId> {
4569 None
4570 }
4571
4572 fn request_layout(
4573 &mut self,
4574 _: Option<&GlobalElementId>,
4575 cx: &mut WindowContext,
4576 ) -> (gpui::LayoutId, ()) {
4577 let rem_size = self.rem_size(cx);
4578 cx.with_rem_size(rem_size, |cx| {
4579 self.editor.update(cx, |editor, cx| {
4580 editor.set_style(self.style.clone(), cx);
4581
4582 let layout_id = match editor.mode {
4583 EditorMode::SingleLine { auto_width } => {
4584 let rem_size = cx.rem_size();
4585
4586 let height = self.style.text.line_height_in_pixels(rem_size);
4587 if auto_width {
4588 let editor_handle = cx.view().clone();
4589 let style = self.style.clone();
4590 cx.request_measured_layout(Style::default(), move |_, _, cx| {
4591 let editor_snapshot =
4592 editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
4593 let line = Self::layout_lines(
4594 DisplayRow(0)..DisplayRow(1),
4595 &[],
4596 &editor_snapshot,
4597 &style,
4598 cx,
4599 )
4600 .pop()
4601 .unwrap();
4602
4603 let font_id = cx.text_system().resolve_font(&style.text.font());
4604 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4605 let em_width = cx
4606 .text_system()
4607 .typographic_bounds(font_id, font_size, 'm')
4608 .unwrap()
4609 .size
4610 .width;
4611
4612 size(line.width + em_width, height)
4613 })
4614 } else {
4615 let mut style = Style::default();
4616 style.size.height = height.into();
4617 style.size.width = relative(1.).into();
4618 cx.request_layout(style, None)
4619 }
4620 }
4621 EditorMode::AutoHeight { max_lines } => {
4622 let editor_handle = cx.view().clone();
4623 let max_line_number_width =
4624 self.max_line_number_width(&editor.snapshot(cx), cx);
4625 cx.request_measured_layout(
4626 Style::default(),
4627 move |known_dimensions, available_space, cx| {
4628 editor_handle
4629 .update(cx, |editor, cx| {
4630 compute_auto_height_layout(
4631 editor,
4632 max_lines,
4633 max_line_number_width,
4634 known_dimensions,
4635 available_space.width,
4636 cx,
4637 )
4638 })
4639 .unwrap_or_default()
4640 },
4641 )
4642 }
4643 EditorMode::Full => {
4644 let mut style = Style::default();
4645 style.size.width = relative(1.).into();
4646 style.size.height = relative(1.).into();
4647 cx.request_layout(style, None)
4648 }
4649 };
4650
4651 (layout_id, ())
4652 })
4653 })
4654 }
4655
4656 fn prepaint(
4657 &mut self,
4658 _: Option<&GlobalElementId>,
4659 bounds: Bounds<Pixels>,
4660 _: &mut Self::RequestLayoutState,
4661 cx: &mut WindowContext,
4662 ) -> Self::PrepaintState {
4663 let text_style = TextStyleRefinement {
4664 font_size: Some(self.style.text.font_size),
4665 line_height: Some(self.style.text.line_height),
4666 ..Default::default()
4667 };
4668 cx.set_view_id(self.editor.entity_id());
4669
4670 let rem_size = self.rem_size(cx);
4671 cx.with_rem_size(rem_size, |cx| {
4672 cx.with_text_style(Some(text_style), |cx| {
4673 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4674 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4675 let style = self.style.clone();
4676
4677 let font_id = cx.text_system().resolve_font(&style.text.font());
4678 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4679 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4680 let em_width = cx
4681 .text_system()
4682 .typographic_bounds(font_id, font_size, 'm')
4683 .unwrap()
4684 .size
4685 .width;
4686 let em_advance = cx
4687 .text_system()
4688 .advance(font_id, font_size, 'm')
4689 .unwrap()
4690 .width;
4691
4692 let gutter_dimensions = snapshot.gutter_dimensions(
4693 font_id,
4694 font_size,
4695 em_width,
4696 self.max_line_number_width(&snapshot, cx),
4697 cx,
4698 );
4699 let text_width = bounds.size.width - gutter_dimensions.width;
4700
4701 let right_margin = if snapshot.mode == EditorMode::Full {
4702 EditorElement::SCROLLBAR_WIDTH
4703 } else {
4704 px(0.)
4705 };
4706 let overscroll = size(em_width + right_margin, px(0.));
4707
4708 snapshot = self.editor.update(cx, |editor, cx| {
4709 editor.last_bounds = Some(bounds);
4710 editor.gutter_dimensions = gutter_dimensions;
4711 editor.set_visible_line_count(bounds.size.height / line_height, cx);
4712
4713 let editor_width =
4714 text_width - gutter_dimensions.margin - overscroll.width - em_width;
4715 let wrap_width = match editor.soft_wrap_mode(cx) {
4716 SoftWrap::None => None,
4717 SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4718 SoftWrap::EditorWidth => Some(editor_width),
4719 SoftWrap::Column(column) => {
4720 Some(editor_width.min(column as f32 * em_advance))
4721 }
4722 };
4723
4724 if editor.set_wrap_width(wrap_width, cx) {
4725 editor.snapshot(cx)
4726 } else {
4727 snapshot
4728 }
4729 });
4730
4731 let wrap_guides = self
4732 .editor
4733 .read(cx)
4734 .wrap_guides(cx)
4735 .iter()
4736 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4737 .collect::<SmallVec<[_; 2]>>();
4738
4739 let hitbox = cx.insert_hitbox(bounds, false);
4740 let gutter_hitbox = cx.insert_hitbox(
4741 Bounds {
4742 origin: bounds.origin,
4743 size: size(gutter_dimensions.width, bounds.size.height),
4744 },
4745 false,
4746 );
4747 let text_hitbox = cx.insert_hitbox(
4748 Bounds {
4749 origin: gutter_hitbox.upper_right(),
4750 size: size(text_width, bounds.size.height),
4751 },
4752 false,
4753 );
4754 // Offset the content_bounds from the text_bounds by the gutter margin (which
4755 // is roughly half a character wide) to make hit testing work more like how we want.
4756 let content_origin =
4757 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4758
4759 let height_in_lines = bounds.size.height / line_height;
4760 let max_row = snapshot.max_point().row().as_f32();
4761 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
4762 (max_row - height_in_lines + 1.).max(0.)
4763 } else {
4764 let settings = EditorSettings::get_global(cx);
4765 match settings.scroll_beyond_last_line {
4766 ScrollBeyondLastLine::OnePage => max_row,
4767 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
4768 ScrollBeyondLastLine::VerticalScrollMargin => {
4769 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
4770 .max(0.)
4771 }
4772 }
4773 };
4774
4775 let mut autoscroll_containing_element = false;
4776 let mut autoscroll_horizontally = false;
4777 self.editor.update(cx, |editor, cx| {
4778 autoscroll_containing_element =
4779 editor.autoscroll_requested() || editor.has_pending_selection();
4780 autoscroll_horizontally =
4781 editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
4782 snapshot = editor.snapshot(cx);
4783 });
4784
4785 let mut scroll_position = snapshot.scroll_position();
4786 // The scroll position is a fractional point, the whole number of which represents
4787 // the top of the window in terms of display rows.
4788 let start_row = DisplayRow(scroll_position.y as u32);
4789 let max_row = snapshot.max_point().row();
4790 let end_row = cmp::min(
4791 (scroll_position.y + height_in_lines).ceil() as u32,
4792 max_row.next_row().0,
4793 );
4794 let end_row = DisplayRow(end_row);
4795
4796 let buffer_rows = snapshot
4797 .buffer_rows(start_row)
4798 .take((start_row..end_row).len())
4799 .collect::<Vec<_>>();
4800
4801 let start_anchor = if start_row == Default::default() {
4802 Anchor::min()
4803 } else {
4804 snapshot.buffer_snapshot.anchor_before(
4805 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4806 )
4807 };
4808 let end_anchor = if end_row > max_row {
4809 Anchor::max()
4810 } else {
4811 snapshot.buffer_snapshot.anchor_before(
4812 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4813 )
4814 };
4815
4816 let highlighted_rows = self
4817 .editor
4818 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4819 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4820 start_anchor..end_anchor,
4821 &snapshot.display_snapshot,
4822 cx.theme().colors(),
4823 );
4824 let highlighted_gutter_ranges =
4825 self.editor.read(cx).gutter_highlights_in_range(
4826 start_anchor..end_anchor,
4827 &snapshot.display_snapshot,
4828 cx,
4829 );
4830
4831 let redacted_ranges = self.editor.read(cx).redacted_ranges(
4832 start_anchor..end_anchor,
4833 &snapshot.display_snapshot,
4834 cx,
4835 );
4836
4837 let (selections, active_rows, newest_selection_head) = self.layout_selections(
4838 start_anchor,
4839 end_anchor,
4840 &snapshot,
4841 start_row,
4842 end_row,
4843 cx,
4844 );
4845
4846 let line_numbers = self.layout_line_numbers(
4847 start_row..end_row,
4848 buffer_rows.iter().copied(),
4849 &active_rows,
4850 newest_selection_head,
4851 &snapshot,
4852 cx,
4853 );
4854
4855 let mut gutter_fold_toggles =
4856 cx.with_element_namespace("gutter_fold_toggles", |cx| {
4857 self.layout_gutter_fold_toggles(
4858 start_row..end_row,
4859 buffer_rows.iter().copied(),
4860 &active_rows,
4861 &snapshot,
4862 cx,
4863 )
4864 });
4865 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4866 self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4867 });
4868
4869 let display_hunks = self.layout_git_gutters(
4870 line_height,
4871 &gutter_hitbox,
4872 start_row..end_row,
4873 &snapshot,
4874 cx,
4875 );
4876
4877 let mut max_visible_line_width = Pixels::ZERO;
4878 let mut line_layouts = Self::layout_lines(
4879 start_row..end_row,
4880 &line_numbers,
4881 &snapshot,
4882 &self.style,
4883 cx,
4884 );
4885 for line_with_invisibles in &line_layouts {
4886 if line_with_invisibles.width > max_visible_line_width {
4887 max_visible_line_width = line_with_invisibles.width;
4888 }
4889 }
4890
4891 let longest_line_width =
4892 layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4893 let mut scroll_width =
4894 longest_line_width.max(max_visible_line_width) + overscroll.width;
4895
4896 let mut blocks = cx.with_element_namespace("blocks", |cx| {
4897 self.build_blocks(
4898 start_row..end_row,
4899 &snapshot,
4900 &hitbox,
4901 &text_hitbox,
4902 &mut scroll_width,
4903 &gutter_dimensions,
4904 em_width,
4905 gutter_dimensions.full_width(),
4906 line_height,
4907 &line_layouts,
4908 cx,
4909 )
4910 });
4911
4912 let start_buffer_row =
4913 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4914 let end_buffer_row =
4915 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4916
4917 let scroll_max = point(
4918 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4919 max_row.as_f32(),
4920 );
4921
4922 self.editor.update(cx, |editor, cx| {
4923 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4924
4925 let autoscrolled = if autoscroll_horizontally {
4926 editor.autoscroll_horizontally(
4927 start_row,
4928 text_hitbox.size.width,
4929 scroll_width,
4930 em_width,
4931 &line_layouts,
4932 cx,
4933 )
4934 } else {
4935 false
4936 };
4937
4938 if clamped || autoscrolled {
4939 snapshot = editor.snapshot(cx);
4940 scroll_position = snapshot.scroll_position();
4941 }
4942 });
4943
4944 let scroll_pixel_position = point(
4945 scroll_position.x * em_width,
4946 scroll_position.y * line_height,
4947 );
4948
4949 let indent_guides = self.layout_indent_guides(
4950 content_origin,
4951 text_hitbox.origin,
4952 start_buffer_row..end_buffer_row,
4953 scroll_pixel_position,
4954 line_height,
4955 &snapshot,
4956 cx,
4957 );
4958
4959 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4960 self.prepaint_crease_trailers(
4961 crease_trailers,
4962 &line_layouts,
4963 line_height,
4964 content_origin,
4965 scroll_pixel_position,
4966 em_width,
4967 cx,
4968 )
4969 });
4970
4971 let mut inline_blame = None;
4972 if let Some(newest_selection_head) = newest_selection_head {
4973 let display_row = newest_selection_head.row();
4974 if (start_row..end_row).contains(&display_row) {
4975 let line_ix = display_row.minus(start_row) as usize;
4976 let line_layout = &line_layouts[line_ix];
4977 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
4978 inline_blame = self.layout_inline_blame(
4979 display_row,
4980 &snapshot.display_snapshot,
4981 line_layout,
4982 crease_trailer_layout,
4983 em_width,
4984 content_origin,
4985 scroll_pixel_position,
4986 line_height,
4987 cx,
4988 );
4989 }
4990 }
4991
4992 let blamed_display_rows = self.layout_blame_entries(
4993 buffer_rows.into_iter(),
4994 em_width,
4995 scroll_position,
4996 line_height,
4997 &gutter_hitbox,
4998 gutter_dimensions.git_blame_entries_width,
4999 cx,
5000 );
5001
5002 let scroll_max = point(
5003 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5004 max_scroll_top,
5005 );
5006
5007 self.editor.update(cx, |editor, cx| {
5008 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5009
5010 let autoscrolled = if autoscroll_horizontally {
5011 editor.autoscroll_horizontally(
5012 start_row,
5013 text_hitbox.size.width,
5014 scroll_width,
5015 em_width,
5016 &line_layouts,
5017 cx,
5018 )
5019 } else {
5020 false
5021 };
5022
5023 if clamped || autoscrolled {
5024 snapshot = editor.snapshot(cx);
5025 scroll_position = snapshot.scroll_position();
5026 }
5027 });
5028
5029 let line_elements = self.prepaint_lines(
5030 start_row,
5031 &mut line_layouts,
5032 line_height,
5033 scroll_pixel_position,
5034 content_origin,
5035 cx,
5036 );
5037
5038 cx.with_element_namespace("blocks", |cx| {
5039 self.layout_blocks(
5040 &mut blocks,
5041 &hitbox,
5042 line_height,
5043 scroll_pixel_position,
5044 cx,
5045 );
5046 });
5047
5048 let cursors = self.collect_cursors(&snapshot, cx);
5049 let visible_row_range = start_row..end_row;
5050 let non_visible_cursors = cursors
5051 .iter()
5052 .any(move |c| !visible_row_range.contains(&c.0.row()));
5053
5054 let visible_cursors = self.layout_visible_cursors(
5055 &snapshot,
5056 &selections,
5057 start_row..end_row,
5058 &line_layouts,
5059 &text_hitbox,
5060 content_origin,
5061 scroll_position,
5062 scroll_pixel_position,
5063 line_height,
5064 em_width,
5065 autoscroll_containing_element,
5066 cx,
5067 );
5068
5069 let scrollbar_layout = self.layout_scrollbar(
5070 &snapshot,
5071 bounds,
5072 scroll_position,
5073 height_in_lines,
5074 non_visible_cursors,
5075 cx,
5076 );
5077
5078 let gutter_settings = EditorSettings::get_global(cx).gutter;
5079
5080 let mut _context_menu_visible = false;
5081 let mut code_actions_indicator = None;
5082 if let Some(newest_selection_head) = newest_selection_head {
5083 if (start_row..end_row).contains(&newest_selection_head.row()) {
5084 _context_menu_visible = self.layout_context_menu(
5085 line_height,
5086 &hitbox,
5087 &text_hitbox,
5088 content_origin,
5089 start_row,
5090 scroll_pixel_position,
5091 &line_layouts,
5092 newest_selection_head,
5093 gutter_dimensions.width - gutter_dimensions.left_padding,
5094 cx,
5095 );
5096
5097 let show_code_actions = snapshot
5098 .show_code_actions
5099 .unwrap_or_else(|| gutter_settings.code_actions);
5100 if show_code_actions {
5101 let newest_selection_point =
5102 newest_selection_head.to_point(&snapshot.display_snapshot);
5103 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5104 MultiBufferRow(newest_selection_point.row),
5105 );
5106 if let Some((buffer, range)) = buffer {
5107 let buffer_id = buffer.remote_id();
5108 let row = range.start.row;
5109 let has_test_indicator =
5110 self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
5111
5112 if !has_test_indicator {
5113 code_actions_indicator = self
5114 .layout_code_actions_indicator(
5115 line_height,
5116 newest_selection_head,
5117 scroll_pixel_position,
5118 &gutter_dimensions,
5119 &gutter_hitbox,
5120 cx,
5121 );
5122 }
5123 }
5124 }
5125 }
5126 }
5127
5128 let test_indicators = if gutter_settings.runnables {
5129 self.layout_run_indicators(
5130 line_height,
5131 scroll_pixel_position,
5132 &gutter_dimensions,
5133 &gutter_hitbox,
5134 &snapshot,
5135 cx,
5136 )
5137 } else {
5138 vec![]
5139 };
5140
5141 self.layout_signature_help(
5142 &hitbox,
5143 content_origin,
5144 scroll_pixel_position,
5145 newest_selection_head,
5146 start_row,
5147 &line_layouts,
5148 line_height,
5149 em_width,
5150 cx,
5151 );
5152
5153 if !cx.has_active_drag() {
5154 self.layout_hover_popovers(
5155 &snapshot,
5156 &hitbox,
5157 &text_hitbox,
5158 start_row..end_row,
5159 content_origin,
5160 scroll_pixel_position,
5161 &line_layouts,
5162 line_height,
5163 em_width,
5164 cx,
5165 );
5166 }
5167
5168 let mouse_context_menu = self.layout_mouse_context_menu(cx);
5169
5170 cx.with_element_namespace("gutter_fold_toggles", |cx| {
5171 self.prepaint_gutter_fold_toggles(
5172 &mut gutter_fold_toggles,
5173 line_height,
5174 &gutter_dimensions,
5175 gutter_settings,
5176 scroll_pixel_position,
5177 &gutter_hitbox,
5178 cx,
5179 )
5180 });
5181
5182 let invisible_symbol_font_size = font_size / 2.;
5183 let tab_invisible = cx
5184 .text_system()
5185 .shape_line(
5186 "→".into(),
5187 invisible_symbol_font_size,
5188 &[TextRun {
5189 len: "→".len(),
5190 font: self.style.text.font(),
5191 color: cx.theme().colors().editor_invisible,
5192 background_color: None,
5193 underline: None,
5194 strikethrough: None,
5195 }],
5196 )
5197 .unwrap();
5198 let space_invisible = cx
5199 .text_system()
5200 .shape_line(
5201 "•".into(),
5202 invisible_symbol_font_size,
5203 &[TextRun {
5204 len: "•".len(),
5205 font: self.style.text.font(),
5206 color: cx.theme().colors().editor_invisible,
5207 background_color: None,
5208 underline: None,
5209 strikethrough: None,
5210 }],
5211 )
5212 .unwrap();
5213
5214 EditorLayout {
5215 mode: snapshot.mode,
5216 position_map: Arc::new(PositionMap {
5217 size: bounds.size,
5218 scroll_pixel_position,
5219 scroll_max,
5220 line_layouts,
5221 line_height,
5222 em_width,
5223 em_advance,
5224 snapshot,
5225 }),
5226 visible_display_row_range: start_row..end_row,
5227 wrap_guides,
5228 indent_guides,
5229 hitbox,
5230 text_hitbox,
5231 gutter_hitbox,
5232 gutter_dimensions,
5233 content_origin,
5234 scrollbar_layout,
5235 active_rows,
5236 highlighted_rows,
5237 highlighted_ranges,
5238 highlighted_gutter_ranges,
5239 redacted_ranges,
5240 line_elements,
5241 line_numbers,
5242 display_hunks,
5243 blamed_display_rows,
5244 inline_blame,
5245 blocks,
5246 cursors,
5247 visible_cursors,
5248 selections,
5249 mouse_context_menu,
5250 test_indicators,
5251 code_actions_indicator,
5252 gutter_fold_toggles,
5253 crease_trailers,
5254 tab_invisible,
5255 space_invisible,
5256 }
5257 })
5258 })
5259 })
5260 }
5261
5262 fn paint(
5263 &mut self,
5264 _: Option<&GlobalElementId>,
5265 bounds: Bounds<gpui::Pixels>,
5266 _: &mut Self::RequestLayoutState,
5267 layout: &mut Self::PrepaintState,
5268 cx: &mut WindowContext,
5269 ) {
5270 let focus_handle = self.editor.focus_handle(cx);
5271 let key_context = self.editor.read(cx).key_context(cx);
5272 cx.set_focus_handle(&focus_handle);
5273 cx.set_key_context(key_context);
5274 cx.handle_input(
5275 &focus_handle,
5276 ElementInputHandler::new(bounds, self.editor.clone()),
5277 );
5278 self.register_actions(cx);
5279 self.register_key_listeners(cx, layout);
5280
5281 let text_style = TextStyleRefinement {
5282 font_size: Some(self.style.text.font_size),
5283 line_height: Some(self.style.text.line_height),
5284 ..Default::default()
5285 };
5286 let mouse_position = cx.mouse_position();
5287 let hovered_hunk = layout
5288 .display_hunks
5289 .iter()
5290 .find_map(|(hunk, hunk_hitbox)| match hunk {
5291 DisplayDiffHunk::Folded { .. } => None,
5292 DisplayDiffHunk::Unfolded {
5293 diff_base_byte_range,
5294 multi_buffer_range,
5295 status,
5296 ..
5297 } => {
5298 if hunk_hitbox
5299 .as_ref()
5300 .map(|hitbox| hitbox.contains(&mouse_position))
5301 .unwrap_or(false)
5302 {
5303 Some(HunkToExpand {
5304 status: *status,
5305 multi_buffer_range: multi_buffer_range.clone(),
5306 diff_base_byte_range: diff_base_byte_range.clone(),
5307 })
5308 } else {
5309 None
5310 }
5311 }
5312 });
5313 let rem_size = self.rem_size(cx);
5314 cx.with_rem_size(rem_size, |cx| {
5315 cx.with_text_style(Some(text_style), |cx| {
5316 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5317 self.paint_mouse_listeners(layout, hovered_hunk, cx);
5318 self.paint_background(layout, cx);
5319 self.paint_indent_guides(layout, cx);
5320
5321 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5322 self.paint_blamed_display_rows(layout, cx);
5323 self.paint_line_numbers(layout, cx);
5324 }
5325
5326 self.paint_text(layout, cx);
5327
5328 if !layout.blocks.is_empty() {
5329 cx.with_element_namespace("blocks", |cx| {
5330 self.paint_blocks(layout, cx);
5331 });
5332 }
5333
5334 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5335 self.paint_gutter_highlights(layout, cx);
5336 self.paint_gutter_indicators(layout, cx);
5337 }
5338
5339 self.paint_scrollbar(layout, cx);
5340 self.paint_mouse_context_menu(layout, cx);
5341 });
5342 })
5343 })
5344 }
5345}
5346
5347impl IntoElement for EditorElement {
5348 type Element = Self;
5349
5350 fn into_element(self) -> Self::Element {
5351 self
5352 }
5353}
5354
5355pub struct EditorLayout {
5356 position_map: Arc<PositionMap>,
5357 hitbox: Hitbox,
5358 text_hitbox: Hitbox,
5359 gutter_hitbox: Hitbox,
5360 gutter_dimensions: GutterDimensions,
5361 content_origin: gpui::Point<Pixels>,
5362 scrollbar_layout: Option<ScrollbarLayout>,
5363 mode: EditorMode,
5364 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5365 indent_guides: Option<Vec<IndentGuideLayout>>,
5366 visible_display_row_range: Range<DisplayRow>,
5367 active_rows: BTreeMap<DisplayRow, bool>,
5368 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5369 line_elements: SmallVec<[AnyElement; 1]>,
5370 line_numbers: Vec<Option<ShapedLine>>,
5371 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5372 blamed_display_rows: Option<Vec<AnyElement>>,
5373 inline_blame: Option<AnyElement>,
5374 blocks: Vec<BlockLayout>,
5375 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5376 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5377 redacted_ranges: Vec<Range<DisplayPoint>>,
5378 cursors: Vec<(DisplayPoint, Hsla)>,
5379 visible_cursors: Vec<CursorLayout>,
5380 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5381 code_actions_indicator: Option<AnyElement>,
5382 test_indicators: Vec<AnyElement>,
5383 gutter_fold_toggles: Vec<Option<AnyElement>>,
5384 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5385 mouse_context_menu: Option<AnyElement>,
5386 tab_invisible: ShapedLine,
5387 space_invisible: ShapedLine,
5388}
5389
5390impl EditorLayout {
5391 fn line_end_overshoot(&self) -> Pixels {
5392 0.15 * self.position_map.line_height
5393 }
5394}
5395
5396struct ColoredRange<T> {
5397 start: T,
5398 end: T,
5399 color: Hsla,
5400}
5401
5402#[derive(Clone)]
5403struct ScrollbarLayout {
5404 hitbox: Hitbox,
5405 visible_row_range: Range<f32>,
5406 visible: bool,
5407 row_height: Pixels,
5408 thumb_height: Pixels,
5409}
5410
5411impl ScrollbarLayout {
5412 const BORDER_WIDTH: Pixels = px(1.0);
5413 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5414 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5415 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5416
5417 fn thumb_bounds(&self) -> Bounds<Pixels> {
5418 let thumb_top = self.y_for_row(self.visible_row_range.start);
5419 let thumb_bottom = thumb_top + self.thumb_height;
5420 Bounds::from_corners(
5421 point(self.hitbox.left(), thumb_top),
5422 point(self.hitbox.right(), thumb_bottom),
5423 )
5424 }
5425
5426 fn y_for_row(&self, row: f32) -> Pixels {
5427 self.hitbox.top() + row * self.row_height
5428 }
5429
5430 fn marker_quads_for_ranges(
5431 &self,
5432 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5433 column: Option<usize>,
5434 ) -> Vec<PaintQuad> {
5435 struct MinMax {
5436 min: Pixels,
5437 max: Pixels,
5438 }
5439 let (x_range, height_limit) = if let Some(column) = column {
5440 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5441 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5442 let end = start + column_width;
5443 (
5444 Range { start, end },
5445 MinMax {
5446 min: Self::MIN_MARKER_HEIGHT,
5447 max: px(f32::MAX),
5448 },
5449 )
5450 } else {
5451 (
5452 Range {
5453 start: Self::BORDER_WIDTH,
5454 end: self.hitbox.size.width,
5455 },
5456 MinMax {
5457 min: Self::LINE_MARKER_HEIGHT,
5458 max: Self::LINE_MARKER_HEIGHT,
5459 },
5460 )
5461 };
5462
5463 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5464 let mut pixel_ranges = row_ranges
5465 .into_iter()
5466 .map(|range| {
5467 let start_y = row_to_y(range.start);
5468 let end_y = row_to_y(range.end)
5469 + self.row_height.max(height_limit.min).min(height_limit.max);
5470 ColoredRange {
5471 start: start_y,
5472 end: end_y,
5473 color: range.color,
5474 }
5475 })
5476 .peekable();
5477
5478 let mut quads = Vec::new();
5479 while let Some(mut pixel_range) = pixel_ranges.next() {
5480 while let Some(next_pixel_range) = pixel_ranges.peek() {
5481 if pixel_range.end >= next_pixel_range.start - px(1.0)
5482 && pixel_range.color == next_pixel_range.color
5483 {
5484 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5485 pixel_ranges.next();
5486 } else {
5487 break;
5488 }
5489 }
5490
5491 let bounds = Bounds::from_corners(
5492 point(x_range.start, pixel_range.start),
5493 point(x_range.end, pixel_range.end),
5494 );
5495 quads.push(quad(
5496 bounds,
5497 Corners::default(),
5498 pixel_range.color,
5499 Edges::default(),
5500 Hsla::transparent_black(),
5501 ));
5502 }
5503
5504 quads
5505 }
5506}
5507
5508struct CreaseTrailerLayout {
5509 element: AnyElement,
5510 bounds: Bounds<Pixels>,
5511}
5512
5513struct PositionMap {
5514 size: Size<Pixels>,
5515 line_height: Pixels,
5516 scroll_pixel_position: gpui::Point<Pixels>,
5517 scroll_max: gpui::Point<f32>,
5518 em_width: Pixels,
5519 em_advance: Pixels,
5520 line_layouts: Vec<LineWithInvisibles>,
5521 snapshot: EditorSnapshot,
5522}
5523
5524#[derive(Debug, Copy, Clone)]
5525pub struct PointForPosition {
5526 pub previous_valid: DisplayPoint,
5527 pub next_valid: DisplayPoint,
5528 pub exact_unclipped: DisplayPoint,
5529 pub column_overshoot_after_line_end: u32,
5530}
5531
5532impl PointForPosition {
5533 pub fn as_valid(&self) -> Option<DisplayPoint> {
5534 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5535 Some(self.previous_valid)
5536 } else {
5537 None
5538 }
5539 }
5540}
5541
5542impl PositionMap {
5543 fn point_for_position(
5544 &self,
5545 text_bounds: Bounds<Pixels>,
5546 position: gpui::Point<Pixels>,
5547 ) -> PointForPosition {
5548 let scroll_position = self.snapshot.scroll_position();
5549 let position = position - text_bounds.origin;
5550 let y = position.y.max(px(0.)).min(self.size.height);
5551 let x = position.x + (scroll_position.x * self.em_width);
5552 let row = ((y / self.line_height) + scroll_position.y) as u32;
5553
5554 let (column, x_overshoot_after_line_end) = if let Some(line) = self
5555 .line_layouts
5556 .get(row as usize - scroll_position.y as usize)
5557 {
5558 if let Some(ix) = line.index_for_x(x) {
5559 (ix as u32, px(0.))
5560 } else {
5561 (line.len as u32, px(0.).max(x - line.width))
5562 }
5563 } else {
5564 (0, x)
5565 };
5566
5567 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5568 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5569 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5570
5571 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5572 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5573 PointForPosition {
5574 previous_valid,
5575 next_valid,
5576 exact_unclipped,
5577 column_overshoot_after_line_end,
5578 }
5579 }
5580}
5581
5582struct BlockLayout {
5583 row: DisplayRow,
5584 element: AnyElement,
5585 available_space: Size<AvailableSpace>,
5586 style: BlockStyle,
5587}
5588
5589fn layout_line(
5590 row: DisplayRow,
5591 snapshot: &EditorSnapshot,
5592 style: &EditorStyle,
5593 cx: &mut WindowContext,
5594) -> LineWithInvisibles {
5595 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5596 LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5597 .pop()
5598 .unwrap()
5599}
5600
5601#[derive(Debug)]
5602pub struct IndentGuideLayout {
5603 origin: gpui::Point<Pixels>,
5604 length: Pixels,
5605 single_indent_width: Pixels,
5606 depth: u32,
5607 active: bool,
5608 settings: IndentGuideSettings,
5609}
5610
5611pub struct CursorLayout {
5612 origin: gpui::Point<Pixels>,
5613 block_width: Pixels,
5614 line_height: Pixels,
5615 color: Hsla,
5616 shape: CursorShape,
5617 block_text: Option<ShapedLine>,
5618 cursor_name: Option<AnyElement>,
5619}
5620
5621#[derive(Debug)]
5622pub struct CursorName {
5623 string: SharedString,
5624 color: Hsla,
5625 is_top_row: bool,
5626}
5627
5628impl CursorLayout {
5629 pub fn new(
5630 origin: gpui::Point<Pixels>,
5631 block_width: Pixels,
5632 line_height: Pixels,
5633 color: Hsla,
5634 shape: CursorShape,
5635 block_text: Option<ShapedLine>,
5636 ) -> CursorLayout {
5637 CursorLayout {
5638 origin,
5639 block_width,
5640 line_height,
5641 color,
5642 shape,
5643 block_text,
5644 cursor_name: None,
5645 }
5646 }
5647
5648 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5649 Bounds {
5650 origin: self.origin + origin,
5651 size: size(self.block_width, self.line_height),
5652 }
5653 }
5654
5655 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5656 match self.shape {
5657 CursorShape::Bar => Bounds {
5658 origin: self.origin + origin,
5659 size: size(px(2.0), self.line_height),
5660 },
5661 CursorShape::Block | CursorShape::Hollow => Bounds {
5662 origin: self.origin + origin,
5663 size: size(self.block_width, self.line_height),
5664 },
5665 CursorShape::Underscore => Bounds {
5666 origin: self.origin
5667 + origin
5668 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5669 size: size(self.block_width, px(2.0)),
5670 },
5671 }
5672 }
5673
5674 pub fn layout(
5675 &mut self,
5676 origin: gpui::Point<Pixels>,
5677 cursor_name: Option<CursorName>,
5678 cx: &mut WindowContext,
5679 ) {
5680 if let Some(cursor_name) = cursor_name {
5681 let bounds = self.bounds(origin);
5682 let text_size = self.line_height / 1.5;
5683
5684 let name_origin = if cursor_name.is_top_row {
5685 point(bounds.right() - px(1.), bounds.top())
5686 } else {
5687 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5688 };
5689 let mut name_element = div()
5690 .bg(self.color)
5691 .text_size(text_size)
5692 .px_0p5()
5693 .line_height(text_size + px(2.))
5694 .text_color(cursor_name.color)
5695 .child(cursor_name.string.clone())
5696 .into_any_element();
5697
5698 name_element.prepaint_as_root(
5699 name_origin,
5700 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5701 cx,
5702 );
5703
5704 self.cursor_name = Some(name_element);
5705 }
5706 }
5707
5708 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5709 let bounds = self.bounds(origin);
5710
5711 //Draw background or border quad
5712 let cursor = if matches!(self.shape, CursorShape::Hollow) {
5713 outline(bounds, self.color)
5714 } else {
5715 fill(bounds, self.color)
5716 };
5717
5718 if let Some(name) = &mut self.cursor_name {
5719 name.paint(cx);
5720 }
5721
5722 cx.paint_quad(cursor);
5723
5724 if let Some(block_text) = &self.block_text {
5725 block_text
5726 .paint(self.origin + origin, self.line_height, cx)
5727 .log_err();
5728 }
5729 }
5730
5731 pub fn shape(&self) -> CursorShape {
5732 self.shape
5733 }
5734}
5735
5736#[derive(Debug)]
5737pub struct HighlightedRange {
5738 pub start_y: Pixels,
5739 pub line_height: Pixels,
5740 pub lines: Vec<HighlightedRangeLine>,
5741 pub color: Hsla,
5742 pub corner_radius: Pixels,
5743}
5744
5745#[derive(Debug)]
5746pub struct HighlightedRangeLine {
5747 pub start_x: Pixels,
5748 pub end_x: Pixels,
5749}
5750
5751impl HighlightedRange {
5752 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5753 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5754 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5755 self.paint_lines(
5756 self.start_y + self.line_height,
5757 &self.lines[1..],
5758 bounds,
5759 cx,
5760 );
5761 } else {
5762 self.paint_lines(self.start_y, &self.lines, bounds, cx);
5763 }
5764 }
5765
5766 fn paint_lines(
5767 &self,
5768 start_y: Pixels,
5769 lines: &[HighlightedRangeLine],
5770 _bounds: Bounds<Pixels>,
5771 cx: &mut WindowContext,
5772 ) {
5773 if lines.is_empty() {
5774 return;
5775 }
5776
5777 let first_line = lines.first().unwrap();
5778 let last_line = lines.last().unwrap();
5779
5780 let first_top_left = point(first_line.start_x, start_y);
5781 let first_top_right = point(first_line.end_x, start_y);
5782
5783 let curve_height = point(Pixels::ZERO, self.corner_radius);
5784 let curve_width = |start_x: Pixels, end_x: Pixels| {
5785 let max = (end_x - start_x) / 2.;
5786 let width = if max < self.corner_radius {
5787 max
5788 } else {
5789 self.corner_radius
5790 };
5791
5792 point(width, Pixels::ZERO)
5793 };
5794
5795 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5796 let mut path = gpui::Path::new(first_top_right - top_curve_width);
5797 path.curve_to(first_top_right + curve_height, first_top_right);
5798
5799 let mut iter = lines.iter().enumerate().peekable();
5800 while let Some((ix, line)) = iter.next() {
5801 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5802
5803 if let Some((_, next_line)) = iter.peek() {
5804 let next_top_right = point(next_line.end_x, bottom_right.y);
5805
5806 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5807 Ordering::Equal => {
5808 path.line_to(bottom_right);
5809 }
5810 Ordering::Less => {
5811 let curve_width = curve_width(next_top_right.x, bottom_right.x);
5812 path.line_to(bottom_right - curve_height);
5813 if self.corner_radius > Pixels::ZERO {
5814 path.curve_to(bottom_right - curve_width, bottom_right);
5815 }
5816 path.line_to(next_top_right + curve_width);
5817 if self.corner_radius > Pixels::ZERO {
5818 path.curve_to(next_top_right + curve_height, next_top_right);
5819 }
5820 }
5821 Ordering::Greater => {
5822 let curve_width = curve_width(bottom_right.x, next_top_right.x);
5823 path.line_to(bottom_right - curve_height);
5824 if self.corner_radius > Pixels::ZERO {
5825 path.curve_to(bottom_right + curve_width, bottom_right);
5826 }
5827 path.line_to(next_top_right - curve_width);
5828 if self.corner_radius > Pixels::ZERO {
5829 path.curve_to(next_top_right + curve_height, next_top_right);
5830 }
5831 }
5832 }
5833 } else {
5834 let curve_width = curve_width(line.start_x, line.end_x);
5835 path.line_to(bottom_right - curve_height);
5836 if self.corner_radius > Pixels::ZERO {
5837 path.curve_to(bottom_right - curve_width, bottom_right);
5838 }
5839
5840 let bottom_left = point(line.start_x, bottom_right.y);
5841 path.line_to(bottom_left + curve_width);
5842 if self.corner_radius > Pixels::ZERO {
5843 path.curve_to(bottom_left - curve_height, bottom_left);
5844 }
5845 }
5846 }
5847
5848 if first_line.start_x > last_line.start_x {
5849 let curve_width = curve_width(last_line.start_x, first_line.start_x);
5850 let second_top_left = point(last_line.start_x, start_y + self.line_height);
5851 path.line_to(second_top_left + curve_height);
5852 if self.corner_radius > Pixels::ZERO {
5853 path.curve_to(second_top_left + curve_width, second_top_left);
5854 }
5855 let first_bottom_left = point(first_line.start_x, second_top_left.y);
5856 path.line_to(first_bottom_left - curve_width);
5857 if self.corner_radius > Pixels::ZERO {
5858 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5859 }
5860 }
5861
5862 path.line_to(first_top_left + curve_height);
5863 if self.corner_radius > Pixels::ZERO {
5864 path.curve_to(first_top_left + top_curve_width, first_top_left);
5865 }
5866 path.line_to(first_top_right - top_curve_width);
5867
5868 cx.paint_path(path, self.color);
5869 }
5870}
5871
5872pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5873 (delta.pow(1.5) / 100.0).into()
5874}
5875
5876fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5877 (delta.pow(1.2) / 300.0).into()
5878}
5879
5880#[cfg(test)]
5881mod tests {
5882 use super::*;
5883 use crate::{
5884 display_map::{BlockDisposition, BlockProperties},
5885 editor_tests::{init_test, update_test_language_settings},
5886 Editor, MultiBuffer,
5887 };
5888 use gpui::{TestAppContext, VisualTestContext};
5889 use language::language_settings;
5890 use log::info;
5891 use std::num::NonZeroU32;
5892 use ui::Context;
5893 use util::test::sample_text;
5894
5895 #[gpui::test]
5896 fn test_shape_line_numbers(cx: &mut TestAppContext) {
5897 init_test(cx, |_| {});
5898 let window = cx.add_window(|cx| {
5899 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5900 Editor::new(EditorMode::Full, buffer, None, true, cx)
5901 });
5902
5903 let editor = window.root(cx).unwrap();
5904 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5905 let element = EditorElement::new(&editor, style);
5906 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5907
5908 let layouts = cx
5909 .update_window(*window, |_, cx| {
5910 element.layout_line_numbers(
5911 DisplayRow(0)..DisplayRow(6),
5912 (0..6).map(MultiBufferRow).map(Some),
5913 &Default::default(),
5914 Some(DisplayPoint::new(DisplayRow(0), 0)),
5915 &snapshot,
5916 cx,
5917 )
5918 })
5919 .unwrap();
5920 assert_eq!(layouts.len(), 6);
5921
5922 let relative_rows = window
5923 .update(cx, |editor, cx| {
5924 let snapshot = editor.snapshot(cx);
5925 element.calculate_relative_line_numbers(
5926 &snapshot,
5927 &(DisplayRow(0)..DisplayRow(6)),
5928 Some(DisplayRow(3)),
5929 )
5930 })
5931 .unwrap();
5932 assert_eq!(relative_rows[&DisplayRow(0)], 3);
5933 assert_eq!(relative_rows[&DisplayRow(1)], 2);
5934 assert_eq!(relative_rows[&DisplayRow(2)], 1);
5935 // current line has no relative number
5936 assert_eq!(relative_rows[&DisplayRow(4)], 1);
5937 assert_eq!(relative_rows[&DisplayRow(5)], 2);
5938
5939 // works if cursor is before screen
5940 let relative_rows = window
5941 .update(cx, |editor, cx| {
5942 let snapshot = editor.snapshot(cx);
5943 element.calculate_relative_line_numbers(
5944 &snapshot,
5945 &(DisplayRow(3)..DisplayRow(6)),
5946 Some(DisplayRow(1)),
5947 )
5948 })
5949 .unwrap();
5950 assert_eq!(relative_rows.len(), 3);
5951 assert_eq!(relative_rows[&DisplayRow(3)], 2);
5952 assert_eq!(relative_rows[&DisplayRow(4)], 3);
5953 assert_eq!(relative_rows[&DisplayRow(5)], 4);
5954
5955 // works if cursor is after screen
5956 let relative_rows = window
5957 .update(cx, |editor, cx| {
5958 let snapshot = editor.snapshot(cx);
5959 element.calculate_relative_line_numbers(
5960 &snapshot,
5961 &(DisplayRow(0)..DisplayRow(3)),
5962 Some(DisplayRow(6)),
5963 )
5964 })
5965 .unwrap();
5966 assert_eq!(relative_rows.len(), 3);
5967 assert_eq!(relative_rows[&DisplayRow(0)], 5);
5968 assert_eq!(relative_rows[&DisplayRow(1)], 4);
5969 assert_eq!(relative_rows[&DisplayRow(2)], 3);
5970 }
5971
5972 #[gpui::test]
5973 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5974 init_test(cx, |_| {});
5975
5976 let window = cx.add_window(|cx| {
5977 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5978 Editor::new(EditorMode::Full, buffer, None, true, cx)
5979 });
5980 let cx = &mut VisualTestContext::from_window(*window, cx);
5981 let editor = window.root(cx).unwrap();
5982 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5983
5984 window
5985 .update(cx, |editor, cx| {
5986 editor.cursor_shape = CursorShape::Block;
5987 editor.change_selections(None, cx, |s| {
5988 s.select_ranges([
5989 Point::new(0, 0)..Point::new(1, 0),
5990 Point::new(3, 2)..Point::new(3, 3),
5991 Point::new(5, 6)..Point::new(6, 0),
5992 ]);
5993 });
5994 })
5995 .unwrap();
5996
5997 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5998 EditorElement::new(&editor, style)
5999 });
6000
6001 assert_eq!(state.selections.len(), 1);
6002 let local_selections = &state.selections[0].1;
6003 assert_eq!(local_selections.len(), 3);
6004 // moves cursor back one line
6005 assert_eq!(
6006 local_selections[0].head,
6007 DisplayPoint::new(DisplayRow(0), 6)
6008 );
6009 assert_eq!(
6010 local_selections[0].range,
6011 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6012 );
6013
6014 // moves cursor back one column
6015 assert_eq!(
6016 local_selections[1].range,
6017 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6018 );
6019 assert_eq!(
6020 local_selections[1].head,
6021 DisplayPoint::new(DisplayRow(3), 2)
6022 );
6023
6024 // leaves cursor on the max point
6025 assert_eq!(
6026 local_selections[2].range,
6027 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6028 );
6029 assert_eq!(
6030 local_selections[2].head,
6031 DisplayPoint::new(DisplayRow(6), 0)
6032 );
6033
6034 // active lines does not include 1 (even though the range of the selection does)
6035 assert_eq!(
6036 state.active_rows.keys().cloned().collect::<Vec<_>>(),
6037 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6038 );
6039
6040 // multi-buffer support
6041 // in DisplayPoint coordinates, this is what we're dealing with:
6042 // 0: [[file
6043 // 1: header
6044 // 2: section]]
6045 // 3: aaaaaa
6046 // 4: bbbbbb
6047 // 5: cccccc
6048 // 6:
6049 // 7: [[footer]]
6050 // 8: [[header]]
6051 // 9: ffffff
6052 // 10: gggggg
6053 // 11: hhhhhh
6054 // 12:
6055 // 13: [[footer]]
6056 // 14: [[file
6057 // 15: header
6058 // 16: section]]
6059 // 17: bbbbbb
6060 // 18: cccccc
6061 // 19: dddddd
6062 // 20: [[footer]]
6063 let window = cx.add_window(|cx| {
6064 let buffer = MultiBuffer::build_multi(
6065 [
6066 (
6067 &(sample_text(8, 6, 'a') + "\n"),
6068 vec![
6069 Point::new(0, 0)..Point::new(3, 0),
6070 Point::new(4, 0)..Point::new(7, 0),
6071 ],
6072 ),
6073 (
6074 &(sample_text(8, 6, 'a') + "\n"),
6075 vec![Point::new(1, 0)..Point::new(3, 0)],
6076 ),
6077 ],
6078 cx,
6079 );
6080 Editor::new(EditorMode::Full, buffer, None, true, cx)
6081 });
6082 let editor = window.root(cx).unwrap();
6083 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6084 let _state = window.update(cx, |editor, cx| {
6085 editor.cursor_shape = CursorShape::Block;
6086 editor.change_selections(None, cx, |s| {
6087 s.select_display_ranges([
6088 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6089 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6090 ]);
6091 });
6092 });
6093
6094 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6095 EditorElement::new(&editor, style)
6096 });
6097 assert_eq!(state.selections.len(), 1);
6098 let local_selections = &state.selections[0].1;
6099 assert_eq!(local_selections.len(), 2);
6100
6101 // moves cursor on excerpt boundary back a line
6102 // and doesn't allow selection to bleed through
6103 assert_eq!(
6104 local_selections[0].range,
6105 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6106 );
6107 assert_eq!(
6108 local_selections[0].head,
6109 DisplayPoint::new(DisplayRow(6), 0)
6110 );
6111 // moves cursor on buffer boundary back two lines
6112 // and doesn't allow selection to bleed through
6113 assert_eq!(
6114 local_selections[1].range,
6115 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6116 );
6117 assert_eq!(
6118 local_selections[1].head,
6119 DisplayPoint::new(DisplayRow(12), 0)
6120 );
6121 }
6122
6123 #[gpui::test]
6124 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6125 init_test(cx, |_| {});
6126
6127 let window = cx.add_window(|cx| {
6128 let buffer = MultiBuffer::build_simple("", cx);
6129 Editor::new(EditorMode::Full, buffer, None, true, cx)
6130 });
6131 let cx = &mut VisualTestContext::from_window(*window, cx);
6132 let editor = window.root(cx).unwrap();
6133 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6134 window
6135 .update(cx, |editor, cx| {
6136 editor.set_placeholder_text("hello", cx);
6137 editor.insert_blocks(
6138 [BlockProperties {
6139 style: BlockStyle::Fixed,
6140 disposition: BlockDisposition::Above,
6141 height: 3,
6142 position: Anchor::min(),
6143 render: Box::new(|_| div().into_any()),
6144 }],
6145 None,
6146 cx,
6147 );
6148
6149 // Blur the editor so that it displays placeholder text.
6150 cx.blur();
6151 })
6152 .unwrap();
6153
6154 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6155 EditorElement::new(&editor, style)
6156 });
6157 assert_eq!(state.position_map.line_layouts.len(), 4);
6158 assert_eq!(
6159 state
6160 .line_numbers
6161 .iter()
6162 .map(Option::is_some)
6163 .collect::<Vec<_>>(),
6164 &[false, false, false, true]
6165 );
6166 }
6167
6168 #[gpui::test]
6169 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6170 const TAB_SIZE: u32 = 4;
6171
6172 let input_text = "\t \t|\t| a b";
6173 let expected_invisibles = vec![
6174 Invisible::Tab {
6175 line_start_offset: 0,
6176 line_end_offset: TAB_SIZE as usize,
6177 },
6178 Invisible::Whitespace {
6179 line_offset: TAB_SIZE as usize,
6180 },
6181 Invisible::Tab {
6182 line_start_offset: TAB_SIZE as usize + 1,
6183 line_end_offset: TAB_SIZE as usize * 2,
6184 },
6185 Invisible::Tab {
6186 line_start_offset: TAB_SIZE as usize * 2 + 1,
6187 line_end_offset: TAB_SIZE as usize * 3,
6188 },
6189 Invisible::Whitespace {
6190 line_offset: TAB_SIZE as usize * 3 + 1,
6191 },
6192 Invisible::Whitespace {
6193 line_offset: TAB_SIZE as usize * 3 + 3,
6194 },
6195 ];
6196 assert_eq!(
6197 expected_invisibles.len(),
6198 input_text
6199 .chars()
6200 .filter(|initial_char| initial_char.is_whitespace())
6201 .count(),
6202 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6203 );
6204
6205 init_test(cx, |s| {
6206 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6207 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6208 });
6209
6210 let actual_invisibles =
6211 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
6212
6213 assert_eq!(expected_invisibles, actual_invisibles);
6214 }
6215
6216 #[gpui::test]
6217 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6218 init_test(cx, |s| {
6219 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6220 s.defaults.tab_size = NonZeroU32::new(4);
6221 });
6222
6223 for editor_mode_without_invisibles in [
6224 EditorMode::SingleLine { auto_width: false },
6225 EditorMode::AutoHeight { max_lines: 100 },
6226 ] {
6227 let invisibles = collect_invisibles_from_new_editor(
6228 cx,
6229 editor_mode_without_invisibles,
6230 "\t\t\t| | a b",
6231 px(500.0),
6232 );
6233 assert!(invisibles.is_empty(),
6234 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6235 }
6236 }
6237
6238 #[gpui::test]
6239 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6240 let tab_size = 4;
6241 let input_text = "a\tbcd ".repeat(9);
6242 let repeated_invisibles = [
6243 Invisible::Tab {
6244 line_start_offset: 1,
6245 line_end_offset: tab_size as usize,
6246 },
6247 Invisible::Whitespace {
6248 line_offset: tab_size as usize + 3,
6249 },
6250 Invisible::Whitespace {
6251 line_offset: tab_size as usize + 4,
6252 },
6253 Invisible::Whitespace {
6254 line_offset: tab_size as usize + 5,
6255 },
6256 Invisible::Whitespace {
6257 line_offset: tab_size as usize + 6,
6258 },
6259 Invisible::Whitespace {
6260 line_offset: tab_size as usize + 7,
6261 },
6262 ];
6263 let expected_invisibles = std::iter::once(repeated_invisibles)
6264 .cycle()
6265 .take(9)
6266 .flatten()
6267 .collect::<Vec<_>>();
6268 assert_eq!(
6269 expected_invisibles.len(),
6270 input_text
6271 .chars()
6272 .filter(|initial_char| initial_char.is_whitespace())
6273 .count(),
6274 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6275 );
6276 info!("Expected invisibles: {expected_invisibles:?}");
6277
6278 init_test(cx, |_| {});
6279
6280 // Put the same string with repeating whitespace pattern into editors of various size,
6281 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6282 let resize_step = 10.0;
6283 let mut editor_width = 200.0;
6284 while editor_width <= 1000.0 {
6285 update_test_language_settings(cx, |s| {
6286 s.defaults.tab_size = NonZeroU32::new(tab_size);
6287 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6288 s.defaults.preferred_line_length = Some(editor_width as u32);
6289 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6290 });
6291
6292 let actual_invisibles = collect_invisibles_from_new_editor(
6293 cx,
6294 EditorMode::Full,
6295 &input_text,
6296 px(editor_width),
6297 );
6298
6299 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6300 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6301 let mut i = 0;
6302 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6303 i = actual_index;
6304 match expected_invisibles.get(i) {
6305 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6306 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6307 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6308 _ => {
6309 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6310 }
6311 },
6312 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6313 }
6314 }
6315 let missing_expected_invisibles = &expected_invisibles[i + 1..];
6316 assert!(
6317 missing_expected_invisibles.is_empty(),
6318 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6319 );
6320
6321 editor_width += resize_step;
6322 }
6323 }
6324
6325 fn collect_invisibles_from_new_editor(
6326 cx: &mut TestAppContext,
6327 editor_mode: EditorMode,
6328 input_text: &str,
6329 editor_width: Pixels,
6330 ) -> Vec<Invisible> {
6331 info!(
6332 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6333 editor_width.0
6334 );
6335 let window = cx.add_window(|cx| {
6336 let buffer = MultiBuffer::build_simple(&input_text, cx);
6337 Editor::new(editor_mode, buffer, None, true, cx)
6338 });
6339 let cx = &mut VisualTestContext::from_window(*window, cx);
6340 let editor = window.root(cx).unwrap();
6341 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6342 window
6343 .update(cx, |editor, cx| {
6344 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6345 editor.set_wrap_width(Some(editor_width), cx);
6346 })
6347 .unwrap();
6348 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6349 EditorElement::new(&editor, style)
6350 });
6351 state
6352 .position_map
6353 .line_layouts
6354 .iter()
6355 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6356 .cloned()
6357 .collect()
6358 }
6359}
6360
6361pub fn register_action<T: Action>(
6362 view: &View<Editor>,
6363 cx: &mut WindowContext,
6364 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6365) {
6366 let view = view.clone();
6367 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6368 let action = action.downcast_ref().unwrap();
6369 if phase == DispatchPhase::Bubble {
6370 view.update(cx, |editor, cx| {
6371 listener(editor, action, cx);
6372 })
6373 }
6374 })
6375}
6376
6377fn compute_auto_height_layout(
6378 editor: &mut Editor,
6379 max_lines: usize,
6380 max_line_number_width: Pixels,
6381 known_dimensions: Size<Option<Pixels>>,
6382 available_width: AvailableSpace,
6383 cx: &mut ViewContext<Editor>,
6384) -> Option<Size<Pixels>> {
6385 let width = known_dimensions.width.or_else(|| {
6386 if let AvailableSpace::Definite(available_width) = available_width {
6387 Some(available_width)
6388 } else {
6389 None
6390 }
6391 })?;
6392 if let Some(height) = known_dimensions.height {
6393 return Some(size(width, height));
6394 }
6395
6396 let style = editor.style.as_ref().unwrap();
6397 let font_id = cx.text_system().resolve_font(&style.text.font());
6398 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6399 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6400 let em_width = cx
6401 .text_system()
6402 .typographic_bounds(font_id, font_size, 'm')
6403 .unwrap()
6404 .size
6405 .width;
6406
6407 let mut snapshot = editor.snapshot(cx);
6408 let gutter_dimensions =
6409 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6410
6411 editor.gutter_dimensions = gutter_dimensions;
6412 let text_width = width - gutter_dimensions.width;
6413 let overscroll = size(em_width, px(0.));
6414
6415 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6416 if editor.set_wrap_width(Some(editor_width), cx) {
6417 snapshot = editor.snapshot(cx);
6418 }
6419
6420 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6421 let height = scroll_height
6422 .max(line_height)
6423 .min(line_height * max_lines as f32);
6424
6425 Some(size(width, height))
6426}