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