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