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