1use crate::{
2 blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
3 display_map::{
4 BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint, TransformBlock,
5 },
6 editor_settings::{
7 CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar,
8 },
9 git::{
10 blame::{CommitDetails, GitBlame},
11 diff_hunk_to_display, DisplayDiffHunk,
12 },
13 hover_popover::{
14 self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
15 },
16 hunk_status,
17 items::BufferSearchHighlights,
18 mouse_context_menu::{self, MouseContextMenu},
19 scroll::scroll_amount::ScrollAmount,
20 CodeActionsMenu, CursorShape, DisplayPoint, DisplayRow, DocumentHighlightRead,
21 DocumentHighlightWrite, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle,
22 ExpandExcerpts, GutterDimensions, HalfPageDown, HalfPageUp, HoveredCursor, HunkToExpand,
23 LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, RowExt, RowRangeExt, SelectPhase,
24 Selection, SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
25};
26use client::ParticipantIndex;
27use collections::{BTreeMap, HashMap};
28use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
29use gpui::{
30 anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
31 transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
32 ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity,
33 FontId, GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, Length,
34 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
35 ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
36 StatefulInteractiveElement, Style, Styled, TextRun, TextStyle, TextStyleRefinement, View,
37 ViewContext, WeakView, WindowContext,
38};
39use itertools::Itertools;
40use language::language_settings::{
41 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
42};
43use lsp::DiagnosticSeverity;
44use multi_buffer::{Anchor, MultiBufferPoint, MultiBufferRow};
45use project::{
46 project_settings::{GitGutterSetting, ProjectSettings},
47 ProjectPath,
48};
49use settings::Settings;
50use smallvec::{smallvec, SmallVec};
51use std::{
52 any::TypeId,
53 borrow::Cow,
54 cmp::{self, Ordering},
55 fmt::{self, Write},
56 iter, mem,
57 ops::{Deref, Range},
58 sync::Arc,
59};
60use sum_tree::Bias;
61use theme::{ActiveTheme, PlayerColor};
62use ui::prelude::*;
63use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
64use util::ResultExt;
65use workspace::{item::Item, Workspace};
66
67struct SelectionLayout {
68 head: DisplayPoint,
69 cursor_shape: CursorShape,
70 is_newest: bool,
71 is_local: bool,
72 range: Range<DisplayPoint>,
73 active_rows: Range<DisplayRow>,
74 user_name: Option<SharedString>,
75}
76
77impl SelectionLayout {
78 fn new<T: ToPoint + ToDisplayPoint + Clone>(
79 selection: Selection<T>,
80 line_mode: bool,
81 cursor_shape: CursorShape,
82 map: &DisplaySnapshot,
83 is_newest: bool,
84 is_local: bool,
85 user_name: Option<SharedString>,
86 ) -> Self {
87 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
88 let display_selection = point_selection.map(|p| p.to_display_point(map));
89 let mut range = display_selection.range();
90 let mut head = display_selection.head();
91 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
92 ..map.next_line_boundary(point_selection.end).1.row();
93
94 // vim visual line mode
95 if line_mode {
96 let point_range = map.expand_to_line(point_selection.range());
97 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
98 }
99
100 // any vim visual mode (including line mode)
101 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
102 && !range.is_empty()
103 && !selection.reversed
104 {
105 if head.column() > 0 {
106 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
107 } else if head.row().0 > 0 && head != map.max_point() {
108 head = map.clip_point(
109 DisplayPoint::new(
110 head.row().previous_row(),
111 map.line_len(head.row().previous_row()),
112 ),
113 Bias::Left,
114 );
115 // updating range.end is a no-op unless you're cursor is
116 // on the newline containing a multi-buffer divider
117 // in which case the clip_point may have moved the head up
118 // an additional row.
119 range.end = DisplayPoint::new(head.row().next_row(), 0);
120 active_rows.end = head.row();
121 }
122 }
123
124 Self {
125 head,
126 cursor_shape,
127 is_newest,
128 is_local,
129 range,
130 active_rows,
131 user_name,
132 }
133 }
134}
135
136pub struct EditorElement {
137 editor: View<Editor>,
138 style: EditorStyle,
139}
140
141type DisplayRowDelta = u32;
142
143impl EditorElement {
144 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(13.);
145
146 pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
147 Self {
148 editor: editor.clone(),
149 style,
150 }
151 }
152
153 fn register_actions(&self, cx: &mut WindowContext) {
154 let view = &self.editor;
155 view.update(cx, |editor, cx| {
156 for action in editor.editor_actions.borrow().values() {
157 (action)(cx)
158 }
159 });
160
161 crate::rust_analyzer_ext::apply_related_actions(view, cx);
162 register_action(view, cx, Editor::move_left);
163 register_action(view, cx, Editor::move_right);
164 register_action(view, cx, Editor::move_down);
165 register_action(view, cx, Editor::move_down_by_lines);
166 register_action(view, cx, Editor::select_down_by_lines);
167 register_action(view, cx, Editor::move_up);
168 register_action(view, cx, Editor::move_up_by_lines);
169 register_action(view, cx, Editor::select_up_by_lines);
170 register_action(view, cx, Editor::cancel);
171 register_action(view, cx, Editor::newline);
172 register_action(view, cx, Editor::newline_above);
173 register_action(view, cx, Editor::newline_below);
174 register_action(view, cx, Editor::backspace);
175 register_action(view, cx, Editor::delete);
176 register_action(view, cx, Editor::tab);
177 register_action(view, cx, Editor::tab_prev);
178 register_action(view, cx, Editor::indent);
179 register_action(view, cx, Editor::outdent);
180 register_action(view, cx, Editor::delete_line);
181 register_action(view, cx, Editor::join_lines);
182 register_action(view, cx, Editor::sort_lines_case_sensitive);
183 register_action(view, cx, Editor::sort_lines_case_insensitive);
184 register_action(view, cx, Editor::reverse_lines);
185 register_action(view, cx, Editor::shuffle_lines);
186 register_action(view, cx, Editor::convert_to_upper_case);
187 register_action(view, cx, Editor::convert_to_lower_case);
188 register_action(view, cx, Editor::convert_to_title_case);
189 register_action(view, cx, Editor::convert_to_snake_case);
190 register_action(view, cx, Editor::convert_to_kebab_case);
191 register_action(view, cx, Editor::convert_to_upper_camel_case);
192 register_action(view, cx, Editor::convert_to_lower_camel_case);
193 register_action(view, cx, Editor::convert_to_opposite_case);
194 register_action(view, cx, Editor::delete_to_previous_word_start);
195 register_action(view, cx, Editor::delete_to_previous_subword_start);
196 register_action(view, cx, Editor::delete_to_next_word_end);
197 register_action(view, cx, Editor::delete_to_next_subword_end);
198 register_action(view, cx, Editor::delete_to_beginning_of_line);
199 register_action(view, cx, Editor::delete_to_end_of_line);
200 register_action(view, cx, Editor::cut_to_end_of_line);
201 register_action(view, cx, Editor::duplicate_line_up);
202 register_action(view, cx, Editor::duplicate_line_down);
203 register_action(view, cx, Editor::move_line_up);
204 register_action(view, cx, Editor::move_line_down);
205 register_action(view, cx, Editor::transpose);
206 register_action(view, cx, Editor::cut);
207 register_action(view, cx, Editor::copy);
208 register_action(view, cx, Editor::paste);
209 register_action(view, cx, Editor::undo);
210 register_action(view, cx, Editor::redo);
211 register_action(view, cx, Editor::move_page_up);
212 register_action(view, cx, Editor::move_page_down);
213 register_action(view, cx, Editor::next_screen);
214 register_action(view, cx, Editor::scroll_cursor_top);
215 register_action(view, cx, Editor::scroll_cursor_center);
216 register_action(view, cx, Editor::scroll_cursor_bottom);
217 register_action(view, cx, |editor, _: &LineDown, cx| {
218 editor.scroll_screen(&ScrollAmount::Line(1.), cx)
219 });
220 register_action(view, cx, |editor, _: &LineUp, cx| {
221 editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
222 });
223 register_action(view, cx, |editor, _: &HalfPageDown, cx| {
224 editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
225 });
226 register_action(view, cx, |editor, _: &HalfPageUp, cx| {
227 editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
228 });
229 register_action(view, cx, |editor, _: &PageDown, cx| {
230 editor.scroll_screen(&ScrollAmount::Page(1.), cx)
231 });
232 register_action(view, cx, |editor, _: &PageUp, cx| {
233 editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
234 });
235 register_action(view, cx, Editor::move_to_previous_word_start);
236 register_action(view, cx, Editor::move_to_previous_subword_start);
237 register_action(view, cx, Editor::move_to_next_word_end);
238 register_action(view, cx, Editor::move_to_next_subword_end);
239 register_action(view, cx, Editor::move_to_beginning_of_line);
240 register_action(view, cx, Editor::move_to_end_of_line);
241 register_action(view, cx, Editor::move_to_start_of_paragraph);
242 register_action(view, cx, Editor::move_to_end_of_paragraph);
243 register_action(view, cx, Editor::move_to_beginning);
244 register_action(view, cx, Editor::move_to_end);
245 register_action(view, cx, Editor::select_up);
246 register_action(view, cx, Editor::select_down);
247 register_action(view, cx, Editor::select_left);
248 register_action(view, cx, Editor::select_right);
249 register_action(view, cx, Editor::select_to_previous_word_start);
250 register_action(view, cx, Editor::select_to_previous_subword_start);
251 register_action(view, cx, Editor::select_to_next_word_end);
252 register_action(view, cx, Editor::select_to_next_subword_end);
253 register_action(view, cx, Editor::select_to_beginning_of_line);
254 register_action(view, cx, Editor::select_to_end_of_line);
255 register_action(view, cx, Editor::select_to_start_of_paragraph);
256 register_action(view, cx, Editor::select_to_end_of_paragraph);
257 register_action(view, cx, Editor::select_to_beginning);
258 register_action(view, cx, Editor::select_to_end);
259 register_action(view, cx, Editor::select_all);
260 register_action(view, cx, |editor, action, cx| {
261 editor.select_all_matches(action, cx).log_err();
262 });
263 register_action(view, cx, Editor::select_line);
264 register_action(view, cx, Editor::split_selection_into_lines);
265 register_action(view, cx, Editor::add_selection_above);
266 register_action(view, cx, Editor::add_selection_below);
267 register_action(view, cx, |editor, action, cx| {
268 editor.select_next(action, cx).log_err();
269 });
270 register_action(view, cx, |editor, action, cx| {
271 editor.select_previous(action, cx).log_err();
272 });
273 register_action(view, cx, Editor::toggle_comments);
274 register_action(view, cx, Editor::select_larger_syntax_node);
275 register_action(view, cx, Editor::select_smaller_syntax_node);
276 register_action(view, cx, Editor::move_to_enclosing_bracket);
277 register_action(view, cx, Editor::undo_selection);
278 register_action(view, cx, Editor::redo_selection);
279 if !view.read(cx).is_singleton(cx) {
280 register_action(view, cx, Editor::expand_excerpts);
281 register_action(view, cx, Editor::expand_excerpts_up);
282 register_action(view, cx, Editor::expand_excerpts_down);
283 }
284 register_action(view, cx, Editor::go_to_diagnostic);
285 register_action(view, cx, Editor::go_to_prev_diagnostic);
286 register_action(view, cx, Editor::go_to_hunk);
287 register_action(view, cx, Editor::go_to_prev_hunk);
288 register_action(view, cx, |editor, a, cx| {
289 editor.go_to_definition(a, cx).detach_and_log_err(cx);
290 });
291 register_action(view, cx, |editor, a, cx| {
292 editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
293 });
294 register_action(view, cx, |editor, a, cx| {
295 editor.go_to_implementation(a, cx).detach_and_log_err(cx);
296 });
297 register_action(view, cx, |editor, a, cx| {
298 editor
299 .go_to_implementation_split(a, cx)
300 .detach_and_log_err(cx);
301 });
302 register_action(view, cx, |editor, a, cx| {
303 editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
304 });
305 register_action(view, cx, |editor, a, cx| {
306 editor
307 .go_to_type_definition_split(a, cx)
308 .detach_and_log_err(cx);
309 });
310 register_action(view, cx, Editor::open_url);
311 register_action(view, cx, Editor::fold);
312 register_action(view, cx, Editor::fold_at);
313 register_action(view, cx, Editor::unfold_lines);
314 register_action(view, cx, Editor::unfold_at);
315 register_action(view, cx, Editor::fold_selected_ranges);
316 register_action(view, cx, Editor::show_completions);
317 register_action(view, cx, Editor::toggle_code_actions);
318 register_action(view, cx, Editor::open_excerpts);
319 register_action(view, cx, Editor::open_excerpts_in_split);
320 register_action(view, cx, Editor::toggle_soft_wrap);
321 register_action(view, cx, Editor::toggle_tab_bar);
322 register_action(view, cx, Editor::toggle_line_numbers);
323 register_action(view, cx, Editor::toggle_indent_guides);
324 register_action(view, cx, Editor::toggle_inlay_hints);
325 register_action(view, cx, hover_popover::hover);
326 register_action(view, cx, Editor::reveal_in_finder);
327 register_action(view, cx, Editor::copy_path);
328 register_action(view, cx, Editor::copy_relative_path);
329 register_action(view, cx, Editor::copy_highlight_json);
330 register_action(view, cx, Editor::copy_permalink_to_line);
331 register_action(view, cx, Editor::open_permalink_to_line);
332 register_action(view, cx, Editor::toggle_git_blame);
333 register_action(view, cx, Editor::toggle_git_blame_inline);
334 register_action(view, cx, Editor::toggle_hunk_diff);
335 register_action(view, cx, Editor::expand_all_hunk_diffs);
336 register_action(view, cx, |editor, action, cx| {
337 if let Some(task) = editor.format(action, cx) {
338 task.detach_and_log_err(cx);
339 } else {
340 cx.propagate();
341 }
342 });
343 register_action(view, cx, Editor::restart_language_server);
344 register_action(view, cx, Editor::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 && pending_nonempty_selections {
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_primary() {
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_crease_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<CreaseTrailerLayout>> {
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(CreaseTrailerLayout {
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 crease_trailer: Option<&CreaseTrailerLayout>,
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(crease_trailer) = crease_trailer {
1310 crease_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_crease_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_crease_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_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2814 let line_height = layout.position_map.line_height;
2815 let scroll_position = layout.position_map.snapshot.scroll_position();
2816 let scroll_top = scroll_position.y * line_height;
2817
2818 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2819
2820 for (ix, line) in layout.line_numbers.iter().enumerate() {
2821 if let Some(line) = line {
2822 let line_origin = layout.gutter_hitbox.origin
2823 + point(
2824 layout.gutter_hitbox.size.width
2825 - line.width
2826 - layout.gutter_dimensions.right_padding,
2827 ix as f32 * line_height - (scroll_top % line_height),
2828 );
2829
2830 line.paint(line_origin, line_height, cx).log_err();
2831 }
2832 }
2833 }
2834
2835 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2836 if layout.display_hunks.is_empty() {
2837 return;
2838 }
2839
2840 let line_height = layout.position_map.line_height;
2841 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2842 for (hunk, hitbox) in &layout.display_hunks {
2843 let hunk_to_paint = match hunk {
2844 DisplayDiffHunk::Folded { .. } => {
2845 let hunk_bounds = Self::diff_hunk_bounds(
2846 &layout.position_map.snapshot,
2847 line_height,
2848 layout.gutter_hitbox.bounds,
2849 &hunk,
2850 );
2851 Some((
2852 hunk_bounds,
2853 cx.theme().status().modified,
2854 Corners::all(1. * line_height),
2855 ))
2856 }
2857 DisplayDiffHunk::Unfolded { status, .. } => {
2858 hitbox.as_ref().map(|hunk_hitbox| match status {
2859 DiffHunkStatus::Added => (
2860 hunk_hitbox.bounds,
2861 cx.theme().status().created,
2862 Corners::all(0.05 * line_height),
2863 ),
2864 DiffHunkStatus::Modified => (
2865 hunk_hitbox.bounds,
2866 cx.theme().status().modified,
2867 Corners::all(0.05 * line_height),
2868 ),
2869 DiffHunkStatus::Removed => (
2870 Bounds::new(
2871 point(
2872 hunk_hitbox.origin.x - hunk_hitbox.size.width,
2873 hunk_hitbox.origin.y,
2874 ),
2875 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
2876 ),
2877 cx.theme().status().deleted,
2878 Corners::all(1. * line_height),
2879 ),
2880 })
2881 }
2882 };
2883
2884 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2885 cx.paint_quad(quad(
2886 hunk_bounds,
2887 corner_radii,
2888 background_color,
2889 Edges::default(),
2890 transparent_black(),
2891 ));
2892 }
2893 }
2894 });
2895 }
2896
2897 fn diff_hunk_bounds(
2898 snapshot: &EditorSnapshot,
2899 line_height: Pixels,
2900 bounds: Bounds<Pixels>,
2901 hunk: &DisplayDiffHunk,
2902 ) -> Bounds<Pixels> {
2903 let scroll_position = snapshot.scroll_position();
2904 let scroll_top = scroll_position.y * line_height;
2905
2906 match hunk {
2907 DisplayDiffHunk::Folded { display_row, .. } => {
2908 let start_y = display_row.as_f32() * line_height - scroll_top;
2909 let end_y = start_y + line_height;
2910
2911 let width = 0.275 * line_height;
2912 let highlight_origin = bounds.origin + point(px(0.), start_y);
2913 let highlight_size = size(width, end_y - start_y);
2914 Bounds::new(highlight_origin, highlight_size)
2915 }
2916 DisplayDiffHunk::Unfolded {
2917 display_row_range,
2918 status,
2919 ..
2920 } => match status {
2921 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2922 let start_row = display_row_range.start;
2923 let end_row = display_row_range.end;
2924 // If we're in a multibuffer, row range span might include an
2925 // excerpt header, so if we were to draw the marker straight away,
2926 // the hunk might include the rows of that header.
2927 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2928 // Instead, we simply check whether the range we're dealing with includes
2929 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2930 let end_row_in_current_excerpt = snapshot
2931 .blocks_in_range(start_row..end_row)
2932 .find_map(|(start_row, block)| {
2933 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2934 Some(start_row)
2935 } else {
2936 None
2937 }
2938 })
2939 .unwrap_or(end_row);
2940
2941 let start_y = start_row.as_f32() * line_height - scroll_top;
2942 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
2943
2944 let width = 0.275 * line_height;
2945 let highlight_origin = bounds.origin + point(px(0.), start_y);
2946 let highlight_size = size(width, end_y - start_y);
2947 Bounds::new(highlight_origin, highlight_size)
2948 }
2949 DiffHunkStatus::Removed => {
2950 let row = display_row_range.start;
2951
2952 let offset = line_height / 2.;
2953 let start_y = row.as_f32() * line_height - offset - scroll_top;
2954 let end_y = start_y + line_height;
2955
2956 let width = 0.35 * line_height;
2957 let highlight_origin = bounds.origin + point(px(0.), start_y);
2958 let highlight_size = size(width, end_y - start_y);
2959 Bounds::new(highlight_origin, highlight_size)
2960 }
2961 },
2962 }
2963 }
2964
2965 fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2966 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2967 cx.with_element_namespace("gutter_fold_toggles", |cx| {
2968 for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
2969 fold_indicator.paint(cx);
2970 }
2971 });
2972
2973 for test_indicators in layout.test_indicators.iter_mut() {
2974 test_indicators.paint(cx);
2975 }
2976
2977 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2978 indicator.paint(cx);
2979 }
2980 });
2981 }
2982
2983 fn paint_gutter_highlights(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2984 for (_, hunk_hitbox) in &layout.display_hunks {
2985 if let Some(hunk_hitbox) = hunk_hitbox {
2986 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
2987 }
2988 }
2989
2990 let show_git_gutter = layout
2991 .position_map
2992 .snapshot
2993 .show_git_diff_gutter
2994 .unwrap_or_else(|| {
2995 matches!(
2996 ProjectSettings::get_global(cx).git.git_gutter,
2997 Some(GitGutterSetting::TrackedFiles)
2998 )
2999 });
3000 if show_git_gutter {
3001 Self::paint_diff_hunks(layout, cx)
3002 }
3003
3004 let highlight_width = 0.275 * layout.position_map.line_height;
3005 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3006 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3007 for (range, color) in &layout.highlighted_gutter_ranges {
3008 let start_row = if range.start.row() < layout.visible_display_row_range.start {
3009 layout.visible_display_row_range.start - DisplayRow(1)
3010 } else {
3011 range.start.row()
3012 };
3013 let end_row = if range.end.row() > layout.visible_display_row_range.end {
3014 layout.visible_display_row_range.end + DisplayRow(1)
3015 } else {
3016 range.end.row()
3017 };
3018
3019 let start_y = layout.gutter_hitbox.top()
3020 + start_row.0 as f32 * layout.position_map.line_height
3021 - layout.position_map.scroll_pixel_position.y;
3022 let end_y = layout.gutter_hitbox.top()
3023 + (end_row.0 + 1) as f32 * layout.position_map.line_height
3024 - layout.position_map.scroll_pixel_position.y;
3025 let bounds = Bounds::from_corners(
3026 point(layout.gutter_hitbox.left(), start_y),
3027 point(layout.gutter_hitbox.left() + highlight_width, end_y),
3028 );
3029 cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3030 }
3031 });
3032 }
3033
3034 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3035 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3036 return;
3037 };
3038
3039 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3040 for mut blame_element in blamed_display_rows.into_iter() {
3041 blame_element.paint(cx);
3042 }
3043 })
3044 }
3045
3046 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3047 cx.with_content_mask(
3048 Some(ContentMask {
3049 bounds: layout.text_hitbox.bounds,
3050 }),
3051 |cx| {
3052 let cursor_style = if self
3053 .editor
3054 .read(cx)
3055 .hovered_link_state
3056 .as_ref()
3057 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3058 {
3059 CursorStyle::PointingHand
3060 } else {
3061 CursorStyle::IBeam
3062 };
3063 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3064
3065 let invisible_display_ranges = self.paint_highlights(layout, cx);
3066 self.paint_lines(&invisible_display_ranges, layout, cx);
3067 self.paint_redactions(layout, cx);
3068 self.paint_cursors(layout, cx);
3069 self.paint_inline_blame(layout, cx);
3070 cx.with_element_namespace("crease_trailers", |cx| {
3071 for trailer in layout.crease_trailers.iter_mut().flatten() {
3072 trailer.element.paint(cx);
3073 }
3074 });
3075 },
3076 )
3077 }
3078
3079 fn paint_highlights(
3080 &mut self,
3081 layout: &mut EditorLayout,
3082 cx: &mut WindowContext,
3083 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3084 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3085 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3086 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3087 for (range, color) in &layout.highlighted_ranges {
3088 self.paint_highlighted_range(
3089 range.clone(),
3090 *color,
3091 Pixels::ZERO,
3092 line_end_overshoot,
3093 layout,
3094 cx,
3095 );
3096 }
3097
3098 let corner_radius = 0.15 * layout.position_map.line_height;
3099
3100 for (player_color, selections) in &layout.selections {
3101 for selection in selections.into_iter() {
3102 self.paint_highlighted_range(
3103 selection.range.clone(),
3104 player_color.selection,
3105 corner_radius,
3106 corner_radius * 2.,
3107 layout,
3108 cx,
3109 );
3110
3111 if selection.is_local && !selection.range.is_empty() {
3112 invisible_display_ranges.push(selection.range.clone());
3113 }
3114 }
3115 }
3116 invisible_display_ranges
3117 })
3118 }
3119
3120 fn paint_lines(
3121 &mut self,
3122 invisible_display_ranges: &[Range<DisplayPoint>],
3123 layout: &mut EditorLayout,
3124 cx: &mut WindowContext,
3125 ) {
3126 let whitespace_setting = self
3127 .editor
3128 .read(cx)
3129 .buffer
3130 .read(cx)
3131 .settings_at(0, cx)
3132 .show_whitespaces;
3133
3134 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3135 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3136 line_with_invisibles.draw(
3137 layout,
3138 row,
3139 layout.content_origin,
3140 whitespace_setting,
3141 invisible_display_ranges,
3142 cx,
3143 )
3144 }
3145
3146 for line_element in &mut layout.line_elements {
3147 line_element.paint(cx);
3148 }
3149 }
3150
3151 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3152 if layout.redacted_ranges.is_empty() {
3153 return;
3154 }
3155
3156 let line_end_overshoot = layout.line_end_overshoot();
3157
3158 // A softer than perfect black
3159 let redaction_color = gpui::rgb(0x0e1111);
3160
3161 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3162 for range in layout.redacted_ranges.iter() {
3163 self.paint_highlighted_range(
3164 range.clone(),
3165 redaction_color.into(),
3166 Pixels::ZERO,
3167 line_end_overshoot,
3168 layout,
3169 cx,
3170 );
3171 }
3172 });
3173 }
3174
3175 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3176 for cursor in &mut layout.visible_cursors {
3177 cursor.paint(layout.content_origin, cx);
3178 }
3179 }
3180
3181 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3182 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3183 return;
3184 };
3185
3186 let thumb_bounds = scrollbar_layout.thumb_bounds();
3187 if scrollbar_layout.visible {
3188 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3189 cx.paint_quad(quad(
3190 scrollbar_layout.hitbox.bounds,
3191 Corners::default(),
3192 cx.theme().colors().scrollbar_track_background,
3193 Edges {
3194 top: Pixels::ZERO,
3195 right: Pixels::ZERO,
3196 bottom: Pixels::ZERO,
3197 left: ScrollbarLayout::BORDER_WIDTH,
3198 },
3199 cx.theme().colors().scrollbar_track_border,
3200 ));
3201
3202 let fast_markers =
3203 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3204 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3205 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3206
3207 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3208 for marker in markers.iter().chain(&fast_markers) {
3209 let mut marker = marker.clone();
3210 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3211 cx.paint_quad(marker);
3212 }
3213
3214 cx.paint_quad(quad(
3215 thumb_bounds,
3216 Corners::default(),
3217 cx.theme().colors().scrollbar_thumb_background,
3218 Edges {
3219 top: Pixels::ZERO,
3220 right: Pixels::ZERO,
3221 bottom: Pixels::ZERO,
3222 left: ScrollbarLayout::BORDER_WIDTH,
3223 },
3224 cx.theme().colors().scrollbar_thumb_border,
3225 ));
3226 });
3227 }
3228
3229 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3230
3231 let row_height = scrollbar_layout.row_height;
3232 let row_range = scrollbar_layout.visible_row_range.clone();
3233
3234 cx.on_mouse_event({
3235 let editor = self.editor.clone();
3236 let hitbox = scrollbar_layout.hitbox.clone();
3237 let mut mouse_position = cx.mouse_position();
3238 move |event: &MouseMoveEvent, phase, cx| {
3239 if phase == DispatchPhase::Capture {
3240 return;
3241 }
3242
3243 editor.update(cx, |editor, cx| {
3244 if event.pressed_button == Some(MouseButton::Left)
3245 && editor.scroll_manager.is_dragging_scrollbar()
3246 {
3247 let y = mouse_position.y;
3248 let new_y = event.position.y;
3249 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3250 let mut position = editor.scroll_position(cx);
3251 position.y += (new_y - y) / row_height;
3252 if position.y < 0.0 {
3253 position.y = 0.0;
3254 }
3255 editor.set_scroll_position(position, cx);
3256 }
3257
3258 cx.stop_propagation();
3259 } else {
3260 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3261 if hitbox.is_hovered(cx) {
3262 editor.scroll_manager.show_scrollbar(cx);
3263 }
3264 }
3265 mouse_position = event.position;
3266 })
3267 }
3268 });
3269
3270 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3271 cx.on_mouse_event({
3272 let editor = self.editor.clone();
3273 move |_: &MouseUpEvent, phase, cx| {
3274 if phase == DispatchPhase::Capture {
3275 return;
3276 }
3277
3278 editor.update(cx, |editor, cx| {
3279 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3280 cx.stop_propagation();
3281 });
3282 }
3283 });
3284 } else {
3285 cx.on_mouse_event({
3286 let editor = self.editor.clone();
3287 let hitbox = scrollbar_layout.hitbox.clone();
3288 move |event: &MouseDownEvent, phase, cx| {
3289 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3290 return;
3291 }
3292
3293 editor.update(cx, |editor, cx| {
3294 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3295
3296 let y = event.position.y;
3297 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3298 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3299 let top_row = center_row
3300 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3301 let mut position = editor.scroll_position(cx);
3302 position.y = top_row as f32;
3303 editor.set_scroll_position(position, cx);
3304 } else {
3305 editor.scroll_manager.show_scrollbar(cx);
3306 }
3307
3308 cx.stop_propagation();
3309 });
3310 }
3311 });
3312 }
3313 }
3314
3315 fn collect_fast_scrollbar_markers(
3316 &self,
3317 layout: &EditorLayout,
3318 scrollbar_layout: &ScrollbarLayout,
3319 cx: &mut WindowContext,
3320 ) -> Vec<PaintQuad> {
3321 const LIMIT: usize = 100;
3322 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3323 return vec![];
3324 }
3325 let cursor_ranges = layout
3326 .cursors
3327 .iter()
3328 .map(|(point, color)| ColoredRange {
3329 start: point.row(),
3330 end: point.row(),
3331 color: *color,
3332 })
3333 .collect_vec();
3334 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3335 }
3336
3337 fn refresh_slow_scrollbar_markers(
3338 &self,
3339 layout: &EditorLayout,
3340 scrollbar_layout: &ScrollbarLayout,
3341 cx: &mut WindowContext,
3342 ) {
3343 self.editor.update(cx, |editor, cx| {
3344 if !editor.is_singleton(cx)
3345 || !editor
3346 .scrollbar_marker_state
3347 .should_refresh(scrollbar_layout.hitbox.size)
3348 {
3349 return;
3350 }
3351
3352 let scrollbar_layout = scrollbar_layout.clone();
3353 let background_highlights = editor.background_highlights.clone();
3354 let snapshot = layout.position_map.snapshot.clone();
3355 let theme = cx.theme().clone();
3356 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3357
3358 editor.scrollbar_marker_state.dirty = false;
3359 editor.scrollbar_marker_state.pending_refresh =
3360 Some(cx.spawn(|editor, mut cx| async move {
3361 let scrollbar_size = scrollbar_layout.hitbox.size;
3362 let scrollbar_markers = cx
3363 .background_executor()
3364 .spawn(async move {
3365 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3366 let mut marker_quads = Vec::new();
3367 if scrollbar_settings.git_diff {
3368 let marker_row_ranges = snapshot
3369 .buffer_snapshot
3370 .git_diff_hunks_in_range(
3371 MultiBufferRow::MIN..MultiBufferRow::MAX,
3372 )
3373 .map(|hunk| {
3374 let start_display_row =
3375 MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3376 .to_display_point(&snapshot.display_snapshot)
3377 .row();
3378 let mut end_display_row =
3379 MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3380 .to_display_point(&snapshot.display_snapshot)
3381 .row();
3382 if end_display_row != start_display_row {
3383 end_display_row.0 -= 1;
3384 }
3385 let color = match hunk_status(&hunk) {
3386 DiffHunkStatus::Added => theme.status().created,
3387 DiffHunkStatus::Modified => theme.status().modified,
3388 DiffHunkStatus::Removed => theme.status().deleted,
3389 };
3390 ColoredRange {
3391 start: start_display_row,
3392 end: end_display_row,
3393 color,
3394 }
3395 });
3396
3397 marker_quads.extend(
3398 scrollbar_layout
3399 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3400 );
3401 }
3402
3403 for (background_highlight_id, (_, background_ranges)) in
3404 background_highlights.iter()
3405 {
3406 let is_search_highlights = *background_highlight_id
3407 == TypeId::of::<BufferSearchHighlights>();
3408 let is_symbol_occurrences = *background_highlight_id
3409 == TypeId::of::<DocumentHighlightRead>()
3410 || *background_highlight_id
3411 == TypeId::of::<DocumentHighlightWrite>();
3412 if (is_search_highlights && scrollbar_settings.search_results)
3413 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3414 {
3415 let mut color = theme.status().info;
3416 if is_symbol_occurrences {
3417 color.fade_out(0.5);
3418 }
3419 let marker_row_ranges =
3420 background_ranges.into_iter().map(|range| {
3421 let display_start = range
3422 .start
3423 .to_display_point(&snapshot.display_snapshot);
3424 let display_end = range
3425 .end
3426 .to_display_point(&snapshot.display_snapshot);
3427 ColoredRange {
3428 start: display_start.row(),
3429 end: display_end.row(),
3430 color,
3431 }
3432 });
3433 marker_quads.extend(
3434 scrollbar_layout
3435 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3436 );
3437 }
3438 }
3439
3440 if scrollbar_settings.diagnostics {
3441 let diagnostics = snapshot
3442 .buffer_snapshot
3443 .diagnostics_in_range::<_, Point>(
3444 Point::zero()..max_point,
3445 false,
3446 )
3447 // We want to sort by severity, in order to paint the most severe diagnostics last.
3448 .sorted_by_key(|diagnostic| {
3449 std::cmp::Reverse(diagnostic.diagnostic.severity)
3450 });
3451
3452 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3453 let start_display = diagnostic
3454 .range
3455 .start
3456 .to_display_point(&snapshot.display_snapshot);
3457 let end_display = diagnostic
3458 .range
3459 .end
3460 .to_display_point(&snapshot.display_snapshot);
3461 let color = match diagnostic.diagnostic.severity {
3462 DiagnosticSeverity::ERROR => theme.status().error,
3463 DiagnosticSeverity::WARNING => theme.status().warning,
3464 DiagnosticSeverity::INFORMATION => theme.status().info,
3465 _ => theme.status().hint,
3466 };
3467 ColoredRange {
3468 start: start_display.row(),
3469 end: end_display.row(),
3470 color,
3471 }
3472 });
3473 marker_quads.extend(
3474 scrollbar_layout
3475 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3476 );
3477 }
3478
3479 Arc::from(marker_quads)
3480 })
3481 .await;
3482
3483 editor.update(&mut cx, |editor, cx| {
3484 editor.scrollbar_marker_state.markers = scrollbar_markers;
3485 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3486 editor.scrollbar_marker_state.pending_refresh = None;
3487 cx.notify();
3488 })?;
3489
3490 Ok(())
3491 }));
3492 });
3493 }
3494
3495 #[allow(clippy::too_many_arguments)]
3496 fn paint_highlighted_range(
3497 &self,
3498 range: Range<DisplayPoint>,
3499 color: Hsla,
3500 corner_radius: Pixels,
3501 line_end_overshoot: Pixels,
3502 layout: &EditorLayout,
3503 cx: &mut WindowContext,
3504 ) {
3505 let start_row = layout.visible_display_row_range.start;
3506 let end_row = layout.visible_display_row_range.end;
3507 if range.start != range.end {
3508 let row_range = if range.end.column() == 0 {
3509 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3510 } else {
3511 cmp::max(range.start.row(), start_row)
3512 ..cmp::min(range.end.row().next_row(), end_row)
3513 };
3514
3515 let highlighted_range = HighlightedRange {
3516 color,
3517 line_height: layout.position_map.line_height,
3518 corner_radius,
3519 start_y: layout.content_origin.y
3520 + row_range.start.as_f32() * layout.position_map.line_height
3521 - layout.position_map.scroll_pixel_position.y,
3522 lines: row_range
3523 .iter_rows()
3524 .map(|row| {
3525 let line_layout =
3526 &layout.position_map.line_layouts[row.minus(start_row) as usize];
3527 HighlightedRangeLine {
3528 start_x: if row == range.start.row() {
3529 layout.content_origin.x
3530 + line_layout.x_for_index(range.start.column() as usize)
3531 - layout.position_map.scroll_pixel_position.x
3532 } else {
3533 layout.content_origin.x
3534 - layout.position_map.scroll_pixel_position.x
3535 },
3536 end_x: if row == range.end.row() {
3537 layout.content_origin.x
3538 + line_layout.x_for_index(range.end.column() as usize)
3539 - layout.position_map.scroll_pixel_position.x
3540 } else {
3541 layout.content_origin.x + line_layout.width + line_end_overshoot
3542 - layout.position_map.scroll_pixel_position.x
3543 },
3544 }
3545 })
3546 .collect(),
3547 };
3548
3549 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3550 }
3551 }
3552
3553 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3554 if let Some(mut inline_blame) = layout.inline_blame.take() {
3555 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3556 inline_blame.paint(cx);
3557 })
3558 }
3559 }
3560
3561 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3562 for mut block in layout.blocks.drain(..) {
3563 block.element.paint(cx);
3564 }
3565 }
3566
3567 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3568 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3569 mouse_context_menu.paint(cx);
3570 }
3571 }
3572
3573 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3574 cx.on_mouse_event({
3575 let position_map = layout.position_map.clone();
3576 let editor = self.editor.clone();
3577 let hitbox = layout.hitbox.clone();
3578 let mut delta = ScrollDelta::default();
3579
3580 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3581 // accidentally turn off their scrolling.
3582 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3583
3584 move |event: &ScrollWheelEvent, phase, cx| {
3585 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3586 delta = delta.coalesce(event.delta);
3587 editor.update(cx, |editor, cx| {
3588 let position_map: &PositionMap = &position_map;
3589
3590 let line_height = position_map.line_height;
3591 let max_glyph_width = position_map.em_width;
3592 let (delta, axis) = match delta {
3593 gpui::ScrollDelta::Pixels(mut pixels) => {
3594 //Trackpad
3595 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3596 (pixels, axis)
3597 }
3598
3599 gpui::ScrollDelta::Lines(lines) => {
3600 //Not trackpad
3601 let pixels =
3602 point(lines.x * max_glyph_width, lines.y * line_height);
3603 (pixels, None)
3604 }
3605 };
3606
3607 let current_scroll_position = position_map.snapshot.scroll_position();
3608 let x = (current_scroll_position.x * max_glyph_width
3609 - (delta.x * scroll_sensitivity))
3610 / max_glyph_width;
3611 let y = (current_scroll_position.y * line_height
3612 - (delta.y * scroll_sensitivity))
3613 / line_height;
3614 let mut scroll_position =
3615 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3616 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3617 if forbid_vertical_scroll {
3618 scroll_position.y = current_scroll_position.y;
3619 if scroll_position == current_scroll_position {
3620 return;
3621 }
3622 }
3623 editor.scroll(scroll_position, axis, cx);
3624 cx.stop_propagation();
3625 });
3626 }
3627 }
3628 });
3629 }
3630
3631 fn paint_mouse_listeners(
3632 &mut self,
3633 layout: &EditorLayout,
3634 hovered_hunk: Option<HunkToExpand>,
3635 cx: &mut WindowContext,
3636 ) {
3637 self.paint_scroll_wheel_listener(layout, cx);
3638
3639 cx.on_mouse_event({
3640 let position_map = layout.position_map.clone();
3641 let editor = self.editor.clone();
3642 let text_hitbox = layout.text_hitbox.clone();
3643 let gutter_hitbox = layout.gutter_hitbox.clone();
3644
3645 move |event: &MouseDownEvent, phase, cx| {
3646 if phase == DispatchPhase::Bubble {
3647 match event.button {
3648 MouseButton::Left => editor.update(cx, |editor, cx| {
3649 Self::mouse_left_down(
3650 editor,
3651 event,
3652 hovered_hunk.as_ref(),
3653 &position_map,
3654 &text_hitbox,
3655 &gutter_hitbox,
3656 cx,
3657 );
3658 }),
3659 MouseButton::Right => editor.update(cx, |editor, cx| {
3660 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3661 }),
3662 MouseButton::Middle => editor.update(cx, |editor, cx| {
3663 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3664 }),
3665 _ => {}
3666 };
3667 }
3668 }
3669 });
3670
3671 cx.on_mouse_event({
3672 let editor = self.editor.clone();
3673 let position_map = layout.position_map.clone();
3674 let text_hitbox = layout.text_hitbox.clone();
3675
3676 move |event: &MouseUpEvent, phase, cx| {
3677 if phase == DispatchPhase::Bubble {
3678 editor.update(cx, |editor, cx| {
3679 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3680 });
3681 }
3682 }
3683 });
3684 cx.on_mouse_event({
3685 let position_map = layout.position_map.clone();
3686 let editor = self.editor.clone();
3687 let text_hitbox = layout.text_hitbox.clone();
3688 let gutter_hitbox = layout.gutter_hitbox.clone();
3689
3690 move |event: &MouseMoveEvent, phase, cx| {
3691 if phase == DispatchPhase::Bubble {
3692 editor.update(cx, |editor, cx| {
3693 if event.pressed_button == Some(MouseButton::Left)
3694 || event.pressed_button == Some(MouseButton::Middle)
3695 {
3696 Self::mouse_dragged(
3697 editor,
3698 event,
3699 &position_map,
3700 text_hitbox.bounds,
3701 cx,
3702 )
3703 }
3704
3705 Self::mouse_moved(
3706 editor,
3707 event,
3708 &position_map,
3709 &text_hitbox,
3710 &gutter_hitbox,
3711 cx,
3712 )
3713 });
3714 }
3715 }
3716 });
3717 }
3718
3719 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3720 bounds.upper_right().x - self.style.scrollbar_width
3721 }
3722
3723 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3724 let style = &self.style;
3725 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3726 let layout = cx
3727 .text_system()
3728 .shape_line(
3729 SharedString::from(" ".repeat(column)),
3730 font_size,
3731 &[TextRun {
3732 len: column,
3733 font: style.text.font(),
3734 color: Hsla::default(),
3735 background_color: None,
3736 underline: None,
3737 strikethrough: None,
3738 }],
3739 )
3740 .unwrap();
3741
3742 layout.width
3743 }
3744
3745 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3746 let digit_count = snapshot
3747 .max_buffer_row()
3748 .next_row()
3749 .as_f32()
3750 .log10()
3751 .floor() as usize
3752 + 1;
3753 self.column_pixels(digit_count, cx)
3754 }
3755}
3756
3757fn prepaint_gutter_button(
3758 button: IconButton,
3759 row: DisplayRow,
3760 line_height: Pixels,
3761 gutter_dimensions: &GutterDimensions,
3762 scroll_pixel_position: gpui::Point<Pixels>,
3763 gutter_hitbox: &Hitbox,
3764 cx: &mut WindowContext<'_>,
3765) -> AnyElement {
3766 let mut button = button.into_any_element();
3767 let available_space = size(
3768 AvailableSpace::MinContent,
3769 AvailableSpace::Definite(line_height),
3770 );
3771 let indicator_size = button.layout_as_root(available_space, cx);
3772
3773 let blame_width = gutter_dimensions
3774 .git_blame_entries_width
3775 .unwrap_or(Pixels::ZERO);
3776
3777 let mut x = blame_width;
3778 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3779 - indicator_size.width
3780 - blame_width;
3781 x += available_width / 2.;
3782
3783 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3784 y += (line_height - indicator_size.height) / 2.;
3785
3786 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3787 button
3788}
3789
3790fn render_inline_blame_entry(
3791 blame: &gpui::Model<GitBlame>,
3792 blame_entry: BlameEntry,
3793 style: &EditorStyle,
3794 workspace: Option<WeakView<Workspace>>,
3795 cx: &mut WindowContext<'_>,
3796) -> AnyElement {
3797 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3798
3799 let author = blame_entry.author.as_deref().unwrap_or_default();
3800 let text = format!("{}, {}", author, relative_timestamp);
3801
3802 let details = blame.read(cx).details_for_entry(&blame_entry);
3803
3804 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3805
3806 h_flex()
3807 .id("inline-blame")
3808 .w_full()
3809 .font_family(style.text.font().family)
3810 .text_color(cx.theme().status().hint)
3811 .line_height(style.text.line_height)
3812 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3813 .child(text)
3814 .gap_2()
3815 .hoverable_tooltip(move |_| tooltip.clone().into())
3816 .into_any()
3817}
3818
3819fn render_blame_entry(
3820 ix: usize,
3821 blame: &gpui::Model<GitBlame>,
3822 blame_entry: BlameEntry,
3823 style: &EditorStyle,
3824 last_used_color: &mut Option<(PlayerColor, Oid)>,
3825 editor: View<Editor>,
3826 cx: &mut WindowContext<'_>,
3827) -> AnyElement {
3828 let mut sha_color = cx
3829 .theme()
3830 .players()
3831 .color_for_participant(blame_entry.sha.into());
3832 // If the last color we used is the same as the one we get for this line, but
3833 // the commit SHAs are different, then we try again to get a different color.
3834 match *last_used_color {
3835 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3836 let index: u32 = blame_entry.sha.into();
3837 sha_color = cx.theme().players().color_for_participant(index + 1);
3838 }
3839 _ => {}
3840 };
3841 last_used_color.replace((sha_color, blame_entry.sha));
3842
3843 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3844
3845 let short_commit_id = blame_entry.sha.display_short();
3846
3847 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3848 let name = util::truncate_and_trailoff(author_name, 20);
3849
3850 let details = blame.read(cx).details_for_entry(&blame_entry);
3851
3852 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3853
3854 let tooltip = cx.new_view(|_| {
3855 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3856 });
3857
3858 h_flex()
3859 .w_full()
3860 .font_family(style.text.font().family)
3861 .line_height(style.text.line_height)
3862 .id(("blame", ix))
3863 .children([
3864 div()
3865 .text_color(sha_color.cursor)
3866 .child(short_commit_id)
3867 .mr_2(),
3868 div()
3869 .w_full()
3870 .h_flex()
3871 .justify_between()
3872 .text_color(cx.theme().status().hint)
3873 .child(name)
3874 .child(relative_timestamp),
3875 ])
3876 .on_mouse_down(MouseButton::Right, {
3877 let blame_entry = blame_entry.clone();
3878 let details = details.clone();
3879 move |event, cx| {
3880 deploy_blame_entry_context_menu(
3881 &blame_entry,
3882 details.as_ref(),
3883 editor.clone(),
3884 event.position,
3885 cx,
3886 );
3887 }
3888 })
3889 .hover(|style| style.bg(cx.theme().colors().element_hover))
3890 .when_some(
3891 details.and_then(|details| details.permalink),
3892 |this, url| {
3893 let url = url.clone();
3894 this.cursor_pointer().on_click(move |_, cx| {
3895 cx.stop_propagation();
3896 cx.open_url(url.as_str())
3897 })
3898 },
3899 )
3900 .hoverable_tooltip(move |_| tooltip.clone().into())
3901 .into_any()
3902}
3903
3904fn deploy_blame_entry_context_menu(
3905 blame_entry: &BlameEntry,
3906 details: Option<&CommitDetails>,
3907 editor: View<Editor>,
3908 position: gpui::Point<Pixels>,
3909 cx: &mut WindowContext<'_>,
3910) {
3911 let context_menu = ContextMenu::build(cx, move |this, _| {
3912 let sha = format!("{}", blame_entry.sha);
3913 this.entry("Copy commit SHA", None, move |cx| {
3914 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3915 })
3916 .when_some(
3917 details.and_then(|details| details.permalink.clone()),
3918 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
3919 )
3920 });
3921
3922 editor.update(cx, move |editor, cx| {
3923 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3924 cx.notify();
3925 });
3926}
3927
3928#[derive(Debug)]
3929pub(crate) struct LineWithInvisibles {
3930 fragments: SmallVec<[LineFragment; 1]>,
3931 invisibles: Vec<Invisible>,
3932 len: usize,
3933 width: Pixels,
3934 font_size: Pixels,
3935}
3936
3937#[allow(clippy::large_enum_variant)]
3938enum LineFragment {
3939 Text(ShapedLine),
3940 Element {
3941 element: Option<AnyElement>,
3942 size: Size<Pixels>,
3943 len: usize,
3944 },
3945}
3946
3947impl fmt::Debug for LineFragment {
3948 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3949 match self {
3950 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
3951 LineFragment::Element { size, len, .. } => f
3952 .debug_struct("Element")
3953 .field("size", size)
3954 .field("len", len)
3955 .finish(),
3956 }
3957 }
3958}
3959
3960impl LineWithInvisibles {
3961 fn from_chunks<'a>(
3962 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3963 text_style: &TextStyle,
3964 max_line_len: usize,
3965 max_line_count: usize,
3966 line_number_layouts: &[Option<ShapedLine>],
3967 editor_mode: EditorMode,
3968 cx: &mut WindowContext,
3969 ) -> Vec<Self> {
3970 let mut layouts = Vec::with_capacity(max_line_count);
3971 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
3972 let mut line = String::new();
3973 let mut invisibles = Vec::new();
3974 let mut width = Pixels::ZERO;
3975 let mut len = 0;
3976 let mut styles = Vec::new();
3977 let mut non_whitespace_added = false;
3978 let mut row = 0;
3979 let mut line_exceeded_max_len = false;
3980 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3981
3982 let ellipsis = SharedString::from("⋯");
3983
3984 for highlighted_chunk in chunks.chain([HighlightedChunk {
3985 text: "\n",
3986 style: None,
3987 is_tab: false,
3988 renderer: None,
3989 }]) {
3990 if let Some(renderer) = highlighted_chunk.renderer {
3991 if !line.is_empty() {
3992 let shaped_line = cx
3993 .text_system()
3994 .shape_line(line.clone().into(), font_size, &styles)
3995 .unwrap();
3996 width += shaped_line.width;
3997 len += shaped_line.len;
3998 fragments.push(LineFragment::Text(shaped_line));
3999 line.clear();
4000 styles.clear();
4001 }
4002
4003 let available_width = if renderer.constrain_width {
4004 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4005 ellipsis.clone()
4006 } else {
4007 SharedString::from(Arc::from(highlighted_chunk.text))
4008 };
4009 let shaped_line = cx
4010 .text_system()
4011 .shape_line(
4012 chunk,
4013 font_size,
4014 &[text_style.to_run(highlighted_chunk.text.len())],
4015 )
4016 .unwrap();
4017 AvailableSpace::Definite(shaped_line.width)
4018 } else {
4019 AvailableSpace::MinContent
4020 };
4021
4022 let mut element = (renderer.render)(cx);
4023 let line_height = text_style.line_height_in_pixels(cx.rem_size());
4024 let size = element.layout_as_root(
4025 size(available_width, AvailableSpace::Definite(line_height)),
4026 cx,
4027 );
4028
4029 width += size.width;
4030 len += highlighted_chunk.text.len();
4031 fragments.push(LineFragment::Element {
4032 element: Some(element),
4033 size,
4034 len: highlighted_chunk.text.len(),
4035 });
4036 } else {
4037 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4038 if ix > 0 {
4039 let shaped_line = cx
4040 .text_system()
4041 .shape_line(line.clone().into(), font_size, &styles)
4042 .unwrap();
4043 width += shaped_line.width;
4044 len += shaped_line.len;
4045 fragments.push(LineFragment::Text(shaped_line));
4046 layouts.push(Self {
4047 width: mem::take(&mut width),
4048 len: mem::take(&mut len),
4049 fragments: mem::take(&mut fragments),
4050 invisibles: std::mem::take(&mut invisibles),
4051 font_size,
4052 });
4053
4054 line.clear();
4055 styles.clear();
4056 row += 1;
4057 line_exceeded_max_len = false;
4058 non_whitespace_added = false;
4059 if row == max_line_count {
4060 return layouts;
4061 }
4062 }
4063
4064 if !line_chunk.is_empty() && !line_exceeded_max_len {
4065 let text_style = if let Some(style) = highlighted_chunk.style {
4066 Cow::Owned(text_style.clone().highlight(style))
4067 } else {
4068 Cow::Borrowed(text_style)
4069 };
4070
4071 if line.len() + line_chunk.len() > max_line_len {
4072 let mut chunk_len = max_line_len - line.len();
4073 while !line_chunk.is_char_boundary(chunk_len) {
4074 chunk_len -= 1;
4075 }
4076 line_chunk = &line_chunk[..chunk_len];
4077 line_exceeded_max_len = true;
4078 }
4079
4080 styles.push(TextRun {
4081 len: line_chunk.len(),
4082 font: text_style.font(),
4083 color: text_style.color,
4084 background_color: text_style.background_color,
4085 underline: text_style.underline,
4086 strikethrough: text_style.strikethrough,
4087 });
4088
4089 if editor_mode == EditorMode::Full {
4090 // Line wrap pads its contents with fake whitespaces,
4091 // avoid printing them
4092 let inside_wrapped_string = line_number_layouts
4093 .get(row)
4094 .and_then(|layout| layout.as_ref())
4095 .is_none();
4096 if highlighted_chunk.is_tab {
4097 if non_whitespace_added || !inside_wrapped_string {
4098 invisibles.push(Invisible::Tab {
4099 line_start_offset: line.len(),
4100 line_end_offset: line.len() + line_chunk.len(),
4101 });
4102 }
4103 } else {
4104 invisibles.extend(
4105 line_chunk
4106 .bytes()
4107 .enumerate()
4108 .filter(|(_, line_byte)| {
4109 let is_whitespace =
4110 (*line_byte as char).is_whitespace();
4111 non_whitespace_added |= !is_whitespace;
4112 is_whitespace
4113 && (non_whitespace_added || !inside_wrapped_string)
4114 })
4115 .map(|(whitespace_index, _)| Invisible::Whitespace {
4116 line_offset: line.len() + whitespace_index,
4117 }),
4118 )
4119 }
4120 }
4121
4122 line.push_str(line_chunk);
4123 }
4124 }
4125 }
4126 }
4127
4128 layouts
4129 }
4130
4131 fn prepaint(
4132 &mut self,
4133 line_height: Pixels,
4134 scroll_pixel_position: gpui::Point<Pixels>,
4135 row: DisplayRow,
4136 content_origin: gpui::Point<Pixels>,
4137 line_elements: &mut SmallVec<[AnyElement; 1]>,
4138 cx: &mut WindowContext,
4139 ) {
4140 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4141 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4142 for fragment in &mut self.fragments {
4143 match fragment {
4144 LineFragment::Text(line) => {
4145 fragment_origin.x += line.width;
4146 }
4147 LineFragment::Element { element, size, .. } => {
4148 let mut element = element
4149 .take()
4150 .expect("you can't prepaint LineWithInvisibles twice");
4151
4152 // Center the element vertically within the line.
4153 let mut element_origin = fragment_origin;
4154 element_origin.y += (line_height - size.height) / 2.;
4155 element.prepaint_at(element_origin, cx);
4156 line_elements.push(element);
4157
4158 fragment_origin.x += size.width;
4159 }
4160 }
4161 }
4162 }
4163
4164 fn draw(
4165 &self,
4166 layout: &EditorLayout,
4167 row: DisplayRow,
4168 content_origin: gpui::Point<Pixels>,
4169 whitespace_setting: ShowWhitespaceSetting,
4170 selection_ranges: &[Range<DisplayPoint>],
4171 cx: &mut WindowContext,
4172 ) {
4173 let line_height = layout.position_map.line_height;
4174 let line_y = line_height
4175 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4176
4177 let mut fragment_origin =
4178 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4179
4180 for fragment in &self.fragments {
4181 match fragment {
4182 LineFragment::Text(line) => {
4183 line.paint(fragment_origin, line_height, cx).log_err();
4184 fragment_origin.x += line.width;
4185 }
4186 LineFragment::Element { size, .. } => {
4187 fragment_origin.x += size.width;
4188 }
4189 }
4190 }
4191
4192 self.draw_invisibles(
4193 &selection_ranges,
4194 layout,
4195 content_origin,
4196 line_y,
4197 row,
4198 line_height,
4199 whitespace_setting,
4200 cx,
4201 );
4202 }
4203
4204 #[allow(clippy::too_many_arguments)]
4205 fn draw_invisibles(
4206 &self,
4207 selection_ranges: &[Range<DisplayPoint>],
4208 layout: &EditorLayout,
4209 content_origin: gpui::Point<Pixels>,
4210 line_y: Pixels,
4211 row: DisplayRow,
4212 line_height: Pixels,
4213 whitespace_setting: ShowWhitespaceSetting,
4214 cx: &mut WindowContext,
4215 ) {
4216 let extract_whitespace_info = |invisible: &Invisible| {
4217 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4218 Invisible::Tab {
4219 line_start_offset,
4220 line_end_offset,
4221 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4222 Invisible::Whitespace { line_offset } => {
4223 (*line_offset, line_offset + 1, &layout.space_invisible)
4224 }
4225 };
4226
4227 let x_offset = self.x_for_index(token_offset);
4228 let invisible_offset =
4229 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4230 let origin = content_origin
4231 + gpui::point(
4232 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4233 line_y,
4234 );
4235
4236 (
4237 [token_offset, token_end_offset],
4238 Box::new(move |cx: &mut WindowContext| {
4239 invisible_symbol.paint(origin, line_height, cx).log_err();
4240 }),
4241 )
4242 };
4243
4244 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4245 match whitespace_setting {
4246 ShowWhitespaceSetting::None => return,
4247 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4248 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4249 let invisible_point = DisplayPoint::new(row, start as u32);
4250 if !selection_ranges
4251 .iter()
4252 .any(|region| region.start <= invisible_point && invisible_point < region.end)
4253 {
4254 return;
4255 }
4256
4257 paint(cx);
4258 }),
4259
4260 // For a whitespace to be on a boundary, any of the following conditions need to be met:
4261 // - It is a tab
4262 // - It is adjacent to an edge (start or end)
4263 // - It is adjacent to a whitespace (left or right)
4264 ShowWhitespaceSetting::Boundary => {
4265 // 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
4266 // the above cases.
4267 // Note: We zip in the original `invisibles` to check for tab equality
4268 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4269 for (([start, end], paint), invisible) in
4270 invisible_iter.zip_eq(self.invisibles.iter())
4271 {
4272 let should_render = match (&last_seen, invisible) {
4273 (_, Invisible::Tab { .. }) => true,
4274 (Some((_, last_end, _)), _) => *last_end == start,
4275 _ => false,
4276 };
4277
4278 if should_render || start == 0 || end == self.len {
4279 paint(cx);
4280
4281 // Since we are scanning from the left, we will skip over the first available whitespace that is part
4282 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4283 if let Some((should_render_last, last_end, paint_last)) = last_seen {
4284 // Note that we need to make sure that the last one is actually adjacent
4285 if !should_render_last && last_end == start {
4286 paint_last(cx);
4287 }
4288 }
4289 }
4290
4291 // Manually render anything within a selection
4292 let invisible_point = DisplayPoint::new(row, start as u32);
4293 if selection_ranges.iter().any(|region| {
4294 region.start <= invisible_point && invisible_point < region.end
4295 }) {
4296 paint(cx);
4297 }
4298
4299 last_seen = Some((should_render, end, paint));
4300 }
4301 }
4302 };
4303 }
4304
4305 pub fn x_for_index(&self, index: usize) -> Pixels {
4306 let mut fragment_start_x = Pixels::ZERO;
4307 let mut fragment_start_index = 0;
4308
4309 for fragment in &self.fragments {
4310 match fragment {
4311 LineFragment::Text(shaped_line) => {
4312 let fragment_end_index = fragment_start_index + shaped_line.len;
4313 if index < fragment_end_index {
4314 return fragment_start_x
4315 + shaped_line.x_for_index(index - fragment_start_index);
4316 }
4317 fragment_start_x += shaped_line.width;
4318 fragment_start_index = fragment_end_index;
4319 }
4320 LineFragment::Element { len, size, .. } => {
4321 let fragment_end_index = fragment_start_index + len;
4322 if index < fragment_end_index {
4323 return fragment_start_x;
4324 }
4325 fragment_start_x += size.width;
4326 fragment_start_index = fragment_end_index;
4327 }
4328 }
4329 }
4330
4331 fragment_start_x
4332 }
4333
4334 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4335 let mut fragment_start_x = Pixels::ZERO;
4336 let mut fragment_start_index = 0;
4337
4338 for fragment in &self.fragments {
4339 match fragment {
4340 LineFragment::Text(shaped_line) => {
4341 let fragment_end_x = fragment_start_x + shaped_line.width;
4342 if x < fragment_end_x {
4343 return Some(
4344 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4345 );
4346 }
4347 fragment_start_x = fragment_end_x;
4348 fragment_start_index += shaped_line.len;
4349 }
4350 LineFragment::Element { len, size, .. } => {
4351 let fragment_end_x = fragment_start_x + size.width;
4352 if x < fragment_end_x {
4353 return Some(fragment_start_index);
4354 }
4355 fragment_start_index += len;
4356 fragment_start_x = fragment_end_x;
4357 }
4358 }
4359 }
4360
4361 None
4362 }
4363
4364 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4365 let mut fragment_start_index = 0;
4366
4367 for fragment in &self.fragments {
4368 match fragment {
4369 LineFragment::Text(shaped_line) => {
4370 let fragment_end_index = fragment_start_index + shaped_line.len;
4371 if index < fragment_end_index {
4372 return shaped_line.font_id_for_index(index - fragment_start_index);
4373 }
4374 fragment_start_index = fragment_end_index;
4375 }
4376 LineFragment::Element { len, .. } => {
4377 let fragment_end_index = fragment_start_index + len;
4378 if index < fragment_end_index {
4379 return None;
4380 }
4381 fragment_start_index = fragment_end_index;
4382 }
4383 }
4384 }
4385
4386 None
4387 }
4388}
4389
4390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4391enum Invisible {
4392 /// A tab character
4393 ///
4394 /// A tab character is internally represented by spaces (configured by the user's tab width)
4395 /// aligned to the nearest column, so it's necessary to store the start and end offset for
4396 /// adjacency checks.
4397 Tab {
4398 line_start_offset: usize,
4399 line_end_offset: usize,
4400 },
4401 Whitespace {
4402 line_offset: usize,
4403 },
4404}
4405
4406impl EditorElement {
4407 /// Returns the rem size to use when rendering the [`EditorElement`].
4408 ///
4409 /// This allows UI elements to scale based on the `buffer_font_size`.
4410 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4411 match self.editor.read(cx).mode {
4412 EditorMode::Full => {
4413 let buffer_font_size = self.style.text.font_size;
4414 match buffer_font_size {
4415 AbsoluteLength::Pixels(pixels) => {
4416 let rem_size_scale = {
4417 // Our default UI font size is 14px on a 16px base scale.
4418 // This means the default UI font size is 0.875rems.
4419 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4420
4421 // We then determine the delta between a single rem and the default font
4422 // size scale.
4423 let default_font_size_delta = 1. - default_font_size_scale;
4424
4425 // Finally, we add this delta to 1rem to get the scale factor that
4426 // should be used to scale up the UI.
4427 1. + default_font_size_delta
4428 };
4429
4430 Some(pixels * rem_size_scale)
4431 }
4432 AbsoluteLength::Rems(rems) => {
4433 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4434 }
4435 }
4436 }
4437 // We currently use single-line and auto-height editors in UI contexts,
4438 // so we don't want to scale everything with the buffer font size, as it
4439 // ends up looking off.
4440 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => None,
4441 }
4442 }
4443}
4444
4445impl Element for EditorElement {
4446 type RequestLayoutState = ();
4447 type PrepaintState = EditorLayout;
4448
4449 fn id(&self) -> Option<ElementId> {
4450 None
4451 }
4452
4453 fn request_layout(
4454 &mut self,
4455 _: Option<&GlobalElementId>,
4456 cx: &mut WindowContext,
4457 ) -> (gpui::LayoutId, ()) {
4458 let rem_size = self.rem_size(cx);
4459 cx.with_rem_size(rem_size, |cx| {
4460 self.editor.update(cx, |editor, cx| {
4461 editor.set_style(self.style.clone(), cx);
4462
4463 let layout_id = match editor.mode {
4464 EditorMode::SingleLine => {
4465 let rem_size = cx.rem_size();
4466 let mut style = Style::default();
4467 style.size.width = relative(1.).into();
4468 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
4469 cx.request_layout(style, None)
4470 }
4471 EditorMode::AutoHeight { max_lines } => {
4472 let editor_handle = cx.view().clone();
4473 let max_line_number_width =
4474 self.max_line_number_width(&editor.snapshot(cx), cx);
4475 cx.request_measured_layout(
4476 Style::default(),
4477 move |known_dimensions, available_space, cx| {
4478 editor_handle
4479 .update(cx, |editor, cx| {
4480 compute_auto_height_layout(
4481 editor,
4482 max_lines,
4483 max_line_number_width,
4484 known_dimensions,
4485 available_space.width,
4486 cx,
4487 )
4488 })
4489 .unwrap_or_default()
4490 },
4491 )
4492 }
4493 EditorMode::Full => {
4494 let mut style = Style::default();
4495 style.size.width = relative(1.).into();
4496 style.size.height = relative(1.).into();
4497 cx.request_layout(style, None)
4498 }
4499 };
4500
4501 (layout_id, ())
4502 })
4503 })
4504 }
4505
4506 fn prepaint(
4507 &mut self,
4508 _: Option<&GlobalElementId>,
4509 bounds: Bounds<Pixels>,
4510 _: &mut Self::RequestLayoutState,
4511 cx: &mut WindowContext,
4512 ) -> Self::PrepaintState {
4513 let text_style = TextStyleRefinement {
4514 font_size: Some(self.style.text.font_size),
4515 line_height: Some(self.style.text.line_height),
4516 ..Default::default()
4517 };
4518 cx.set_view_id(self.editor.entity_id());
4519
4520 let rem_size = self.rem_size(cx);
4521 cx.with_rem_size(rem_size, |cx| {
4522 cx.with_text_style(Some(text_style), |cx| {
4523 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4524 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4525 let style = self.style.clone();
4526
4527 let font_id = cx.text_system().resolve_font(&style.text.font());
4528 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4529 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4530 let em_width = cx
4531 .text_system()
4532 .typographic_bounds(font_id, font_size, 'm')
4533 .unwrap()
4534 .size
4535 .width;
4536 let em_advance = cx
4537 .text_system()
4538 .advance(font_id, font_size, 'm')
4539 .unwrap()
4540 .width;
4541
4542 let gutter_dimensions = snapshot.gutter_dimensions(
4543 font_id,
4544 font_size,
4545 em_width,
4546 self.max_line_number_width(&snapshot, cx),
4547 cx,
4548 );
4549 let text_width = bounds.size.width - gutter_dimensions.width;
4550
4551 let right_margin = if snapshot.mode == EditorMode::Full {
4552 EditorElement::SCROLLBAR_WIDTH
4553 } else {
4554 px(0.)
4555 };
4556 let overscroll = size(em_width + right_margin, px(0.));
4557
4558 snapshot = self.editor.update(cx, |editor, cx| {
4559 editor.last_bounds = Some(bounds);
4560 editor.gutter_dimensions = gutter_dimensions;
4561 editor.set_visible_line_count(bounds.size.height / line_height, cx);
4562
4563 let editor_width =
4564 text_width - gutter_dimensions.margin - overscroll.width - em_width;
4565 let wrap_width = match editor.soft_wrap_mode(cx) {
4566 SoftWrap::None => None,
4567 SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4568 SoftWrap::EditorWidth => Some(editor_width),
4569 SoftWrap::Column(column) => {
4570 Some(editor_width.min(column as f32 * em_advance))
4571 }
4572 };
4573
4574 if editor.set_wrap_width(wrap_width, cx) {
4575 editor.snapshot(cx)
4576 } else {
4577 snapshot
4578 }
4579 });
4580
4581 let wrap_guides = self
4582 .editor
4583 .read(cx)
4584 .wrap_guides(cx)
4585 .iter()
4586 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4587 .collect::<SmallVec<[_; 2]>>();
4588
4589 let hitbox = cx.insert_hitbox(bounds, false);
4590 let gutter_hitbox = cx.insert_hitbox(
4591 Bounds {
4592 origin: bounds.origin,
4593 size: size(gutter_dimensions.width, bounds.size.height),
4594 },
4595 false,
4596 );
4597 let text_hitbox = cx.insert_hitbox(
4598 Bounds {
4599 origin: gutter_hitbox.upper_right(),
4600 size: size(text_width, bounds.size.height),
4601 },
4602 false,
4603 );
4604 // Offset the content_bounds from the text_bounds by the gutter margin (which
4605 // is roughly half a character wide) to make hit testing work more like how we want.
4606 let content_origin =
4607 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4608
4609 let mut autoscroll_containing_element = false;
4610 let mut autoscroll_horizontally = false;
4611 self.editor.update(cx, |editor, cx| {
4612 autoscroll_containing_element =
4613 editor.autoscroll_requested() || editor.has_pending_selection();
4614 autoscroll_horizontally =
4615 editor.autoscroll_vertically(bounds, line_height, cx);
4616 snapshot = editor.snapshot(cx);
4617 });
4618
4619 let mut scroll_position = snapshot.scroll_position();
4620 // The scroll position is a fractional point, the whole number of which represents
4621 // the top of the window in terms of display rows.
4622 let start_row = DisplayRow(scroll_position.y as u32);
4623 let height_in_lines = bounds.size.height / line_height;
4624 let max_row = snapshot.max_point().row();
4625 let end_row = cmp::min(
4626 (scroll_position.y + height_in_lines).ceil() as u32,
4627 max_row.next_row().0,
4628 );
4629 let end_row = DisplayRow(end_row);
4630
4631 let buffer_rows = snapshot
4632 .buffer_rows(start_row)
4633 .take((start_row..end_row).len())
4634 .collect::<Vec<_>>();
4635
4636 let start_anchor = if start_row == Default::default() {
4637 Anchor::min()
4638 } else {
4639 snapshot.buffer_snapshot.anchor_before(
4640 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4641 )
4642 };
4643 let end_anchor = if end_row > max_row {
4644 Anchor::max()
4645 } else {
4646 snapshot.buffer_snapshot.anchor_before(
4647 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4648 )
4649 };
4650
4651 let highlighted_rows = self
4652 .editor
4653 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4654 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4655 start_anchor..end_anchor,
4656 &snapshot.display_snapshot,
4657 cx.theme().colors(),
4658 );
4659 let highlighted_gutter_ranges =
4660 self.editor.read(cx).gutter_highlights_in_range(
4661 start_anchor..end_anchor,
4662 &snapshot.display_snapshot,
4663 cx,
4664 );
4665
4666 let redacted_ranges = self.editor.read(cx).redacted_ranges(
4667 start_anchor..end_anchor,
4668 &snapshot.display_snapshot,
4669 cx,
4670 );
4671
4672 let (selections, active_rows, newest_selection_head) = self.layout_selections(
4673 start_anchor,
4674 end_anchor,
4675 &snapshot,
4676 start_row,
4677 end_row,
4678 cx,
4679 );
4680
4681 let line_numbers = self.layout_line_numbers(
4682 start_row..end_row,
4683 buffer_rows.iter().copied(),
4684 &active_rows,
4685 newest_selection_head,
4686 &snapshot,
4687 cx,
4688 );
4689
4690 let mut gutter_fold_toggles =
4691 cx.with_element_namespace("gutter_fold_toggles", |cx| {
4692 self.layout_gutter_fold_toggles(
4693 start_row..end_row,
4694 buffer_rows.iter().copied(),
4695 &active_rows,
4696 &snapshot,
4697 cx,
4698 )
4699 });
4700 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4701 self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4702 });
4703
4704 let display_hunks = self.layout_git_gutters(
4705 line_height,
4706 &gutter_hitbox,
4707 start_row..end_row,
4708 &snapshot,
4709 cx,
4710 );
4711
4712 let mut max_visible_line_width = Pixels::ZERO;
4713 let mut line_layouts =
4714 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
4715 for line_with_invisibles in &line_layouts {
4716 if line_with_invisibles.width > max_visible_line_width {
4717 max_visible_line_width = line_with_invisibles.width;
4718 }
4719 }
4720
4721 let longest_line_width =
4722 layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4723 let mut scroll_width =
4724 longest_line_width.max(max_visible_line_width) + overscroll.width;
4725
4726 let mut blocks = cx.with_element_namespace("blocks", |cx| {
4727 self.build_blocks(
4728 start_row..end_row,
4729 &snapshot,
4730 &hitbox,
4731 &text_hitbox,
4732 &mut scroll_width,
4733 &gutter_dimensions,
4734 em_width,
4735 gutter_dimensions.full_width(),
4736 line_height,
4737 &line_layouts,
4738 cx,
4739 )
4740 });
4741
4742 let scroll_pixel_position = point(
4743 scroll_position.x * em_width,
4744 scroll_position.y * line_height,
4745 );
4746
4747 let start_buffer_row =
4748 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4749 let end_buffer_row =
4750 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4751
4752 let indent_guides = self.layout_indent_guides(
4753 content_origin,
4754 text_hitbox.origin,
4755 start_buffer_row..end_buffer_row,
4756 scroll_pixel_position,
4757 line_height,
4758 &snapshot,
4759 cx,
4760 );
4761
4762 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4763 self.prepaint_crease_trailers(
4764 crease_trailers,
4765 &line_layouts,
4766 line_height,
4767 content_origin,
4768 scroll_pixel_position,
4769 em_width,
4770 cx,
4771 )
4772 });
4773
4774 let mut inline_blame = None;
4775 if let Some(newest_selection_head) = newest_selection_head {
4776 let display_row = newest_selection_head.row();
4777 if (start_row..end_row).contains(&display_row) {
4778 let line_ix = display_row.minus(start_row) as usize;
4779 let line_layout = &line_layouts[line_ix];
4780 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
4781 inline_blame = self.layout_inline_blame(
4782 display_row,
4783 &snapshot.display_snapshot,
4784 line_layout,
4785 crease_trailer_layout,
4786 em_width,
4787 content_origin,
4788 scroll_pixel_position,
4789 line_height,
4790 cx,
4791 );
4792 }
4793 }
4794
4795 let blamed_display_rows = self.layout_blame_entries(
4796 buffer_rows.into_iter(),
4797 em_width,
4798 scroll_position,
4799 line_height,
4800 &gutter_hitbox,
4801 gutter_dimensions.git_blame_entries_width,
4802 cx,
4803 );
4804
4805 let scroll_max = point(
4806 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4807 max_row.as_f32(),
4808 );
4809
4810 self.editor.update(cx, |editor, cx| {
4811 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4812
4813 let autoscrolled = if autoscroll_horizontally {
4814 editor.autoscroll_horizontally(
4815 start_row,
4816 text_hitbox.size.width,
4817 scroll_width,
4818 em_width,
4819 &line_layouts,
4820 cx,
4821 )
4822 } else {
4823 false
4824 };
4825
4826 if clamped || autoscrolled {
4827 snapshot = editor.snapshot(cx);
4828 scroll_position = snapshot.scroll_position();
4829 }
4830 });
4831
4832 let line_elements = self.prepaint_lines(
4833 start_row,
4834 &mut line_layouts,
4835 line_height,
4836 scroll_pixel_position,
4837 content_origin,
4838 cx,
4839 );
4840
4841 cx.with_element_namespace("blocks", |cx| {
4842 self.layout_blocks(
4843 &mut blocks,
4844 &hitbox,
4845 line_height,
4846 scroll_pixel_position,
4847 cx,
4848 );
4849 });
4850
4851 let cursors = self.collect_cursors(&snapshot, cx);
4852 let visible_row_range = start_row..end_row;
4853 let non_visible_cursors = cursors
4854 .iter()
4855 .any(move |c| !visible_row_range.contains(&c.0.row()));
4856
4857 let visible_cursors = self.layout_visible_cursors(
4858 &snapshot,
4859 &selections,
4860 start_row..end_row,
4861 &line_layouts,
4862 &text_hitbox,
4863 content_origin,
4864 scroll_position,
4865 scroll_pixel_position,
4866 line_height,
4867 em_width,
4868 autoscroll_containing_element,
4869 cx,
4870 );
4871
4872 let scrollbar_layout = self.layout_scrollbar(
4873 &snapshot,
4874 bounds,
4875 scroll_position,
4876 height_in_lines,
4877 non_visible_cursors,
4878 cx,
4879 );
4880
4881 let gutter_settings = EditorSettings::get_global(cx).gutter;
4882
4883 let mut _context_menu_visible = false;
4884 let mut code_actions_indicator = None;
4885 if let Some(newest_selection_head) = newest_selection_head {
4886 if (start_row..end_row).contains(&newest_selection_head.row()) {
4887 _context_menu_visible = self.layout_context_menu(
4888 line_height,
4889 &hitbox,
4890 &text_hitbox,
4891 content_origin,
4892 start_row,
4893 scroll_pixel_position,
4894 &line_layouts,
4895 newest_selection_head,
4896 gutter_dimensions.width - gutter_dimensions.left_padding,
4897 cx,
4898 );
4899
4900 let show_code_actions = snapshot
4901 .show_code_actions
4902 .unwrap_or_else(|| gutter_settings.code_actions);
4903 if show_code_actions {
4904 let newest_selection_point =
4905 newest_selection_head.to_point(&snapshot.display_snapshot);
4906 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
4907 MultiBufferRow(newest_selection_point.row),
4908 );
4909 if let Some((buffer, range)) = buffer {
4910 let buffer_id = buffer.remote_id();
4911 let row = range.start.row;
4912 let has_test_indicator =
4913 self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
4914
4915 if !has_test_indicator {
4916 code_actions_indicator = self
4917 .layout_code_actions_indicator(
4918 line_height,
4919 newest_selection_head,
4920 scroll_pixel_position,
4921 &gutter_dimensions,
4922 &gutter_hitbox,
4923 cx,
4924 );
4925 }
4926 }
4927 }
4928 }
4929 }
4930
4931 let test_indicators = self.layout_run_indicators(
4932 line_height,
4933 scroll_pixel_position,
4934 &gutter_dimensions,
4935 &gutter_hitbox,
4936 &snapshot,
4937 cx,
4938 );
4939
4940 if !cx.has_active_drag() {
4941 self.layout_hover_popovers(
4942 &snapshot,
4943 &hitbox,
4944 &text_hitbox,
4945 start_row..end_row,
4946 content_origin,
4947 scroll_pixel_position,
4948 &line_layouts,
4949 line_height,
4950 em_width,
4951 cx,
4952 );
4953 }
4954
4955 let mouse_context_menu = self.layout_mouse_context_menu(cx);
4956
4957 cx.with_element_namespace("gutter_fold_toggles", |cx| {
4958 self.prepaint_gutter_fold_toggles(
4959 &mut gutter_fold_toggles,
4960 line_height,
4961 &gutter_dimensions,
4962 gutter_settings,
4963 scroll_pixel_position,
4964 &gutter_hitbox,
4965 cx,
4966 )
4967 });
4968
4969 let invisible_symbol_font_size = font_size / 2.;
4970 let tab_invisible = cx
4971 .text_system()
4972 .shape_line(
4973 "→".into(),
4974 invisible_symbol_font_size,
4975 &[TextRun {
4976 len: "→".len(),
4977 font: self.style.text.font(),
4978 color: cx.theme().colors().editor_invisible,
4979 background_color: None,
4980 underline: None,
4981 strikethrough: None,
4982 }],
4983 )
4984 .unwrap();
4985 let space_invisible = cx
4986 .text_system()
4987 .shape_line(
4988 "•".into(),
4989 invisible_symbol_font_size,
4990 &[TextRun {
4991 len: "•".len(),
4992 font: self.style.text.font(),
4993 color: cx.theme().colors().editor_invisible,
4994 background_color: None,
4995 underline: None,
4996 strikethrough: None,
4997 }],
4998 )
4999 .unwrap();
5000
5001 EditorLayout {
5002 mode: snapshot.mode,
5003 position_map: Arc::new(PositionMap {
5004 size: bounds.size,
5005 scroll_pixel_position,
5006 scroll_max,
5007 line_layouts,
5008 line_height,
5009 em_width,
5010 em_advance,
5011 snapshot,
5012 }),
5013 visible_display_row_range: start_row..end_row,
5014 wrap_guides,
5015 indent_guides,
5016 hitbox,
5017 text_hitbox,
5018 gutter_hitbox,
5019 gutter_dimensions,
5020 content_origin,
5021 scrollbar_layout,
5022 active_rows,
5023 highlighted_rows,
5024 highlighted_ranges,
5025 highlighted_gutter_ranges,
5026 redacted_ranges,
5027 line_elements,
5028 line_numbers,
5029 display_hunks,
5030 blamed_display_rows,
5031 inline_blame,
5032 blocks,
5033 cursors,
5034 visible_cursors,
5035 selections,
5036 mouse_context_menu,
5037 test_indicators,
5038 code_actions_indicator,
5039 gutter_fold_toggles,
5040 crease_trailers,
5041 tab_invisible,
5042 space_invisible,
5043 }
5044 })
5045 })
5046 })
5047 }
5048
5049 fn paint(
5050 &mut self,
5051 _: Option<&GlobalElementId>,
5052 bounds: Bounds<gpui::Pixels>,
5053 _: &mut Self::RequestLayoutState,
5054 layout: &mut Self::PrepaintState,
5055 cx: &mut WindowContext,
5056 ) {
5057 let focus_handle = self.editor.focus_handle(cx);
5058 let key_context = self.editor.read(cx).key_context(cx);
5059 cx.set_focus_handle(&focus_handle);
5060 cx.set_key_context(key_context);
5061 cx.handle_input(
5062 &focus_handle,
5063 ElementInputHandler::new(bounds, self.editor.clone()),
5064 );
5065 self.register_actions(cx);
5066 self.register_key_listeners(cx, layout);
5067
5068 let text_style = TextStyleRefinement {
5069 font_size: Some(self.style.text.font_size),
5070 line_height: Some(self.style.text.line_height),
5071 ..Default::default()
5072 };
5073 let mouse_position = cx.mouse_position();
5074 let hovered_hunk = layout
5075 .display_hunks
5076 .iter()
5077 .find_map(|(hunk, hunk_hitbox)| match hunk {
5078 DisplayDiffHunk::Folded { .. } => None,
5079 DisplayDiffHunk::Unfolded {
5080 diff_base_byte_range,
5081 multi_buffer_range,
5082 status,
5083 ..
5084 } => {
5085 if hunk_hitbox
5086 .as_ref()
5087 .map(|hitbox| hitbox.contains(&mouse_position))
5088 .unwrap_or(false)
5089 {
5090 Some(HunkToExpand {
5091 status: *status,
5092 multi_buffer_range: multi_buffer_range.clone(),
5093 diff_base_byte_range: diff_base_byte_range.clone(),
5094 })
5095 } else {
5096 None
5097 }
5098 }
5099 });
5100 let rem_size = self.rem_size(cx);
5101 cx.with_rem_size(rem_size, |cx| {
5102 cx.with_text_style(Some(text_style), |cx| {
5103 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5104 self.paint_mouse_listeners(layout, hovered_hunk, cx);
5105 self.paint_background(layout, cx);
5106 self.paint_indent_guides(layout, cx);
5107
5108 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5109 self.paint_blamed_display_rows(layout, cx);
5110 self.paint_line_numbers(layout, cx);
5111 }
5112
5113 self.paint_text(layout, cx);
5114
5115 if !layout.blocks.is_empty() {
5116 cx.with_element_namespace("blocks", |cx| {
5117 self.paint_blocks(layout, cx);
5118 });
5119 }
5120
5121 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5122 self.paint_gutter_highlights(layout, cx);
5123 self.paint_gutter_indicators(layout, cx);
5124 }
5125
5126 self.paint_scrollbar(layout, cx);
5127 self.paint_mouse_context_menu(layout, cx);
5128 });
5129 })
5130 })
5131 }
5132}
5133
5134impl IntoElement for EditorElement {
5135 type Element = Self;
5136
5137 fn into_element(self) -> Self::Element {
5138 self
5139 }
5140}
5141
5142pub struct EditorLayout {
5143 position_map: Arc<PositionMap>,
5144 hitbox: Hitbox,
5145 text_hitbox: Hitbox,
5146 gutter_hitbox: Hitbox,
5147 gutter_dimensions: GutterDimensions,
5148 content_origin: gpui::Point<Pixels>,
5149 scrollbar_layout: Option<ScrollbarLayout>,
5150 mode: EditorMode,
5151 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5152 indent_guides: Option<Vec<IndentGuideLayout>>,
5153 visible_display_row_range: Range<DisplayRow>,
5154 active_rows: BTreeMap<DisplayRow, bool>,
5155 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5156 line_elements: SmallVec<[AnyElement; 1]>,
5157 line_numbers: Vec<Option<ShapedLine>>,
5158 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5159 blamed_display_rows: Option<Vec<AnyElement>>,
5160 inline_blame: Option<AnyElement>,
5161 blocks: Vec<BlockLayout>,
5162 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5163 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5164 redacted_ranges: Vec<Range<DisplayPoint>>,
5165 cursors: Vec<(DisplayPoint, Hsla)>,
5166 visible_cursors: Vec<CursorLayout>,
5167 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5168 code_actions_indicator: Option<AnyElement>,
5169 test_indicators: Vec<AnyElement>,
5170 gutter_fold_toggles: Vec<Option<AnyElement>>,
5171 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5172 mouse_context_menu: Option<AnyElement>,
5173 tab_invisible: ShapedLine,
5174 space_invisible: ShapedLine,
5175}
5176
5177impl EditorLayout {
5178 fn line_end_overshoot(&self) -> Pixels {
5179 0.15 * self.position_map.line_height
5180 }
5181}
5182
5183struct ColoredRange<T> {
5184 start: T,
5185 end: T,
5186 color: Hsla,
5187}
5188
5189#[derive(Clone)]
5190struct ScrollbarLayout {
5191 hitbox: Hitbox,
5192 visible_row_range: Range<f32>,
5193 visible: bool,
5194 row_height: Pixels,
5195 thumb_height: Pixels,
5196}
5197
5198impl ScrollbarLayout {
5199 const BORDER_WIDTH: Pixels = px(1.0);
5200 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5201 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5202 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5203
5204 fn thumb_bounds(&self) -> Bounds<Pixels> {
5205 let thumb_top = self.y_for_row(self.visible_row_range.start);
5206 let thumb_bottom = thumb_top + self.thumb_height;
5207 Bounds::from_corners(
5208 point(self.hitbox.left(), thumb_top),
5209 point(self.hitbox.right(), thumb_bottom),
5210 )
5211 }
5212
5213 fn y_for_row(&self, row: f32) -> Pixels {
5214 self.hitbox.top() + row * self.row_height
5215 }
5216
5217 fn marker_quads_for_ranges(
5218 &self,
5219 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5220 column: Option<usize>,
5221 ) -> Vec<PaintQuad> {
5222 struct MinMax {
5223 min: Pixels,
5224 max: Pixels,
5225 }
5226 let (x_range, height_limit) = if let Some(column) = column {
5227 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5228 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5229 let end = start + column_width;
5230 (
5231 Range { start, end },
5232 MinMax {
5233 min: Self::MIN_MARKER_HEIGHT,
5234 max: px(f32::MAX),
5235 },
5236 )
5237 } else {
5238 (
5239 Range {
5240 start: Self::BORDER_WIDTH,
5241 end: self.hitbox.size.width,
5242 },
5243 MinMax {
5244 min: Self::LINE_MARKER_HEIGHT,
5245 max: Self::LINE_MARKER_HEIGHT,
5246 },
5247 )
5248 };
5249
5250 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5251 let mut pixel_ranges = row_ranges
5252 .into_iter()
5253 .map(|range| {
5254 let start_y = row_to_y(range.start);
5255 let end_y = row_to_y(range.end)
5256 + self.row_height.max(height_limit.min).min(height_limit.max);
5257 ColoredRange {
5258 start: start_y,
5259 end: end_y,
5260 color: range.color,
5261 }
5262 })
5263 .peekable();
5264
5265 let mut quads = Vec::new();
5266 while let Some(mut pixel_range) = pixel_ranges.next() {
5267 while let Some(next_pixel_range) = pixel_ranges.peek() {
5268 if pixel_range.end >= next_pixel_range.start - px(1.0)
5269 && pixel_range.color == next_pixel_range.color
5270 {
5271 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5272 pixel_ranges.next();
5273 } else {
5274 break;
5275 }
5276 }
5277
5278 let bounds = Bounds::from_corners(
5279 point(x_range.start, pixel_range.start),
5280 point(x_range.end, pixel_range.end),
5281 );
5282 quads.push(quad(
5283 bounds,
5284 Corners::default(),
5285 pixel_range.color,
5286 Edges::default(),
5287 Hsla::transparent_black(),
5288 ));
5289 }
5290
5291 quads
5292 }
5293}
5294
5295struct CreaseTrailerLayout {
5296 element: AnyElement,
5297 bounds: Bounds<Pixels>,
5298}
5299
5300struct PositionMap {
5301 size: Size<Pixels>,
5302 line_height: Pixels,
5303 scroll_pixel_position: gpui::Point<Pixels>,
5304 scroll_max: gpui::Point<f32>,
5305 em_width: Pixels,
5306 em_advance: Pixels,
5307 line_layouts: Vec<LineWithInvisibles>,
5308 snapshot: EditorSnapshot,
5309}
5310
5311#[derive(Debug, Copy, Clone)]
5312pub struct PointForPosition {
5313 pub previous_valid: DisplayPoint,
5314 pub next_valid: DisplayPoint,
5315 pub exact_unclipped: DisplayPoint,
5316 pub column_overshoot_after_line_end: u32,
5317}
5318
5319impl PointForPosition {
5320 pub fn as_valid(&self) -> Option<DisplayPoint> {
5321 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5322 Some(self.previous_valid)
5323 } else {
5324 None
5325 }
5326 }
5327}
5328
5329impl PositionMap {
5330 fn point_for_position(
5331 &self,
5332 text_bounds: Bounds<Pixels>,
5333 position: gpui::Point<Pixels>,
5334 ) -> PointForPosition {
5335 let scroll_position = self.snapshot.scroll_position();
5336 let position = position - text_bounds.origin;
5337 let y = position.y.max(px(0.)).min(self.size.height);
5338 let x = position.x + (scroll_position.x * self.em_width);
5339 let row = ((y / self.line_height) + scroll_position.y) as u32;
5340
5341 let (column, x_overshoot_after_line_end) = if let Some(line) = self
5342 .line_layouts
5343 .get(row as usize - scroll_position.y as usize)
5344 {
5345 if let Some(ix) = line.index_for_x(x) {
5346 (ix as u32, px(0.))
5347 } else {
5348 (line.len as u32, px(0.).max(x - line.width))
5349 }
5350 } else {
5351 (0, x)
5352 };
5353
5354 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5355 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5356 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5357
5358 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5359 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5360 PointForPosition {
5361 previous_valid,
5362 next_valid,
5363 exact_unclipped,
5364 column_overshoot_after_line_end,
5365 }
5366 }
5367}
5368
5369struct BlockLayout {
5370 row: DisplayRow,
5371 element: AnyElement,
5372 available_space: Size<AvailableSpace>,
5373 style: BlockStyle,
5374}
5375
5376fn layout_line(
5377 row: DisplayRow,
5378 snapshot: &EditorSnapshot,
5379 style: &EditorStyle,
5380 cx: &mut WindowContext,
5381) -> LineWithInvisibles {
5382 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5383 LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5384 .pop()
5385 .unwrap()
5386}
5387
5388#[derive(Debug)]
5389pub struct IndentGuideLayout {
5390 origin: gpui::Point<Pixels>,
5391 length: Pixels,
5392 single_indent_width: Pixels,
5393 depth: u32,
5394 active: bool,
5395 settings: IndentGuideSettings,
5396}
5397
5398pub struct CursorLayout {
5399 origin: gpui::Point<Pixels>,
5400 block_width: Pixels,
5401 line_height: Pixels,
5402 color: Hsla,
5403 shape: CursorShape,
5404 block_text: Option<ShapedLine>,
5405 cursor_name: Option<AnyElement>,
5406}
5407
5408#[derive(Debug)]
5409pub struct CursorName {
5410 string: SharedString,
5411 color: Hsla,
5412 is_top_row: bool,
5413}
5414
5415impl CursorLayout {
5416 pub fn new(
5417 origin: gpui::Point<Pixels>,
5418 block_width: Pixels,
5419 line_height: Pixels,
5420 color: Hsla,
5421 shape: CursorShape,
5422 block_text: Option<ShapedLine>,
5423 ) -> CursorLayout {
5424 CursorLayout {
5425 origin,
5426 block_width,
5427 line_height,
5428 color,
5429 shape,
5430 block_text,
5431 cursor_name: None,
5432 }
5433 }
5434
5435 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5436 Bounds {
5437 origin: self.origin + origin,
5438 size: size(self.block_width, self.line_height),
5439 }
5440 }
5441
5442 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5443 match self.shape {
5444 CursorShape::Bar => Bounds {
5445 origin: self.origin + origin,
5446 size: size(px(2.0), self.line_height),
5447 },
5448 CursorShape::Block | CursorShape::Hollow => Bounds {
5449 origin: self.origin + origin,
5450 size: size(self.block_width, self.line_height),
5451 },
5452 CursorShape::Underscore => Bounds {
5453 origin: self.origin
5454 + origin
5455 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5456 size: size(self.block_width, px(2.0)),
5457 },
5458 }
5459 }
5460
5461 pub fn layout(
5462 &mut self,
5463 origin: gpui::Point<Pixels>,
5464 cursor_name: Option<CursorName>,
5465 cx: &mut WindowContext,
5466 ) {
5467 if let Some(cursor_name) = cursor_name {
5468 let bounds = self.bounds(origin);
5469 let text_size = self.line_height / 1.5;
5470
5471 let name_origin = if cursor_name.is_top_row {
5472 point(bounds.right() - px(1.), bounds.top())
5473 } else {
5474 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5475 };
5476 let mut name_element = div()
5477 .bg(self.color)
5478 .text_size(text_size)
5479 .px_0p5()
5480 .line_height(text_size + px(2.))
5481 .text_color(cursor_name.color)
5482 .child(cursor_name.string.clone())
5483 .into_any_element();
5484
5485 name_element.prepaint_as_root(
5486 name_origin,
5487 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5488 cx,
5489 );
5490
5491 self.cursor_name = Some(name_element);
5492 }
5493 }
5494
5495 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5496 let bounds = self.bounds(origin);
5497
5498 //Draw background or border quad
5499 let cursor = if matches!(self.shape, CursorShape::Hollow) {
5500 outline(bounds, self.color)
5501 } else {
5502 fill(bounds, self.color)
5503 };
5504
5505 if let Some(name) = &mut self.cursor_name {
5506 name.paint(cx);
5507 }
5508
5509 cx.paint_quad(cursor);
5510
5511 if let Some(block_text) = &self.block_text {
5512 block_text
5513 .paint(self.origin + origin, self.line_height, cx)
5514 .log_err();
5515 }
5516 }
5517
5518 pub fn shape(&self) -> CursorShape {
5519 self.shape
5520 }
5521}
5522
5523#[derive(Debug)]
5524pub struct HighlightedRange {
5525 pub start_y: Pixels,
5526 pub line_height: Pixels,
5527 pub lines: Vec<HighlightedRangeLine>,
5528 pub color: Hsla,
5529 pub corner_radius: Pixels,
5530}
5531
5532#[derive(Debug)]
5533pub struct HighlightedRangeLine {
5534 pub start_x: Pixels,
5535 pub end_x: Pixels,
5536}
5537
5538impl HighlightedRange {
5539 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5540 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5541 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5542 self.paint_lines(
5543 self.start_y + self.line_height,
5544 &self.lines[1..],
5545 bounds,
5546 cx,
5547 );
5548 } else {
5549 self.paint_lines(self.start_y, &self.lines, bounds, cx);
5550 }
5551 }
5552
5553 fn paint_lines(
5554 &self,
5555 start_y: Pixels,
5556 lines: &[HighlightedRangeLine],
5557 _bounds: Bounds<Pixels>,
5558 cx: &mut WindowContext,
5559 ) {
5560 if lines.is_empty() {
5561 return;
5562 }
5563
5564 let first_line = lines.first().unwrap();
5565 let last_line = lines.last().unwrap();
5566
5567 let first_top_left = point(first_line.start_x, start_y);
5568 let first_top_right = point(first_line.end_x, start_y);
5569
5570 let curve_height = point(Pixels::ZERO, self.corner_radius);
5571 let curve_width = |start_x: Pixels, end_x: Pixels| {
5572 let max = (end_x - start_x) / 2.;
5573 let width = if max < self.corner_radius {
5574 max
5575 } else {
5576 self.corner_radius
5577 };
5578
5579 point(width, Pixels::ZERO)
5580 };
5581
5582 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5583 let mut path = gpui::Path::new(first_top_right - top_curve_width);
5584 path.curve_to(first_top_right + curve_height, first_top_right);
5585
5586 let mut iter = lines.iter().enumerate().peekable();
5587 while let Some((ix, line)) = iter.next() {
5588 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5589
5590 if let Some((_, next_line)) = iter.peek() {
5591 let next_top_right = point(next_line.end_x, bottom_right.y);
5592
5593 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5594 Ordering::Equal => {
5595 path.line_to(bottom_right);
5596 }
5597 Ordering::Less => {
5598 let curve_width = curve_width(next_top_right.x, bottom_right.x);
5599 path.line_to(bottom_right - curve_height);
5600 if self.corner_radius > Pixels::ZERO {
5601 path.curve_to(bottom_right - curve_width, bottom_right);
5602 }
5603 path.line_to(next_top_right + curve_width);
5604 if self.corner_radius > Pixels::ZERO {
5605 path.curve_to(next_top_right + curve_height, next_top_right);
5606 }
5607 }
5608 Ordering::Greater => {
5609 let curve_width = curve_width(bottom_right.x, next_top_right.x);
5610 path.line_to(bottom_right - curve_height);
5611 if self.corner_radius > Pixels::ZERO {
5612 path.curve_to(bottom_right + curve_width, bottom_right);
5613 }
5614 path.line_to(next_top_right - curve_width);
5615 if self.corner_radius > Pixels::ZERO {
5616 path.curve_to(next_top_right + curve_height, next_top_right);
5617 }
5618 }
5619 }
5620 } else {
5621 let curve_width = curve_width(line.start_x, line.end_x);
5622 path.line_to(bottom_right - curve_height);
5623 if self.corner_radius > Pixels::ZERO {
5624 path.curve_to(bottom_right - curve_width, bottom_right);
5625 }
5626
5627 let bottom_left = point(line.start_x, bottom_right.y);
5628 path.line_to(bottom_left + curve_width);
5629 if self.corner_radius > Pixels::ZERO {
5630 path.curve_to(bottom_left - curve_height, bottom_left);
5631 }
5632 }
5633 }
5634
5635 if first_line.start_x > last_line.start_x {
5636 let curve_width = curve_width(last_line.start_x, first_line.start_x);
5637 let second_top_left = point(last_line.start_x, start_y + self.line_height);
5638 path.line_to(second_top_left + curve_height);
5639 if self.corner_radius > Pixels::ZERO {
5640 path.curve_to(second_top_left + curve_width, second_top_left);
5641 }
5642 let first_bottom_left = point(first_line.start_x, second_top_left.y);
5643 path.line_to(first_bottom_left - curve_width);
5644 if self.corner_radius > Pixels::ZERO {
5645 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5646 }
5647 }
5648
5649 path.line_to(first_top_left + curve_height);
5650 if self.corner_radius > Pixels::ZERO {
5651 path.curve_to(first_top_left + top_curve_width, first_top_left);
5652 }
5653 path.line_to(first_top_right - top_curve_width);
5654
5655 cx.paint_path(path, self.color);
5656 }
5657}
5658
5659pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5660 (delta.pow(1.5) / 100.0).into()
5661}
5662
5663fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5664 (delta.pow(1.2) / 300.0).into()
5665}
5666
5667#[cfg(test)]
5668mod tests {
5669 use super::*;
5670 use crate::{
5671 display_map::{BlockDisposition, BlockProperties},
5672 editor_tests::{init_test, update_test_language_settings},
5673 Editor, MultiBuffer,
5674 };
5675 use gpui::{TestAppContext, VisualTestContext};
5676 use language::language_settings;
5677 use log::info;
5678 use std::num::NonZeroU32;
5679 use ui::Context;
5680 use util::test::sample_text;
5681
5682 #[gpui::test]
5683 fn test_shape_line_numbers(cx: &mut TestAppContext) {
5684 init_test(cx, |_| {});
5685 let window = cx.add_window(|cx| {
5686 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5687 Editor::new(EditorMode::Full, buffer, None, true, cx)
5688 });
5689
5690 let editor = window.root(cx).unwrap();
5691 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5692 let element = EditorElement::new(&editor, style);
5693 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5694
5695 let layouts = cx
5696 .update_window(*window, |_, cx| {
5697 element.layout_line_numbers(
5698 DisplayRow(0)..DisplayRow(6),
5699 (0..6).map(MultiBufferRow).map(Some),
5700 &Default::default(),
5701 Some(DisplayPoint::new(DisplayRow(0), 0)),
5702 &snapshot,
5703 cx,
5704 )
5705 })
5706 .unwrap();
5707 assert_eq!(layouts.len(), 6);
5708
5709 let relative_rows = window
5710 .update(cx, |editor, cx| {
5711 let snapshot = editor.snapshot(cx);
5712 element.calculate_relative_line_numbers(
5713 &snapshot,
5714 &(DisplayRow(0)..DisplayRow(6)),
5715 Some(DisplayRow(3)),
5716 )
5717 })
5718 .unwrap();
5719 assert_eq!(relative_rows[&DisplayRow(0)], 3);
5720 assert_eq!(relative_rows[&DisplayRow(1)], 2);
5721 assert_eq!(relative_rows[&DisplayRow(2)], 1);
5722 // current line has no relative number
5723 assert_eq!(relative_rows[&DisplayRow(4)], 1);
5724 assert_eq!(relative_rows[&DisplayRow(5)], 2);
5725
5726 // works if cursor is before screen
5727 let relative_rows = window
5728 .update(cx, |editor, cx| {
5729 let snapshot = editor.snapshot(cx);
5730 element.calculate_relative_line_numbers(
5731 &snapshot,
5732 &(DisplayRow(3)..DisplayRow(6)),
5733 Some(DisplayRow(1)),
5734 )
5735 })
5736 .unwrap();
5737 assert_eq!(relative_rows.len(), 3);
5738 assert_eq!(relative_rows[&DisplayRow(3)], 2);
5739 assert_eq!(relative_rows[&DisplayRow(4)], 3);
5740 assert_eq!(relative_rows[&DisplayRow(5)], 4);
5741
5742 // works if cursor is after screen
5743 let relative_rows = window
5744 .update(cx, |editor, cx| {
5745 let snapshot = editor.snapshot(cx);
5746 element.calculate_relative_line_numbers(
5747 &snapshot,
5748 &(DisplayRow(0)..DisplayRow(3)),
5749 Some(DisplayRow(6)),
5750 )
5751 })
5752 .unwrap();
5753 assert_eq!(relative_rows.len(), 3);
5754 assert_eq!(relative_rows[&DisplayRow(0)], 5);
5755 assert_eq!(relative_rows[&DisplayRow(1)], 4);
5756 assert_eq!(relative_rows[&DisplayRow(2)], 3);
5757 }
5758
5759 #[gpui::test]
5760 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5761 init_test(cx, |_| {});
5762
5763 let window = cx.add_window(|cx| {
5764 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5765 Editor::new(EditorMode::Full, buffer, None, true, cx)
5766 });
5767 let cx = &mut VisualTestContext::from_window(*window, cx);
5768 let editor = window.root(cx).unwrap();
5769 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5770
5771 window
5772 .update(cx, |editor, cx| {
5773 editor.cursor_shape = CursorShape::Block;
5774 editor.change_selections(None, cx, |s| {
5775 s.select_ranges([
5776 Point::new(0, 0)..Point::new(1, 0),
5777 Point::new(3, 2)..Point::new(3, 3),
5778 Point::new(5, 6)..Point::new(6, 0),
5779 ]);
5780 });
5781 })
5782 .unwrap();
5783
5784 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5785 EditorElement::new(&editor, style)
5786 });
5787
5788 assert_eq!(state.selections.len(), 1);
5789 let local_selections = &state.selections[0].1;
5790 assert_eq!(local_selections.len(), 3);
5791 // moves cursor back one line
5792 assert_eq!(
5793 local_selections[0].head,
5794 DisplayPoint::new(DisplayRow(0), 6)
5795 );
5796 assert_eq!(
5797 local_selections[0].range,
5798 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
5799 );
5800
5801 // moves cursor back one column
5802 assert_eq!(
5803 local_selections[1].range,
5804 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
5805 );
5806 assert_eq!(
5807 local_selections[1].head,
5808 DisplayPoint::new(DisplayRow(3), 2)
5809 );
5810
5811 // leaves cursor on the max point
5812 assert_eq!(
5813 local_selections[2].range,
5814 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
5815 );
5816 assert_eq!(
5817 local_selections[2].head,
5818 DisplayPoint::new(DisplayRow(6), 0)
5819 );
5820
5821 // active lines does not include 1 (even though the range of the selection does)
5822 assert_eq!(
5823 state.active_rows.keys().cloned().collect::<Vec<_>>(),
5824 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
5825 );
5826
5827 // multi-buffer support
5828 // in DisplayPoint coordinates, this is what we're dealing with:
5829 // 0: [[file
5830 // 1: header
5831 // 2: section]]
5832 // 3: aaaaaa
5833 // 4: bbbbbb
5834 // 5: cccccc
5835 // 6:
5836 // 7: [[footer]]
5837 // 8: [[header]]
5838 // 9: ffffff
5839 // 10: gggggg
5840 // 11: hhhhhh
5841 // 12:
5842 // 13: [[footer]]
5843 // 14: [[file
5844 // 15: header
5845 // 16: section]]
5846 // 17: bbbbbb
5847 // 18: cccccc
5848 // 19: dddddd
5849 // 20: [[footer]]
5850 let window = cx.add_window(|cx| {
5851 let buffer = MultiBuffer::build_multi(
5852 [
5853 (
5854 &(sample_text(8, 6, 'a') + "\n"),
5855 vec![
5856 Point::new(0, 0)..Point::new(3, 0),
5857 Point::new(4, 0)..Point::new(7, 0),
5858 ],
5859 ),
5860 (
5861 &(sample_text(8, 6, 'a') + "\n"),
5862 vec![Point::new(1, 0)..Point::new(3, 0)],
5863 ),
5864 ],
5865 cx,
5866 );
5867 Editor::new(EditorMode::Full, buffer, None, true, cx)
5868 });
5869 let editor = window.root(cx).unwrap();
5870 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5871 let _state = window.update(cx, |editor, cx| {
5872 editor.cursor_shape = CursorShape::Block;
5873 editor.change_selections(None, cx, |s| {
5874 s.select_display_ranges([
5875 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
5876 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
5877 ]);
5878 });
5879 });
5880
5881 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5882 EditorElement::new(&editor, style)
5883 });
5884 assert_eq!(state.selections.len(), 1);
5885 let local_selections = &state.selections[0].1;
5886 assert_eq!(local_selections.len(), 2);
5887
5888 // moves cursor on excerpt boundary back a line
5889 // and doesn't allow selection to bleed through
5890 assert_eq!(
5891 local_selections[0].range,
5892 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
5893 );
5894 assert_eq!(
5895 local_selections[0].head,
5896 DisplayPoint::new(DisplayRow(6), 0)
5897 );
5898 // moves cursor on buffer boundary back two lines
5899 // and doesn't allow selection to bleed through
5900 assert_eq!(
5901 local_selections[1].range,
5902 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
5903 );
5904 assert_eq!(
5905 local_selections[1].head,
5906 DisplayPoint::new(DisplayRow(12), 0)
5907 );
5908 }
5909
5910 #[gpui::test]
5911 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
5912 init_test(cx, |_| {});
5913
5914 let window = cx.add_window(|cx| {
5915 let buffer = MultiBuffer::build_simple("", cx);
5916 Editor::new(EditorMode::Full, buffer, None, true, cx)
5917 });
5918 let cx = &mut VisualTestContext::from_window(*window, cx);
5919 let editor = window.root(cx).unwrap();
5920 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5921 window
5922 .update(cx, |editor, cx| {
5923 editor.set_placeholder_text("hello", cx);
5924 editor.insert_blocks(
5925 [BlockProperties {
5926 style: BlockStyle::Fixed,
5927 disposition: BlockDisposition::Above,
5928 height: 3,
5929 position: Anchor::min(),
5930 render: Box::new(|_| div().into_any()),
5931 }],
5932 None,
5933 cx,
5934 );
5935
5936 // Blur the editor so that it displays placeholder text.
5937 cx.blur();
5938 })
5939 .unwrap();
5940
5941 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5942 EditorElement::new(&editor, style)
5943 });
5944 assert_eq!(state.position_map.line_layouts.len(), 4);
5945 assert_eq!(
5946 state
5947 .line_numbers
5948 .iter()
5949 .map(Option::is_some)
5950 .collect::<Vec<_>>(),
5951 &[false, false, false, true]
5952 );
5953 }
5954
5955 #[gpui::test]
5956 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
5957 const TAB_SIZE: u32 = 4;
5958
5959 let input_text = "\t \t|\t| a b";
5960 let expected_invisibles = vec![
5961 Invisible::Tab {
5962 line_start_offset: 0,
5963 line_end_offset: TAB_SIZE as usize,
5964 },
5965 Invisible::Whitespace {
5966 line_offset: TAB_SIZE as usize,
5967 },
5968 Invisible::Tab {
5969 line_start_offset: TAB_SIZE as usize + 1,
5970 line_end_offset: TAB_SIZE as usize * 2,
5971 },
5972 Invisible::Tab {
5973 line_start_offset: TAB_SIZE as usize * 2 + 1,
5974 line_end_offset: TAB_SIZE as usize * 3,
5975 },
5976 Invisible::Whitespace {
5977 line_offset: TAB_SIZE as usize * 3 + 1,
5978 },
5979 Invisible::Whitespace {
5980 line_offset: TAB_SIZE as usize * 3 + 3,
5981 },
5982 ];
5983 assert_eq!(
5984 expected_invisibles.len(),
5985 input_text
5986 .chars()
5987 .filter(|initial_char| initial_char.is_whitespace())
5988 .count(),
5989 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5990 );
5991
5992 init_test(cx, |s| {
5993 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5994 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
5995 });
5996
5997 let actual_invisibles =
5998 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
5999
6000 assert_eq!(expected_invisibles, actual_invisibles);
6001 }
6002
6003 #[gpui::test]
6004 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6005 init_test(cx, |s| {
6006 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6007 s.defaults.tab_size = NonZeroU32::new(4);
6008 });
6009
6010 for editor_mode_without_invisibles in [
6011 EditorMode::SingleLine,
6012 EditorMode::AutoHeight { max_lines: 100 },
6013 ] {
6014 let invisibles = collect_invisibles_from_new_editor(
6015 cx,
6016 editor_mode_without_invisibles,
6017 "\t\t\t| | a b",
6018 px(500.0),
6019 );
6020 assert!(invisibles.is_empty(),
6021 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6022 }
6023 }
6024
6025 #[gpui::test]
6026 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6027 let tab_size = 4;
6028 let input_text = "a\tbcd ".repeat(9);
6029 let repeated_invisibles = [
6030 Invisible::Tab {
6031 line_start_offset: 1,
6032 line_end_offset: tab_size as usize,
6033 },
6034 Invisible::Whitespace {
6035 line_offset: tab_size as usize + 3,
6036 },
6037 Invisible::Whitespace {
6038 line_offset: tab_size as usize + 4,
6039 },
6040 Invisible::Whitespace {
6041 line_offset: tab_size as usize + 5,
6042 },
6043 Invisible::Whitespace {
6044 line_offset: tab_size as usize + 6,
6045 },
6046 Invisible::Whitespace {
6047 line_offset: tab_size as usize + 7,
6048 },
6049 ];
6050 let expected_invisibles = std::iter::once(repeated_invisibles)
6051 .cycle()
6052 .take(9)
6053 .flatten()
6054 .collect::<Vec<_>>();
6055 assert_eq!(
6056 expected_invisibles.len(),
6057 input_text
6058 .chars()
6059 .filter(|initial_char| initial_char.is_whitespace())
6060 .count(),
6061 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6062 );
6063 info!("Expected invisibles: {expected_invisibles:?}");
6064
6065 init_test(cx, |_| {});
6066
6067 // Put the same string with repeating whitespace pattern into editors of various size,
6068 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6069 let resize_step = 10.0;
6070 let mut editor_width = 200.0;
6071 while editor_width <= 1000.0 {
6072 update_test_language_settings(cx, |s| {
6073 s.defaults.tab_size = NonZeroU32::new(tab_size);
6074 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6075 s.defaults.preferred_line_length = Some(editor_width as u32);
6076 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6077 });
6078
6079 let actual_invisibles = collect_invisibles_from_new_editor(
6080 cx,
6081 EditorMode::Full,
6082 &input_text,
6083 px(editor_width),
6084 );
6085
6086 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6087 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6088 let mut i = 0;
6089 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6090 i = actual_index;
6091 match expected_invisibles.get(i) {
6092 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6093 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6094 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6095 _ => {
6096 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6097 }
6098 },
6099 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6100 }
6101 }
6102 let missing_expected_invisibles = &expected_invisibles[i + 1..];
6103 assert!(
6104 missing_expected_invisibles.is_empty(),
6105 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6106 );
6107
6108 editor_width += resize_step;
6109 }
6110 }
6111
6112 fn collect_invisibles_from_new_editor(
6113 cx: &mut TestAppContext,
6114 editor_mode: EditorMode,
6115 input_text: &str,
6116 editor_width: Pixels,
6117 ) -> Vec<Invisible> {
6118 info!(
6119 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6120 editor_width.0
6121 );
6122 let window = cx.add_window(|cx| {
6123 let buffer = MultiBuffer::build_simple(&input_text, cx);
6124 Editor::new(editor_mode, buffer, None, true, cx)
6125 });
6126 let cx = &mut VisualTestContext::from_window(*window, cx);
6127 let editor = window.root(cx).unwrap();
6128 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6129 window
6130 .update(cx, |editor, cx| {
6131 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6132 editor.set_wrap_width(Some(editor_width), cx);
6133 })
6134 .unwrap();
6135 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6136 EditorElement::new(&editor, style)
6137 });
6138 state
6139 .position_map
6140 .line_layouts
6141 .iter()
6142 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6143 .cloned()
6144 .collect()
6145 }
6146}
6147
6148pub fn register_action<T: Action>(
6149 view: &View<Editor>,
6150 cx: &mut WindowContext,
6151 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6152) {
6153 let view = view.clone();
6154 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6155 let action = action.downcast_ref().unwrap();
6156 if phase == DispatchPhase::Bubble {
6157 view.update(cx, |editor, cx| {
6158 listener(editor, action, cx);
6159 })
6160 }
6161 })
6162}
6163
6164fn compute_auto_height_layout(
6165 editor: &mut Editor,
6166 max_lines: usize,
6167 max_line_number_width: Pixels,
6168 known_dimensions: Size<Option<Pixels>>,
6169 available_width: AvailableSpace,
6170 cx: &mut ViewContext<Editor>,
6171) -> Option<Size<Pixels>> {
6172 let width = known_dimensions.width.or_else(|| {
6173 if let AvailableSpace::Definite(available_width) = available_width {
6174 Some(available_width)
6175 } else {
6176 None
6177 }
6178 })?;
6179 if let Some(height) = known_dimensions.height {
6180 return Some(size(width, height));
6181 }
6182
6183 let style = editor.style.as_ref().unwrap();
6184 let font_id = cx.text_system().resolve_font(&style.text.font());
6185 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6186 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6187 let em_width = cx
6188 .text_system()
6189 .typographic_bounds(font_id, font_size, 'm')
6190 .unwrap()
6191 .size
6192 .width;
6193
6194 let mut snapshot = editor.snapshot(cx);
6195 let gutter_dimensions =
6196 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6197
6198 editor.gutter_dimensions = gutter_dimensions;
6199 let text_width = width - gutter_dimensions.width;
6200 let overscroll = size(em_width, px(0.));
6201
6202 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6203 if editor.set_wrap_width(Some(editor_width), cx) {
6204 snapshot = editor.snapshot(cx);
6205 }
6206
6207 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6208 let height = scroll_height
6209 .max(line_height)
6210 .min(line_height * max_lines as f32);
6211
6212 Some(size(width, height))
6213}