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