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 let line_layout = &line_layouts[(row - start_row) as usize];
1137 let line_width = line_layout.line.width;
1138
1139 // TODO: define the padding as a constant
1140 content_origin.x + line_width + (em_width * 6.)
1141 };
1142
1143 let absolute_offset = point(start_x, start_y);
1144 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1145
1146 element.layout(absolute_offset, available_space, cx);
1147
1148 Some(element)
1149 }
1150
1151 #[allow(clippy::too_many_arguments)]
1152 fn layout_blame_entries(
1153 &self,
1154 buffer_rows: impl Iterator<Item = Option<u32>>,
1155 em_width: Pixels,
1156 scroll_position: gpui::Point<f32>,
1157 line_height: Pixels,
1158 gutter_hitbox: &Hitbox,
1159 max_width: Option<Pixels>,
1160 cx: &mut ElementContext,
1161 ) -> Option<Vec<AnyElement>> {
1162 if !self
1163 .editor
1164 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1165 {
1166 return None;
1167 }
1168
1169 let blame = self.editor.read(cx).blame.clone()?;
1170 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1171 blame.blame_for_rows(buffer_rows, cx).collect()
1172 });
1173
1174 let width = if let Some(max_width) = max_width {
1175 AvailableSpace::Definite(max_width)
1176 } else {
1177 AvailableSpace::MaxContent
1178 };
1179 let scroll_top = scroll_position.y * line_height;
1180 let start_x = em_width * 1;
1181
1182 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1183
1184 let shaped_lines = blamed_rows
1185 .into_iter()
1186 .enumerate()
1187 .flat_map(|(ix, blame_entry)| {
1188 if let Some(blame_entry) = blame_entry {
1189 let mut element = render_blame_entry(
1190 ix,
1191 &blame,
1192 blame_entry,
1193 &self.style,
1194 &mut last_used_color,
1195 self.editor.clone(),
1196 cx,
1197 );
1198
1199 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1200 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1201
1202 element.layout(absolute_offset, size(width, AvailableSpace::MinContent), cx);
1203
1204 Some(element)
1205 } else {
1206 None
1207 }
1208 })
1209 .collect();
1210
1211 Some(shaped_lines)
1212 }
1213
1214 fn layout_code_actions_indicator(
1215 &self,
1216 line_height: Pixels,
1217 newest_selection_head: DisplayPoint,
1218 scroll_pixel_position: gpui::Point<Pixels>,
1219 gutter_dimensions: &GutterDimensions,
1220 gutter_hitbox: &Hitbox,
1221 cx: &mut ElementContext,
1222 ) -> Option<AnyElement> {
1223 let mut active = false;
1224 let mut button = None;
1225 self.editor.update(cx, |editor, cx| {
1226 active = matches!(
1227 editor.context_menu.read().as_ref(),
1228 Some(crate::ContextMenu::CodeActions(_))
1229 );
1230 button = editor.render_code_actions_indicator(&self.style, active, cx);
1231 });
1232
1233 let mut button = button?.into_any_element();
1234 let available_space = size(
1235 AvailableSpace::MinContent,
1236 AvailableSpace::Definite(line_height),
1237 );
1238 let indicator_size = button.measure(available_space, cx);
1239
1240 let blame_width = gutter_dimensions
1241 .git_blame_entries_width
1242 .unwrap_or(Pixels::ZERO);
1243
1244 let mut x = blame_width;
1245 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
1246 - indicator_size.width
1247 - blame_width;
1248 x += available_width / 2.;
1249
1250 let mut y = newest_selection_head.row() as f32 * line_height - scroll_pixel_position.y;
1251 y += (line_height - indicator_size.height) / 2.;
1252
1253 button.layout(gutter_hitbox.origin + point(x, y), available_space, cx);
1254 Some(button)
1255 }
1256
1257 fn calculate_relative_line_numbers(
1258 &self,
1259 buffer_rows: Vec<Option<u32>>,
1260 rows: &Range<u32>,
1261 relative_to: Option<u32>,
1262 ) -> HashMap<u32, u32> {
1263 let mut relative_rows: HashMap<u32, u32> = Default::default();
1264 let Some(relative_to) = relative_to else {
1265 return relative_rows;
1266 };
1267
1268 let start = rows.start.min(relative_to);
1269
1270 let head_idx = relative_to - start;
1271 let mut delta = 1;
1272 let mut i = head_idx + 1;
1273 while i < buffer_rows.len() as u32 {
1274 if buffer_rows[i as usize].is_some() {
1275 if rows.contains(&(i + start)) {
1276 relative_rows.insert(i + start, delta);
1277 }
1278 delta += 1;
1279 }
1280 i += 1;
1281 }
1282 delta = 1;
1283 i = head_idx.min(buffer_rows.len() as u32 - 1);
1284 while i > 0 && buffer_rows[i as usize].is_none() {
1285 i -= 1;
1286 }
1287
1288 while i > 0 {
1289 i -= 1;
1290 if buffer_rows[i as usize].is_some() {
1291 if rows.contains(&(i + start)) {
1292 relative_rows.insert(i + start, delta);
1293 }
1294 delta += 1;
1295 }
1296 }
1297
1298 relative_rows
1299 }
1300
1301 fn layout_line_numbers(
1302 &self,
1303 rows: Range<u32>,
1304 buffer_rows: impl Iterator<Item = Option<u32>>,
1305 active_rows: &BTreeMap<u32, bool>,
1306 newest_selection_head: Option<DisplayPoint>,
1307 snapshot: &EditorSnapshot,
1308 cx: &ElementContext,
1309 ) -> (
1310 Vec<Option<ShapedLine>>,
1311 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1312 ) {
1313 let editor = self.editor.read(cx);
1314 let is_singleton = editor.is_singleton(cx);
1315 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1316 let newest = editor.selections.newest::<Point>(cx);
1317 SelectionLayout::new(
1318 newest,
1319 editor.selections.line_mode,
1320 editor.cursor_shape,
1321 &snapshot.display_snapshot,
1322 true,
1323 true,
1324 None,
1325 )
1326 .head
1327 });
1328 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1329 let include_line_numbers =
1330 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1331 let include_fold_statuses =
1332 EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1333 let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1334 let mut fold_statuses = Vec::with_capacity(rows.len());
1335 let mut line_number = String::new();
1336 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1337 let relative_to = if is_relative {
1338 Some(newest_selection_head.row())
1339 } else {
1340 None
1341 };
1342
1343 let buffer_rows = buffer_rows.collect::<Vec<_>>();
1344 let relative_rows =
1345 self.calculate_relative_line_numbers(buffer_rows.clone(), &rows, relative_to);
1346
1347 for (ix, row) in buffer_rows.into_iter().enumerate() {
1348 let display_row = rows.start + ix as u32;
1349 let (active, color) = if active_rows.contains_key(&display_row) {
1350 (true, cx.theme().colors().editor_active_line_number)
1351 } else {
1352 (false, cx.theme().colors().editor_line_number)
1353 };
1354 if let Some(buffer_row) = row {
1355 if include_line_numbers {
1356 line_number.clear();
1357 let default_number = buffer_row + 1;
1358 let number = relative_rows
1359 .get(&(ix as u32 + rows.start))
1360 .unwrap_or(&default_number);
1361 write!(&mut line_number, "{}", number).unwrap();
1362 let run = TextRun {
1363 len: line_number.len(),
1364 font: self.style.text.font(),
1365 color,
1366 background_color: None,
1367 underline: None,
1368 strikethrough: None,
1369 };
1370 let shaped_line = cx
1371 .text_system()
1372 .shape_line(line_number.clone().into(), font_size, &[run])
1373 .unwrap();
1374 shaped_line_numbers.push(Some(shaped_line));
1375 }
1376 if include_fold_statuses {
1377 fold_statuses.push(
1378 is_singleton
1379 .then(|| {
1380 snapshot
1381 .fold_for_line(buffer_row)
1382 .map(|fold_status| (fold_status, buffer_row, active))
1383 })
1384 .flatten(),
1385 )
1386 }
1387 } else {
1388 fold_statuses.push(None);
1389 shaped_line_numbers.push(None);
1390 }
1391 }
1392
1393 (shaped_line_numbers, fold_statuses)
1394 }
1395
1396 fn layout_lines(
1397 &self,
1398 rows: Range<u32>,
1399 line_number_layouts: &[Option<ShapedLine>],
1400 snapshot: &EditorSnapshot,
1401 cx: &ElementContext,
1402 ) -> Vec<LineWithInvisibles> {
1403 if rows.start >= rows.end {
1404 return Vec::new();
1405 }
1406
1407 // Show the placeholder when the editor is empty
1408 if snapshot.is_empty() {
1409 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1410 let placeholder_color = cx.theme().colors().text_placeholder;
1411 let placeholder_text = snapshot.placeholder_text();
1412
1413 let placeholder_lines = placeholder_text
1414 .as_ref()
1415 .map_or("", AsRef::as_ref)
1416 .split('\n')
1417 .skip(rows.start as usize)
1418 .chain(iter::repeat(""))
1419 .take(rows.len());
1420 placeholder_lines
1421 .filter_map(move |line| {
1422 let run = TextRun {
1423 len: line.len(),
1424 font: self.style.text.font(),
1425 color: placeholder_color,
1426 background_color: None,
1427 underline: Default::default(),
1428 strikethrough: None,
1429 };
1430 cx.text_system()
1431 .shape_line(line.to_string().into(), font_size, &[run])
1432 .log_err()
1433 })
1434 .map(|line| LineWithInvisibles {
1435 line,
1436 invisibles: Vec::new(),
1437 })
1438 .collect()
1439 } else {
1440 let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1441 LineWithInvisibles::from_chunks(
1442 chunks,
1443 &self.style.text,
1444 MAX_LINE_LEN,
1445 rows.len(),
1446 line_number_layouts,
1447 snapshot.mode,
1448 cx,
1449 )
1450 }
1451 }
1452
1453 #[allow(clippy::too_many_arguments)]
1454 fn build_blocks(
1455 &self,
1456 rows: Range<u32>,
1457 snapshot: &EditorSnapshot,
1458 hitbox: &Hitbox,
1459 text_hitbox: &Hitbox,
1460 scroll_width: &mut Pixels,
1461 gutter_dimensions: &GutterDimensions,
1462 em_width: Pixels,
1463 text_x: Pixels,
1464 line_height: Pixels,
1465 line_layouts: &[LineWithInvisibles],
1466 cx: &mut ElementContext,
1467 ) -> Vec<BlockLayout> {
1468 let mut block_id = 0;
1469 let (fixed_blocks, non_fixed_blocks) = snapshot
1470 .blocks_in_range(rows.clone())
1471 .partition::<Vec<_>, _>(|(_, block)| match block {
1472 TransformBlock::ExcerptHeader { .. } => false,
1473 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1474 });
1475
1476 let render_block = |block: &TransformBlock,
1477 available_space: Size<AvailableSpace>,
1478 block_id: usize,
1479 block_row_start: u32,
1480 cx: &mut ElementContext| {
1481 let mut element = match block {
1482 TransformBlock::Custom(block) => {
1483 let align_to = block
1484 .position()
1485 .to_point(&snapshot.buffer_snapshot)
1486 .to_display_point(snapshot);
1487 let anchor_x = text_x
1488 + if rows.contains(&align_to.row()) {
1489 line_layouts[(align_to.row() - rows.start) as usize]
1490 .line
1491 .x_for_index(align_to.column() as usize)
1492 } else {
1493 layout_line(align_to.row(), snapshot, &self.style, cx)
1494 .unwrap()
1495 .x_for_index(align_to.column() as usize)
1496 };
1497
1498 block.render(&mut BlockContext {
1499 context: cx,
1500 anchor_x,
1501 gutter_dimensions,
1502 line_height,
1503 em_width,
1504 block_id,
1505 max_width: text_hitbox.size.width.max(*scroll_width),
1506 editor_style: &self.style,
1507 })
1508 }
1509
1510 TransformBlock::ExcerptHeader {
1511 buffer,
1512 range,
1513 starts_new_buffer,
1514 height,
1515 ..
1516 } => {
1517 let include_root = self
1518 .editor
1519 .read(cx)
1520 .project
1521 .as_ref()
1522 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1523 .unwrap_or_default();
1524
1525 #[derive(Clone)]
1526 struct JumpData {
1527 position: Point,
1528 anchor: text::Anchor,
1529 path: ProjectPath,
1530 line_offset_from_top: u32,
1531 }
1532
1533 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1534 let jump_path = ProjectPath {
1535 worktree_id: file.worktree_id(cx),
1536 path: file.path.clone(),
1537 };
1538 let jump_anchor = range
1539 .primary
1540 .as_ref()
1541 .map_or(range.context.start, |primary| primary.start);
1542
1543 let excerpt_start = range.context.start;
1544 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1545 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
1546 0
1547 } else {
1548 let excerpt_start_row =
1549 language::ToPoint::to_point(&jump_anchor, buffer).row;
1550 jump_position.row - excerpt_start_row
1551 };
1552
1553 let line_offset_from_top =
1554 block_row_start + *height as u32 + offset_from_excerpt_start
1555 - snapshot
1556 .scroll_anchor
1557 .scroll_position(&snapshot.display_snapshot)
1558 .y as u32;
1559
1560 JumpData {
1561 position: jump_position,
1562 anchor: jump_anchor,
1563 path: jump_path,
1564 line_offset_from_top,
1565 }
1566 });
1567
1568 let element = if *starts_new_buffer {
1569 let path = buffer.resolve_file_path(cx, include_root);
1570 let mut filename = None;
1571 let mut parent_path = None;
1572 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1573 if let Some(path) = path {
1574 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1575 parent_path = path
1576 .parent()
1577 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1578 }
1579
1580 v_flex()
1581 .id(("path header container", block_id))
1582 .size_full()
1583 .justify_center()
1584 .p(gpui::px(6.))
1585 .child(
1586 h_flex()
1587 .id("path header block")
1588 .size_full()
1589 .pl(gpui::px(12.))
1590 .pr(gpui::px(8.))
1591 .rounded_md()
1592 .shadow_md()
1593 .border()
1594 .border_color(cx.theme().colors().border)
1595 .bg(cx.theme().colors().editor_subheader_background)
1596 .justify_between()
1597 .hover(|style| style.bg(cx.theme().colors().element_hover))
1598 .child(
1599 h_flex().gap_3().child(
1600 h_flex()
1601 .gap_2()
1602 .child(
1603 filename
1604 .map(SharedString::from)
1605 .unwrap_or_else(|| "untitled".into()),
1606 )
1607 .when_some(parent_path, |then, path| {
1608 then.child(
1609 div().child(path).text_color(
1610 cx.theme().colors().text_muted,
1611 ),
1612 )
1613 }),
1614 ),
1615 )
1616 .when_some(jump_data.clone(), |this, jump_data| {
1617 this.cursor_pointer()
1618 .tooltip(|cx| {
1619 Tooltip::for_action(
1620 "Jump to File",
1621 &OpenExcerpts,
1622 cx,
1623 )
1624 })
1625 .on_mouse_down(MouseButton::Left, |_, cx| {
1626 cx.stop_propagation()
1627 })
1628 .on_click(cx.listener_for(&self.editor, {
1629 move |editor, _, cx| {
1630 editor.jump(
1631 jump_data.path.clone(),
1632 jump_data.position,
1633 jump_data.anchor,
1634 jump_data.line_offset_from_top,
1635 cx,
1636 );
1637 }
1638 }))
1639 }),
1640 )
1641 } else {
1642 v_flex()
1643 .id(("collapsed context", block_id))
1644 .size_full()
1645 .child(
1646 div()
1647 .flex()
1648 .v_flex()
1649 .justify_start()
1650 .id("jump to collapsed context")
1651 .w(relative(1.0))
1652 .h_full()
1653 .child(
1654 div()
1655 .h_px()
1656 .w_full()
1657 .bg(cx.theme().colors().border_variant)
1658 .group_hover("excerpt-jump-action", |style| {
1659 style.bg(cx.theme().colors().border)
1660 }),
1661 ),
1662 )
1663 .child(
1664 h_flex()
1665 .justify_end()
1666 .flex_none()
1667 .w(
1668 gutter_dimensions.width - (gutter_dimensions.left_padding), // + gutter_dimensions.right_padding)
1669 )
1670 .h_full()
1671 .child(
1672 ButtonLike::new("jump-icon")
1673 .style(ButtonStyle::Transparent)
1674 .child(
1675 svg()
1676 .path(IconName::ArrowUpRight.path())
1677 .size(IconSize::XSmall.rems())
1678 .text_color(cx.theme().colors().border)
1679 .group_hover("excerpt-jump-action", |style| {
1680 style.text_color(
1681 cx.theme().colors().editor_line_number,
1682 )
1683 }),
1684 )
1685 .when_some(jump_data.clone(), |this, jump_data| {
1686 this.on_click(cx.listener_for(&self.editor, {
1687 let path = jump_data.path.clone();
1688 move |editor, _, cx| {
1689 editor.jump(
1690 path.clone(),
1691 jump_data.position,
1692 jump_data.anchor,
1693 jump_data.line_offset_from_top,
1694 cx,
1695 );
1696 }
1697 }))
1698 .tooltip({
1699 move |cx| {
1700 Tooltip::for_action(
1701 format!(
1702 "Jump to {}:L{}",
1703 jump_data.path.path.display(),
1704 jump_data.position.row + 1
1705 ),
1706 &OpenExcerpts,
1707 cx,
1708 )
1709 }
1710 })
1711 }),
1712 ),
1713 )
1714 .group("excerpt-jump-action")
1715 .cursor_pointer()
1716 .when_some(jump_data.clone(), |this, jump_data| {
1717 this.on_click(cx.listener_for(&self.editor, {
1718 let path = jump_data.path.clone();
1719 move |editor, _, cx| {
1720 cx.stop_propagation();
1721
1722 editor.jump(
1723 path.clone(),
1724 jump_data.position,
1725 jump_data.anchor,
1726 jump_data.line_offset_from_top,
1727 cx,
1728 );
1729 }
1730 }))
1731 .tooltip(move |cx| {
1732 Tooltip::for_action(
1733 format!(
1734 "Jump to {}:L{}",
1735 jump_data.path.path.display(),
1736 jump_data.position.row + 1
1737 ),
1738 &OpenExcerpts,
1739 cx,
1740 )
1741 })
1742 })
1743 };
1744 element.into_any()
1745 }
1746 };
1747
1748 let size = element.measure(available_space, cx);
1749 (element, size)
1750 };
1751
1752 let mut fixed_block_max_width = Pixels::ZERO;
1753 let mut blocks = Vec::new();
1754 for (row, block) in fixed_blocks {
1755 let available_space = size(
1756 AvailableSpace::MinContent,
1757 AvailableSpace::Definite(block.height() as f32 * line_height),
1758 );
1759 let (element, element_size) = render_block(block, available_space, block_id, row, cx);
1760 block_id += 1;
1761 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1762 blocks.push(BlockLayout {
1763 row,
1764 element,
1765 available_space,
1766 style: BlockStyle::Fixed,
1767 });
1768 }
1769 for (row, block) in non_fixed_blocks {
1770 let style = match block {
1771 TransformBlock::Custom(block) => block.style(),
1772 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1773 };
1774 let width = match style {
1775 BlockStyle::Sticky => hitbox.size.width,
1776 BlockStyle::Flex => hitbox
1777 .size
1778 .width
1779 .max(fixed_block_max_width)
1780 .max(gutter_dimensions.width + *scroll_width),
1781 BlockStyle::Fixed => unreachable!(),
1782 };
1783 let available_space = size(
1784 AvailableSpace::Definite(width),
1785 AvailableSpace::Definite(block.height() as f32 * line_height),
1786 );
1787 let (element, _) = render_block(block, available_space, block_id, row, cx);
1788 block_id += 1;
1789 blocks.push(BlockLayout {
1790 row,
1791 element,
1792 available_space,
1793 style,
1794 });
1795 }
1796
1797 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1798 blocks
1799 }
1800
1801 fn layout_blocks(
1802 &self,
1803 blocks: &mut Vec<BlockLayout>,
1804 hitbox: &Hitbox,
1805 line_height: Pixels,
1806 scroll_pixel_position: gpui::Point<Pixels>,
1807 cx: &mut ElementContext,
1808 ) {
1809 for block in blocks {
1810 let mut origin = hitbox.origin
1811 + point(
1812 Pixels::ZERO,
1813 block.row as f32 * line_height - scroll_pixel_position.y,
1814 );
1815 if !matches!(block.style, BlockStyle::Sticky) {
1816 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1817 }
1818 block.element.layout(origin, block.available_space, cx);
1819 }
1820 }
1821
1822 #[allow(clippy::too_many_arguments)]
1823 fn layout_context_menu(
1824 &self,
1825 line_height: Pixels,
1826 hitbox: &Hitbox,
1827 text_hitbox: &Hitbox,
1828 content_origin: gpui::Point<Pixels>,
1829 start_row: u32,
1830 scroll_pixel_position: gpui::Point<Pixels>,
1831 line_layouts: &[LineWithInvisibles],
1832 newest_selection_head: DisplayPoint,
1833 cx: &mut ElementContext,
1834 ) -> bool {
1835 let max_height = cmp::min(
1836 12. * line_height,
1837 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1838 );
1839 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1840 if editor.context_menu_visible() {
1841 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1842 } else {
1843 None
1844 }
1845 }) else {
1846 return false;
1847 };
1848
1849 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1850 let context_menu_size = context_menu.measure(available_space, cx);
1851
1852 let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1853 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1854 let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1855 let mut list_origin = content_origin + point(x, y);
1856 let list_width = context_menu_size.width;
1857 let list_height = context_menu_size.height;
1858
1859 // Snap the right edge of the list to the right edge of the window if
1860 // its horizontal bounds overflow.
1861 if list_origin.x + list_width > cx.viewport_size().width {
1862 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1863 }
1864
1865 if list_origin.y + list_height > text_hitbox.lower_right().y {
1866 list_origin.y -= line_height + list_height;
1867 }
1868
1869 cx.defer_draw(context_menu, list_origin, 1);
1870 true
1871 }
1872
1873 fn layout_mouse_context_menu(&self, cx: &mut ElementContext) -> Option<AnyElement> {
1874 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1875 let mut element = deferred(
1876 anchored()
1877 .position(mouse_context_menu.position)
1878 .child(mouse_context_menu.context_menu.clone())
1879 .anchor(AnchorCorner::TopLeft)
1880 .snap_to_window(),
1881 )
1882 .with_priority(1)
1883 .into_any();
1884
1885 element.layout(gpui::Point::default(), AvailableSpace::min_size(), cx);
1886 Some(element)
1887 }
1888
1889 #[allow(clippy::too_many_arguments)]
1890 fn layout_hover_popovers(
1891 &self,
1892 snapshot: &EditorSnapshot,
1893 hitbox: &Hitbox,
1894 text_hitbox: &Hitbox,
1895 visible_display_row_range: Range<u32>,
1896 content_origin: gpui::Point<Pixels>,
1897 scroll_pixel_position: gpui::Point<Pixels>,
1898 line_layouts: &[LineWithInvisibles],
1899 line_height: Pixels,
1900 em_width: Pixels,
1901 cx: &mut ElementContext,
1902 ) {
1903 struct MeasuredHoverPopover {
1904 element: AnyElement,
1905 size: Size<Pixels>,
1906 horizontal_offset: Pixels,
1907 }
1908
1909 let max_size = size(
1910 (120. * em_width) // Default size
1911 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
1912 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1913 (16. * line_height) // Default size
1914 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
1915 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1916 );
1917
1918 let hover_popovers = self.editor.update(cx, |editor, cx| {
1919 editor.hover_state.render(
1920 &snapshot,
1921 &self.style,
1922 visible_display_row_range.clone(),
1923 max_size,
1924 editor.workspace.as_ref().map(|(w, _)| w.clone()),
1925 cx,
1926 )
1927 });
1928 let Some((position, hover_popovers)) = hover_popovers else {
1929 return;
1930 };
1931
1932 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1933
1934 // This is safe because we check on layout whether the required row is available
1935 let hovered_row_layout =
1936 &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
1937
1938 // Compute Hovered Point
1939 let x =
1940 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1941 let y = position.row() as f32 * line_height - scroll_pixel_position.y;
1942 let hovered_point = content_origin + point(x, y);
1943
1944 let mut overall_height = Pixels::ZERO;
1945 let mut measured_hover_popovers = Vec::new();
1946 for mut hover_popover in hover_popovers {
1947 let size = hover_popover.measure(available_space, cx);
1948 let horizontal_offset =
1949 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
1950
1951 overall_height += HOVER_POPOVER_GAP + size.height;
1952
1953 measured_hover_popovers.push(MeasuredHoverPopover {
1954 element: hover_popover,
1955 size,
1956 horizontal_offset,
1957 });
1958 }
1959 overall_height += HOVER_POPOVER_GAP;
1960
1961 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
1962 let mut occlusion = div()
1963 .size_full()
1964 .occlude()
1965 .on_mouse_move(|_, cx| cx.stop_propagation())
1966 .into_any_element();
1967 occlusion.measure(size(width, HOVER_POPOVER_GAP).into(), cx);
1968 cx.defer_draw(occlusion, origin, 2);
1969 }
1970
1971 if hovered_point.y > overall_height {
1972 // There is enough space above. Render popovers above the hovered point
1973 let mut current_y = hovered_point.y;
1974 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1975 let size = popover.size;
1976 let popover_origin = point(
1977 hovered_point.x + popover.horizontal_offset,
1978 current_y - size.height,
1979 );
1980
1981 cx.defer_draw(popover.element, popover_origin, 2);
1982 if position != itertools::Position::Last {
1983 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
1984 draw_occluder(size.width, origin, cx);
1985 }
1986
1987 current_y = popover_origin.y - HOVER_POPOVER_GAP;
1988 }
1989 } else {
1990 // There is not enough space above. Render popovers below the hovered point
1991 let mut current_y = hovered_point.y + line_height;
1992 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1993 let size = popover.size;
1994 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
1995
1996 cx.defer_draw(popover.element, popover_origin, 2);
1997 if position != itertools::Position::Last {
1998 let origin = point(popover_origin.x, popover_origin.y + size.height);
1999 draw_occluder(size.width, origin, cx);
2000 }
2001
2002 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2003 }
2004 }
2005 }
2006
2007 fn paint_background(&self, layout: &EditorLayout, cx: &mut ElementContext) {
2008 cx.paint_layer(layout.hitbox.bounds, |cx| {
2009 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2010 let gutter_bg = cx.theme().colors().editor_gutter_background;
2011 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2012 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2013
2014 if let EditorMode::Full = layout.mode {
2015 let mut active_rows = layout.active_rows.iter().peekable();
2016 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2017 let mut end_row = *start_row;
2018 while active_rows.peek().map_or(false, |r| {
2019 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
2020 }) {
2021 active_rows.next().unwrap();
2022 end_row += 1;
2023 }
2024
2025 if !contains_non_empty_selection {
2026 let origin = point(
2027 layout.hitbox.origin.x,
2028 layout.hitbox.origin.y
2029 + (*start_row as f32 - scroll_top)
2030 * layout.position_map.line_height,
2031 );
2032 let size = size(
2033 layout.hitbox.size.width,
2034 layout.position_map.line_height * (end_row - start_row + 1) as f32,
2035 );
2036 let active_line_bg = cx.theme().colors().editor_active_line_background;
2037 cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
2038 }
2039 }
2040
2041 let mut paint_highlight =
2042 |highlight_row_start: u32, highlight_row_end: u32, color| {
2043 let origin = point(
2044 layout.hitbox.origin.x,
2045 layout.hitbox.origin.y
2046 + (highlight_row_start as f32 - scroll_top)
2047 * layout.position_map.line_height,
2048 );
2049 let size = size(
2050 layout.hitbox.size.width,
2051 layout.position_map.line_height
2052 * (highlight_row_end + 1 - highlight_row_start) as f32,
2053 );
2054 cx.paint_quad(fill(Bounds { origin, size }, color));
2055 };
2056
2057 let mut last_row = None;
2058 let mut highlight_row_start = 0u32;
2059 let mut highlight_row_end = 0u32;
2060 for (&row, &color) in &layout.highlighted_rows {
2061 let paint = last_row.map_or(false, |(last_row, last_color)| {
2062 last_color != color || last_row + 1 < row
2063 });
2064
2065 if paint {
2066 let paint_range_is_unfinished = highlight_row_end == 0;
2067 if paint_range_is_unfinished {
2068 highlight_row_end = row;
2069 last_row = None;
2070 }
2071 paint_highlight(highlight_row_start, highlight_row_end, color);
2072 highlight_row_start = 0;
2073 highlight_row_end = 0;
2074 if !paint_range_is_unfinished {
2075 highlight_row_start = row;
2076 last_row = Some((row, color));
2077 }
2078 } else {
2079 if last_row.is_none() {
2080 highlight_row_start = row;
2081 } else {
2082 highlight_row_end = row;
2083 }
2084 last_row = Some((row, color));
2085 }
2086 }
2087 if let Some((row, hsla)) = last_row {
2088 highlight_row_end = row;
2089 paint_highlight(highlight_row_start, highlight_row_end, hsla);
2090 }
2091
2092 let scroll_left =
2093 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2094
2095 for (wrap_position, active) in layout.wrap_guides.iter() {
2096 let x = (layout.text_hitbox.origin.x
2097 + *wrap_position
2098 + layout.position_map.em_width / 2.)
2099 - scroll_left;
2100
2101 let show_scrollbars = layout
2102 .scrollbar_layout
2103 .as_ref()
2104 .map_or(false, |scrollbar| scrollbar.visible);
2105 if x < layout.text_hitbox.origin.x
2106 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2107 {
2108 continue;
2109 }
2110
2111 let color = if *active {
2112 cx.theme().colors().editor_active_wrap_guide
2113 } else {
2114 cx.theme().colors().editor_wrap_guide
2115 };
2116 cx.paint_quad(fill(
2117 Bounds {
2118 origin: point(x, layout.text_hitbox.origin.y),
2119 size: size(px(1.), layout.text_hitbox.size.height),
2120 },
2121 color,
2122 ));
2123 }
2124 }
2125 })
2126 }
2127
2128 fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2129 let line_height = layout.position_map.line_height;
2130
2131 let scroll_position = layout.position_map.snapshot.scroll_position();
2132 let scroll_top = scroll_position.y * line_height;
2133
2134 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2135
2136 let show_git_gutter = matches!(
2137 ProjectSettings::get_global(cx).git.git_gutter,
2138 Some(GitGutterSetting::TrackedFiles)
2139 );
2140
2141 if show_git_gutter {
2142 Self::paint_diff_hunks(layout, cx);
2143 }
2144
2145 if layout.blamed_display_rows.is_some() {
2146 self.paint_blamed_display_rows(layout, cx);
2147 }
2148
2149 for (ix, line) in layout.line_numbers.iter().enumerate() {
2150 if let Some(line) = line {
2151 let line_origin = layout.gutter_hitbox.origin
2152 + point(
2153 layout.gutter_hitbox.size.width
2154 - line.width
2155 - layout.gutter_dimensions.right_padding,
2156 ix as f32 * line_height - (scroll_top % line_height),
2157 );
2158
2159 line.paint(line_origin, line_height, cx).log_err();
2160 }
2161 }
2162
2163 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2164 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2165 for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2166 fold_indicator.paint(cx);
2167 }
2168 });
2169
2170 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2171 indicator.paint(cx);
2172 }
2173 })
2174 }
2175
2176 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut ElementContext) {
2177 if layout.display_hunks.is_empty() {
2178 return;
2179 }
2180
2181 let line_height = layout.position_map.line_height;
2182
2183 let scroll_position = layout.position_map.snapshot.scroll_position();
2184 let scroll_top = scroll_position.y * line_height;
2185
2186 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2187 for hunk in &layout.display_hunks {
2188 let (display_row_range, status) = match hunk {
2189 //TODO: This rendering is entirely a horrible hack
2190 &DisplayDiffHunk::Folded { display_row: row } => {
2191 let start_y = row as f32 * line_height - scroll_top;
2192 let end_y = start_y + line_height;
2193
2194 let width = 0.275 * line_height;
2195 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2196 let highlight_size = size(width * 2., end_y - start_y);
2197 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2198 cx.paint_quad(quad(
2199 highlight_bounds,
2200 Corners::all(1. * line_height),
2201 cx.theme().status().modified,
2202 Edges::default(),
2203 transparent_black(),
2204 ));
2205
2206 continue;
2207 }
2208
2209 DisplayDiffHunk::Unfolded {
2210 display_row_range,
2211 status,
2212 } => (display_row_range, status),
2213 };
2214
2215 let color = match status {
2216 DiffHunkStatus::Added => cx.theme().status().created,
2217 DiffHunkStatus::Modified => cx.theme().status().modified,
2218
2219 //TODO: This rendering is entirely a horrible hack
2220 DiffHunkStatus::Removed => {
2221 let row = display_row_range.start;
2222
2223 let offset = line_height / 2.;
2224 let start_y = row as f32 * line_height - offset - scroll_top;
2225 let end_y = start_y + line_height;
2226
2227 let width = 0.275 * line_height;
2228 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2229 let highlight_size = size(width * 2., end_y - start_y);
2230 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2231 cx.paint_quad(quad(
2232 highlight_bounds,
2233 Corners::all(1. * line_height),
2234 cx.theme().status().deleted,
2235 Edges::default(),
2236 transparent_black(),
2237 ));
2238
2239 continue;
2240 }
2241 };
2242
2243 let start_row = display_row_range.start;
2244 let end_row = display_row_range.end;
2245 // If we're in a multibuffer, row range span might include an
2246 // excerpt header, so if we were to draw the marker straight away,
2247 // the hunk might include the rows of that header.
2248 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2249 // Instead, we simply check whether the range we're dealing with includes
2250 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2251 let end_row_in_current_excerpt = layout
2252 .position_map
2253 .snapshot
2254 .blocks_in_range(start_row..end_row)
2255 .find_map(|(start_row, block)| {
2256 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2257 Some(start_row)
2258 } else {
2259 None
2260 }
2261 })
2262 .unwrap_or(end_row);
2263
2264 let start_y = start_row as f32 * line_height - scroll_top;
2265 let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2266
2267 let width = 0.275 * line_height;
2268 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2269 let highlight_size = size(width * 2., end_y - start_y);
2270 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2271 cx.paint_quad(quad(
2272 highlight_bounds,
2273 Corners::all(0.05 * line_height),
2274 color,
2275 Edges::default(),
2276 transparent_black(),
2277 ));
2278 }
2279 })
2280 }
2281
2282 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2283 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2284 return;
2285 };
2286
2287 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2288 for mut blame_element in blamed_display_rows.into_iter() {
2289 blame_element.paint(cx);
2290 }
2291 })
2292 }
2293
2294 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2295 cx.with_content_mask(
2296 Some(ContentMask {
2297 bounds: layout.text_hitbox.bounds,
2298 }),
2299 |cx| {
2300 let cursor_style = if self
2301 .editor
2302 .read(cx)
2303 .hovered_link_state
2304 .as_ref()
2305 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2306 {
2307 CursorStyle::PointingHand
2308 } else {
2309 CursorStyle::IBeam
2310 };
2311 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2312
2313 cx.with_element_id(Some("folds"), |cx| self.paint_folds(layout, cx));
2314 let invisible_display_ranges = self.paint_highlights(layout, cx);
2315 self.paint_lines(&invisible_display_ranges, layout, cx);
2316 self.paint_redactions(layout, cx);
2317 self.paint_cursors(layout, cx);
2318 self.paint_inline_blame(layout, cx);
2319 },
2320 )
2321 }
2322
2323 fn paint_highlights(
2324 &mut self,
2325 layout: &mut EditorLayout,
2326 cx: &mut ElementContext,
2327 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2328 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2329 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2330 let line_end_overshoot = 0.15 * layout.position_map.line_height;
2331 for (range, color) in &layout.highlighted_ranges {
2332 self.paint_highlighted_range(
2333 range.clone(),
2334 *color,
2335 Pixels::ZERO,
2336 line_end_overshoot,
2337 layout,
2338 cx,
2339 );
2340 }
2341
2342 let corner_radius = 0.15 * layout.position_map.line_height;
2343
2344 for (player_color, selections) in &layout.selections {
2345 for selection in selections.into_iter() {
2346 self.paint_highlighted_range(
2347 selection.range.clone(),
2348 player_color.selection,
2349 corner_radius,
2350 corner_radius * 2.,
2351 layout,
2352 cx,
2353 );
2354
2355 if selection.is_local && !selection.range.is_empty() {
2356 invisible_display_ranges.push(selection.range.clone());
2357 }
2358 }
2359 }
2360 invisible_display_ranges
2361 })
2362 }
2363
2364 fn paint_lines(
2365 &mut self,
2366 invisible_display_ranges: &[Range<DisplayPoint>],
2367 layout: &EditorLayout,
2368 cx: &mut ElementContext,
2369 ) {
2370 let whitespace_setting = self
2371 .editor
2372 .read(cx)
2373 .buffer
2374 .read(cx)
2375 .settings_at(0, cx)
2376 .show_whitespaces;
2377
2378 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2379 let row = layout.visible_display_row_range.start + ix as u32;
2380 line_with_invisibles.draw(
2381 layout,
2382 row,
2383 layout.content_origin,
2384 whitespace_setting,
2385 invisible_display_ranges,
2386 cx,
2387 )
2388 }
2389 }
2390
2391 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2392 if layout.redacted_ranges.is_empty() {
2393 return;
2394 }
2395
2396 let line_end_overshoot = layout.line_end_overshoot();
2397
2398 // A softer than perfect black
2399 let redaction_color = gpui::rgb(0x0e1111);
2400
2401 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2402 for range in layout.redacted_ranges.iter() {
2403 self.paint_highlighted_range(
2404 range.clone(),
2405 redaction_color.into(),
2406 Pixels::ZERO,
2407 line_end_overshoot,
2408 layout,
2409 cx,
2410 );
2411 }
2412 });
2413 }
2414
2415 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2416 for cursor in &mut layout.cursors {
2417 cursor.paint(layout.content_origin, cx);
2418 }
2419 }
2420
2421 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2422 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2423 return;
2424 };
2425
2426 let thumb_bounds = scrollbar_layout.thumb_bounds();
2427 if scrollbar_layout.visible {
2428 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2429 cx.paint_quad(quad(
2430 scrollbar_layout.hitbox.bounds,
2431 Corners::default(),
2432 cx.theme().colors().scrollbar_track_background,
2433 Edges {
2434 top: Pixels::ZERO,
2435 right: Pixels::ZERO,
2436 bottom: Pixels::ZERO,
2437 left: ScrollbarLayout::BORDER_WIDTH,
2438 },
2439 cx.theme().colors().scrollbar_track_border,
2440 ));
2441
2442 // Refresh scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2443 self.refresh_scrollbar_markers(layout, scrollbar_layout, cx);
2444
2445 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2446 for marker in markers.iter() {
2447 let mut marker = marker.clone();
2448 marker.bounds.origin += scrollbar_layout.hitbox.origin;
2449 cx.paint_quad(marker);
2450 }
2451
2452 cx.paint_quad(quad(
2453 thumb_bounds,
2454 Corners::default(),
2455 cx.theme().colors().scrollbar_thumb_background,
2456 Edges {
2457 top: Pixels::ZERO,
2458 right: Pixels::ZERO,
2459 bottom: Pixels::ZERO,
2460 left: ScrollbarLayout::BORDER_WIDTH,
2461 },
2462 cx.theme().colors().scrollbar_thumb_border,
2463 ));
2464 });
2465 }
2466
2467 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2468
2469 let scroll_height = scrollbar_layout.scroll_height;
2470 let height = scrollbar_layout.height;
2471 let row_range = scrollbar_layout.visible_row_range.clone();
2472
2473 cx.on_mouse_event({
2474 let editor = self.editor.clone();
2475 let hitbox = scrollbar_layout.hitbox.clone();
2476 let mut mouse_position = cx.mouse_position();
2477 move |event: &MouseMoveEvent, phase, cx| {
2478 if phase == DispatchPhase::Capture {
2479 return;
2480 }
2481
2482 editor.update(cx, |editor, cx| {
2483 if event.pressed_button == Some(MouseButton::Left)
2484 && editor.scroll_manager.is_dragging_scrollbar()
2485 {
2486 let y = mouse_position.y;
2487 let new_y = event.position.y;
2488 if (hitbox.top()..hitbox.bottom()).contains(&y) {
2489 let mut position = editor.scroll_position(cx);
2490 position.y += (new_y - y) * scroll_height / height;
2491 if position.y < 0.0 {
2492 position.y = 0.0;
2493 }
2494 editor.set_scroll_position(position, cx);
2495 }
2496
2497 mouse_position = event.position;
2498 cx.stop_propagation();
2499 } else {
2500 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2501 if hitbox.is_hovered(cx) {
2502 editor.scroll_manager.show_scrollbar(cx);
2503 }
2504 }
2505 })
2506 }
2507 });
2508
2509 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2510 cx.on_mouse_event({
2511 let editor = self.editor.clone();
2512 move |_: &MouseUpEvent, phase, cx| {
2513 if phase == DispatchPhase::Capture {
2514 return;
2515 }
2516
2517 editor.update(cx, |editor, cx| {
2518 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2519 cx.stop_propagation();
2520 });
2521 }
2522 });
2523 } else {
2524 cx.on_mouse_event({
2525 let editor = self.editor.clone();
2526 let hitbox = scrollbar_layout.hitbox.clone();
2527 move |event: &MouseDownEvent, phase, cx| {
2528 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2529 return;
2530 }
2531
2532 editor.update(cx, |editor, cx| {
2533 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2534
2535 let y = event.position.y;
2536 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2537 let center_row =
2538 ((y - hitbox.top()) * scroll_height / height).round() as u32;
2539 let top_row = center_row
2540 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2541 let mut position = editor.scroll_position(cx);
2542 position.y = top_row as f32;
2543 editor.set_scroll_position(position, cx);
2544 } else {
2545 editor.scroll_manager.show_scrollbar(cx);
2546 }
2547
2548 cx.stop_propagation();
2549 });
2550 }
2551 });
2552 }
2553 }
2554
2555 fn refresh_scrollbar_markers(
2556 &self,
2557 layout: &EditorLayout,
2558 scrollbar_layout: &ScrollbarLayout,
2559 cx: &mut ElementContext,
2560 ) {
2561 self.editor.update(cx, |editor, cx| {
2562 if !editor.is_singleton(cx)
2563 || !editor
2564 .scrollbar_marker_state
2565 .should_refresh(scrollbar_layout.hitbox.size)
2566 {
2567 return;
2568 }
2569
2570 let scrollbar_layout = scrollbar_layout.clone();
2571 let background_highlights = editor.background_highlights.clone();
2572 let snapshot = layout.position_map.snapshot.clone();
2573 let theme = cx.theme().clone();
2574 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2575 let max_row = layout.max_row;
2576
2577 editor.scrollbar_marker_state.dirty = false;
2578 editor.scrollbar_marker_state.pending_refresh =
2579 Some(cx.spawn(|editor, mut cx| async move {
2580 let scrollbar_size = scrollbar_layout.hitbox.size;
2581 let scrollbar_markers = cx
2582 .background_executor()
2583 .spawn(async move {
2584 let mut marker_quads = Vec::new();
2585
2586 if scrollbar_settings.git_diff {
2587 let marker_row_ranges = snapshot
2588 .buffer_snapshot
2589 .git_diff_hunks_in_range(0..max_row)
2590 .map(|hunk| {
2591 let start_display_row =
2592 Point::new(hunk.associated_range.start, 0)
2593 .to_display_point(&snapshot.display_snapshot)
2594 .row();
2595 let mut end_display_row =
2596 Point::new(hunk.associated_range.end, 0)
2597 .to_display_point(&snapshot.display_snapshot)
2598 .row();
2599 if end_display_row != start_display_row {
2600 end_display_row -= 1;
2601 }
2602 let color = match hunk.status() {
2603 DiffHunkStatus::Added => theme.status().created,
2604 DiffHunkStatus::Modified => theme.status().modified,
2605 DiffHunkStatus::Removed => theme.status().deleted,
2606 };
2607 ColoredRange {
2608 start: start_display_row,
2609 end: end_display_row,
2610 color,
2611 }
2612 });
2613
2614 marker_quads.extend(
2615 scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 0),
2616 );
2617 }
2618
2619 for (background_highlight_id, (_, background_ranges)) in
2620 background_highlights.iter()
2621 {
2622 if (*background_highlight_id
2623 == TypeId::of::<BufferSearchHighlights>()
2624 && scrollbar_settings.selections)
2625 || scrollbar_settings.symbols_selections
2626 {
2627 let marker_row_ranges =
2628 background_ranges.into_iter().map(|range| {
2629 let display_start = range
2630 .start
2631 .to_display_point(&snapshot.display_snapshot);
2632 let display_end = range
2633 .end
2634 .to_display_point(&snapshot.display_snapshot);
2635 ColoredRange {
2636 start: display_start.row(),
2637 end: display_end.row(),
2638 color: theme.status().info,
2639 }
2640 });
2641 marker_quads.extend(
2642 scrollbar_layout
2643 .marker_quads_for_ranges(marker_row_ranges, 1),
2644 );
2645 }
2646 }
2647
2648 if scrollbar_settings.diagnostics {
2649 let max_point =
2650 snapshot.display_snapshot.buffer_snapshot.max_point();
2651
2652 let diagnostics = snapshot
2653 .buffer_snapshot
2654 .diagnostics_in_range::<_, Point>(
2655 Point::zero()..max_point,
2656 false,
2657 )
2658 // We want to sort by severity, in order to paint the most severe diagnostics last.
2659 .sorted_by_key(|diagnostic| {
2660 std::cmp::Reverse(diagnostic.diagnostic.severity)
2661 });
2662
2663 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2664 let start_display = diagnostic
2665 .range
2666 .start
2667 .to_display_point(&snapshot.display_snapshot);
2668 let end_display = diagnostic
2669 .range
2670 .end
2671 .to_display_point(&snapshot.display_snapshot);
2672 let color = match diagnostic.diagnostic.severity {
2673 DiagnosticSeverity::ERROR => theme.status().error,
2674 DiagnosticSeverity::WARNING => theme.status().warning,
2675 DiagnosticSeverity::INFORMATION => theme.status().info,
2676 _ => theme.status().hint,
2677 };
2678 ColoredRange {
2679 start: start_display.row(),
2680 end: end_display.row(),
2681 color,
2682 }
2683 });
2684 marker_quads.extend(
2685 scrollbar_layout.marker_quads_for_ranges(marker_row_ranges, 2),
2686 );
2687 }
2688
2689 Arc::from(marker_quads)
2690 })
2691 .await;
2692
2693 editor.update(&mut cx, |editor, cx| {
2694 editor.scrollbar_marker_state.markers = scrollbar_markers;
2695 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2696 editor.scrollbar_marker_state.pending_refresh = None;
2697 cx.notify();
2698 })?;
2699
2700 Ok(())
2701 }));
2702 });
2703 }
2704
2705 #[allow(clippy::too_many_arguments)]
2706 fn paint_highlighted_range(
2707 &self,
2708 range: Range<DisplayPoint>,
2709 color: Hsla,
2710 corner_radius: Pixels,
2711 line_end_overshoot: Pixels,
2712 layout: &EditorLayout,
2713 cx: &mut ElementContext,
2714 ) {
2715 let start_row = layout.visible_display_row_range.start;
2716 let end_row = layout.visible_display_row_range.end;
2717 if range.start != range.end {
2718 let row_range = if range.end.column() == 0 {
2719 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2720 } else {
2721 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2722 };
2723
2724 let highlighted_range = HighlightedRange {
2725 color,
2726 line_height: layout.position_map.line_height,
2727 corner_radius,
2728 start_y: layout.content_origin.y
2729 + row_range.start as f32 * layout.position_map.line_height
2730 - layout.position_map.scroll_pixel_position.y,
2731 lines: row_range
2732 .into_iter()
2733 .map(|row| {
2734 let line_layout =
2735 &layout.position_map.line_layouts[(row - start_row) as usize].line;
2736 HighlightedRangeLine {
2737 start_x: if row == range.start.row() {
2738 layout.content_origin.x
2739 + line_layout.x_for_index(range.start.column() as usize)
2740 - layout.position_map.scroll_pixel_position.x
2741 } else {
2742 layout.content_origin.x
2743 - layout.position_map.scroll_pixel_position.x
2744 },
2745 end_x: if row == range.end.row() {
2746 layout.content_origin.x
2747 + line_layout.x_for_index(range.end.column() as usize)
2748 - layout.position_map.scroll_pixel_position.x
2749 } else {
2750 layout.content_origin.x + line_layout.width + line_end_overshoot
2751 - layout.position_map.scroll_pixel_position.x
2752 },
2753 }
2754 })
2755 .collect(),
2756 };
2757
2758 highlighted_range.paint(layout.text_hitbox.bounds, cx);
2759 }
2760 }
2761
2762 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2763 if layout.folds.is_empty() {
2764 return;
2765 }
2766
2767 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2768 let fold_corner_radius = 0.15 * layout.position_map.line_height;
2769 for mut fold in mem::take(&mut layout.folds) {
2770 fold.hover_element.paint(cx);
2771
2772 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2773 let fold_background = if hover_element.interactivity().active.unwrap() {
2774 cx.theme().colors().ghost_element_active
2775 } else if hover_element.interactivity().hovered.unwrap() {
2776 cx.theme().colors().ghost_element_hover
2777 } else {
2778 cx.theme().colors().ghost_element_background
2779 };
2780
2781 self.paint_highlighted_range(
2782 fold.display_range.clone(),
2783 fold_background,
2784 fold_corner_radius,
2785 fold_corner_radius * 2.,
2786 layout,
2787 cx,
2788 );
2789 }
2790 })
2791 }
2792
2793 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2794 if let Some(mut inline_blame) = layout.inline_blame.take() {
2795 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2796 inline_blame.paint(cx);
2797 })
2798 }
2799 }
2800
2801 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2802 for mut block in layout.blocks.drain(..) {
2803 block.element.paint(cx);
2804 }
2805 }
2806
2807 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2808 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2809 mouse_context_menu.paint(cx);
2810 }
2811 }
2812
2813 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2814 cx.on_mouse_event({
2815 let position_map = layout.position_map.clone();
2816 let editor = self.editor.clone();
2817 let hitbox = layout.hitbox.clone();
2818 let mut delta = ScrollDelta::default();
2819
2820 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
2821 // accidentally turn off their scrolling.
2822 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
2823
2824 move |event: &ScrollWheelEvent, phase, cx| {
2825 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2826 delta = delta.coalesce(event.delta);
2827 editor.update(cx, |editor, cx| {
2828 let position_map: &PositionMap = &position_map;
2829
2830 let line_height = position_map.line_height;
2831 let max_glyph_width = position_map.em_width;
2832 let (delta, axis) = match delta {
2833 gpui::ScrollDelta::Pixels(mut pixels) => {
2834 //Trackpad
2835 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2836 (pixels, axis)
2837 }
2838
2839 gpui::ScrollDelta::Lines(lines) => {
2840 //Not trackpad
2841 let pixels =
2842 point(lines.x * max_glyph_width, lines.y * line_height);
2843 (pixels, None)
2844 }
2845 };
2846
2847 let scroll_position = position_map.snapshot.scroll_position();
2848 let x = (scroll_position.x * max_glyph_width
2849 - (delta.x * scroll_sensitivity))
2850 / max_glyph_width;
2851 let y = (scroll_position.y * line_height - (delta.y * scroll_sensitivity))
2852 / line_height;
2853 let scroll_position =
2854 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2855 editor.scroll(scroll_position, axis, cx);
2856 cx.stop_propagation();
2857 });
2858 }
2859 }
2860 });
2861 }
2862
2863 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2864 self.paint_scroll_wheel_listener(layout, cx);
2865
2866 cx.on_mouse_event({
2867 let position_map = layout.position_map.clone();
2868 let editor = self.editor.clone();
2869 let text_hitbox = layout.text_hitbox.clone();
2870 let gutter_hitbox = layout.gutter_hitbox.clone();
2871
2872 move |event: &MouseDownEvent, phase, cx| {
2873 if phase == DispatchPhase::Bubble {
2874 match event.button {
2875 MouseButton::Left => editor.update(cx, |editor, cx| {
2876 Self::mouse_left_down(
2877 editor,
2878 event,
2879 &position_map,
2880 &text_hitbox,
2881 &gutter_hitbox,
2882 cx,
2883 );
2884 }),
2885 MouseButton::Right => editor.update(cx, |editor, cx| {
2886 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2887 }),
2888 _ => {}
2889 };
2890 }
2891 }
2892 });
2893
2894 cx.on_mouse_event({
2895 let editor = self.editor.clone();
2896 let position_map = layout.position_map.clone();
2897 let text_hitbox = layout.text_hitbox.clone();
2898
2899 move |event: &MouseUpEvent, phase, cx| {
2900 if phase == DispatchPhase::Bubble {
2901 editor.update(cx, |editor, cx| {
2902 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2903 });
2904 }
2905 }
2906 });
2907 cx.on_mouse_event({
2908 let position_map = layout.position_map.clone();
2909 let editor = self.editor.clone();
2910 let text_hitbox = layout.text_hitbox.clone();
2911 let gutter_hitbox = layout.gutter_hitbox.clone();
2912
2913 move |event: &MouseMoveEvent, phase, cx| {
2914 if phase == DispatchPhase::Bubble {
2915 editor.update(cx, |editor, cx| {
2916 if event.pressed_button == Some(MouseButton::Left) {
2917 Self::mouse_dragged(
2918 editor,
2919 event,
2920 &position_map,
2921 text_hitbox.bounds,
2922 cx,
2923 )
2924 }
2925
2926 Self::mouse_moved(
2927 editor,
2928 event,
2929 &position_map,
2930 &text_hitbox,
2931 &gutter_hitbox,
2932 cx,
2933 )
2934 });
2935 }
2936 }
2937 });
2938 }
2939
2940 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2941 bounds.upper_right().x - self.style.scrollbar_width
2942 }
2943
2944 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2945 let style = &self.style;
2946 let font_size = style.text.font_size.to_pixels(cx.rem_size());
2947 let layout = cx
2948 .text_system()
2949 .shape_line(
2950 SharedString::from(" ".repeat(column)),
2951 font_size,
2952 &[TextRun {
2953 len: column,
2954 font: style.text.font(),
2955 color: Hsla::default(),
2956 background_color: None,
2957 underline: None,
2958 strikethrough: None,
2959 }],
2960 )
2961 .unwrap();
2962
2963 layout.width
2964 }
2965
2966 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2967 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2968 self.column_pixels(digit_count, cx)
2969 }
2970}
2971
2972fn render_inline_blame_entry(
2973 blame: &gpui::Model<GitBlame>,
2974 blame_entry: BlameEntry,
2975 style: &EditorStyle,
2976 workspace: Option<WeakView<Workspace>>,
2977 cx: &mut ElementContext<'_>,
2978) -> AnyElement {
2979 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
2980
2981 let author = blame_entry.author.as_deref().unwrap_or_default();
2982 let text = format!("{}, {}", author, relative_timestamp);
2983
2984 let details = blame.read(cx).details_for_entry(&blame_entry);
2985
2986 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
2987
2988 h_flex()
2989 .id("inline-blame")
2990 .w_full()
2991 .font(style.text.font().family)
2992 .text_color(cx.theme().status().hint)
2993 .line_height(style.text.line_height)
2994 .child(Icon::new(IconName::FileGit).color(Color::Hint))
2995 .child(text)
2996 .gap_2()
2997 .hoverable_tooltip(move |_| tooltip.clone().into())
2998 .into_any()
2999}
3000
3001fn blame_entry_timestamp(
3002 blame_entry: &BlameEntry,
3003 format: time_format::TimestampFormat,
3004 cx: &WindowContext,
3005) -> String {
3006 match blame_entry.author_offset_date_time() {
3007 Ok(timestamp) => time_format::format_localized_timestamp(
3008 timestamp,
3009 time::OffsetDateTime::now_utc(),
3010 cx.local_timezone(),
3011 format,
3012 ),
3013 Err(_) => "Error parsing date".to_string(),
3014 }
3015}
3016
3017fn blame_entry_relative_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3018 blame_entry_timestamp(blame_entry, time_format::TimestampFormat::Relative, cx)
3019}
3020
3021fn blame_entry_absolute_timestamp(blame_entry: &BlameEntry, cx: &WindowContext) -> String {
3022 blame_entry_timestamp(
3023 blame_entry,
3024 time_format::TimestampFormat::MediumAbsolute,
3025 cx,
3026 )
3027}
3028
3029struct BlameEntryTooltip {
3030 blame_entry: BlameEntry,
3031 details: Option<CommitDetails>,
3032 style: EditorStyle,
3033 workspace: Option<WeakView<Workspace>>,
3034 scroll_handle: ScrollHandle,
3035}
3036
3037impl BlameEntryTooltip {
3038 fn new(
3039 blame_entry: BlameEntry,
3040 details: Option<CommitDetails>,
3041 style: &EditorStyle,
3042 workspace: Option<WeakView<Workspace>>,
3043 ) -> Self {
3044 Self {
3045 style: style.clone(),
3046 blame_entry,
3047 details,
3048 workspace,
3049 scroll_handle: ScrollHandle::new(),
3050 }
3051 }
3052}
3053
3054impl Render for BlameEntryTooltip {
3055 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
3056 let author = self
3057 .blame_entry
3058 .author
3059 .clone()
3060 .unwrap_or("<no name>".to_string());
3061
3062 let author_email = self.blame_entry.author_mail.clone();
3063
3064 let pretty_commit_id = format!("{}", self.blame_entry.sha);
3065 let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3066 let absolute_timestamp = blame_entry_absolute_timestamp(&self.blame_entry, cx);
3067
3068 let message = self
3069 .details
3070 .as_ref()
3071 .map(|details| {
3072 crate::render_parsed_markdown(
3073 "blame-message",
3074 &details.parsed_message,
3075 &self.style,
3076 self.workspace.clone(),
3077 cx,
3078 )
3079 .into_any()
3080 })
3081 .unwrap_or("<no commit message>".into_any());
3082
3083 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
3084 let message_max_height = cx.line_height() * 12 + (ui_font_size / 0.4);
3085
3086 tooltip_container(cx, move |this, cx| {
3087 this.occlude()
3088 .on_mouse_move(|_, cx| cx.stop_propagation())
3089 .child(
3090 v_flex()
3091 .w(gpui::rems(30.))
3092 .gap_4()
3093 .child(
3094 h_flex()
3095 .gap_2()
3096 .child(author)
3097 .when_some(author_email, |this, author_email| {
3098 this.child(
3099 div()
3100 .text_color(cx.theme().colors().text_muted)
3101 .child(author_email),
3102 )
3103 })
3104 .pb_1()
3105 .border_b_1()
3106 .border_color(cx.theme().colors().border),
3107 )
3108 .child(
3109 div()
3110 .id("inline-blame-commit-message")
3111 .occlude()
3112 .child(message)
3113 .max_h(message_max_height)
3114 .overflow_y_scroll()
3115 .track_scroll(&self.scroll_handle),
3116 )
3117 .child(
3118 h_flex()
3119 .text_color(cx.theme().colors().text_muted)
3120 .w_full()
3121 .justify_between()
3122 .child(absolute_timestamp)
3123 .child(
3124 Button::new("commit-sha-button", short_commit_id.clone())
3125 .style(ButtonStyle::Transparent)
3126 .color(Color::Muted)
3127 .icon(IconName::FileGit)
3128 .icon_color(Color::Muted)
3129 .icon_position(IconPosition::Start)
3130 .disabled(
3131 self.details.as_ref().map_or(true, |details| {
3132 details.permalink.is_none()
3133 }),
3134 )
3135 .when_some(
3136 self.details
3137 .as_ref()
3138 .and_then(|details| details.permalink.clone()),
3139 |this, url| {
3140 this.on_click(move |_, cx| {
3141 cx.stop_propagation();
3142 cx.open_url(url.as_str())
3143 })
3144 },
3145 ),
3146 ),
3147 ),
3148 )
3149 })
3150 }
3151}
3152
3153fn render_blame_entry(
3154 ix: usize,
3155 blame: &gpui::Model<GitBlame>,
3156 blame_entry: BlameEntry,
3157 style: &EditorStyle,
3158 last_used_color: &mut Option<(PlayerColor, Oid)>,
3159 editor: View<Editor>,
3160 cx: &mut ElementContext<'_>,
3161) -> AnyElement {
3162 let mut sha_color = cx
3163 .theme()
3164 .players()
3165 .color_for_participant(blame_entry.sha.into());
3166 // If the last color we used is the same as the one we get for this line, but
3167 // the commit SHAs are different, then we try again to get a different color.
3168 match *last_used_color {
3169 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3170 let index: u32 = blame_entry.sha.into();
3171 sha_color = cx.theme().players().color_for_participant(index + 1);
3172 }
3173 _ => {}
3174 };
3175 last_used_color.replace((sha_color, blame_entry.sha));
3176
3177 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3178
3179 let pretty_commit_id = format!("{}", blame_entry.sha);
3180 let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3181
3182 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3183 let name = util::truncate_and_trailoff(author_name, 20);
3184
3185 let details = blame.read(cx).details_for_entry(&blame_entry);
3186
3187 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3188
3189 let tooltip = cx.new_view(|_| {
3190 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3191 });
3192
3193 h_flex()
3194 .w_full()
3195 .font(style.text.font().family)
3196 .line_height(style.text.line_height)
3197 .id(("blame", ix))
3198 .children([
3199 div()
3200 .text_color(sha_color.cursor)
3201 .child(short_commit_id)
3202 .mr_2(),
3203 div()
3204 .w_full()
3205 .h_flex()
3206 .justify_between()
3207 .text_color(cx.theme().status().hint)
3208 .child(name)
3209 .child(relative_timestamp),
3210 ])
3211 .on_mouse_down(MouseButton::Right, {
3212 let blame_entry = blame_entry.clone();
3213 move |event, cx| {
3214 deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3215 }
3216 })
3217 .hover(|style| style.bg(cx.theme().colors().element_hover))
3218 .when_some(
3219 details.and_then(|details| details.permalink),
3220 |this, url| {
3221 let url = url.clone();
3222 this.cursor_pointer().on_click(move |_, cx| {
3223 cx.stop_propagation();
3224 cx.open_url(url.as_str())
3225 })
3226 },
3227 )
3228 .hoverable_tooltip(move |_| tooltip.clone().into())
3229 .into_any()
3230}
3231
3232fn deploy_blame_entry_context_menu(
3233 blame_entry: &BlameEntry,
3234 editor: View<Editor>,
3235 position: gpui::Point<Pixels>,
3236 cx: &mut WindowContext<'_>,
3237) {
3238 let context_menu = ContextMenu::build(cx, move |this, _| {
3239 let sha = format!("{}", blame_entry.sha);
3240 this.entry("Copy commit SHA", None, move |cx| {
3241 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3242 })
3243 });
3244
3245 editor.update(cx, move |editor, cx| {
3246 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3247 cx.notify();
3248 });
3249}
3250
3251#[derive(Debug)]
3252pub(crate) struct LineWithInvisibles {
3253 pub line: ShapedLine,
3254 invisibles: Vec<Invisible>,
3255}
3256
3257impl LineWithInvisibles {
3258 fn from_chunks<'a>(
3259 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3260 text_style: &TextStyle,
3261 max_line_len: usize,
3262 max_line_count: usize,
3263 line_number_layouts: &[Option<ShapedLine>],
3264 editor_mode: EditorMode,
3265 cx: &WindowContext,
3266 ) -> Vec<Self> {
3267 let mut layouts = Vec::with_capacity(max_line_count);
3268 let mut line = String::new();
3269 let mut invisibles = Vec::new();
3270 let mut styles = Vec::new();
3271 let mut non_whitespace_added = false;
3272 let mut row = 0;
3273 let mut line_exceeded_max_len = false;
3274 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3275
3276 for highlighted_chunk in chunks.chain([HighlightedChunk {
3277 chunk: "\n",
3278 style: None,
3279 is_tab: false,
3280 }]) {
3281 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3282 if ix > 0 {
3283 let shaped_line = cx
3284 .text_system()
3285 .shape_line(line.clone().into(), font_size, &styles)
3286 .unwrap();
3287 layouts.push(Self {
3288 line: shaped_line,
3289 invisibles: std::mem::take(&mut invisibles),
3290 });
3291
3292 line.clear();
3293 styles.clear();
3294 row += 1;
3295 line_exceeded_max_len = false;
3296 non_whitespace_added = false;
3297 if row == max_line_count {
3298 return layouts;
3299 }
3300 }
3301
3302 if !line_chunk.is_empty() && !line_exceeded_max_len {
3303 let text_style = if let Some(style) = highlighted_chunk.style {
3304 Cow::Owned(text_style.clone().highlight(style))
3305 } else {
3306 Cow::Borrowed(text_style)
3307 };
3308
3309 if line.len() + line_chunk.len() > max_line_len {
3310 let mut chunk_len = max_line_len - line.len();
3311 while !line_chunk.is_char_boundary(chunk_len) {
3312 chunk_len -= 1;
3313 }
3314 line_chunk = &line_chunk[..chunk_len];
3315 line_exceeded_max_len = true;
3316 }
3317
3318 styles.push(TextRun {
3319 len: line_chunk.len(),
3320 font: text_style.font(),
3321 color: text_style.color,
3322 background_color: text_style.background_color,
3323 underline: text_style.underline,
3324 strikethrough: text_style.strikethrough,
3325 });
3326
3327 if editor_mode == EditorMode::Full {
3328 // Line wrap pads its contents with fake whitespaces,
3329 // avoid printing them
3330 let inside_wrapped_string = line_number_layouts
3331 .get(row)
3332 .and_then(|layout| layout.as_ref())
3333 .is_none();
3334 if highlighted_chunk.is_tab {
3335 if non_whitespace_added || !inside_wrapped_string {
3336 invisibles.push(Invisible::Tab {
3337 line_start_offset: line.len(),
3338 });
3339 }
3340 } else {
3341 invisibles.extend(
3342 line_chunk
3343 .chars()
3344 .enumerate()
3345 .filter(|(_, line_char)| {
3346 let is_whitespace = line_char.is_whitespace();
3347 non_whitespace_added |= !is_whitespace;
3348 is_whitespace
3349 && (non_whitespace_added || !inside_wrapped_string)
3350 })
3351 .map(|(whitespace_index, _)| Invisible::Whitespace {
3352 line_offset: line.len() + whitespace_index,
3353 }),
3354 )
3355 }
3356 }
3357
3358 line.push_str(line_chunk);
3359 }
3360 }
3361 }
3362
3363 layouts
3364 }
3365
3366 fn draw(
3367 &self,
3368 layout: &EditorLayout,
3369 row: u32,
3370 content_origin: gpui::Point<Pixels>,
3371 whitespace_setting: ShowWhitespaceSetting,
3372 selection_ranges: &[Range<DisplayPoint>],
3373 cx: &mut ElementContext,
3374 ) {
3375 let line_height = layout.position_map.line_height;
3376 let line_y =
3377 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3378
3379 let line_origin =
3380 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3381 self.line.paint(line_origin, line_height, cx).log_err();
3382
3383 self.draw_invisibles(
3384 &selection_ranges,
3385 layout,
3386 content_origin,
3387 line_y,
3388 row,
3389 line_height,
3390 whitespace_setting,
3391 cx,
3392 );
3393 }
3394
3395 #[allow(clippy::too_many_arguments)]
3396 fn draw_invisibles(
3397 &self,
3398 selection_ranges: &[Range<DisplayPoint>],
3399 layout: &EditorLayout,
3400 content_origin: gpui::Point<Pixels>,
3401 line_y: Pixels,
3402 row: u32,
3403 line_height: Pixels,
3404 whitespace_setting: ShowWhitespaceSetting,
3405 cx: &mut ElementContext,
3406 ) {
3407 let allowed_invisibles_regions = match whitespace_setting {
3408 ShowWhitespaceSetting::None => return,
3409 ShowWhitespaceSetting::Selection => Some(selection_ranges),
3410 ShowWhitespaceSetting::All => None,
3411 };
3412
3413 for invisible in &self.invisibles {
3414 let (&token_offset, invisible_symbol) = match invisible {
3415 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3416 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3417 };
3418
3419 let x_offset = self.line.x_for_index(token_offset);
3420 let invisible_offset =
3421 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3422 let origin = content_origin
3423 + gpui::point(
3424 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3425 line_y,
3426 );
3427
3428 if let Some(allowed_regions) = allowed_invisibles_regions {
3429 let invisible_point = DisplayPoint::new(row, token_offset as u32);
3430 if !allowed_regions
3431 .iter()
3432 .any(|region| region.start <= invisible_point && invisible_point < region.end)
3433 {
3434 continue;
3435 }
3436 }
3437 invisible_symbol.paint(origin, line_height, cx).log_err();
3438 }
3439 }
3440}
3441
3442#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3443enum Invisible {
3444 Tab { line_start_offset: usize },
3445 Whitespace { line_offset: usize },
3446}
3447
3448impl Element for EditorElement {
3449 type BeforeLayout = ();
3450 type AfterLayout = EditorLayout;
3451
3452 fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
3453 self.editor.update(cx, |editor, cx| {
3454 editor.set_style(self.style.clone(), cx);
3455
3456 let layout_id = match editor.mode {
3457 EditorMode::SingleLine => {
3458 let rem_size = cx.rem_size();
3459 let mut style = Style::default();
3460 style.size.width = relative(1.).into();
3461 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3462 cx.with_element_context(|cx| cx.request_layout(&style, None))
3463 }
3464 EditorMode::AutoHeight { max_lines } => {
3465 let editor_handle = cx.view().clone();
3466 let max_line_number_width =
3467 self.max_line_number_width(&editor.snapshot(cx), cx);
3468 cx.with_element_context(|cx| {
3469 cx.request_measured_layout(
3470 Style::default(),
3471 move |known_dimensions, _, cx| {
3472 editor_handle
3473 .update(cx, |editor, cx| {
3474 compute_auto_height_layout(
3475 editor,
3476 max_lines,
3477 max_line_number_width,
3478 known_dimensions,
3479 cx,
3480 )
3481 })
3482 .unwrap_or_default()
3483 },
3484 )
3485 })
3486 }
3487 EditorMode::Full => {
3488 let mut style = Style::default();
3489 style.size.width = relative(1.).into();
3490 style.size.height = relative(1.).into();
3491 cx.with_element_context(|cx| cx.request_layout(&style, None))
3492 }
3493 };
3494
3495 (layout_id, ())
3496 })
3497 }
3498
3499 fn after_layout(
3500 &mut self,
3501 bounds: Bounds<Pixels>,
3502 _: &mut Self::BeforeLayout,
3503 cx: &mut ElementContext,
3504 ) -> Self::AfterLayout {
3505 let text_style = TextStyleRefinement {
3506 font_size: Some(self.style.text.font_size),
3507 line_height: Some(self.style.text.line_height),
3508 ..Default::default()
3509 };
3510 cx.with_text_style(Some(text_style), |cx| {
3511 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3512 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3513 let style = self.style.clone();
3514
3515 let font_id = cx.text_system().resolve_font(&style.text.font());
3516 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3517 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3518 let em_width = cx
3519 .text_system()
3520 .typographic_bounds(font_id, font_size, 'm')
3521 .unwrap()
3522 .size
3523 .width;
3524 let em_advance = cx
3525 .text_system()
3526 .advance(font_id, font_size, 'm')
3527 .unwrap()
3528 .width;
3529
3530 let gutter_dimensions = snapshot.gutter_dimensions(
3531 font_id,
3532 font_size,
3533 em_width,
3534 self.max_line_number_width(&snapshot, cx),
3535 cx,
3536 );
3537 let text_width = bounds.size.width - gutter_dimensions.width;
3538 let overscroll = size(em_width, px(0.));
3539
3540 snapshot = self.editor.update(cx, |editor, cx| {
3541 editor.last_bounds = Some(bounds);
3542 editor.gutter_width = gutter_dimensions.width;
3543 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3544
3545 let editor_width =
3546 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3547 let wrap_width = match editor.soft_wrap_mode(cx) {
3548 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3549 SoftWrap::EditorWidth => editor_width,
3550 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3551 };
3552
3553 if editor.set_wrap_width(Some(wrap_width), cx) {
3554 editor.snapshot(cx)
3555 } else {
3556 snapshot
3557 }
3558 });
3559
3560 let wrap_guides = self
3561 .editor
3562 .read(cx)
3563 .wrap_guides(cx)
3564 .iter()
3565 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3566 .collect::<SmallVec<[_; 2]>>();
3567
3568 let hitbox = cx.insert_hitbox(bounds, false);
3569 let gutter_hitbox = cx.insert_hitbox(
3570 Bounds {
3571 origin: bounds.origin,
3572 size: size(gutter_dimensions.width, bounds.size.height),
3573 },
3574 false,
3575 );
3576 let text_hitbox = cx.insert_hitbox(
3577 Bounds {
3578 origin: gutter_hitbox.upper_right(),
3579 size: size(text_width, bounds.size.height),
3580 },
3581 false,
3582 );
3583 // Offset the content_bounds from the text_bounds by the gutter margin (which
3584 // is roughly half a character wide) to make hit testing work more like how we want.
3585 let content_origin =
3586 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3587
3588 let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
3589 let autoscroll_horizontally =
3590 editor.autoscroll_vertically(bounds, line_height, cx);
3591 snapshot = editor.snapshot(cx);
3592 autoscroll_horizontally
3593 });
3594
3595 let mut scroll_position = snapshot.scroll_position();
3596 // The scroll position is a fractional point, the whole number of which represents
3597 // the top of the window in terms of display rows.
3598 let start_row = scroll_position.y as u32;
3599 let height_in_lines = bounds.size.height / line_height;
3600 let max_row = snapshot.max_point().row();
3601
3602 // Add 1 to ensure selections bleed off screen
3603 let end_row =
3604 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3605
3606 let buffer_rows = snapshot
3607 .buffer_rows(start_row)
3608 .take((start_row..end_row).len());
3609
3610 let start_anchor = if start_row == 0 {
3611 Anchor::min()
3612 } else {
3613 snapshot.buffer_snapshot.anchor_before(
3614 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3615 )
3616 };
3617 let end_anchor = if end_row > max_row {
3618 Anchor::max()
3619 } else {
3620 snapshot.buffer_snapshot.anchor_before(
3621 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3622 )
3623 };
3624
3625 let highlighted_rows = self
3626 .editor
3627 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3628 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3629 start_anchor..end_anchor,
3630 &snapshot.display_snapshot,
3631 cx.theme().colors(),
3632 );
3633
3634 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3635 start_anchor..end_anchor,
3636 &snapshot.display_snapshot,
3637 cx,
3638 );
3639
3640 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3641 start_anchor,
3642 end_anchor,
3643 &snapshot,
3644 start_row,
3645 end_row,
3646 cx,
3647 );
3648
3649 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3650 start_row..end_row,
3651 buffer_rows.clone(),
3652 &active_rows,
3653 newest_selection_head,
3654 &snapshot,
3655 cx,
3656 );
3657
3658 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3659
3660 let mut max_visible_line_width = Pixels::ZERO;
3661 let line_layouts =
3662 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3663 for line_with_invisibles in &line_layouts {
3664 if line_with_invisibles.line.width > max_visible_line_width {
3665 max_visible_line_width = line_with_invisibles.line.width;
3666 }
3667 }
3668
3669 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3670 .unwrap()
3671 .width;
3672 let mut scroll_width =
3673 longest_line_width.max(max_visible_line_width) + overscroll.width;
3674 let mut blocks = self.build_blocks(
3675 start_row..end_row,
3676 &snapshot,
3677 &hitbox,
3678 &text_hitbox,
3679 &mut scroll_width,
3680 &gutter_dimensions,
3681 em_width,
3682 gutter_dimensions.width + gutter_dimensions.margin,
3683 line_height,
3684 &line_layouts,
3685 cx,
3686 );
3687
3688 let scroll_pixel_position = point(
3689 scroll_position.x * em_width,
3690 scroll_position.y * line_height,
3691 );
3692
3693 let mut inline_blame = None;
3694 if let Some(newest_selection_head) = newest_selection_head {
3695 if (start_row..end_row).contains(&newest_selection_head.row()) {
3696 inline_blame = self.layout_inline_blame(
3697 start_row,
3698 newest_selection_head.row(),
3699 &line_layouts,
3700 em_width,
3701 content_origin,
3702 scroll_pixel_position,
3703 line_height,
3704 cx,
3705 );
3706 }
3707 }
3708
3709 let blamed_display_rows = self.layout_blame_entries(
3710 buffer_rows,
3711 em_width,
3712 scroll_position,
3713 line_height,
3714 &gutter_hitbox,
3715 gutter_dimensions.git_blame_entries_width,
3716 cx,
3717 );
3718
3719 let scroll_max = point(
3720 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3721 max_row as f32,
3722 );
3723
3724 self.editor.update(cx, |editor, cx| {
3725 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3726
3727 let autoscrolled = if autoscroll_horizontally {
3728 editor.autoscroll_horizontally(
3729 start_row,
3730 text_hitbox.size.width,
3731 scroll_width,
3732 em_width,
3733 &line_layouts,
3734 cx,
3735 )
3736 } else {
3737 false
3738 };
3739
3740 if clamped || autoscrolled {
3741 snapshot = editor.snapshot(cx);
3742 scroll_position = snapshot.scroll_position();
3743 }
3744 });
3745
3746 cx.with_element_id(Some("blocks"), |cx| {
3747 self.layout_blocks(
3748 &mut blocks,
3749 &hitbox,
3750 line_height,
3751 scroll_pixel_position,
3752 cx,
3753 );
3754 });
3755
3756 let cursors = self.layout_cursors(
3757 &snapshot,
3758 &selections,
3759 start_row..end_row,
3760 &line_layouts,
3761 &text_hitbox,
3762 content_origin,
3763 scroll_pixel_position,
3764 line_height,
3765 em_width,
3766 cx,
3767 );
3768
3769 let scrollbar_layout = self.layout_scrollbar(
3770 &snapshot,
3771 bounds,
3772 scroll_position,
3773 line_height,
3774 height_in_lines,
3775 cx,
3776 );
3777
3778 let folds = cx.with_element_id(Some("folds"), |cx| {
3779 self.layout_folds(
3780 &snapshot,
3781 content_origin,
3782 start_anchor..end_anchor,
3783 start_row..end_row,
3784 scroll_pixel_position,
3785 line_height,
3786 &line_layouts,
3787 cx,
3788 )
3789 });
3790
3791 let gutter_settings = EditorSettings::get_global(cx).gutter;
3792
3793 let mut context_menu_visible = false;
3794 let mut code_actions_indicator = None;
3795 if let Some(newest_selection_head) = newest_selection_head {
3796 if (start_row..end_row).contains(&newest_selection_head.row()) {
3797 context_menu_visible = self.layout_context_menu(
3798 line_height,
3799 &hitbox,
3800 &text_hitbox,
3801 content_origin,
3802 start_row,
3803 scroll_pixel_position,
3804 &line_layouts,
3805 newest_selection_head,
3806 cx,
3807 );
3808 if gutter_settings.code_actions {
3809 code_actions_indicator = self.layout_code_actions_indicator(
3810 line_height,
3811 newest_selection_head,
3812 scroll_pixel_position,
3813 &gutter_dimensions,
3814 &gutter_hitbox,
3815 cx,
3816 );
3817 }
3818 }
3819 }
3820
3821 if !context_menu_visible && !cx.has_active_drag() {
3822 self.layout_hover_popovers(
3823 &snapshot,
3824 &hitbox,
3825 &text_hitbox,
3826 start_row..end_row,
3827 content_origin,
3828 scroll_pixel_position,
3829 &line_layouts,
3830 line_height,
3831 em_width,
3832 cx,
3833 );
3834 }
3835
3836 let mouse_context_menu = self.layout_mouse_context_menu(cx);
3837
3838 let fold_indicators = if gutter_settings.folds {
3839 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3840 self.layout_gutter_fold_indicators(
3841 fold_statuses,
3842 line_height,
3843 &gutter_dimensions,
3844 gutter_settings,
3845 scroll_pixel_position,
3846 &gutter_hitbox,
3847 cx,
3848 )
3849 })
3850 } else {
3851 Vec::new()
3852 };
3853
3854 let invisible_symbol_font_size = font_size / 2.;
3855 let tab_invisible = cx
3856 .text_system()
3857 .shape_line(
3858 "→".into(),
3859 invisible_symbol_font_size,
3860 &[TextRun {
3861 len: "→".len(),
3862 font: self.style.text.font(),
3863 color: cx.theme().colors().editor_invisible,
3864 background_color: None,
3865 underline: None,
3866 strikethrough: None,
3867 }],
3868 )
3869 .unwrap();
3870 let space_invisible = cx
3871 .text_system()
3872 .shape_line(
3873 "•".into(),
3874 invisible_symbol_font_size,
3875 &[TextRun {
3876 len: "•".len(),
3877 font: self.style.text.font(),
3878 color: cx.theme().colors().editor_invisible,
3879 background_color: None,
3880 underline: None,
3881 strikethrough: None,
3882 }],
3883 )
3884 .unwrap();
3885
3886 EditorLayout {
3887 mode: snapshot.mode,
3888 position_map: Arc::new(PositionMap {
3889 size: bounds.size,
3890 scroll_pixel_position,
3891 scroll_max,
3892 line_layouts,
3893 line_height,
3894 em_width,
3895 em_advance,
3896 snapshot,
3897 }),
3898 visible_display_row_range: start_row..end_row,
3899 wrap_guides,
3900 hitbox,
3901 text_hitbox,
3902 gutter_hitbox,
3903 gutter_dimensions,
3904 content_origin,
3905 scrollbar_layout,
3906 max_row,
3907 active_rows,
3908 highlighted_rows,
3909 highlighted_ranges,
3910 redacted_ranges,
3911 line_numbers,
3912 display_hunks,
3913 blamed_display_rows,
3914 inline_blame,
3915 folds,
3916 blocks,
3917 cursors,
3918 selections,
3919 mouse_context_menu,
3920 code_actions_indicator,
3921 fold_indicators,
3922 tab_invisible,
3923 space_invisible,
3924 }
3925 })
3926 })
3927 }
3928
3929 fn paint(
3930 &mut self,
3931 bounds: Bounds<gpui::Pixels>,
3932 _: &mut Self::BeforeLayout,
3933 layout: &mut Self::AfterLayout,
3934 cx: &mut ElementContext,
3935 ) {
3936 let focus_handle = self.editor.focus_handle(cx);
3937 let key_context = self.editor.read(cx).key_context(cx);
3938 cx.set_focus_handle(&focus_handle);
3939 cx.set_key_context(key_context);
3940 cx.set_view_id(self.editor.entity_id());
3941 cx.handle_input(
3942 &focus_handle,
3943 ElementInputHandler::new(bounds, self.editor.clone()),
3944 );
3945 self.register_actions(cx);
3946 self.register_key_listeners(cx, layout);
3947
3948 let text_style = TextStyleRefinement {
3949 font_size: Some(self.style.text.font_size),
3950 line_height: Some(self.style.text.line_height),
3951 ..Default::default()
3952 };
3953 cx.with_text_style(Some(text_style), |cx| {
3954 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3955 self.paint_mouse_listeners(layout, cx);
3956
3957 self.paint_background(layout, cx);
3958 if layout.gutter_hitbox.size.width > Pixels::ZERO {
3959 self.paint_gutter(layout, cx);
3960 }
3961 self.paint_text(layout, cx);
3962
3963 if !layout.blocks.is_empty() {
3964 cx.with_element_id(Some("blocks"), |cx| {
3965 self.paint_blocks(layout, cx);
3966 });
3967 }
3968
3969 self.paint_scrollbar(layout, cx);
3970 self.paint_mouse_context_menu(layout, cx);
3971 });
3972 })
3973 }
3974}
3975
3976impl IntoElement for EditorElement {
3977 type Element = Self;
3978
3979 fn into_element(self) -> Self::Element {
3980 self
3981 }
3982}
3983
3984type BufferRow = u32;
3985
3986pub struct EditorLayout {
3987 position_map: Arc<PositionMap>,
3988 hitbox: Hitbox,
3989 text_hitbox: Hitbox,
3990 gutter_hitbox: Hitbox,
3991 gutter_dimensions: GutterDimensions,
3992 content_origin: gpui::Point<Pixels>,
3993 scrollbar_layout: Option<ScrollbarLayout>,
3994 mode: EditorMode,
3995 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3996 visible_display_row_range: Range<u32>,
3997 active_rows: BTreeMap<u32, bool>,
3998 highlighted_rows: BTreeMap<u32, Hsla>,
3999 line_numbers: Vec<Option<ShapedLine>>,
4000 display_hunks: Vec<DisplayDiffHunk>,
4001 blamed_display_rows: Option<Vec<AnyElement>>,
4002 inline_blame: Option<AnyElement>,
4003 folds: Vec<FoldLayout>,
4004 blocks: Vec<BlockLayout>,
4005 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4006 redacted_ranges: Vec<Range<DisplayPoint>>,
4007 cursors: Vec<CursorLayout>,
4008 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4009 max_row: u32,
4010 code_actions_indicator: Option<AnyElement>,
4011 fold_indicators: Vec<Option<AnyElement>>,
4012 mouse_context_menu: Option<AnyElement>,
4013 tab_invisible: ShapedLine,
4014 space_invisible: ShapedLine,
4015}
4016
4017impl EditorLayout {
4018 fn line_end_overshoot(&self) -> Pixels {
4019 0.15 * self.position_map.line_height
4020 }
4021}
4022
4023struct ColoredRange<T> {
4024 start: T,
4025 end: T,
4026 color: Hsla,
4027}
4028
4029#[derive(Clone)]
4030struct ScrollbarLayout {
4031 hitbox: Hitbox,
4032 visible_row_range: Range<f32>,
4033 visible: bool,
4034 height: Pixels,
4035 scroll_height: f32,
4036 first_row_y_offset: Pixels,
4037 row_height: Pixels,
4038}
4039
4040impl ScrollbarLayout {
4041 const BORDER_WIDTH: Pixels = px(1.0);
4042 const MIN_MARKER_HEIGHT: Pixels = px(2.0);
4043
4044 fn thumb_bounds(&self) -> Bounds<Pixels> {
4045 let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
4046 let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
4047 Bounds::from_corners(
4048 point(self.hitbox.left(), thumb_top),
4049 point(self.hitbox.right(), thumb_bottom),
4050 )
4051 }
4052
4053 fn y_for_row(&self, row: f32) -> Pixels {
4054 self.hitbox.top() + self.first_row_y_offset + row * self.row_height
4055 }
4056
4057 fn marker_quads_for_ranges(
4058 &self,
4059 row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4060 column: usize,
4061 ) -> Vec<PaintQuad> {
4062 let column_width =
4063 px(((self.hitbox.size.width - ScrollbarLayout::BORDER_WIDTH).0 / 3.0).floor());
4064
4065 let left_x = ScrollbarLayout::BORDER_WIDTH + (column as f32 * column_width);
4066 let right_x = left_x + column_width;
4067
4068 let mut background_pixel_ranges = row_ranges
4069 .into_iter()
4070 .map(|range| {
4071 let start_y = self.first_row_y_offset + range.start as f32 * self.row_height;
4072 let end_y = self.first_row_y_offset + (range.end + 1) as f32 * self.row_height;
4073 ColoredRange {
4074 start: start_y,
4075 end: end_y,
4076 color: range.color,
4077 }
4078 })
4079 .peekable();
4080
4081 let mut quads = Vec::new();
4082 while let Some(mut pixel_range) = background_pixel_ranges.next() {
4083 pixel_range.end = pixel_range
4084 .end
4085 .max(pixel_range.start + Self::MIN_MARKER_HEIGHT);
4086 while let Some(next_pixel_range) = background_pixel_ranges.peek() {
4087 if pixel_range.end >= next_pixel_range.start
4088 && pixel_range.color == next_pixel_range.color
4089 {
4090 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4091 background_pixel_ranges.next();
4092 } else {
4093 break;
4094 }
4095 }
4096
4097 let bounds = Bounds::from_corners(
4098 point(left_x, pixel_range.start),
4099 point(right_x, pixel_range.end),
4100 );
4101 quads.push(quad(
4102 bounds,
4103 Corners::default(),
4104 pixel_range.color,
4105 Edges::default(),
4106 Hsla::transparent_black(),
4107 ));
4108 }
4109
4110 quads
4111 }
4112}
4113
4114struct FoldLayout {
4115 display_range: Range<DisplayPoint>,
4116 hover_element: AnyElement,
4117}
4118
4119struct PositionMap {
4120 size: Size<Pixels>,
4121 line_height: Pixels,
4122 scroll_pixel_position: gpui::Point<Pixels>,
4123 scroll_max: gpui::Point<f32>,
4124 em_width: Pixels,
4125 em_advance: Pixels,
4126 line_layouts: Vec<LineWithInvisibles>,
4127 snapshot: EditorSnapshot,
4128}
4129
4130#[derive(Debug, Copy, Clone)]
4131pub struct PointForPosition {
4132 pub previous_valid: DisplayPoint,
4133 pub next_valid: DisplayPoint,
4134 pub exact_unclipped: DisplayPoint,
4135 pub column_overshoot_after_line_end: u32,
4136}
4137
4138impl PointForPosition {
4139 pub fn as_valid(&self) -> Option<DisplayPoint> {
4140 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4141 Some(self.previous_valid)
4142 } else {
4143 None
4144 }
4145 }
4146}
4147
4148impl PositionMap {
4149 fn point_for_position(
4150 &self,
4151 text_bounds: Bounds<Pixels>,
4152 position: gpui::Point<Pixels>,
4153 ) -> PointForPosition {
4154 let scroll_position = self.snapshot.scroll_position();
4155 let position = position - text_bounds.origin;
4156 let y = position.y.max(px(0.)).min(self.size.height);
4157 let x = position.x + (scroll_position.x * self.em_width);
4158 let row = ((y / self.line_height) + scroll_position.y) as u32;
4159
4160 let (column, x_overshoot_after_line_end) = if let Some(line) = self
4161 .line_layouts
4162 .get(row as usize - scroll_position.y as usize)
4163 .map(|LineWithInvisibles { line, .. }| line)
4164 {
4165 if let Some(ix) = line.index_for_x(x) {
4166 (ix as u32, px(0.))
4167 } else {
4168 (line.len as u32, px(0.).max(x - line.width))
4169 }
4170 } else {
4171 (0, x)
4172 };
4173
4174 let mut exact_unclipped = DisplayPoint::new(row, column);
4175 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4176 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4177
4178 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4179 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4180 PointForPosition {
4181 previous_valid,
4182 next_valid,
4183 exact_unclipped,
4184 column_overshoot_after_line_end,
4185 }
4186 }
4187}
4188
4189struct BlockLayout {
4190 row: u32,
4191 element: AnyElement,
4192 available_space: Size<AvailableSpace>,
4193 style: BlockStyle,
4194}
4195
4196fn layout_line(
4197 row: u32,
4198 snapshot: &EditorSnapshot,
4199 style: &EditorStyle,
4200 cx: &WindowContext,
4201) -> Result<ShapedLine> {
4202 let mut line = snapshot.line(row);
4203
4204 if line.len() > MAX_LINE_LEN {
4205 let mut len = MAX_LINE_LEN;
4206 while !line.is_char_boundary(len) {
4207 len -= 1;
4208 }
4209
4210 line.truncate(len);
4211 }
4212
4213 cx.text_system().shape_line(
4214 line.into(),
4215 style.text.font_size.to_pixels(cx.rem_size()),
4216 &[TextRun {
4217 len: snapshot.line_len(row) as usize,
4218 font: style.text.font(),
4219 color: Hsla::default(),
4220 background_color: None,
4221 underline: None,
4222 strikethrough: None,
4223 }],
4224 )
4225}
4226
4227pub struct CursorLayout {
4228 origin: gpui::Point<Pixels>,
4229 block_width: Pixels,
4230 line_height: Pixels,
4231 color: Hsla,
4232 shape: CursorShape,
4233 block_text: Option<ShapedLine>,
4234 cursor_name: Option<AnyElement>,
4235}
4236
4237#[derive(Debug)]
4238pub struct CursorName {
4239 string: SharedString,
4240 color: Hsla,
4241 is_top_row: bool,
4242}
4243
4244impl CursorLayout {
4245 pub fn new(
4246 origin: gpui::Point<Pixels>,
4247 block_width: Pixels,
4248 line_height: Pixels,
4249 color: Hsla,
4250 shape: CursorShape,
4251 block_text: Option<ShapedLine>,
4252 ) -> CursorLayout {
4253 CursorLayout {
4254 origin,
4255 block_width,
4256 line_height,
4257 color,
4258 shape,
4259 block_text,
4260 cursor_name: None,
4261 }
4262 }
4263
4264 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4265 Bounds {
4266 origin: self.origin + origin,
4267 size: size(self.block_width, self.line_height),
4268 }
4269 }
4270
4271 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4272 match self.shape {
4273 CursorShape::Bar => Bounds {
4274 origin: self.origin + origin,
4275 size: size(px(2.0), self.line_height),
4276 },
4277 CursorShape::Block | CursorShape::Hollow => Bounds {
4278 origin: self.origin + origin,
4279 size: size(self.block_width, self.line_height),
4280 },
4281 CursorShape::Underscore => Bounds {
4282 origin: self.origin
4283 + origin
4284 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4285 size: size(self.block_width, px(2.0)),
4286 },
4287 }
4288 }
4289
4290 pub fn layout(
4291 &mut self,
4292 origin: gpui::Point<Pixels>,
4293 cursor_name: Option<CursorName>,
4294 cx: &mut ElementContext,
4295 ) {
4296 if let Some(cursor_name) = cursor_name {
4297 let bounds = self.bounds(origin);
4298 let text_size = self.line_height / 1.5;
4299
4300 let name_origin = if cursor_name.is_top_row {
4301 point(bounds.right() - px(1.), bounds.top())
4302 } else {
4303 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4304 };
4305 let mut name_element = div()
4306 .bg(self.color)
4307 .text_size(text_size)
4308 .px_0p5()
4309 .line_height(text_size + px(2.))
4310 .text_color(cursor_name.color)
4311 .child(cursor_name.string.clone())
4312 .into_any_element();
4313
4314 name_element.layout(
4315 name_origin,
4316 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4317 cx,
4318 );
4319
4320 self.cursor_name = Some(name_element);
4321 }
4322 }
4323
4324 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
4325 let bounds = self.bounds(origin);
4326
4327 //Draw background or border quad
4328 let cursor = if matches!(self.shape, CursorShape::Hollow) {
4329 outline(bounds, self.color)
4330 } else {
4331 fill(bounds, self.color)
4332 };
4333
4334 if let Some(name) = &mut self.cursor_name {
4335 name.paint(cx);
4336 }
4337
4338 cx.paint_quad(cursor);
4339
4340 if let Some(block_text) = &self.block_text {
4341 block_text
4342 .paint(self.origin + origin, self.line_height, cx)
4343 .log_err();
4344 }
4345 }
4346
4347 pub fn shape(&self) -> CursorShape {
4348 self.shape
4349 }
4350}
4351
4352#[derive(Debug)]
4353pub struct HighlightedRange {
4354 pub start_y: Pixels,
4355 pub line_height: Pixels,
4356 pub lines: Vec<HighlightedRangeLine>,
4357 pub color: Hsla,
4358 pub corner_radius: Pixels,
4359}
4360
4361#[derive(Debug)]
4362pub struct HighlightedRangeLine {
4363 pub start_x: Pixels,
4364 pub end_x: Pixels,
4365}
4366
4367impl HighlightedRange {
4368 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
4369 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4370 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4371 self.paint_lines(
4372 self.start_y + self.line_height,
4373 &self.lines[1..],
4374 bounds,
4375 cx,
4376 );
4377 } else {
4378 self.paint_lines(self.start_y, &self.lines, bounds, cx);
4379 }
4380 }
4381
4382 fn paint_lines(
4383 &self,
4384 start_y: Pixels,
4385 lines: &[HighlightedRangeLine],
4386 _bounds: Bounds<Pixels>,
4387 cx: &mut ElementContext,
4388 ) {
4389 if lines.is_empty() {
4390 return;
4391 }
4392
4393 let first_line = lines.first().unwrap();
4394 let last_line = lines.last().unwrap();
4395
4396 let first_top_left = point(first_line.start_x, start_y);
4397 let first_top_right = point(first_line.end_x, start_y);
4398
4399 let curve_height = point(Pixels::ZERO, self.corner_radius);
4400 let curve_width = |start_x: Pixels, end_x: Pixels| {
4401 let max = (end_x - start_x) / 2.;
4402 let width = if max < self.corner_radius {
4403 max
4404 } else {
4405 self.corner_radius
4406 };
4407
4408 point(width, Pixels::ZERO)
4409 };
4410
4411 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4412 let mut path = gpui::Path::new(first_top_right - top_curve_width);
4413 path.curve_to(first_top_right + curve_height, first_top_right);
4414
4415 let mut iter = lines.iter().enumerate().peekable();
4416 while let Some((ix, line)) = iter.next() {
4417 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4418
4419 if let Some((_, next_line)) = iter.peek() {
4420 let next_top_right = point(next_line.end_x, bottom_right.y);
4421
4422 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4423 Ordering::Equal => {
4424 path.line_to(bottom_right);
4425 }
4426 Ordering::Less => {
4427 let curve_width = curve_width(next_top_right.x, bottom_right.x);
4428 path.line_to(bottom_right - curve_height);
4429 if self.corner_radius > Pixels::ZERO {
4430 path.curve_to(bottom_right - curve_width, bottom_right);
4431 }
4432 path.line_to(next_top_right + curve_width);
4433 if self.corner_radius > Pixels::ZERO {
4434 path.curve_to(next_top_right + curve_height, next_top_right);
4435 }
4436 }
4437 Ordering::Greater => {
4438 let curve_width = curve_width(bottom_right.x, next_top_right.x);
4439 path.line_to(bottom_right - curve_height);
4440 if self.corner_radius > Pixels::ZERO {
4441 path.curve_to(bottom_right + curve_width, bottom_right);
4442 }
4443 path.line_to(next_top_right - curve_width);
4444 if self.corner_radius > Pixels::ZERO {
4445 path.curve_to(next_top_right + curve_height, next_top_right);
4446 }
4447 }
4448 }
4449 } else {
4450 let curve_width = curve_width(line.start_x, line.end_x);
4451 path.line_to(bottom_right - curve_height);
4452 if self.corner_radius > Pixels::ZERO {
4453 path.curve_to(bottom_right - curve_width, bottom_right);
4454 }
4455
4456 let bottom_left = point(line.start_x, bottom_right.y);
4457 path.line_to(bottom_left + curve_width);
4458 if self.corner_radius > Pixels::ZERO {
4459 path.curve_to(bottom_left - curve_height, bottom_left);
4460 }
4461 }
4462 }
4463
4464 if first_line.start_x > last_line.start_x {
4465 let curve_width = curve_width(last_line.start_x, first_line.start_x);
4466 let second_top_left = point(last_line.start_x, start_y + self.line_height);
4467 path.line_to(second_top_left + curve_height);
4468 if self.corner_radius > Pixels::ZERO {
4469 path.curve_to(second_top_left + curve_width, second_top_left);
4470 }
4471 let first_bottom_left = point(first_line.start_x, second_top_left.y);
4472 path.line_to(first_bottom_left - curve_width);
4473 if self.corner_radius > Pixels::ZERO {
4474 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4475 }
4476 }
4477
4478 path.line_to(first_top_left + curve_height);
4479 if self.corner_radius > Pixels::ZERO {
4480 path.curve_to(first_top_left + top_curve_width, first_top_left);
4481 }
4482 path.line_to(first_top_right - top_curve_width);
4483
4484 cx.paint_path(path, self.color);
4485 }
4486}
4487
4488pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4489 (delta.pow(1.5) / 100.0).into()
4490}
4491
4492fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4493 (delta.pow(1.2) / 300.0).into()
4494}
4495
4496#[cfg(test)]
4497mod tests {
4498 use super::*;
4499 use crate::{
4500 display_map::{BlockDisposition, BlockProperties},
4501 editor_tests::{init_test, update_test_language_settings},
4502 Editor, MultiBuffer,
4503 };
4504 use gpui::TestAppContext;
4505 use language::language_settings;
4506 use log::info;
4507 use std::num::NonZeroU32;
4508 use util::test::sample_text;
4509
4510 #[gpui::test]
4511 fn test_shape_line_numbers(cx: &mut TestAppContext) {
4512 init_test(cx, |_| {});
4513 let window = cx.add_window(|cx| {
4514 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4515 Editor::new(EditorMode::Full, buffer, None, cx)
4516 });
4517
4518 let editor = window.root(cx).unwrap();
4519 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4520 let element = EditorElement::new(&editor, style);
4521 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4522
4523 let layouts = cx
4524 .update_window(*window, |_, cx| {
4525 cx.with_element_context(|cx| {
4526 element
4527 .layout_line_numbers(
4528 0..6,
4529 (0..6).map(Some),
4530 &Default::default(),
4531 Some(DisplayPoint::new(0, 0)),
4532 &snapshot,
4533 cx,
4534 )
4535 .0
4536 })
4537 })
4538 .unwrap();
4539 assert_eq!(layouts.len(), 6);
4540
4541 let relative_rows =
4542 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..6), Some(3));
4543 assert_eq!(relative_rows[&0], 3);
4544 assert_eq!(relative_rows[&1], 2);
4545 assert_eq!(relative_rows[&2], 1);
4546 // current line has no relative number
4547 assert_eq!(relative_rows[&4], 1);
4548 assert_eq!(relative_rows[&5], 2);
4549
4550 // works if cursor is before screen
4551 let relative_rows =
4552 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(3..6), Some(1));
4553 assert_eq!(relative_rows.len(), 3);
4554 assert_eq!(relative_rows[&3], 2);
4555 assert_eq!(relative_rows[&4], 3);
4556 assert_eq!(relative_rows[&5], 4);
4557
4558 // works if cursor is after screen
4559 let relative_rows =
4560 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..3), Some(6));
4561 assert_eq!(relative_rows.len(), 3);
4562 assert_eq!(relative_rows[&0], 5);
4563 assert_eq!(relative_rows[&1], 4);
4564 assert_eq!(relative_rows[&2], 3);
4565 }
4566
4567 #[gpui::test]
4568 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4569 init_test(cx, |_| {});
4570
4571 let window = cx.add_window(|cx| {
4572 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4573 Editor::new(EditorMode::Full, buffer, None, cx)
4574 });
4575 let editor = window.root(cx).unwrap();
4576 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4577 let mut element = EditorElement::new(&editor, style);
4578
4579 window
4580 .update(cx, |editor, cx| {
4581 editor.cursor_shape = CursorShape::Block;
4582 editor.change_selections(None, cx, |s| {
4583 s.select_ranges([
4584 Point::new(0, 0)..Point::new(1, 0),
4585 Point::new(3, 2)..Point::new(3, 3),
4586 Point::new(5, 6)..Point::new(6, 0),
4587 ]);
4588 });
4589 })
4590 .unwrap();
4591 let state = cx
4592 .update_window(window.into(), |_view, cx| {
4593 cx.with_element_context(|cx| {
4594 element.after_layout(
4595 Bounds {
4596 origin: point(px(500.), px(500.)),
4597 size: size(px(500.), px(500.)),
4598 },
4599 &mut (),
4600 cx,
4601 )
4602 })
4603 })
4604 .unwrap();
4605
4606 assert_eq!(state.selections.len(), 1);
4607 let local_selections = &state.selections[0].1;
4608 assert_eq!(local_selections.len(), 3);
4609 // moves cursor back one line
4610 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4611 assert_eq!(
4612 local_selections[0].range,
4613 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4614 );
4615
4616 // moves cursor back one column
4617 assert_eq!(
4618 local_selections[1].range,
4619 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4620 );
4621 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4622
4623 // leaves cursor on the max point
4624 assert_eq!(
4625 local_selections[2].range,
4626 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4627 );
4628 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4629
4630 // active lines does not include 1 (even though the range of the selection does)
4631 assert_eq!(
4632 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4633 vec![0, 3, 5, 6]
4634 );
4635
4636 // multi-buffer support
4637 // in DisplayPoint coordinates, this is what we're dealing with:
4638 // 0: [[file
4639 // 1: header]]
4640 // 2: aaaaaa
4641 // 3: bbbbbb
4642 // 4: cccccc
4643 // 5:
4644 // 6: ...
4645 // 7: ffffff
4646 // 8: gggggg
4647 // 9: hhhhhh
4648 // 10:
4649 // 11: [[file
4650 // 12: header]]
4651 // 13: bbbbbb
4652 // 14: cccccc
4653 // 15: dddddd
4654 let window = cx.add_window(|cx| {
4655 let buffer = MultiBuffer::build_multi(
4656 [
4657 (
4658 &(sample_text(8, 6, 'a') + "\n"),
4659 vec![
4660 Point::new(0, 0)..Point::new(3, 0),
4661 Point::new(4, 0)..Point::new(7, 0),
4662 ],
4663 ),
4664 (
4665 &(sample_text(8, 6, 'a') + "\n"),
4666 vec![Point::new(1, 0)..Point::new(3, 0)],
4667 ),
4668 ],
4669 cx,
4670 );
4671 Editor::new(EditorMode::Full, buffer, None, cx)
4672 });
4673 let editor = window.root(cx).unwrap();
4674 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4675 let mut element = EditorElement::new(&editor, style);
4676 let _state = window.update(cx, |editor, cx| {
4677 editor.cursor_shape = CursorShape::Block;
4678 editor.change_selections(None, cx, |s| {
4679 s.select_display_ranges([
4680 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4681 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4682 ]);
4683 });
4684 });
4685
4686 let state = cx
4687 .update_window(window.into(), |_view, cx| {
4688 cx.with_element_context(|cx| {
4689 element.after_layout(
4690 Bounds {
4691 origin: point(px(500.), px(500.)),
4692 size: size(px(500.), px(500.)),
4693 },
4694 &mut (),
4695 cx,
4696 )
4697 })
4698 })
4699 .unwrap();
4700 assert_eq!(state.selections.len(), 1);
4701 let local_selections = &state.selections[0].1;
4702 assert_eq!(local_selections.len(), 2);
4703
4704 // moves cursor on excerpt boundary back a line
4705 // and doesn't allow selection to bleed through
4706 assert_eq!(
4707 local_selections[0].range,
4708 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4709 );
4710 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4711 // moves cursor on buffer boundary back two lines
4712 // and doesn't allow selection to bleed through
4713 assert_eq!(
4714 local_selections[1].range,
4715 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4716 );
4717 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4718 }
4719
4720 #[gpui::test]
4721 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4722 init_test(cx, |_| {});
4723
4724 let window = cx.add_window(|cx| {
4725 let buffer = MultiBuffer::build_simple("", cx);
4726 Editor::new(EditorMode::Full, buffer, None, cx)
4727 });
4728 let editor = window.root(cx).unwrap();
4729 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4730 window
4731 .update(cx, |editor, cx| {
4732 editor.set_placeholder_text("hello", cx);
4733 editor.insert_blocks(
4734 [BlockProperties {
4735 style: BlockStyle::Fixed,
4736 disposition: BlockDisposition::Above,
4737 height: 3,
4738 position: Anchor::min(),
4739 render: Box::new(|_| div().into_any()),
4740 }],
4741 None,
4742 cx,
4743 );
4744
4745 // Blur the editor so that it displays placeholder text.
4746 cx.blur();
4747 })
4748 .unwrap();
4749
4750 let mut element = EditorElement::new(&editor, style);
4751 let state = cx
4752 .update_window(window.into(), |_view, cx| {
4753 cx.with_element_context(|cx| {
4754 element.after_layout(
4755 Bounds {
4756 origin: point(px(500.), px(500.)),
4757 size: size(px(500.), px(500.)),
4758 },
4759 &mut (),
4760 cx,
4761 )
4762 })
4763 })
4764 .unwrap();
4765
4766 assert_eq!(state.position_map.line_layouts.len(), 4);
4767 assert_eq!(
4768 state
4769 .line_numbers
4770 .iter()
4771 .map(Option::is_some)
4772 .collect::<Vec<_>>(),
4773 &[false, false, false, true]
4774 );
4775 }
4776
4777 #[gpui::test]
4778 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4779 const TAB_SIZE: u32 = 4;
4780
4781 let input_text = "\t \t|\t| a b";
4782 let expected_invisibles = vec![
4783 Invisible::Tab {
4784 line_start_offset: 0,
4785 },
4786 Invisible::Whitespace {
4787 line_offset: TAB_SIZE as usize,
4788 },
4789 Invisible::Tab {
4790 line_start_offset: TAB_SIZE as usize + 1,
4791 },
4792 Invisible::Tab {
4793 line_start_offset: TAB_SIZE as usize * 2 + 1,
4794 },
4795 Invisible::Whitespace {
4796 line_offset: TAB_SIZE as usize * 3 + 1,
4797 },
4798 Invisible::Whitespace {
4799 line_offset: TAB_SIZE as usize * 3 + 3,
4800 },
4801 ];
4802 assert_eq!(
4803 expected_invisibles.len(),
4804 input_text
4805 .chars()
4806 .filter(|initial_char| initial_char.is_whitespace())
4807 .count(),
4808 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4809 );
4810
4811 init_test(cx, |s| {
4812 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4813 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4814 });
4815
4816 let actual_invisibles =
4817 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4818
4819 assert_eq!(expected_invisibles, actual_invisibles);
4820 }
4821
4822 #[gpui::test]
4823 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4824 init_test(cx, |s| {
4825 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4826 s.defaults.tab_size = NonZeroU32::new(4);
4827 });
4828
4829 for editor_mode_without_invisibles in [
4830 EditorMode::SingleLine,
4831 EditorMode::AutoHeight { max_lines: 100 },
4832 ] {
4833 let invisibles = collect_invisibles_from_new_editor(
4834 cx,
4835 editor_mode_without_invisibles,
4836 "\t\t\t| | a b",
4837 px(500.0),
4838 );
4839 assert!(invisibles.is_empty(),
4840 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4841 }
4842 }
4843
4844 #[gpui::test]
4845 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4846 let tab_size = 4;
4847 let input_text = "a\tbcd ".repeat(9);
4848 let repeated_invisibles = [
4849 Invisible::Tab {
4850 line_start_offset: 1,
4851 },
4852 Invisible::Whitespace {
4853 line_offset: tab_size as usize + 3,
4854 },
4855 Invisible::Whitespace {
4856 line_offset: tab_size as usize + 4,
4857 },
4858 Invisible::Whitespace {
4859 line_offset: tab_size as usize + 5,
4860 },
4861 ];
4862 let expected_invisibles = std::iter::once(repeated_invisibles)
4863 .cycle()
4864 .take(9)
4865 .flatten()
4866 .collect::<Vec<_>>();
4867 assert_eq!(
4868 expected_invisibles.len(),
4869 input_text
4870 .chars()
4871 .filter(|initial_char| initial_char.is_whitespace())
4872 .count(),
4873 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4874 );
4875 info!("Expected invisibles: {expected_invisibles:?}");
4876
4877 init_test(cx, |_| {});
4878
4879 // Put the same string with repeating whitespace pattern into editors of various size,
4880 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4881 let resize_step = 10.0;
4882 let mut editor_width = 200.0;
4883 while editor_width <= 1000.0 {
4884 update_test_language_settings(cx, |s| {
4885 s.defaults.tab_size = NonZeroU32::new(tab_size);
4886 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4887 s.defaults.preferred_line_length = Some(editor_width as u32);
4888 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4889 });
4890
4891 let actual_invisibles = collect_invisibles_from_new_editor(
4892 cx,
4893 EditorMode::Full,
4894 &input_text,
4895 px(editor_width),
4896 );
4897
4898 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4899 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4900 let mut i = 0;
4901 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4902 i = actual_index;
4903 match expected_invisibles.get(i) {
4904 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4905 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4906 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4907 _ => {
4908 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4909 }
4910 },
4911 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4912 }
4913 }
4914 let missing_expected_invisibles = &expected_invisibles[i + 1..];
4915 assert!(
4916 missing_expected_invisibles.is_empty(),
4917 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4918 );
4919
4920 editor_width += resize_step;
4921 }
4922 }
4923
4924 fn collect_invisibles_from_new_editor(
4925 cx: &mut TestAppContext,
4926 editor_mode: EditorMode,
4927 input_text: &str,
4928 editor_width: Pixels,
4929 ) -> Vec<Invisible> {
4930 info!(
4931 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4932 editor_width.0
4933 );
4934 let window = cx.add_window(|cx| {
4935 let buffer = MultiBuffer::build_simple(&input_text, cx);
4936 Editor::new(editor_mode, buffer, None, cx)
4937 });
4938 let editor = window.root(cx).unwrap();
4939 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4940 let mut element = EditorElement::new(&editor, style);
4941 window
4942 .update(cx, |editor, cx| {
4943 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4944 editor.set_wrap_width(Some(editor_width), cx);
4945 })
4946 .unwrap();
4947 let layout_state = cx
4948 .update_window(window.into(), |_, cx| {
4949 cx.with_element_context(|cx| {
4950 element.after_layout(
4951 Bounds {
4952 origin: point(px(500.), px(500.)),
4953 size: size(px(500.), px(500.)),
4954 },
4955 &mut (),
4956 cx,
4957 )
4958 })
4959 })
4960 .unwrap();
4961
4962 layout_state
4963 .position_map
4964 .line_layouts
4965 .iter()
4966 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4967 .cloned()
4968 .collect()
4969 }
4970}
4971
4972pub fn register_action<T: Action>(
4973 view: &View<Editor>,
4974 cx: &mut WindowContext,
4975 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4976) {
4977 let view = view.clone();
4978 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4979 let action = action.downcast_ref().unwrap();
4980 if phase == DispatchPhase::Bubble {
4981 view.update(cx, |editor, cx| {
4982 listener(editor, action, cx);
4983 })
4984 }
4985 })
4986}
4987
4988fn compute_auto_height_layout(
4989 editor: &mut Editor,
4990 max_lines: usize,
4991 max_line_number_width: Pixels,
4992 known_dimensions: Size<Option<Pixels>>,
4993 cx: &mut ViewContext<Editor>,
4994) -> Option<Size<Pixels>> {
4995 let width = known_dimensions.width?;
4996 if let Some(height) = known_dimensions.height {
4997 return Some(size(width, height));
4998 }
4999
5000 let style = editor.style.as_ref().unwrap();
5001 let font_id = cx.text_system().resolve_font(&style.text.font());
5002 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5003 let line_height = style.text.line_height_in_pixels(cx.rem_size());
5004 let em_width = cx
5005 .text_system()
5006 .typographic_bounds(font_id, font_size, 'm')
5007 .unwrap()
5008 .size
5009 .width;
5010
5011 let mut snapshot = editor.snapshot(cx);
5012 let gutter_dimensions =
5013 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5014
5015 editor.gutter_width = gutter_dimensions.width;
5016 let text_width = width - gutter_dimensions.width;
5017 let overscroll = size(em_width, px(0.));
5018
5019 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5020 if editor.set_wrap_width(Some(editor_width), cx) {
5021 snapshot = editor.snapshot(cx);
5022 }
5023
5024 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5025 let height = scroll_height
5026 .max(line_height)
5027 .min(line_height * max_lines as f32);
5028
5029 Some(size(width, height))
5030}