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