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