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 // Selections
969 (is_singleton && scrollbar_settings.selections && editor.has_background_highlights::<BufferSearchHighlights>())
970 ||
971 // Symbols Selections
972 (is_singleton && scrollbar_settings.symbols_selections && (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 if (*background_highlight_id
2624 == TypeId::of::<BufferSearchHighlights>()
2625 && scrollbar_settings.selections)
2626 || scrollbar_settings.symbols_selections
2627 {
2628 let marker_row_ranges =
2629 background_ranges.into_iter().map(|range| {
2630 let display_start = range
2631 .start
2632 .to_display_point(&snapshot.display_snapshot);
2633 let display_end = range
2634 .end
2635 .to_display_point(&snapshot.display_snapshot);
2636 ColoredRange {
2637 start: display_start.row(),
2638 end: display_end.row(),
2639 color: theme.status().info,
2640 }
2641 });
2642 marker_quads.extend(
2643 scrollbar_layout
2644 .marker_quads_for_ranges(marker_row_ranges, 1),
2645 );
2646 }
2647 }
2648
2649 if scrollbar_settings.diagnostics {
2650 let max_point =
2651 snapshot.display_snapshot.buffer_snapshot.max_point();
2652
2653 let diagnostics = snapshot
2654 .buffer_snapshot
2655 .diagnostics_in_range::<_, Point>(
2656 Point::zero()..max_point,
2657 false,
2658 )
2659 // We want to sort by severity, in order to paint the most severe diagnostics last.
2660 .sorted_by_key(|diagnostic| {
2661 std::cmp::Reverse(diagnostic.diagnostic.severity)
2662 });
2663
2664 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2665 let start_display = diagnostic
2666 .range
2667 .start
2668 .to_display_point(&snapshot.display_snapshot);
2669 let end_display = diagnostic
2670 .range
2671 .end
2672 .to_display_point(&snapshot.display_snapshot);
2673 let color = match diagnostic.diagnostic.severity {
2674 DiagnosticSeverity::ERROR => theme.status().error,
2675 DiagnosticSeverity::WARNING => theme.status().warning,
2676 DiagnosticSeverity::INFORMATION => theme.status().info,
2677 _ => theme.status().hint,
2678 };
2679 ColoredRange {
2680 start: start_display.row(),
2681 end: end_display.row(),
2682 color,
2683 }
2684 });
2685 marker_quads.extend(
2686 scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 2),
2687 );
2688 }
2689
2690 Arc::from(marker_quads)
2691 })
2692 .await;
2693
2694 editor.update(&mut cx, |editor, cx| {
2695 editor.scrollbar_marker_state.markers = scrollbar_markers;
2696 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2697 editor.scrollbar_marker_state.pending_refresh = None;
2698 cx.notify();
2699 })?;
2700
2701 Ok(())
2702 }));
2703 });
2704 }
2705
2706 #[allow(clippy::too_many_arguments)]
2707 fn paint_highlighted_range(
2708 &self,
2709 range: Range<DisplayPoint>,
2710 color: Hsla,
2711 corner_radius: Pixels,
2712 line_end_overshoot: Pixels,
2713 layout: &EditorLayout,
2714 cx: &mut ElementContext,
2715 ) {
2716 let start_row = layout.visible_display_row_range.start;
2717 let end_row = layout.visible_display_row_range.end;
2718 if range.start != range.end {
2719 let row_range = if range.end.column() == 0 {
2720 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2721 } else {
2722 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2723 };
2724
2725 let highlighted_range = HighlightedRange {
2726 color,
2727 line_height: layout.position_map.line_height,
2728 corner_radius,
2729 start_y: layout.content_origin.y
2730 + row_range.start as f32 * layout.position_map.line_height
2731 - layout.position_map.scroll_pixel_position.y,
2732 lines: row_range
2733 .into_iter()
2734 .map(|row| {
2735 let line_layout =
2736 &layout.position_map.line_layouts[(row - start_row) as usize].line;
2737 HighlightedRangeLine {
2738 start_x: if row == range.start.row() {
2739 layout.content_origin.x
2740 + line_layout.x_for_index(range.start.column() as usize)
2741 - layout.position_map.scroll_pixel_position.x
2742 } else {
2743 layout.content_origin.x
2744 - layout.position_map.scroll_pixel_position.x
2745 },
2746 end_x: if row == range.end.row() {
2747 layout.content_origin.x
2748 + line_layout.x_for_index(range.end.column() as usize)
2749 - layout.position_map.scroll_pixel_position.x
2750 } else {
2751 layout.content_origin.x + line_layout.width + line_end_overshoot
2752 - layout.position_map.scroll_pixel_position.x
2753 },
2754 }
2755 })
2756 .collect(),
2757 };
2758
2759 highlighted_range.paint(layout.text_hitbox.bounds, cx);
2760 }
2761 }
2762
2763 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2764 if layout.folds.is_empty() {
2765 return;
2766 }
2767
2768 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2769 let fold_corner_radius = 0.15 * layout.position_map.line_height;
2770 for mut fold in mem::take(&mut layout.folds) {
2771 fold.hover_element.paint(cx);
2772
2773 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2774 let fold_background = if hover_element.interactivity().active.unwrap() {
2775 cx.theme().colors().ghost_element_active
2776 } else if hover_element.interactivity().hovered.unwrap() {
2777 cx.theme().colors().ghost_element_hover
2778 } else {
2779 cx.theme().colors().ghost_element_background
2780 };
2781
2782 self.paint_highlighted_range(
2783 fold.display_range.clone(),
2784 fold_background,
2785 fold_corner_radius,
2786 fold_corner_radius * 2.,
2787 layout,
2788 cx,
2789 );
2790 }
2791 })
2792 }
2793
2794 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2795 if let Some(mut inline_blame) = layout.inline_blame.take() {
2796 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2797 inline_blame.paint(cx);
2798 })
2799 }
2800 }
2801
2802 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2803 for mut block in layout.blocks.drain(..) {
2804 block.element.paint(cx);
2805 }
2806 }
2807
2808 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2809 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2810 mouse_context_menu.paint(cx);
2811 }
2812 }
2813
2814 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2815 cx.on_mouse_event({
2816 let position_map = layout.position_map.clone();
2817 let editor = self.editor.clone();
2818 let hitbox = layout.hitbox.clone();
2819 let mut delta = ScrollDelta::default();
2820
2821 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
2822 // accidentally turn off their scrolling.
2823 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
2824
2825 move |event: &ScrollWheelEvent, phase, cx| {
2826 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2827 delta = delta.coalesce(event.delta);
2828 editor.update(cx, |editor, cx| {
2829 let position_map: &PositionMap = &position_map;
2830
2831 let line_height = position_map.line_height;
2832 let max_glyph_width = position_map.em_width;
2833 let (delta, axis) = match delta {
2834 gpui::ScrollDelta::Pixels(mut pixels) => {
2835 //Trackpad
2836 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2837 (pixels, axis)
2838 }
2839
2840 gpui::ScrollDelta::Lines(lines) => {
2841 //Not trackpad
2842 let pixels =
2843 point(lines.x * max_glyph_width, lines.y * line_height);
2844 (pixels, None)
2845 }
2846 };
2847
2848 let scroll_position = position_map.snapshot.scroll_position();
2849 let x = (scroll_position.x * max_glyph_width
2850 - (delta.x * scroll_sensitivity))
2851 / max_glyph_width;
2852 let y = (scroll_position.y * line_height - (delta.y * scroll_sensitivity))
2853 / line_height;
2854 let scroll_position =
2855 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2856 editor.scroll(scroll_position, axis, cx);
2857 cx.stop_propagation();
2858 });
2859 }
2860 }
2861 });
2862 }
2863
2864 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2865 self.paint_scroll_wheel_listener(layout, cx);
2866
2867 cx.on_mouse_event({
2868 let position_map = layout.position_map.clone();
2869 let editor = self.editor.clone();
2870 let text_hitbox = layout.text_hitbox.clone();
2871 let gutter_hitbox = layout.gutter_hitbox.clone();
2872
2873 move |event: &MouseDownEvent, phase, cx| {
2874 if phase == DispatchPhase::Bubble {
2875 match event.button {
2876 MouseButton::Left => editor.update(cx, |editor, cx| {
2877 Self::mouse_left_down(
2878 editor,
2879 event,
2880 &position_map,
2881 &text_hitbox,
2882 &gutter_hitbox,
2883 cx,
2884 );
2885 }),
2886 MouseButton::Right => editor.update(cx, |editor, cx| {
2887 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2888 }),
2889 _ => {}
2890 };
2891 }
2892 }
2893 });
2894
2895 cx.on_mouse_event({
2896 let editor = self.editor.clone();
2897 let position_map = layout.position_map.clone();
2898 let text_hitbox = layout.text_hitbox.clone();
2899
2900 move |event: &MouseUpEvent, phase, cx| {
2901 if phase == DispatchPhase::Bubble {
2902 editor.update(cx, |editor, cx| {
2903 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2904 });
2905 }
2906 }
2907 });
2908 cx.on_mouse_event({
2909 let position_map = layout.position_map.clone();
2910 let editor = self.editor.clone();
2911 let text_hitbox = layout.text_hitbox.clone();
2912 let gutter_hitbox = layout.gutter_hitbox.clone();
2913
2914 move |event: &MouseMoveEvent, phase, cx| {
2915 if phase == DispatchPhase::Bubble {
2916 editor.update(cx, |editor, cx| {
2917 if event.pressed_button == Some(MouseButton::Left) {
2918 Self::mouse_dragged(
2919 editor,
2920 event,
2921 &position_map,
2922 text_hitbox.bounds,
2923 cx,
2924 )
2925 }
2926
2927 Self::mouse_moved(
2928 editor,
2929 event,
2930 &position_map,
2931 &text_hitbox,
2932 &gutter_hitbox,
2933 cx,
2934 )
2935 });
2936 }
2937 }
2938 });
2939 }
2940
2941 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2942 bounds.upper_right().x - self.style.scrollbar_width
2943 }
2944
2945 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2946 let style = &self.style;
2947 let font_size = style.text.font_size.to_pixels(cx.rem_size());
2948 let layout = cx
2949 .text_system()
2950 .shape_line(
2951 SharedString::from(" ".repeat(column)),
2952 font_size,
2953 &[TextRun {
2954 len: column,
2955 font: style.text.font(),
2956 color: Hsla::default(),
2957 background_color: None,
2958 underline: None,
2959 strikethrough: None,
2960 }],
2961 )
2962 .unwrap();
2963
2964 layout.width
2965 }
2966
2967 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2968 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2969 self.column_pixels(digit_count, cx)
2970 }
2971}
2972
2973fn render_inline_blame_entry(
2974 blame: &gpui::Model<GitBlame>,
2975 blame_entry: BlameEntry,
2976 style: &EditorStyle,
2977 workspace: Option<WeakView<Workspace>>,
2978 cx: &mut ElementContext<'_>,
2979) -> AnyElement {
2980 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
2981
2982 let author = blame_entry.author.as_deref().unwrap_or_default();
2983 let text = format!("{}, {}", author, relative_timestamp);
2984
2985 let details = blame.read(cx).details_for_entry(&blame_entry);
2986
2987 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
2988
2989 h_flex()
2990 .id("inline-blame")
2991 .w_full()
2992 .font(style.text.font().family)
2993 .text_color(cx.theme().status().hint)
2994 .line_height(style.text.line_height)
2995 .child(Icon::new(IconName::FileGit).color(Color::Hint))
2996 .child(text)
2997 .gap_2()
2998 .hoverable_tooltip(move |_| tooltip.clone().into())
2999 .into_any()
3000}
3001
3002fn blame_entry_timestamp(
3003 blame_entry: &BlameEntry,
3004 format: time_format::TimestampFormat,
3005 cx: &WindowContext,
3006) -> String {
3007 match blame_entry.author_offset_date_time() {
3008 Ok(timestamp) => time_format::format_localized_timestamp(
3009 timestamp,
3010 time::OffsetDateTime::now_utc(),
3011 cx.local_timezone(),
3012 format,
3013 ),
3014 Err(_) => "Error parsing date".to_string(),
3015 }
3016}
3017
3018fn blame_entry_relative_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3019 blame_entry_timestamp(blame_entry, time_format::TimestampFormat::Relative, cx)
3020}
3021
3022fn blame_entry_absolute_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3023 blame_entry_timestamp(
3024 blame_entry,
3025 time_format::TimestampFormat::MediumAbsolute,
3026 cx,
3027 )
3028}
3029
3030struct BlameEntryTooltip {
3031 blame_entry: BlameEntry,
3032 details: Option<CommitDetails>,
3033 style: EditorStyle,
3034 workspace: Option<WeakView<Workspace>>,
3035 scroll_handle: ScrollHandle,
3036}
3037
3038impl BlameEntryTooltip {
3039 fn new(
3040 blame_entry: BlameEntry,
3041 details: Option<CommitDetails>,
3042 style: &EditorStyle,
3043 workspace: Option<WeakView<Workspace>>,
3044 ) -> Self {
3045 Self {
3046 style: style.clone(),
3047 blame_entry,
3048 details,
3049 workspace,
3050 scroll_handle: ScrollHandle::new(),
3051 }
3052 }
3053}
3054
3055impl Render for BlameEntryTooltip {
3056 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3057 let author = self
3058 .blame_entry
3059 .author
3060 .clone()
3061 .unwrap_or("<no name>".to_string());
3062
3063 let author_email = self.blame_entry.author_mail.clone();
3064
3065 let pretty_commit_id = format!("{}", self.blame_entry.sha);
3066 let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3067 let absolute_timestamp = blame_entry_absolute_timestamp(&self.blame_entry, cx);
3068
3069 let message = self
3070 .details
3071 .as_ref()
3072 .map(|details| {
3073 crate::render_parsed_markdown(
3074 "blame-message",
3075 &details.parsed_message,
3076 &self.style,
3077 self.workspace.clone(),
3078 cx,
3079 )
3080 .into_any()
3081 })
3082 .unwrap_or("<no commit message>".into_any());
3083
3084 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
3085 let message_max_height = cx.line_height() * 12 + (ui_font_size / 0.4);
3086
3087 tooltip_container(cx, move |this, cx| {
3088 this.occlude()
3089 .on_mouse_move(|_, cx| cx.stop_propagation())
3090 .child(
3091 v_flex()
3092 .w(gpui::rems(30.))
3093 .gap_4()
3094 .child(
3095 h_flex()
3096 .gap_2()
3097 .child(author)
3098 .when_some(author_email, |this, author_email| {
3099 this.child(
3100 div()
3101 .text_color(cx.theme().colors().text_muted)
3102 .child(author_email),
3103 )
3104 })
3105 .pb_1()
3106 .border_b_1()
3107 .border_color(cx.theme().colors().border),
3108 )
3109 .child(
3110 div()
3111 .id("inline-blame-commit-message")
3112 .occlude()
3113 .child(message)
3114 .max_h(message_max_height)
3115 .overflow_y_scroll()
3116 .track_scroll(&self.scroll_handle),
3117 )
3118 .child(
3119 h_flex()
3120 .text_color(cx.theme().colors().text_muted)
3121 .w_full()
3122 .justify_between()
3123 .child(absolute_timestamp)
3124 .child(
3125 Button::new("commit-sha-button", short_commit_id.clone())
3126 .style(ButtonStyle::Transparent)
3127 .color(Color::Muted)
3128 .icon(IconName::FileGit)
3129 .icon_color(Color::Muted)
3130 .icon_position(IconPosition::Start)
3131 .disabled(
3132 self.details.as_ref().map_or(true, |details| {
3133 details.permalink.is_none()
3134 }),
3135 )
3136 .when_some(
3137 self.details
3138 .as_ref()
3139 .and_then(|details| details.permalink.clone()),
3140 |this, url| {
3141 this.on_click(move |_, cx| {
3142 cx.stop_propagation();
3143 cx.open_url(url.as_str())
3144 })
3145 },
3146 ),
3147 ),
3148 ),
3149 )
3150 })
3151 }
3152}
3153
3154fn render_blame_entry(
3155 ix: usize,
3156 blame: &gpui::Model<GitBlame>,
3157 blame_entry: BlameEntry,
3158 style: &EditorStyle,
3159 last_used_color: &mut Option<(PlayerColor, Oid)>,
3160 editor: View<Editor>,
3161 cx: &mut ElementContext<'_>,
3162) -> AnyElement {
3163 let mut sha_color = cx
3164 .theme()
3165 .players()
3166 .color_for_participant(blame_entry.sha.into());
3167 // If the last color we used is the same as the one we get for this line, but
3168 // the commit SHAs are different, then we try again to get a different color.
3169 match *last_used_color {
3170 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3171 let index: u32 = blame_entry.sha.into();
3172 sha_color = cx.theme().players().color_for_participant(index + 1);
3173 }
3174 _ => {}
3175 };
3176 last_used_color.replace((sha_color, blame_entry.sha));
3177
3178 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3179
3180 let pretty_commit_id = format!("{}", blame_entry.sha);
3181 let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3182
3183 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3184 let name = util::truncate_and_trailoff(author_name, 20);
3185
3186 let details = blame.read(cx).details_for_entry(&blame_entry);
3187
3188 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3189
3190 let tooltip = cx.new_view(|_| {
3191 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3192 });
3193
3194 h_flex()
3195 .w_full()
3196 .font(style.text.font().family)
3197 .line_height(style.text.line_height)
3198 .id(("blame", ix))
3199 .children([
3200 div()
3201 .text_color(sha_color.cursor)
3202 .child(short_commit_id)
3203 .mr_2(),
3204 div()
3205 .w_full()
3206 .h_flex()
3207 .justify_between()
3208 .text_color(cx.theme().status().hint)
3209 .child(name)
3210 .child(relative_timestamp),
3211 ])
3212 .on_mouse_down(MouseButton::Right, {
3213 let blame_entry = blame_entry.clone();
3214 move |event, cx| {
3215 deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3216 }
3217 })
3218 .hover(|style| style.bg(cx.theme().colors().element_hover))
3219 .when_some(
3220 details.and_then(|details| details.permalink),
3221 |this, url| {
3222 let url = url.clone();
3223 this.cursor_pointer().on_click(move |_, cx| {
3224 cx.stop_propagation();
3225 cx.open_url(url.as_str())
3226 })
3227 },
3228 )
3229 .hoverable_tooltip(move |_| tooltip.clone().into())
3230 .into_any()
3231}
3232
3233fn deploy_blame_entry_context_menu(
3234 blame_entry: &BlameEntry,
3235 editor: View<Editor>,
3236 position: gpui::Point<Pixels>,
3237 cx: &mut WindowContext<'_>,
3238) {
3239 let context_menu = ContextMenu::build(cx, move |this, _| {
3240 let sha = format!("{}", blame_entry.sha);
3241 this.entry("Copy commit SHA", None, move |cx| {
3242 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3243 })
3244 });
3245
3246 editor.update(cx, move |editor, cx| {
3247 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3248 cx.notify();
3249 });
3250}
3251
3252#[derive(Debug)]
3253pub(crate) struct LineWithInvisibles {
3254 pub line: ShapedLine,
3255 invisibles: Vec<Invisible>,
3256}
3257
3258impl LineWithInvisibles {
3259 fn from_chunks<'a>(
3260 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3261 text_style: &TextStyle,
3262 max_line_len: usize,
3263 max_line_count: usize,
3264 line_number_layouts: &[Option<ShapedLine>],
3265 editor_mode: EditorMode,
3266 cx: &WindowContext,
3267 ) -> Vec<Self> {
3268 let mut layouts = Vec::with_capacity(max_line_count);
3269 let mut line = String::new();
3270 let mut invisibles = Vec::new();
3271 let mut styles = Vec::new();
3272 let mut non_whitespace_added = false;
3273 let mut row = 0;
3274 let mut line_exceeded_max_len = false;
3275 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3276
3277 for highlighted_chunk in chunks.chain([HighlightedChunk {
3278 chunk: "\n",
3279 style: None,
3280 is_tab: false,
3281 }]) {
3282 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3283 if ix > 0 {
3284 let shaped_line = cx
3285 .text_system()
3286 .shape_line(line.clone().into(), font_size, &styles)
3287 .unwrap();
3288 layouts.push(Self {
3289 line: shaped_line,
3290 invisibles: std::mem::take(&mut invisibles),
3291 });
3292
3293 line.clear();
3294 styles.clear();
3295 row += 1;
3296 line_exceeded_max_len = false;
3297 non_whitespace_added = false;
3298 if row == max_line_count {
3299 return layouts;
3300 }
3301 }
3302
3303 if !line_chunk.is_empty() && !line_exceeded_max_len {
3304 let text_style = if let Some(style) = highlighted_chunk.style {
3305 Cow::Owned(text_style.clone().highlight(style))
3306 } else {
3307 Cow::Borrowed(text_style)
3308 };
3309
3310 if line.len() + line_chunk.len() > max_line_len {
3311 let mut chunk_len = max_line_len - line.len();
3312 while !line_chunk.is_char_boundary(chunk_len) {
3313 chunk_len -= 1;
3314 }
3315 line_chunk = &line_chunk[..chunk_len];
3316 line_exceeded_max_len = true;
3317 }
3318
3319 styles.push(TextRun {
3320 len: line_chunk.len(),
3321 font: text_style.font(),
3322 color: text_style.color,
3323 background_color: text_style.background_color,
3324 underline: text_style.underline,
3325 strikethrough: text_style.strikethrough,
3326 });
3327
3328 if editor_mode == EditorMode::Full {
3329 // Line wrap pads its contents with fake whitespaces,
3330 // avoid printing them
3331 let inside_wrapped_string = line_number_layouts
3332 .get(row)
3333 .and_then(|layout| layout.as_ref())
3334 .is_none();
3335 if highlighted_chunk.is_tab {
3336 if non_whitespace_added || !inside_wrapped_string {
3337 invisibles.push(Invisible::Tab {
3338 line_start_offset: line.len(),
3339 });
3340 }
3341 } else {
3342 invisibles.extend(
3343 line_chunk
3344 .chars()
3345 .enumerate()
3346 .filter(|(_, line_char)| {
3347 let is_whitespace = line_char.is_whitespace();
3348 non_whitespace_added |= !is_whitespace;
3349 is_whitespace
3350 && (non_whitespace_added || !inside_wrapped_string)
3351 })
3352 .map(|(whitespace_index, _)| Invisible::Whitespace {
3353 line_offset: line.len() + whitespace_index,
3354 }),
3355 )
3356 }
3357 }
3358
3359 line.push_str(line_chunk);
3360 }
3361 }
3362 }
3363
3364 layouts
3365 }
3366
3367 fn draw(
3368 &self,
3369 layout: &EditorLayout,
3370 row: u32,
3371 content_origin: gpui::Point<Pixels>,
3372 whitespace_setting: ShowWhitespaceSetting,
3373 selection_ranges: &[Range<DisplayPoint>],
3374 cx: &mut ElementContext,
3375 ) {
3376 let line_height = layout.position_map.line_height;
3377 let line_y =
3378 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3379
3380 let line_origin =
3381 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3382 self.line.paint(line_origin, line_height, cx).log_err();
3383
3384 self.draw_invisibles(
3385 &selection_ranges,
3386 layout,
3387 content_origin,
3388 line_y,
3389 row,
3390 line_height,
3391 whitespace_setting,
3392 cx,
3393 );
3394 }
3395
3396 #[allow(clippy::too_many_arguments)]
3397 fn draw_invisibles(
3398 &self,
3399 selection_ranges: &[Range<DisplayPoint>],
3400 layout: &EditorLayout,
3401 content_origin: gpui::Point<Pixels>,
3402 line_y: Pixels,
3403 row: u32,
3404 line_height: Pixels,
3405 whitespace_setting: ShowWhitespaceSetting,
3406 cx: &mut ElementContext,
3407 ) {
3408 let allowed_invisibles_regions = match whitespace_setting {
3409 ShowWhitespaceSetting::None => return,
3410 ShowWhitespaceSetting::Selection => Some(selection_ranges),
3411 ShowWhitespaceSetting::All => None,
3412 };
3413
3414 for invisible in &self.invisibles {
3415 let (&token_offset, invisible_symbol) = match invisible {
3416 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3417 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3418 };
3419
3420 let x_offset = self.line.x_for_index(token_offset);
3421 let invisible_offset =
3422 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3423 let origin = content_origin
3424 + gpui::point(
3425 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3426 line_y,
3427 );
3428
3429 if let Some(allowed_regions) = allowed_invisibles_regions {
3430 let invisible_point = DisplayPoint::new(row, token_offset as u32);
3431 if !allowed_regions
3432 .iter()
3433 .any(|region| region.start <= invisible_point && invisible_point < region.end)
3434 {
3435 continue;
3436 }
3437 }
3438 invisible_symbol.paint(origin, line_height, cx).log_err();
3439 }
3440 }
3441}
3442
3443#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3444enum Invisible {
3445 Tab { line_start_offset: usize },
3446 Whitespace { line_offset: usize },
3447}
3448
3449impl Element for EditorElement {
3450 type BeforeLayout = ();
3451 type AfterLayout = EditorLayout;
3452
3453 fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
3454 self.editor.update(cx, |editor, cx| {
3455 editor.set_style(self.style.clone(), cx);
3456
3457 let layout_id = match editor.mode {
3458 EditorMode::SingleLine => {
3459 let rem_size = cx.rem_size();
3460 let mut style = Style::default();
3461 style.size.width = relative(1.).into();
3462 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3463 cx.with_element_context(|cx| cx.request_layout(&style, None))
3464 }
3465 EditorMode::AutoHeight { max_lines } => {
3466 let editor_handle = cx.view().clone();
3467 let max_line_number_width =
3468 self.max_line_number_width(&editor.snapshot(cx), cx);
3469 cx.with_element_context(|cx| {
3470 cx.request_measured_layout(
3471 Style::default(),
3472 move |known_dimensions, _, cx| {
3473 editor_handle
3474 .update(cx, |editor, cx| {
3475 compute_auto_height_layout(
3476 editor,
3477 max_lines,
3478 max_line_number_width,
3479 known_dimensions,
3480 cx,
3481 )
3482 })
3483 .unwrap_or_default()
3484 },
3485 )
3486 })
3487 }
3488 EditorMode::Full => {
3489 let mut style = Style::default();
3490 style.size.width = relative(1.).into();
3491 style.size.height = relative(1.).into();
3492 cx.with_element_context(|cx| cx.request_layout(&style, None))
3493 }
3494 };
3495
3496 (layout_id, ())
3497 })
3498 }
3499
3500 fn after_layout(
3501 &mut self,
3502 bounds: Bounds<Pixels>,
3503 _: &mut Self::BeforeLayout,
3504 cx: &mut ElementContext,
3505 ) -> Self::AfterLayout {
3506 let text_style = TextStyleRefinement {
3507 font_size: Some(self.style.text.font_size),
3508 line_height: Some(self.style.text.line_height),
3509 ..Default::default()
3510 };
3511 cx.with_text_style(Some(text_style), |cx| {
3512 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3513 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3514 let style = self.style.clone();
3515
3516 let font_id = cx.text_system().resolve_font(&style.text.font());
3517 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3518 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3519 let em_width = cx
3520 .text_system()
3521 .typographic_bounds(font_id, font_size, 'm')
3522 .unwrap()
3523 .size
3524 .width;
3525 let em_advance = cx
3526 .text_system()
3527 .advance(font_id, font_size, 'm')
3528 .unwrap()
3529 .width;
3530
3531 let gutter_dimensions = snapshot.gutter_dimensions(
3532 font_id,
3533 font_size,
3534 em_width,
3535 self.max_line_number_width(&snapshot, cx),
3536 cx,
3537 );
3538 let text_width = bounds.size.width - gutter_dimensions.width;
3539 let overscroll = size(em_width, px(0.));
3540
3541 snapshot = self.editor.update(cx, |editor, cx| {
3542 editor.last_bounds = Some(bounds);
3543 editor.gutter_width = gutter_dimensions.width;
3544 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3545
3546 let editor_width =
3547 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3548 let wrap_width = match editor.soft_wrap_mode(cx) {
3549 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3550 SoftWrap::EditorWidth => editor_width,
3551 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3552 };
3553
3554 if editor.set_wrap_width(Some(wrap_width), cx) {
3555 editor.snapshot(cx)
3556 } else {
3557 snapshot
3558 }
3559 });
3560
3561 let wrap_guides = self
3562 .editor
3563 .read(cx)
3564 .wrap_guides(cx)
3565 .iter()
3566 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3567 .collect::<SmallVec<[_; 2]>>();
3568
3569 let hitbox = cx.insert_hitbox(bounds, false);
3570 let gutter_hitbox = cx.insert_hitbox(
3571 Bounds {
3572 origin: bounds.origin,
3573 size: size(gutter_dimensions.width, bounds.size.height),
3574 },
3575 false,
3576 );
3577 let text_hitbox = cx.insert_hitbox(
3578 Bounds {
3579 origin: gutter_hitbox.upper_right(),
3580 size: size(text_width, bounds.size.height),
3581 },
3582 false,
3583 );
3584 // Offset the content_bounds from the text_bounds by the gutter margin (which
3585 // is roughly half a character wide) to make hit testing work more like how we want.
3586 let content_origin =
3587 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3588
3589 let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
3590 let autoscroll_horizontally =
3591 editor.autoscroll_vertically(bounds, line_height, cx);
3592 snapshot = editor.snapshot(cx);
3593 autoscroll_horizontally
3594 });
3595
3596 let mut scroll_position = snapshot.scroll_position();
3597 // The scroll position is a fractional point, the whole number of which represents
3598 // the top of the window in terms of display rows.
3599 let start_row = scroll_position.y as u32;
3600 let height_in_lines = bounds.size.height / line_height;
3601 let max_row = snapshot.max_point().row();
3602
3603 // Add 1 to ensure selections bleed off screen
3604 let end_row =
3605 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3606
3607 let buffer_rows = snapshot
3608 .buffer_rows(start_row)
3609 .take((start_row..end_row).len());
3610
3611 let start_anchor = if start_row == 0 {
3612 Anchor::min()
3613 } else {
3614 snapshot.buffer_snapshot.anchor_before(
3615 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3616 )
3617 };
3618 let end_anchor = if end_row > max_row {
3619 Anchor::max()
3620 } else {
3621 snapshot.buffer_snapshot.anchor_before(
3622 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3623 )
3624 };
3625
3626 let highlighted_rows = self
3627 .editor
3628 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3629 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3630 start_anchor..end_anchor,
3631 &snapshot.display_snapshot,
3632 cx.theme().colors(),
3633 );
3634
3635 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3636 start_anchor..end_anchor,
3637 &snapshot.display_snapshot,
3638 cx,
3639 );
3640
3641 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3642 start_anchor,
3643 end_anchor,
3644 &snapshot,
3645 start_row,
3646 end_row,
3647 cx,
3648 );
3649
3650 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3651 start_row..end_row,
3652 buffer_rows.clone(),
3653 &active_rows,
3654 newest_selection_head,
3655 &snapshot,
3656 cx,
3657 );
3658
3659 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3660
3661 let mut max_visible_line_width = Pixels::ZERO;
3662 let line_layouts =
3663 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3664 for line_with_invisibles in &line_layouts {
3665 if line_with_invisibles.line.width > max_visible_line_width {
3666 max_visible_line_width = line_with_invisibles.line.width;
3667 }
3668 }
3669
3670 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3671 .unwrap()
3672 .width;
3673 let mut scroll_width =
3674 longest_line_width.max(max_visible_line_width) + overscroll.width;
3675 let mut blocks = self.build_blocks(
3676 start_row..end_row,
3677 &snapshot,
3678 &hitbox,
3679 &text_hitbox,
3680 &mut scroll_width,
3681 &gutter_dimensions,
3682 em_width,
3683 gutter_dimensions.width + gutter_dimensions.margin,
3684 line_height,
3685 &line_layouts,
3686 cx,
3687 );
3688
3689 let scroll_pixel_position = point(
3690 scroll_position.x * em_width,
3691 scroll_position.y * line_height,
3692 );
3693
3694 let mut inline_blame = None;
3695 if let Some(newest_selection_head) = newest_selection_head {
3696 if (start_row..end_row).contains(&newest_selection_head.row()) {
3697 inline_blame = self.layout_inline_blame(
3698 start_row,
3699 newest_selection_head.row(),
3700 &line_layouts,
3701 em_width,
3702 content_origin,
3703 scroll_pixel_position,
3704 line_height,
3705 cx,
3706 );
3707 }
3708 }
3709
3710 let blamed_display_rows = self.layout_blame_entries(
3711 buffer_rows,
3712 em_width,
3713 scroll_position,
3714 line_height,
3715 &gutter_hitbox,
3716 gutter_dimensions.git_blame_entries_width,
3717 cx,
3718 );
3719
3720 let scroll_max = point(
3721 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3722 max_row as f32,
3723 );
3724
3725 self.editor.update(cx, |editor, cx| {
3726 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3727
3728 let autoscrolled = if autoscroll_horizontally {
3729 editor.autoscroll_horizontally(
3730 start_row,
3731 text_hitbox.size.width,
3732 scroll_width,
3733 em_width,
3734 &line_layouts,
3735 cx,
3736 )
3737 } else {
3738 false
3739 };
3740
3741 if clamped || autoscrolled {
3742 snapshot = editor.snapshot(cx);
3743 scroll_position = snapshot.scroll_position();
3744 }
3745 });
3746
3747 cx.with_element_id(Some("blocks"), |cx| {
3748 self.layout_blocks(
3749 &mut blocks,
3750 &hitbox,
3751 line_height,
3752 scroll_pixel_position,
3753 cx,
3754 );
3755 });
3756
3757 let cursors = self.layout_cursors(
3758 &snapshot,
3759 &selections,
3760 start_row..end_row,
3761 &line_layouts,
3762 &text_hitbox,
3763 content_origin,
3764 scroll_pixel_position,
3765 line_height,
3766 em_width,
3767 cx,
3768 );
3769
3770 let scrollbar_layout = self.layout_scrollbar(
3771 &snapshot,
3772 bounds,
3773 scroll_position,
3774 line_height,
3775 height_in_lines,
3776 cx,
3777 );
3778
3779 let folds = cx.with_element_id(Some("folds"), |cx| {
3780 self.layout_folds(
3781 &snapshot,
3782 content_origin,
3783 start_anchor..end_anchor,
3784 start_row..end_row,
3785 scroll_pixel_position,
3786 line_height,
3787 &line_layouts,
3788 cx,
3789 )
3790 });
3791
3792 let gutter_settings = EditorSettings::get_global(cx).gutter;
3793
3794 let mut context_menu_visible = false;
3795 let mut code_actions_indicator = None;
3796 if let Some(newest_selection_head) = newest_selection_head {
3797 if (start_row..end_row).contains(&newest_selection_head.row()) {
3798 context_menu_visible = self.layout_context_menu(
3799 line_height,
3800 &hitbox,
3801 &text_hitbox,
3802 content_origin,
3803 start_row,
3804 scroll_pixel_position,
3805 &line_layouts,
3806 newest_selection_head,
3807 cx,
3808 );
3809 if gutter_settings.code_actions {
3810 code_actions_indicator = self.layout_code_actions_indicator(
3811 line_height,
3812 newest_selection_head,
3813 scroll_pixel_position,
3814 &gutter_dimensions,
3815 &gutter_hitbox,
3816 cx,
3817 );
3818 }
3819 }
3820 }
3821
3822 if !context_menu_visible && !cx.has_active_drag() {
3823 self.layout_hover_popovers(
3824 &snapshot,
3825 &hitbox,
3826 &text_hitbox,
3827 start_row..end_row,
3828 content_origin,
3829 scroll_pixel_position,
3830 &line_layouts,
3831 line_height,
3832 em_width,
3833 cx,
3834 );
3835 }
3836
3837 let mouse_context_menu = self.layout_mouse_context_menu(cx);
3838
3839 let fold_indicators = if gutter_settings.folds {
3840 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3841 self.layout_gutter_fold_indicators(
3842 fold_statuses,
3843 line_height,
3844 &gutter_dimensions,
3845 gutter_settings,
3846 scroll_pixel_position,
3847 &gutter_hitbox,
3848 cx,
3849 )
3850 })
3851 } else {
3852 Vec::new()
3853 };
3854
3855 let invisible_symbol_font_size = font_size / 2.;
3856 let tab_invisible = cx
3857 .text_system()
3858 .shape_line(
3859 "→".into(),
3860 invisible_symbol_font_size,
3861 &[TextRun {
3862 len: "→".len(),
3863 font: self.style.text.font(),
3864 color: cx.theme().colors().editor_invisible,
3865 background_color: None,
3866 underline: None,
3867 strikethrough: None,
3868 }],
3869 )
3870 .unwrap();
3871 let space_invisible = cx
3872 .text_system()
3873 .shape_line(
3874 "•".into(),
3875 invisible_symbol_font_size,
3876 &[TextRun {
3877 len: "•".len(),
3878 font: self.style.text.font(),
3879 color: cx.theme().colors().editor_invisible,
3880 background_color: None,
3881 underline: None,
3882 strikethrough: None,
3883 }],
3884 )
3885 .unwrap();
3886
3887 EditorLayout {
3888 mode: snapshot.mode,
3889 position_map: Arc::new(PositionMap {
3890 size: bounds.size,
3891 scroll_pixel_position,
3892 scroll_max,
3893 line_layouts,
3894 line_height,
3895 em_width,
3896 em_advance,
3897 snapshot,
3898 }),
3899 visible_display_row_range: start_row..end_row,
3900 wrap_guides,
3901 hitbox,
3902 text_hitbox,
3903 gutter_hitbox,
3904 gutter_dimensions,
3905 content_origin,
3906 scrollbar_layout,
3907 max_row,
3908 active_rows,
3909 highlighted_rows,
3910 highlighted_ranges,
3911 redacted_ranges,
3912 line_numbers,
3913 display_hunks,
3914 blamed_display_rows,
3915 inline_blame,
3916 folds,
3917 blocks,
3918 cursors,
3919 selections,
3920 mouse_context_menu,
3921 code_actions_indicator,
3922 fold_indicators,
3923 tab_invisible,
3924 space_invisible,
3925 }
3926 })
3927 })
3928 }
3929
3930 fn paint(
3931 &mut self,
3932 bounds: Bounds<gpui::Pixels>,
3933 _: &mut Self::BeforeLayout,
3934 layout: &mut Self::AfterLayout,
3935 cx: &mut ElementContext,
3936 ) {
3937 let focus_handle = self.editor.focus_handle(cx);
3938 let key_context = self.editor.read(cx).key_context(cx);
3939 cx.set_focus_handle(&focus_handle);
3940 cx.set_key_context(key_context);
3941 cx.set_view_id(self.editor.entity_id());
3942 cx.handle_input(
3943 &focus_handle,
3944 ElementInputHandler::new(bounds, self.editor.clone()),
3945 );
3946 self.register_actions(cx);
3947 self.register_key_listeners(cx, layout);
3948
3949 let text_style = TextStyleRefinement {
3950 font_size: Some(self.style.text.font_size),
3951 line_height: Some(self.style.text.line_height),
3952 ..Default::default()
3953 };
3954 cx.with_text_style(Some(text_style), |cx| {
3955 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3956 self.paint_mouse_listeners(layout, cx);
3957
3958 self.paint_background(layout, cx);
3959 if layout.gutter_hitbox.size.width > Pixels::ZERO {
3960 self.paint_gutter(layout, cx);
3961 }
3962 self.paint_text(layout, cx);
3963
3964 if !layout.blocks.is_empty() {
3965 cx.with_element_id(Some("blocks"), |cx| {
3966 self.paint_blocks(layout, cx);
3967 });
3968 }
3969
3970 self.paint_scrollbar(layout, cx);
3971 self.paint_mouse_context_menu(layout, cx);
3972 });
3973 })
3974 }
3975}
3976
3977impl IntoElement for EditorElement {
3978 type Element = Self;
3979
3980 fn into_element(self) -> Self::Element {
3981 self
3982 }
3983}
3984
3985type BufferRow = u32;
3986
3987pub struct EditorLayout {
3988 position_map: Arc<PositionMap>,
3989 hitbox: Hitbox,
3990 text_hitbox: Hitbox,
3991 gutter_hitbox: Hitbox,
3992 gutter_dimensions: GutterDimensions,
3993 content_origin: gpui::Point<Pixels>,
3994 scrollbar_layout: Option<ScrollbarLayout>,
3995 mode: EditorMode,
3996 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3997 visible_display_row_range: Range<u32>,
3998 active_rows: BTreeMap<u32, bool>,
3999 highlighted_rows: BTreeMap<u32, Hsla>,
4000 line_numbers: Vec<Option<ShapedLine>>,
4001 display_hunks: Vec<DisplayDiffHunk>,
4002 blamed_display_rows: Option<Vec<AnyElement>>,
4003 inline_blame: Option<AnyElement>,
4004 folds: Vec<FoldLayout>,
4005 blocks: Vec<BlockLayout>,
4006 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4007 redacted_ranges: Vec<Range<DisplayPoint>>,
4008 cursors: Vec<CursorLayout>,
4009 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4010 max_row: u32,
4011 code_actions_indicator: Option<AnyElement>,
4012 fold_indicators: Vec<Option<AnyElement>>,
4013 mouse_context_menu: Option<AnyElement>,
4014 tab_invisible: ShapedLine,
4015 space_invisible: ShapedLine,
4016}
4017
4018impl EditorLayout {
4019 fn line_end_overshoot(&self) -> Pixels {
4020 0.15 * self.position_map.line_height
4021 }
4022}
4023
4024struct ColoredRange<T> {
4025 start: T,
4026 end: T,
4027 color: Hsla,
4028}
4029
4030#[derive(Clone)]
4031struct ScrollbarLayout {
4032 hitbox: Hitbox,
4033 visible_row_range: Range<f32>,
4034 visible: bool,
4035 height: Pixels,
4036 scroll_height: f32,
4037 first_row_y_offset: Pixels,
4038 row_height: Pixels,
4039}
4040
4041impl ScrollbarLayout {
4042 const BORDER_WIDTH: Pixels = px(1.0);
4043 const MIN_MARKER_HEIGHT: Pixels = px(2.0);
4044
4045 fn thumb_bounds(&self) -> Bounds<Pixels> {
4046 let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
4047 let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
4048 Bounds::from_corners(
4049 point(self.hitbox.left(), thumb_top),
4050 point(self.hitbox.right(), thumb_bottom),
4051 )
4052 }
4053
4054 fn y_for_row(&self, row: f32) -> Pixels {
4055 self.hitbox.top() + self.first_row_y_offset + row * self.row_height
4056 }
4057
4058 fn marker_quads_for_ranges(
4059 &self,
4060 row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4061 column: usize,
4062 ) -> Vec<PaintQuad> {
4063 let column_width =
4064 px(((self.hitbox.size.width - ScrollbarLayout::BORDER_WIDTH).0 / 3.0).floor());
4065
4066 let left_x = ScrollbarLayout::BORDER_WIDTH + (column as f32 * column_width);
4067 let right_x = left_x + column_width;
4068
4069 let mut background_pixel_ranges = row_ranges
4070 .into_iter()
4071 .map(|range| {
4072 let start_y = self.first_row_y_offset + range.start as f32 * self.row_height;
4073 let end_y = self.first_row_y_offset + (range.end + 1) as f32 * self.row_height;
4074 ColoredRange {
4075 start: start_y,
4076 end: end_y,
4077 color: range.color,
4078 }
4079 })
4080 .peekable();
4081
4082 let mut quads = Vec::new();
4083 while let Some(mut pixel_range) = background_pixel_ranges.next() {
4084 pixel_range.end = pixel_range
4085 .end
4086 .max(pixel_range.start + Self::MIN_MARKER_HEIGHT);
4087 while let Some(next_pixel_range) = background_pixel_ranges.peek() {
4088 if pixel_range.end >= next_pixel_range.start
4089 && pixel_range.color == next_pixel_range.color
4090 {
4091 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4092 background_pixel_ranges.next();
4093 } else {
4094 break;
4095 }
4096 }
4097
4098 let bounds = Bounds::from_corners(
4099 point(left_x, pixel_range.start),
4100 point(right_x, pixel_range.end),
4101 );
4102 quads.push(quad(
4103 bounds,
4104 Corners::default(),
4105 pixel_range.color,
4106 Edges::default(),
4107 Hsla::transparent_black(),
4108 ));
4109 }
4110
4111 quads
4112 }
4113}
4114
4115struct FoldLayout {
4116 display_range: Range<DisplayPoint>,
4117 hover_element: AnyElement,
4118}
4119
4120struct PositionMap {
4121 size: Size<Pixels>,
4122 line_height: Pixels,
4123 scroll_pixel_position: gpui::Point<Pixels>,
4124 scroll_max: gpui::Point<f32>,
4125 em_width: Pixels,
4126 em_advance: Pixels,
4127 line_layouts: Vec<LineWithInvisibles>,
4128 snapshot: EditorSnapshot,
4129}
4130
4131#[derive(Debug, Copy, Clone)]
4132pub struct PointForPosition {
4133 pub previous_valid: DisplayPoint,
4134 pub next_valid: DisplayPoint,
4135 pub exact_unclipped: DisplayPoint,
4136 pub column_overshoot_after_line_end: u32,
4137}
4138
4139impl PointForPosition {
4140 pub fn as_valid(&self) -> Option<DisplayPoint> {
4141 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4142 Some(self.previous_valid)
4143 } else {
4144 None
4145 }
4146 }
4147}
4148
4149impl PositionMap {
4150 fn point_for_position(
4151 &self,
4152 text_bounds: Bounds<Pixels>,
4153 position: gpui::Point<Pixels>,
4154 ) -> PointForPosition {
4155 let scroll_position = self.snapshot.scroll_position();
4156 let position = position - text_bounds.origin;
4157 let y = position.y.max(px(0.)).min(self.size.height);
4158 let x = position.x + (scroll_position.x * self.em_width);
4159 let row = ((y / self.line_height) + scroll_position.y) as u32;
4160
4161 let (column, x_overshoot_after_line_end) = if let Some(line) = self
4162 .line_layouts
4163 .get(row as usize - scroll_position.y as usize)
4164 .map(|LineWithInvisibles { line, .. }| line)
4165 {
4166 if let Some(ix) = line.index_for_x(x) {
4167 (ix as u32, px(0.))
4168 } else {
4169 (line.len as u32, px(0.).max(x - line.width))
4170 }
4171 } else {
4172 (0, x)
4173 };
4174
4175 let mut exact_unclipped = DisplayPoint::new(row, column);
4176 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4177 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4178
4179 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4180 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4181 PointForPosition {
4182 previous_valid,
4183 next_valid,
4184 exact_unclipped,
4185 column_overshoot_after_line_end,
4186 }
4187 }
4188}
4189
4190struct BlockLayout {
4191 row: u32,
4192 element: AnyElement,
4193 available_space: Size<AvailableSpace>,
4194 style: BlockStyle,
4195}
4196
4197fn layout_line(
4198 row: u32,
4199 snapshot: &EditorSnapshot,
4200 style: &EditorStyle,
4201 cx: &WindowContext,
4202) -> Result<ShapedLine> {
4203 let mut line = snapshot.line(row);
4204
4205 if line.len() > MAX_LINE_LEN {
4206 let mut len = MAX_LINE_LEN;
4207 while !line.is_char_boundary(len) {
4208 len -= 1;
4209 }
4210
4211 line.truncate(len);
4212 }
4213
4214 cx.text_system().shape_line(
4215 line.into(),
4216 style.text.font_size.to_pixels(cx.rem_size()),
4217 &[TextRun {
4218 len: snapshot.line_len(row) as usize,
4219 font: style.text.font(),
4220 color: Hsla::default(),
4221 background_color: None,
4222 underline: None,
4223 strikethrough: None,
4224 }],
4225 )
4226}
4227
4228pub struct CursorLayout {
4229 origin: gpui::Point<Pixels>,
4230 block_width: Pixels,
4231 line_height: Pixels,
4232 color: Hsla,
4233 shape: CursorShape,
4234 block_text: Option<ShapedLine>,
4235 cursor_name: Option<AnyElement>,
4236}
4237
4238#[derive(Debug)]
4239pub struct CursorName {
4240 string: SharedString,
4241 color: Hsla,
4242 is_top_row: bool,
4243}
4244
4245impl CursorLayout {
4246 pub fn new(
4247 origin: gpui::Point<Pixels>,
4248 block_width: Pixels,
4249 line_height: Pixels,
4250 color: Hsla,
4251 shape: CursorShape,
4252 block_text: Option<ShapedLine>,
4253 ) -> CursorLayout {
4254 CursorLayout {
4255 origin,
4256 block_width,
4257 line_height,
4258 color,
4259 shape,
4260 block_text,
4261 cursor_name: None,
4262 }
4263 }
4264
4265 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4266 Bounds {
4267 origin: self.origin + origin,
4268 size: size(self.block_width, self.line_height),
4269 }
4270 }
4271
4272 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4273 match self.shape {
4274 CursorShape::Bar => Bounds {
4275 origin: self.origin + origin,
4276 size: size(px(2.0), self.line_height),
4277 },
4278 CursorShape::Block | CursorShape::Hollow => Bounds {
4279 origin: self.origin + origin,
4280 size: size(self.block_width, self.line_height),
4281 },
4282 CursorShape::Underscore => Bounds {
4283 origin: self.origin
4284 + origin
4285 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4286 size: size(self.block_width, px(2.0)),
4287 },
4288 }
4289 }
4290
4291 pub fn layout(
4292 &mut self,
4293 origin: gpui::Point<Pixels>,
4294 cursor_name: Option<CursorName>,
4295 cx: &mut ElementContext,
4296 ) {
4297 if let Some(cursor_name) = cursor_name {
4298 let bounds = self.bounds(origin);
4299 let text_size = self.line_height / 1.5;
4300
4301 let name_origin = if cursor_name.is_top_row {
4302 point(bounds.right() - px(1.), bounds.top())
4303 } else {
4304 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4305 };
4306 let mut name_element = div()
4307 .bg(self.color)
4308 .text_size(text_size)
4309 .px_0p5()
4310 .line_height(text_size + px(2.))
4311 .text_color(cursor_name.color)
4312 .child(cursor_name.string.clone())
4313 .into_any_element();
4314
4315 name_element.layout(
4316 name_origin,
4317 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4318 cx,
4319 );
4320
4321 self.cursor_name = Some(name_element);
4322 }
4323 }
4324
4325 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
4326 let bounds = self.bounds(origin);
4327
4328 //Draw background or border quad
4329 let cursor = if matches!(self.shape, CursorShape::Hollow) {
4330 outline(bounds, self.color)
4331 } else {
4332 fill(bounds, self.color)
4333 };
4334
4335 if let Some(name) = &mut self.cursor_name {
4336 name.paint(cx);
4337 }
4338
4339 cx.paint_quad(cursor);
4340
4341 if let Some(block_text) = &self.block_text {
4342 block_text
4343 .paint(self.origin + origin, self.line_height, cx)
4344 .log_err();
4345 }
4346 }
4347
4348 pub fn shape(&self) -> CursorShape {
4349 self.shape
4350 }
4351}
4352
4353#[derive(Debug)]
4354pub struct HighlightedRange {
4355 pub start_y: Pixels,
4356 pub line_height: Pixels,
4357 pub lines: Vec<HighlightedRangeLine>,
4358 pub color: Hsla,
4359 pub corner_radius: Pixels,
4360}
4361
4362#[derive(Debug)]
4363pub struct HighlightedRangeLine {
4364 pub start_x: Pixels,
4365 pub end_x: Pixels,
4366}
4367
4368impl HighlightedRange {
4369 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
4370 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4371 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4372 self.paint_lines(
4373 self.start_y + self.line_height,
4374 &self.lines[1..],
4375 bounds,
4376 cx,
4377 );
4378 } else {
4379 self.paint_lines(self.start_y, &self.lines, bounds, cx);
4380 }
4381 }
4382
4383 fn paint_lines(
4384 &self,
4385 start_y: Pixels,
4386 lines: &[HighlightedRangeLine],
4387 _bounds: Bounds<Pixels>,
4388 cx: &mut ElementContext,
4389 ) {
4390 if lines.is_empty() {
4391 return;
4392 }
4393
4394 let first_line = lines.first().unwrap();
4395 let last_line = lines.last().unwrap();
4396
4397 let first_top_left = point(first_line.start_x, start_y);
4398 let first_top_right = point(first_line.end_x, start_y);
4399
4400 let curve_height = point(Pixels::ZERO, self.corner_radius);
4401 let curve_width = |start_x: Pixels, end_x: Pixels| {
4402 let max = (end_x - start_x) / 2.;
4403 let width = if max < self.corner_radius {
4404 max
4405 } else {
4406 self.corner_radius
4407 };
4408
4409 point(width, Pixels::ZERO)
4410 };
4411
4412 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4413 let mut path = gpui::Path::new(first_top_right - top_curve_width);
4414 path.curve_to(first_top_right + curve_height, first_top_right);
4415
4416 let mut iter = lines.iter().enumerate().peekable();
4417 while let Some((ix, line)) = iter.next() {
4418 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4419
4420 if let Some((_, next_line)) = iter.peek() {
4421 let next_top_right = point(next_line.end_x, bottom_right.y);
4422
4423 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4424 Ordering::Equal => {
4425 path.line_to(bottom_right);
4426 }
4427 Ordering::Less => {
4428 let curve_width = curve_width(next_top_right.x, bottom_right.x);
4429 path.line_to(bottom_right - curve_height);
4430 if self.corner_radius > Pixels::ZERO {
4431 path.curve_to(bottom_right - curve_width, bottom_right);
4432 }
4433 path.line_to(next_top_right + curve_width);
4434 if self.corner_radius > Pixels::ZERO {
4435 path.curve_to(next_top_right + curve_height, next_top_right);
4436 }
4437 }
4438 Ordering::Greater => {
4439 let curve_width = curve_width(bottom_right.x, next_top_right.x);
4440 path.line_to(bottom_right - curve_height);
4441 if self.corner_radius > Pixels::ZERO {
4442 path.curve_to(bottom_right + curve_width, bottom_right);
4443 }
4444 path.line_to(next_top_right - curve_width);
4445 if self.corner_radius > Pixels::ZERO {
4446 path.curve_to(next_top_right + curve_height, next_top_right);
4447 }
4448 }
4449 }
4450 } else {
4451 let curve_width = curve_width(line.start_x, line.end_x);
4452 path.line_to(bottom_right - curve_height);
4453 if self.corner_radius > Pixels::ZERO {
4454 path.curve_to(bottom_right - curve_width, bottom_right);
4455 }
4456
4457 let bottom_left = point(line.start_x, bottom_right.y);
4458 path.line_to(bottom_left + curve_width);
4459 if self.corner_radius > Pixels::ZERO {
4460 path.curve_to(bottom_left - curve_height, bottom_left);
4461 }
4462 }
4463 }
4464
4465 if first_line.start_x > last_line.start_x {
4466 let curve_width = curve_width(last_line.start_x, first_line.start_x);
4467 let second_top_left = point(last_line.start_x, start_y + self.line_height);
4468 path.line_to(second_top_left + curve_height);
4469 if self.corner_radius > Pixels::ZERO {
4470 path.curve_to(second_top_left + curve_width, second_top_left);
4471 }
4472 let first_bottom_left = point(first_line.start_x, second_top_left.y);
4473 path.line_to(first_bottom_left - curve_width);
4474 if self.corner_radius > Pixels::ZERO {
4475 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4476 }
4477 }
4478
4479 path.line_to(first_top_left + curve_height);
4480 if self.corner_radius > Pixels::ZERO {
4481 path.curve_to(first_top_left + top_curve_width, first_top_left);
4482 }
4483 path.line_to(first_top_right - top_curve_width);
4484
4485 cx.paint_path(path, self.color);
4486 }
4487}
4488
4489pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4490 (delta.pow(1.5) / 100.0).into()
4491}
4492
4493fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4494 (delta.pow(1.2) / 300.0).into()
4495}
4496
4497#[cfg(test)]
4498mod tests {
4499 use super::*;
4500 use crate::{
4501 display_map::{BlockDisposition, BlockProperties},
4502 editor_tests::{init_test, update_test_language_settings},
4503 Editor, MultiBuffer,
4504 };
4505 use gpui::TestAppContext;
4506 use language::language_settings;
4507 use log::info;
4508 use std::num::NonZeroU32;
4509 use util::test::sample_text;
4510
4511 #[gpui::test]
4512 fn test_shape_line_numbers(cx: &mut TestAppContext) {
4513 init_test(cx, |_| {});
4514 let window = cx.add_window(|cx| {
4515 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4516 Editor::new(EditorMode::Full, buffer, None, cx)
4517 });
4518
4519 let editor = window.root(cx).unwrap();
4520 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4521 let element = EditorElement::new(&editor, style);
4522 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4523
4524 let layouts = cx
4525 .update_window(*window, |_, cx| {
4526 cx.with_element_context(|cx| {
4527 element
4528 .layout_line_numbers(
4529 0..6,
4530 (0..6).map(Some),
4531 &Default::default(),
4532 Some(DisplayPoint::new(0, 0)),
4533 &snapshot,
4534 cx,
4535 )
4536 .0
4537 })
4538 })
4539 .unwrap();
4540 assert_eq!(layouts.len(), 6);
4541
4542 let relative_rows =
4543 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..6), Some(3));
4544 assert_eq!(relative_rows[&0], 3);
4545 assert_eq!(relative_rows[&1], 2);
4546 assert_eq!(relative_rows[&2], 1);
4547 // current line has no relative number
4548 assert_eq!(relative_rows[&4], 1);
4549 assert_eq!(relative_rows[&5], 2);
4550
4551 // works if cursor is before screen
4552 let relative_rows =
4553 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(3..6), Some(1));
4554 assert_eq!(relative_rows.len(), 3);
4555 assert_eq!(relative_rows[&3], 2);
4556 assert_eq!(relative_rows[&4], 3);
4557 assert_eq!(relative_rows[&5], 4);
4558
4559 // works if cursor is after screen
4560 let relative_rows =
4561 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..3), Some(6));
4562 assert_eq!(relative_rows.len(), 3);
4563 assert_eq!(relative_rows[&0], 5);
4564 assert_eq!(relative_rows[&1], 4);
4565 assert_eq!(relative_rows[&2], 3);
4566 }
4567
4568 #[gpui::test]
4569 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4570 init_test(cx, |_| {});
4571
4572 let window = cx.add_window(|cx| {
4573 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4574 Editor::new(EditorMode::Full, buffer, None, cx)
4575 });
4576 let editor = window.root(cx).unwrap();
4577 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4578 let mut element = EditorElement::new(&editor, style);
4579
4580 window
4581 .update(cx, |editor, cx| {
4582 editor.cursor_shape = CursorShape::Block;
4583 editor.change_selections(None, cx, |s| {
4584 s.select_ranges([
4585 Point::new(0, 0)..Point::new(1, 0),
4586 Point::new(3, 2)..Point::new(3, 3),
4587 Point::new(5, 6)..Point::new(6, 0),
4588 ]);
4589 });
4590 })
4591 .unwrap();
4592 let state = cx
4593 .update_window(window.into(), |_view, cx| {
4594 cx.with_element_context(|cx| {
4595 element.after_layout(
4596 Bounds {
4597 origin: point(px(500.), px(500.)),
4598 size: size(px(500.), px(500.)),
4599 },
4600 &mut (),
4601 cx,
4602 )
4603 })
4604 })
4605 .unwrap();
4606
4607 assert_eq!(state.selections.len(), 1);
4608 let local_selections = &state.selections[0].1;
4609 assert_eq!(local_selections.len(), 3);
4610 // moves cursor back one line
4611 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4612 assert_eq!(
4613 local_selections[0].range,
4614 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4615 );
4616
4617 // moves cursor back one column
4618 assert_eq!(
4619 local_selections[1].range,
4620 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4621 );
4622 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4623
4624 // leaves cursor on the max point
4625 assert_eq!(
4626 local_selections[2].range,
4627 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4628 );
4629 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4630
4631 // active lines does not include 1 (even though the range of the selection does)
4632 assert_eq!(
4633 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4634 vec![0, 3, 5, 6]
4635 );
4636
4637 // multi-buffer support
4638 // in DisplayPoint coordinates, this is what we're dealing with:
4639 // 0: [[file
4640 // 1: header]]
4641 // 2: aaaaaa
4642 // 3: bbbbbb
4643 // 4: cccccc
4644 // 5:
4645 // 6: ...
4646 // 7: ffffff
4647 // 8: gggggg
4648 // 9: hhhhhh
4649 // 10:
4650 // 11: [[file
4651 // 12: header]]
4652 // 13: bbbbbb
4653 // 14: cccccc
4654 // 15: dddddd
4655 let window = cx.add_window(|cx| {
4656 let buffer = MultiBuffer::build_multi(
4657 [
4658 (
4659 &(sample_text(8, 6, 'a') + "\n"),
4660 vec![
4661 Point::new(0, 0)..Point::new(3, 0),
4662 Point::new(4, 0)..Point::new(7, 0),
4663 ],
4664 ),
4665 (
4666 &(sample_text(8, 6, 'a') + "\n"),
4667 vec![Point::new(1, 0)..Point::new(3, 0)],
4668 ),
4669 ],
4670 cx,
4671 );
4672 Editor::new(EditorMode::Full, buffer, None, cx)
4673 });
4674 let editor = window.root(cx).unwrap();
4675 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4676 let mut element = EditorElement::new(&editor, style);
4677 let _state = window.update(cx, |editor, cx| {
4678 editor.cursor_shape = CursorShape::Block;
4679 editor.change_selections(None, cx, |s| {
4680 s.select_display_ranges([
4681 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4682 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4683 ]);
4684 });
4685 });
4686
4687 let state = cx
4688 .update_window(window.into(), |_view, cx| {
4689 cx.with_element_context(|cx| {
4690 element.after_layout(
4691 Bounds {
4692 origin: point(px(500.), px(500.)),
4693 size: size(px(500.), px(500.)),
4694 },
4695 &mut (),
4696 cx,
4697 )
4698 })
4699 })
4700 .unwrap();
4701 assert_eq!(state.selections.len(), 1);
4702 let local_selections = &state.selections[0].1;
4703 assert_eq!(local_selections.len(), 2);
4704
4705 // moves cursor on excerpt boundary back a line
4706 // and doesn't allow selection to bleed through
4707 assert_eq!(
4708 local_selections[0].range,
4709 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4710 );
4711 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4712 // moves cursor on buffer boundary back two lines
4713 // and doesn't allow selection to bleed through
4714 assert_eq!(
4715 local_selections[1].range,
4716 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4717 );
4718 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4719 }
4720
4721 #[gpui::test]
4722 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4723 init_test(cx, |_| {});
4724
4725 let window = cx.add_window(|cx| {
4726 let buffer = MultiBuffer::build_simple("", cx);
4727 Editor::new(EditorMode::Full, buffer, None, cx)
4728 });
4729 let editor = window.root(cx).unwrap();
4730 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4731 window
4732 .update(cx, |editor, cx| {
4733 editor.set_placeholder_text("hello", cx);
4734 editor.insert_blocks(
4735 [BlockProperties {
4736 style: BlockStyle::Fixed,
4737 disposition: BlockDisposition::Above,
4738 height: 3,
4739 position: Anchor::min(),
4740 render: Box::new(|_| div().into_any()),
4741 }],
4742 None,
4743 cx,
4744 );
4745
4746 // Blur the editor so that it displays placeholder text.
4747 cx.blur();
4748 })
4749 .unwrap();
4750
4751 let mut element = EditorElement::new(&editor, style);
4752 let state = cx
4753 .update_window(window.into(), |_view, cx| {
4754 cx.with_element_context(|cx| {
4755 element.after_layout(
4756 Bounds {
4757 origin: point(px(500.), px(500.)),
4758 size: size(px(500.), px(500.)),
4759 },
4760 &mut (),
4761 cx,
4762 )
4763 })
4764 })
4765 .unwrap();
4766
4767 assert_eq!(state.position_map.line_layouts.len(), 4);
4768 assert_eq!(
4769 state
4770 .line_numbers
4771 .iter()
4772 .map(Option::is_some)
4773 .collect::<Vec<_>>(),
4774 &[false, false, false, true]
4775 );
4776 }
4777
4778 #[gpui::test]
4779 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4780 const TAB_SIZE: u32 = 4;
4781
4782 let input_text = "\t \t|\t| a b";
4783 let expected_invisibles = vec![
4784 Invisible::Tab {
4785 line_start_offset: 0,
4786 },
4787 Invisible::Whitespace {
4788 line_offset: TAB_SIZE as usize,
4789 },
4790 Invisible::Tab {
4791 line_start_offset: TAB_SIZE as usize + 1,
4792 },
4793 Invisible::Tab {
4794 line_start_offset: TAB_SIZE as usize * 2 + 1,
4795 },
4796 Invisible::Whitespace {
4797 line_offset: TAB_SIZE as usize * 3 + 1,
4798 },
4799 Invisible::Whitespace {
4800 line_offset: TAB_SIZE as usize * 3 + 3,
4801 },
4802 ];
4803 assert_eq!(
4804 expected_invisibles.len(),
4805 input_text
4806 .chars()
4807 .filter(|initial_char| initial_char.is_whitespace())
4808 .count(),
4809 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4810 );
4811
4812 init_test(cx, |s| {
4813 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4814 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4815 });
4816
4817 let actual_invisibles =
4818 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4819
4820 assert_eq!(expected_invisibles, actual_invisibles);
4821 }
4822
4823 #[gpui::test]
4824 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4825 init_test(cx, |s| {
4826 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4827 s.defaults.tab_size = NonZeroU32::new(4);
4828 });
4829
4830 for editor_mode_without_invisibles in [
4831 EditorMode::SingleLine,
4832 EditorMode::AutoHeight { max_lines: 100 },
4833 ] {
4834 let invisibles = collect_invisibles_from_new_editor(
4835 cx,
4836 editor_mode_without_invisibles,
4837 "\t\t\t| | a b",
4838 px(500.0),
4839 );
4840 assert!(invisibles.is_empty(),
4841 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4842 }
4843 }
4844
4845 #[gpui::test]
4846 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4847 let tab_size = 4;
4848 let input_text = "a\tbcd ".repeat(9);
4849 let repeated_invisibles = [
4850 Invisible::Tab {
4851 line_start_offset: 1,
4852 },
4853 Invisible::Whitespace {
4854 line_offset: tab_size as usize + 3,
4855 },
4856 Invisible::Whitespace {
4857 line_offset: tab_size as usize + 4,
4858 },
4859 Invisible::Whitespace {
4860 line_offset: tab_size as usize + 5,
4861 },
4862 ];
4863 let expected_invisibles = std::iter::once(repeated_invisibles)
4864 .cycle()
4865 .take(9)
4866 .flatten()
4867 .collect::<Vec<_>>();
4868 assert_eq!(
4869 expected_invisibles.len(),
4870 input_text
4871 .chars()
4872 .filter(|initial_char| initial_char.is_whitespace())
4873 .count(),
4874 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4875 );
4876 info!("Expected invisibles: {expected_invisibles:?}");
4877
4878 init_test(cx, |_| {});
4879
4880 // Put the same string with repeating whitespace pattern into editors of various size,
4881 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4882 let resize_step = 10.0;
4883 let mut editor_width = 200.0;
4884 while editor_width <= 1000.0 {
4885 update_test_language_settings(cx, |s| {
4886 s.defaults.tab_size = NonZeroU32::new(tab_size);
4887 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4888 s.defaults.preferred_line_length = Some(editor_width as u32);
4889 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4890 });
4891
4892 let actual_invisibles = collect_invisibles_from_new_editor(
4893 cx,
4894 EditorMode::Full,
4895 &input_text,
4896 px(editor_width),
4897 );
4898
4899 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4900 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4901 let mut i = 0;
4902 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4903 i = actual_index;
4904 match expected_invisibles.get(i) {
4905 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4906 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4907 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4908 _ => {
4909 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4910 }
4911 },
4912 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4913 }
4914 }
4915 let missing_expected_invisibles = &expected_invisibles[i + 1..];
4916 assert!(
4917 missing_expected_invisibles.is_empty(),
4918 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4919 );
4920
4921 editor_width += resize_step;
4922 }
4923 }
4924
4925 fn collect_invisibles_from_new_editor(
4926 cx: &mut TestAppContext,
4927 editor_mode: EditorMode,
4928 input_text: &str,
4929 editor_width: Pixels,
4930 ) -> Vec<Invisible> {
4931 info!(
4932 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4933 editor_width.0
4934 );
4935 let window = cx.add_window(|cx| {
4936 let buffer = MultiBuffer::build_simple(&input_text, cx);
4937 Editor::new(editor_mode, buffer, None, cx)
4938 });
4939 let editor = window.root(cx).unwrap();
4940 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4941 let mut element = EditorElement::new(&editor, style);
4942 window
4943 .update(cx, |editor, cx| {
4944 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4945 editor.set_wrap_width(Some(editor_width), cx);
4946 })
4947 .unwrap();
4948 let layout_state = cx
4949 .update_window(window.into(), |_, cx| {
4950 cx.with_element_context(|cx| {
4951 element.after_layout(
4952 Bounds {
4953 origin: point(px(500.), px(500.)),
4954 size: size(px(500.), px(500.)),
4955 },
4956 &mut (),
4957 cx,
4958 )
4959 })
4960 })
4961 .unwrap();
4962
4963 layout_state
4964 .position_map
4965 .line_layouts
4966 .iter()
4967 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4968 .cloned()
4969 .collect()
4970 }
4971}
4972
4973pub fn register_action<T: Action>(
4974 view: &View<Editor>,
4975 cx: &mut WindowContext,
4976 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4977) {
4978 let view = view.clone();
4979 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4980 let action = action.downcast_ref().unwrap();
4981 if phase == DispatchPhase::Bubble {
4982 view.update(cx, |editor, cx| {
4983 listener(editor, action, cx);
4984 })
4985 }
4986 })
4987}
4988
4989fn compute_auto_height_layout(
4990 editor: &mut Editor,
4991 max_lines: usize,
4992 max_line_number_width: Pixels,
4993 known_dimensions: Size<Option<Pixels>>,
4994 cx: &mut ViewContext<Editor>,
4995) -> Option<Size<Pixels>> {
4996 let width = known_dimensions.width?;
4997 if let Some(height) = known_dimensions.height {
4998 return Some(size(width, height));
4999 }
5000
5001 let style = editor.style.as_ref().unwrap();
5002 let font_id = cx.text_system().resolve_font(&style.text.font());
5003 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5004 let line_height = style.text.line_height_in_pixels(cx.rem_size());
5005 let em_width = cx
5006 .text_system()
5007 .typographic_bounds(font_id, font_size, 'm')
5008 .unwrap()
5009 .size
5010 .width;
5011
5012 let mut snapshot = editor.snapshot(cx);
5013 let gutter_dimensions =
5014 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5015
5016 editor.gutter_width = gutter_dimensions.width;
5017 let text_width = width - gutter_dimensions.width;
5018 let overscroll = size(em_width, px(0.));
5019
5020 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5021 if editor.set_wrap_width(Some(editor_width), cx) {
5022 snapshot = editor.snapshot(cx);
5023 }
5024
5025 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5026 let height = scroll_height
5027 .max(line_height)
5028 .min(line_height * max_lines as f32);
5029
5030 Some(size(width, height))
5031}