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