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