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