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