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