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