1use crate::editor_settings::ScrollBeyondLastLine;
2use crate::{
3 blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
4 display_map::{
5 BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint, TransformBlock,
6 },
7 editor_settings::{
8 CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar,
9 },
10 git::{
11 blame::{CommitDetails, GitBlame},
12 diff_hunk_to_display, DisplayDiffHunk,
13 },
14 hover_popover::{
15 self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
16 },
17 hunk_status,
18 items::BufferSearchHighlights,
19 mouse_context_menu::{self, MouseContextMenu},
20 scroll::scroll_amount::ScrollAmount,
21 CodeActionsMenu, CursorShape, DisplayPoint, DisplayRow, DocumentHighlightRead,
22 DocumentHighlightWrite, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle,
23 ExpandExcerpts, GutterDimensions, HalfPageDown, HalfPageUp, HoveredCursor, HunkToExpand,
24 LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, RowExt, RowRangeExt, SelectPhase,
25 Selection, SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
26};
27use client::ParticipantIndex;
28use collections::{BTreeMap, HashMap};
29use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
30use gpui::{
31 anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
32 transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
33 ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity,
34 FontId, GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, Length,
35 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
36 ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
37 StatefulInteractiveElement, Style, Styled, TextRun, TextStyle, TextStyleRefinement, View,
38 ViewContext, WeakView, WindowContext,
39};
40use itertools::Itertools;
41use language::language_settings::{
42 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
43};
44use lsp::DiagnosticSeverity;
45use multi_buffer::{Anchor, MultiBufferPoint, MultiBufferRow};
46use project::{
47 project_settings::{GitGutterSetting, ProjectSettings},
48 ProjectPath,
49};
50use settings::Settings;
51use smallvec::{smallvec, SmallVec};
52use std::{
53 any::TypeId,
54 borrow::Cow,
55 cmp::{self, Ordering},
56 fmt::{self, Write},
57 iter, mem,
58 ops::{Deref, Range},
59 sync::Arc,
60};
61use sum_tree::Bias;
62use theme::{ActiveTheme, PlayerColor};
63use ui::prelude::*;
64use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
65use util::ResultExt;
66use workspace::{item::Item, Workspace};
67
68struct SelectionLayout {
69 head: DisplayPoint,
70 cursor_shape: CursorShape,
71 is_newest: bool,
72 is_local: bool,
73 range: Range<DisplayPoint>,
74 active_rows: Range<DisplayRow>,
75 user_name: Option<SharedString>,
76}
77
78impl SelectionLayout {
79 fn new<T: ToPoint + ToDisplayPoint + Clone>(
80 selection: Selection<T>,
81 line_mode: bool,
82 cursor_shape: CursorShape,
83 map: &DisplaySnapshot,
84 is_newest: bool,
85 is_local: bool,
86 user_name: Option<SharedString>,
87 ) -> Self {
88 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
89 let display_selection = point_selection.map(|p| p.to_display_point(map));
90 let mut range = display_selection.range();
91 let mut head = display_selection.head();
92 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
93 ..map.next_line_boundary(point_selection.end).1.row();
94
95 // vim visual line mode
96 if line_mode {
97 let point_range = map.expand_to_line(point_selection.range());
98 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
99 }
100
101 // any vim visual mode (including line mode)
102 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
103 && !range.is_empty()
104 && !selection.reversed
105 {
106 if head.column() > 0 {
107 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
108 } else if head.row().0 > 0 && head != map.max_point() {
109 head = map.clip_point(
110 DisplayPoint::new(
111 head.row().previous_row(),
112 map.line_len(head.row().previous_row()),
113 ),
114 Bias::Left,
115 );
116 // updating range.end is a no-op unless you're cursor is
117 // on the newline containing a multi-buffer divider
118 // in which case the clip_point may have moved the head up
119 // an additional row.
120 range.end = DisplayPoint::new(head.row().next_row(), 0);
121 active_rows.end = head.row();
122 }
123 }
124
125 Self {
126 head,
127 cursor_shape,
128 is_newest,
129 is_local,
130 range,
131 active_rows,
132 user_name,
133 }
134 }
135}
136
137pub struct EditorElement {
138 editor: View<Editor>,
139 style: EditorStyle,
140}
141
142type DisplayRowDelta = u32;
143
144impl EditorElement {
145 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(13.);
146
147 pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
148 Self {
149 editor: editor.clone(),
150 style,
151 }
152 }
153
154 fn register_actions(&self, cx: &mut WindowContext) {
155 let view = &self.editor;
156 view.update(cx, |editor, cx| {
157 for action in editor.editor_actions.borrow().values() {
158 (action)(cx)
159 }
160 });
161
162 crate::rust_analyzer_ext::apply_related_actions(view, cx);
163 register_action(view, cx, Editor::move_left);
164 register_action(view, cx, Editor::move_right);
165 register_action(view, cx, Editor::move_down);
166 register_action(view, cx, Editor::move_down_by_lines);
167 register_action(view, cx, Editor::select_down_by_lines);
168 register_action(view, cx, Editor::move_up);
169 register_action(view, cx, Editor::move_up_by_lines);
170 register_action(view, cx, Editor::select_up_by_lines);
171 register_action(view, cx, Editor::select_page_down);
172 register_action(view, cx, Editor::select_page_up);
173 register_action(view, cx, Editor::cancel);
174 register_action(view, cx, Editor::newline);
175 register_action(view, cx, Editor::newline_above);
176 register_action(view, cx, Editor::newline_below);
177 register_action(view, cx, Editor::backspace);
178 register_action(view, cx, Editor::delete);
179 register_action(view, cx, Editor::tab);
180 register_action(view, cx, Editor::tab_prev);
181 register_action(view, cx, Editor::indent);
182 register_action(view, cx, Editor::outdent);
183 register_action(view, cx, Editor::delete_line);
184 register_action(view, cx, Editor::join_lines);
185 register_action(view, cx, Editor::sort_lines_case_sensitive);
186 register_action(view, cx, Editor::sort_lines_case_insensitive);
187 register_action(view, cx, Editor::reverse_lines);
188 register_action(view, cx, Editor::shuffle_lines);
189 register_action(view, cx, Editor::convert_to_upper_case);
190 register_action(view, cx, Editor::convert_to_lower_case);
191 register_action(view, cx, Editor::convert_to_title_case);
192 register_action(view, cx, Editor::convert_to_snake_case);
193 register_action(view, cx, Editor::convert_to_kebab_case);
194 register_action(view, cx, Editor::convert_to_upper_camel_case);
195 register_action(view, cx, Editor::convert_to_lower_camel_case);
196 register_action(view, cx, Editor::convert_to_opposite_case);
197 register_action(view, cx, Editor::delete_to_previous_word_start);
198 register_action(view, cx, Editor::delete_to_previous_subword_start);
199 register_action(view, cx, Editor::delete_to_next_word_end);
200 register_action(view, cx, Editor::delete_to_next_subword_end);
201 register_action(view, cx, Editor::delete_to_beginning_of_line);
202 register_action(view, cx, Editor::delete_to_end_of_line);
203 register_action(view, cx, Editor::cut_to_end_of_line);
204 register_action(view, cx, Editor::duplicate_line_up);
205 register_action(view, cx, Editor::duplicate_line_down);
206 register_action(view, cx, Editor::move_line_up);
207 register_action(view, cx, Editor::move_line_down);
208 register_action(view, cx, Editor::transpose);
209 register_action(view, cx, Editor::cut);
210 register_action(view, cx, Editor::copy);
211 register_action(view, cx, Editor::paste);
212 register_action(view, cx, Editor::undo);
213 register_action(view, cx, Editor::redo);
214 register_action(view, cx, Editor::move_page_up);
215 register_action(view, cx, Editor::move_page_down);
216 register_action(view, cx, Editor::next_screen);
217 register_action(view, cx, Editor::scroll_cursor_top);
218 register_action(view, cx, Editor::scroll_cursor_center);
219 register_action(view, cx, Editor::scroll_cursor_bottom);
220 register_action(view, cx, |editor, _: &LineDown, cx| {
221 editor.scroll_screen(&ScrollAmount::Line(1.), cx)
222 });
223 register_action(view, cx, |editor, _: &LineUp, cx| {
224 editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
225 });
226 register_action(view, cx, |editor, _: &HalfPageDown, cx| {
227 editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
228 });
229 register_action(view, cx, |editor, _: &HalfPageUp, cx| {
230 editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
231 });
232 register_action(view, cx, |editor, _: &PageDown, cx| {
233 editor.scroll_screen(&ScrollAmount::Page(1.), cx)
234 });
235 register_action(view, cx, |editor, _: &PageUp, cx| {
236 editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
237 });
238 register_action(view, cx, Editor::move_to_previous_word_start);
239 register_action(view, cx, Editor::move_to_previous_subword_start);
240 register_action(view, cx, Editor::move_to_next_word_end);
241 register_action(view, cx, Editor::move_to_next_subword_end);
242 register_action(view, cx, Editor::move_to_beginning_of_line);
243 register_action(view, cx, Editor::move_to_end_of_line);
244 register_action(view, cx, Editor::move_to_start_of_paragraph);
245 register_action(view, cx, Editor::move_to_end_of_paragraph);
246 register_action(view, cx, Editor::move_to_beginning);
247 register_action(view, cx, Editor::move_to_end);
248 register_action(view, cx, Editor::select_up);
249 register_action(view, cx, Editor::select_down);
250 register_action(view, cx, Editor::select_left);
251 register_action(view, cx, Editor::select_right);
252 register_action(view, cx, Editor::select_to_previous_word_start);
253 register_action(view, cx, Editor::select_to_previous_subword_start);
254 register_action(view, cx, Editor::select_to_next_word_end);
255 register_action(view, cx, Editor::select_to_next_subword_end);
256 register_action(view, cx, Editor::select_to_beginning_of_line);
257 register_action(view, cx, Editor::select_to_end_of_line);
258 register_action(view, cx, Editor::select_to_start_of_paragraph);
259 register_action(view, cx, Editor::select_to_end_of_paragraph);
260 register_action(view, cx, Editor::select_to_beginning);
261 register_action(view, cx, Editor::select_to_end);
262 register_action(view, cx, Editor::select_all);
263 register_action(view, cx, |editor, action, cx| {
264 editor.select_all_matches(action, cx).log_err();
265 });
266 register_action(view, cx, Editor::select_line);
267 register_action(view, cx, Editor::split_selection_into_lines);
268 register_action(view, cx, Editor::add_selection_above);
269 register_action(view, cx, Editor::add_selection_below);
270 register_action(view, cx, |editor, action, cx| {
271 editor.select_next(action, cx).log_err();
272 });
273 register_action(view, cx, |editor, action, cx| {
274 editor.select_previous(action, cx).log_err();
275 });
276 register_action(view, cx, Editor::toggle_comments);
277 register_action(view, cx, Editor::select_larger_syntax_node);
278 register_action(view, cx, Editor::select_smaller_syntax_node);
279 register_action(view, cx, Editor::select_enclosing_symbol);
280 register_action(view, cx, Editor::move_to_enclosing_bracket);
281 register_action(view, cx, Editor::undo_selection);
282 register_action(view, cx, Editor::redo_selection);
283 if !view.read(cx).is_singleton(cx) {
284 register_action(view, cx, Editor::expand_excerpts);
285 register_action(view, cx, Editor::expand_excerpts_up);
286 register_action(view, cx, Editor::expand_excerpts_down);
287 }
288 register_action(view, cx, Editor::go_to_diagnostic);
289 register_action(view, cx, Editor::go_to_prev_diagnostic);
290 register_action(view, cx, Editor::go_to_hunk);
291 register_action(view, cx, Editor::go_to_prev_hunk);
292 register_action(view, cx, |editor, a, cx| {
293 editor.go_to_definition(a, cx).detach_and_log_err(cx);
294 });
295 register_action(view, cx, |editor, a, cx| {
296 editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
297 });
298 register_action(view, cx, |editor, a, cx| {
299 editor.go_to_implementation(a, cx).detach_and_log_err(cx);
300 });
301 register_action(view, cx, |editor, a, cx| {
302 editor
303 .go_to_implementation_split(a, cx)
304 .detach_and_log_err(cx);
305 });
306 register_action(view, cx, |editor, a, cx| {
307 editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
308 });
309 register_action(view, cx, |editor, a, cx| {
310 editor
311 .go_to_type_definition_split(a, cx)
312 .detach_and_log_err(cx);
313 });
314 register_action(view, cx, Editor::open_url);
315 register_action(view, cx, Editor::fold);
316 register_action(view, cx, Editor::fold_at);
317 register_action(view, cx, Editor::unfold_lines);
318 register_action(view, cx, Editor::unfold_at);
319 register_action(view, cx, Editor::fold_selected_ranges);
320 register_action(view, cx, Editor::show_completions);
321 register_action(view, cx, Editor::toggle_code_actions);
322 register_action(view, cx, Editor::open_excerpts);
323 register_action(view, cx, Editor::open_excerpts_in_split);
324 register_action(view, cx, Editor::toggle_soft_wrap);
325 register_action(view, cx, Editor::toggle_tab_bar);
326 register_action(view, cx, Editor::toggle_line_numbers);
327 register_action(view, cx, Editor::toggle_indent_guides);
328 register_action(view, cx, Editor::toggle_inlay_hints);
329 register_action(view, cx, hover_popover::hover);
330 register_action(view, cx, Editor::reveal_in_finder);
331 register_action(view, cx, Editor::copy_path);
332 register_action(view, cx, Editor::copy_relative_path);
333 register_action(view, cx, Editor::copy_highlight_json);
334 register_action(view, cx, Editor::copy_permalink_to_line);
335 register_action(view, cx, Editor::open_permalink_to_line);
336 register_action(view, cx, Editor::toggle_git_blame);
337 register_action(view, cx, Editor::toggle_git_blame_inline);
338 register_action(view, cx, Editor::toggle_hunk_diff);
339 register_action(view, cx, Editor::expand_all_hunk_diffs);
340 register_action(view, cx, |editor, action, cx| {
341 if let Some(task) = editor.format(action, cx) {
342 task.detach_and_log_err(cx);
343 } else {
344 cx.propagate();
345 }
346 });
347 register_action(view, cx, Editor::restart_language_server);
348 register_action(view, cx, Editor::cancel_language_server_work);
349 register_action(view, cx, Editor::show_character_palette);
350 register_action(view, cx, |editor, action, cx| {
351 if let Some(task) = editor.confirm_completion(action, cx) {
352 task.detach_and_log_err(cx);
353 } else {
354 cx.propagate();
355 }
356 });
357 register_action(view, cx, |editor, action, cx| {
358 if let Some(task) = editor.confirm_code_action(action, cx) {
359 task.detach_and_log_err(cx);
360 } else {
361 cx.propagate();
362 }
363 });
364 register_action(view, cx, |editor, action, cx| {
365 if let Some(task) = editor.rename(action, cx) {
366 task.detach_and_log_err(cx);
367 } else {
368 cx.propagate();
369 }
370 });
371 register_action(view, cx, |editor, action, cx| {
372 if let Some(task) = editor.confirm_rename(action, cx) {
373 task.detach_and_log_err(cx);
374 } else {
375 cx.propagate();
376 }
377 });
378 register_action(view, cx, |editor, action, cx| {
379 if let Some(task) = editor.find_all_references(action, cx) {
380 task.detach_and_log_err(cx);
381 } else {
382 cx.propagate();
383 }
384 });
385 register_action(view, cx, Editor::next_inline_completion);
386 register_action(view, cx, Editor::previous_inline_completion);
387 register_action(view, cx, Editor::show_inline_completion);
388 register_action(view, cx, Editor::context_menu_first);
389 register_action(view, cx, Editor::context_menu_prev);
390 register_action(view, cx, Editor::context_menu_next);
391 register_action(view, cx, Editor::context_menu_last);
392 register_action(view, cx, Editor::display_cursor_names);
393 register_action(view, cx, Editor::unique_lines_case_insensitive);
394 register_action(view, cx, Editor::unique_lines_case_sensitive);
395 register_action(view, cx, Editor::accept_partial_inline_completion);
396 register_action(view, cx, Editor::accept_inline_completion);
397 register_action(view, cx, Editor::revert_selected_hunks);
398 register_action(view, cx, Editor::open_active_item_in_terminal)
399 }
400
401 fn register_key_listeners(&self, cx: &mut WindowContext, layout: &EditorLayout) {
402 let position_map = layout.position_map.clone();
403 cx.on_key_event({
404 let editor = self.editor.clone();
405 let text_hitbox = layout.text_hitbox.clone();
406 move |event: &ModifiersChangedEvent, phase, cx| {
407 if phase != DispatchPhase::Bubble {
408 return;
409 }
410
411 editor.update(cx, |editor, cx| {
412 Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
413 })
414 }
415 });
416 }
417
418 fn modifiers_changed(
419 editor: &mut Editor,
420 event: &ModifiersChangedEvent,
421 position_map: &PositionMap,
422 text_hitbox: &Hitbox,
423 cx: &mut ViewContext<Editor>,
424 ) {
425 let mouse_position = cx.mouse_position();
426 if !text_hitbox.is_hovered(cx) {
427 return;
428 }
429
430 editor.update_hovered_link(
431 position_map.point_for_position(text_hitbox.bounds, mouse_position),
432 &position_map.snapshot,
433 event.modifiers,
434 cx,
435 )
436 }
437
438 fn mouse_left_down(
439 editor: &mut Editor,
440 event: &MouseDownEvent,
441 hovered_hunk: Option<&HunkToExpand>,
442 position_map: &PositionMap,
443 text_hitbox: &Hitbox,
444 gutter_hitbox: &Hitbox,
445 cx: &mut ViewContext<Editor>,
446 ) {
447 if cx.default_prevented() {
448 return;
449 }
450
451 let mut click_count = event.click_count;
452 let mut modifiers = event.modifiers;
453
454 if let Some(hovered_hunk) = hovered_hunk {
455 editor.expand_diff_hunk(None, hovered_hunk, cx);
456 cx.notify();
457 return;
458 } else if gutter_hitbox.is_hovered(cx) {
459 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
460 } else if !text_hitbox.is_hovered(cx) {
461 return;
462 }
463
464 if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
465 match EditorSettings::get_global(cx).double_click_in_multibuffer {
466 DoubleClickInMultibuffer::Select => {
467 // do nothing special on double click, all selection logic is below
468 }
469 DoubleClickInMultibuffer::Open => {
470 if modifiers.alt {
471 // if double click is made with alt, pretend it's a regular double click without opening and alt,
472 // and run the selection logic.
473 modifiers.alt = false;
474 } else {
475 // if double click is made without alt, open the corresponding excerp
476 editor.open_excerpts(&OpenExcerpts, cx);
477 return;
478 }
479 }
480 }
481 }
482
483 let point_for_position =
484 position_map.point_for_position(text_hitbox.bounds, event.position);
485 let position = point_for_position.previous_valid;
486 if modifiers.shift && modifiers.alt {
487 editor.select(
488 SelectPhase::BeginColumnar {
489 position,
490 reset: false,
491 goal_column: point_for_position.exact_unclipped.column(),
492 },
493 cx,
494 );
495 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
496 {
497 editor.select(
498 SelectPhase::Extend {
499 position,
500 click_count,
501 },
502 cx,
503 );
504 } else {
505 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
506 let multi_cursor_modifier = match multi_cursor_setting {
507 MultiCursorModifier::Alt => modifiers.alt,
508 MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
509 };
510 editor.select(
511 SelectPhase::Begin {
512 position,
513 add: multi_cursor_modifier,
514 click_count,
515 },
516 cx,
517 );
518 }
519
520 cx.stop_propagation();
521 }
522
523 fn mouse_right_down(
524 editor: &mut Editor,
525 event: &MouseDownEvent,
526 position_map: &PositionMap,
527 text_hitbox: &Hitbox,
528 cx: &mut ViewContext<Editor>,
529 ) {
530 if !text_hitbox.is_hovered(cx) {
531 return;
532 }
533 let point_for_position =
534 position_map.point_for_position(text_hitbox.bounds, event.position);
535 mouse_context_menu::deploy_context_menu(
536 editor,
537 event.position,
538 point_for_position.previous_valid,
539 cx,
540 );
541 cx.stop_propagation();
542 }
543
544 fn mouse_middle_down(
545 editor: &mut Editor,
546 event: &MouseDownEvent,
547 position_map: &PositionMap,
548 text_hitbox: &Hitbox,
549 cx: &mut ViewContext<Editor>,
550 ) {
551 if !text_hitbox.is_hovered(cx) || cx.default_prevented() {
552 return;
553 }
554
555 let point_for_position =
556 position_map.point_for_position(text_hitbox.bounds, event.position);
557 let position = point_for_position.previous_valid;
558
559 editor.select(
560 SelectPhase::BeginColumnar {
561 position,
562 reset: true,
563 goal_column: point_for_position.exact_unclipped.column(),
564 },
565 cx,
566 );
567 }
568
569 fn mouse_up(
570 editor: &mut Editor,
571 event: &MouseUpEvent,
572 position_map: &PositionMap,
573 text_hitbox: &Hitbox,
574 cx: &mut ViewContext<Editor>,
575 ) {
576 let end_selection = editor.has_pending_selection();
577 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
578
579 if end_selection {
580 editor.select(SelectPhase::End, cx);
581 }
582
583 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
584 let multi_cursor_modifier = match multi_cursor_setting {
585 MultiCursorModifier::Alt => event.modifiers.secondary(),
586 MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
587 };
588
589 if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
590 let point = position_map.point_for_position(text_hitbox.bounds, event.position);
591 editor.handle_click_hovered_link(point, event.modifiers, cx);
592
593 cx.stop_propagation();
594 } else if end_selection && pending_nonempty_selections {
595 cx.stop_propagation();
596 } else if cfg!(target_os = "linux") && event.button == MouseButton::Middle {
597 if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
598 return;
599 }
600
601 #[cfg(target_os = "linux")]
602 if let Some(item) = cx.read_from_primary() {
603 let point_for_position =
604 position_map.point_for_position(text_hitbox.bounds, event.position);
605 let position = point_for_position.previous_valid;
606
607 editor.select(
608 SelectPhase::Begin {
609 position,
610 add: false,
611 click_count: 1,
612 },
613 cx,
614 );
615 editor.insert(item.text(), cx);
616 }
617 cx.stop_propagation()
618 }
619 }
620
621 fn mouse_dragged(
622 editor: &mut Editor,
623 event: &MouseMoveEvent,
624 position_map: &PositionMap,
625 text_bounds: Bounds<Pixels>,
626 cx: &mut ViewContext<Editor>,
627 ) {
628 if !editor.has_pending_selection() {
629 return;
630 }
631
632 let point_for_position = position_map.point_for_position(text_bounds, event.position);
633 let mut scroll_delta = gpui::Point::<f32>::default();
634 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
635 let top = text_bounds.origin.y + vertical_margin;
636 let bottom = text_bounds.lower_left().y - vertical_margin;
637 if event.position.y < top {
638 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
639 }
640 if event.position.y > bottom {
641 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
642 }
643
644 let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
645 let left = text_bounds.origin.x + horizontal_margin;
646 let right = text_bounds.upper_right().x - horizontal_margin;
647 if event.position.x < left {
648 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
649 }
650 if event.position.x > right {
651 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
652 }
653
654 editor.select(
655 SelectPhase::Update {
656 position: point_for_position.previous_valid,
657 goal_column: point_for_position.exact_unclipped.column(),
658 scroll_delta,
659 },
660 cx,
661 );
662 }
663
664 fn mouse_moved(
665 editor: &mut Editor,
666 event: &MouseMoveEvent,
667 position_map: &PositionMap,
668 text_hitbox: &Hitbox,
669 gutter_hitbox: &Hitbox,
670 cx: &mut ViewContext<Editor>,
671 ) {
672 let modifiers = event.modifiers;
673 let gutter_hovered = gutter_hitbox.is_hovered(cx);
674 editor.set_gutter_hovered(gutter_hovered, cx);
675
676 // Don't trigger hover popover if mouse is hovering over context menu
677 if text_hitbox.is_hovered(cx) {
678 let point_for_position =
679 position_map.point_for_position(text_hitbox.bounds, event.position);
680
681 editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
682
683 if let Some(point) = point_for_position.as_valid() {
684 let anchor = position_map
685 .snapshot
686 .buffer_snapshot
687 .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
688 hover_at(editor, Some(anchor), cx);
689 Self::update_visible_cursor(editor, point, position_map, cx);
690 } else {
691 hover_at(editor, None, cx);
692 }
693 } else {
694 editor.hide_hovered_link(cx);
695 hover_at(editor, None, cx);
696 if gutter_hovered {
697 cx.stop_propagation();
698 }
699 }
700 }
701
702 fn update_visible_cursor(
703 editor: &mut Editor,
704 point: DisplayPoint,
705 position_map: &PositionMap,
706 cx: &mut ViewContext<Editor>,
707 ) {
708 let snapshot = &position_map.snapshot;
709 let Some(hub) = editor.collaboration_hub() else {
710 return;
711 };
712 let range = DisplayPoint::new(point.row(), point.column().saturating_sub(1))
713 ..DisplayPoint::new(
714 point.row(),
715 (point.column() + 1).min(snapshot.line_len(point.row())),
716 );
717
718 let range = snapshot
719 .buffer_snapshot
720 .anchor_at(range.start.to_point(&snapshot.display_snapshot), Bias::Left)
721 ..snapshot
722 .buffer_snapshot
723 .anchor_at(range.end.to_point(&snapshot.display_snapshot), Bias::Right);
724
725 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
726 return;
727 };
728 let key = crate::HoveredCursor {
729 replica_id: selection.replica_id,
730 selection_id: selection.selection.id,
731 };
732 editor.hovered_cursors.insert(
733 key.clone(),
734 cx.spawn(|editor, mut cx| async move {
735 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
736 editor
737 .update(&mut cx, |editor, cx| {
738 editor.hovered_cursors.remove(&key);
739 cx.notify();
740 })
741 .ok();
742 }),
743 );
744 cx.notify()
745 }
746
747 fn layout_selections(
748 &self,
749 start_anchor: Anchor,
750 end_anchor: Anchor,
751 snapshot: &EditorSnapshot,
752 start_row: DisplayRow,
753 end_row: DisplayRow,
754 cx: &mut WindowContext,
755 ) -> (
756 Vec<(PlayerColor, Vec<SelectionLayout>)>,
757 BTreeMap<DisplayRow, bool>,
758 Option<DisplayPoint>,
759 ) {
760 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
761 let mut active_rows = BTreeMap::new();
762 let mut newest_selection_head = None;
763 let editor = self.editor.read(cx);
764
765 if editor.show_local_selections {
766 let mut local_selections: Vec<Selection<Point>> = editor
767 .selections
768 .disjoint_in_range(start_anchor..end_anchor, cx);
769 local_selections.extend(editor.selections.pending(cx));
770 let mut layouts = Vec::new();
771 let newest = editor.selections.newest(cx);
772 for selection in local_selections.drain(..) {
773 let is_empty = selection.start == selection.end;
774 let is_newest = selection == newest;
775
776 let layout = SelectionLayout::new(
777 selection,
778 editor.selections.line_mode,
779 editor.cursor_shape,
780 &snapshot.display_snapshot,
781 is_newest,
782 editor.leader_peer_id.is_none(),
783 None,
784 );
785 if is_newest {
786 newest_selection_head = Some(layout.head);
787 }
788
789 for row in cmp::max(layout.active_rows.start.0, start_row.0)
790 ..=cmp::min(layout.active_rows.end.0, end_row.0)
791 {
792 let contains_non_empty_selection =
793 active_rows.entry(DisplayRow(row)).or_insert(!is_empty);
794 *contains_non_empty_selection |= !is_empty;
795 }
796 layouts.push(layout);
797 }
798
799 let player = if editor.read_only(cx) {
800 cx.theme().players().read_only()
801 } else {
802 self.style.local_player
803 };
804
805 selections.push((player, layouts));
806 }
807
808 if let Some(collaboration_hub) = &editor.collaboration_hub {
809 // When following someone, render the local selections in their color.
810 if let Some(leader_id) = editor.leader_peer_id {
811 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
812 if let Some(participant_index) = collaboration_hub
813 .user_participant_indices(cx)
814 .get(&collaborator.user_id)
815 {
816 if let Some((local_selection_style, _)) = selections.first_mut() {
817 *local_selection_style = cx
818 .theme()
819 .players()
820 .color_for_participant(participant_index.0);
821 }
822 }
823 }
824 }
825
826 let mut remote_selections = HashMap::default();
827 for selection in snapshot.remote_selections_in_range(
828 &(start_anchor..end_anchor),
829 collaboration_hub.as_ref(),
830 cx,
831 ) {
832 let selection_style = Self::get_participant_color(selection.participant_index, cx);
833
834 // Don't re-render the leader's selections, since the local selections
835 // match theirs.
836 if Some(selection.peer_id) == editor.leader_peer_id {
837 continue;
838 }
839 let key = HoveredCursor {
840 replica_id: selection.replica_id,
841 selection_id: selection.selection.id,
842 };
843
844 let is_shown =
845 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
846
847 remote_selections
848 .entry(selection.replica_id)
849 .or_insert((selection_style, Vec::new()))
850 .1
851 .push(SelectionLayout::new(
852 selection.selection,
853 selection.line_mode,
854 selection.cursor_shape,
855 &snapshot.display_snapshot,
856 false,
857 false,
858 if is_shown { selection.user_name } else { None },
859 ));
860 }
861
862 selections.extend(remote_selections.into_values());
863 } else if !editor.is_focused(cx) && editor.show_cursor_when_unfocused {
864 let player = if editor.read_only(cx) {
865 cx.theme().players().read_only()
866 } else {
867 self.style.local_player
868 };
869 let layouts = snapshot
870 .buffer_snapshot
871 .selections_in_range(&(start_anchor..end_anchor), true)
872 .map(move |(_, line_mode, cursor_shape, selection)| {
873 SelectionLayout::new(
874 selection,
875 line_mode,
876 cursor_shape,
877 &snapshot.display_snapshot,
878 false,
879 false,
880 None,
881 )
882 })
883 .collect::<Vec<_>>();
884 selections.push((player, layouts));
885 }
886 (selections, active_rows, newest_selection_head)
887 }
888
889 fn collect_cursors(
890 &self,
891 snapshot: &EditorSnapshot,
892 cx: &mut WindowContext,
893 ) -> Vec<(DisplayPoint, Hsla)> {
894 let editor = self.editor.read(cx);
895 let mut cursors = Vec::new();
896 let mut skip_local = false;
897 let mut add_cursor = |anchor: Anchor, color| {
898 cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
899 };
900 // Remote cursors
901 if let Some(collaboration_hub) = &editor.collaboration_hub {
902 for remote_selection in snapshot.remote_selections_in_range(
903 &(Anchor::min()..Anchor::max()),
904 collaboration_hub.deref(),
905 cx,
906 ) {
907 let color = Self::get_participant_color(remote_selection.participant_index, cx);
908 add_cursor(remote_selection.selection.head(), color.cursor);
909 if Some(remote_selection.peer_id) == editor.leader_peer_id {
910 skip_local = true;
911 }
912 }
913 }
914 // Local cursors
915 if !skip_local {
916 let color = cx.theme().players().local().cursor;
917 editor.selections.disjoint.iter().for_each(|selection| {
918 add_cursor(selection.head(), color);
919 });
920 if let Some(ref selection) = editor.selections.pending_anchor() {
921 add_cursor(selection.head(), color);
922 }
923 }
924 cursors
925 }
926
927 #[allow(clippy::too_many_arguments)]
928 fn layout_visible_cursors(
929 &self,
930 snapshot: &EditorSnapshot,
931 selections: &[(PlayerColor, Vec<SelectionLayout>)],
932 visible_display_row_range: Range<DisplayRow>,
933 line_layouts: &[LineWithInvisibles],
934 text_hitbox: &Hitbox,
935 content_origin: gpui::Point<Pixels>,
936 scroll_position: gpui::Point<f32>,
937 scroll_pixel_position: gpui::Point<Pixels>,
938 line_height: Pixels,
939 em_width: Pixels,
940 autoscroll_containing_element: bool,
941 cx: &mut WindowContext,
942 ) -> Vec<CursorLayout> {
943 let mut autoscroll_bounds = None;
944 let cursor_layouts = self.editor.update(cx, |editor, cx| {
945 let mut cursors = Vec::new();
946 for (player_color, selections) in selections {
947 for selection in selections {
948 let cursor_position = selection.head;
949
950 let in_range = visible_display_row_range.contains(&cursor_position.row());
951 if (selection.is_local && !editor.show_local_cursors(cx)) || !in_range {
952 continue;
953 }
954
955 let cursor_row_layout = &line_layouts
956 [cursor_position.row().minus(visible_display_row_range.start) as usize];
957 let cursor_column = cursor_position.column() as usize;
958
959 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
960 let mut block_width =
961 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
962 if block_width == Pixels::ZERO {
963 block_width = em_width;
964 }
965 let block_text = if let CursorShape::Block = selection.cursor_shape {
966 snapshot.display_chars_at(cursor_position).next().and_then(
967 |(character, _)| {
968 let text = if character == '\n' {
969 SharedString::from(" ")
970 } else {
971 SharedString::from(character.to_string())
972 };
973 let len = text.len();
974
975 let font = cursor_row_layout
976 .font_id_for_index(cursor_column)
977 .and_then(|cursor_font_id| {
978 cx.text_system().get_font_for_id(cursor_font_id)
979 })
980 .unwrap_or(self.style.text.font());
981
982 cx.text_system()
983 .shape_line(
984 text,
985 cursor_row_layout.font_size,
986 &[TextRun {
987 len,
988 font,
989 color: self.style.background,
990 background_color: None,
991 strikethrough: None,
992 underline: None,
993 }],
994 )
995 .log_err()
996 },
997 )
998 } else {
999 None
1000 };
1001
1002 let x = cursor_character_x - scroll_pixel_position.x;
1003 let y = (cursor_position.row().as_f32()
1004 - scroll_pixel_position.y / line_height)
1005 * line_height;
1006 if selection.is_newest {
1007 editor.pixel_position_of_newest_cursor = Some(point(
1008 text_hitbox.origin.x + x + block_width / 2.,
1009 text_hitbox.origin.y + y + line_height / 2.,
1010 ));
1011
1012 if autoscroll_containing_element {
1013 let top = text_hitbox.origin.y
1014 + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1015 * line_height;
1016 let left = text_hitbox.origin.x
1017 + (cursor_position.column() as f32 - scroll_position.x - 3.)
1018 .max(0.)
1019 * em_width;
1020
1021 let bottom = text_hitbox.origin.y
1022 + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1023 * line_height;
1024 let right = text_hitbox.origin.x
1025 + (cursor_position.column() as f32 - scroll_position.x + 4.)
1026 * em_width;
1027
1028 autoscroll_bounds =
1029 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1030 }
1031 }
1032
1033 let mut cursor = CursorLayout {
1034 color: player_color.cursor,
1035 block_width,
1036 origin: point(x, y),
1037 line_height,
1038 shape: selection.cursor_shape,
1039 block_text,
1040 cursor_name: None,
1041 };
1042 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1043 string: name,
1044 color: self.style.background,
1045 is_top_row: cursor_position.row().0 == 0,
1046 });
1047 cursor.layout(content_origin, cursor_name, cx);
1048 cursors.push(cursor);
1049 }
1050 }
1051 cursors
1052 });
1053
1054 if let Some(bounds) = autoscroll_bounds {
1055 cx.request_autoscroll(bounds);
1056 }
1057
1058 cursor_layouts
1059 }
1060
1061 fn layout_scrollbar(
1062 &self,
1063 snapshot: &EditorSnapshot,
1064 bounds: Bounds<Pixels>,
1065 scroll_position: gpui::Point<f32>,
1066 rows_per_page: f32,
1067 non_visible_cursors: bool,
1068 cx: &mut WindowContext,
1069 ) -> Option<ScrollbarLayout> {
1070 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1071 let show_scrollbars = match scrollbar_settings.show {
1072 ShowScrollbar::Auto => {
1073 let editor = self.editor.read(cx);
1074 let is_singleton = editor.is_singleton(cx);
1075 // Git
1076 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1077 ||
1078 // Buffer Search Results
1079 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1080 ||
1081 // Selected Symbol Occurrences
1082 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1083 ||
1084 // Diagnostics
1085 (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
1086 ||
1087 // Cursors out of sight
1088 non_visible_cursors
1089 ||
1090 // Scrollmanager
1091 editor.scroll_manager.scrollbars_visible()
1092 }
1093 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1094 ShowScrollbar::Always => true,
1095 ShowScrollbar::Never => false,
1096 };
1097 if snapshot.mode != EditorMode::Full {
1098 return None;
1099 }
1100
1101 let visible_row_range = scroll_position.y..scroll_position.y + rows_per_page;
1102
1103 // If a drag took place after we started dragging the scrollbar,
1104 // cancel the scrollbar drag.
1105 if cx.has_active_drag() {
1106 self.editor.update(cx, |editor, cx| {
1107 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1108 });
1109 }
1110
1111 let track_bounds = Bounds::from_corners(
1112 point(self.scrollbar_left(&bounds), bounds.origin.y),
1113 point(bounds.lower_right().x, bounds.lower_left().y),
1114 );
1115
1116 let settings = EditorSettings::get_global(cx);
1117 let scroll_beyond_last_line: f32 = match settings.scroll_beyond_last_line {
1118 ScrollBeyondLastLine::OnePage => rows_per_page,
1119 ScrollBeyondLastLine::Off => 1.0,
1120 ScrollBeyondLastLine::VerticalScrollMargin => 1.0 + settings.vertical_scroll_margin,
1121 };
1122 let total_rows =
1123 (snapshot.max_point().row().as_f32() + scroll_beyond_last_line).max(rows_per_page);
1124 let height = bounds.size.height;
1125 let px_per_row = height / total_rows;
1126 let thumb_height = (rows_per_page * px_per_row).max(ScrollbarLayout::MIN_THUMB_HEIGHT);
1127 let row_height = (height - thumb_height) / (total_rows - rows_per_page).max(0.);
1128
1129 Some(ScrollbarLayout {
1130 hitbox: cx.insert_hitbox(track_bounds, false),
1131 visible_row_range,
1132 row_height,
1133 visible: show_scrollbars,
1134 thumb_height,
1135 })
1136 }
1137
1138 #[allow(clippy::too_many_arguments)]
1139 fn prepaint_gutter_fold_toggles(
1140 &self,
1141 toggles: &mut [Option<AnyElement>],
1142 line_height: Pixels,
1143 gutter_dimensions: &GutterDimensions,
1144 gutter_settings: crate::editor_settings::Gutter,
1145 scroll_pixel_position: gpui::Point<Pixels>,
1146 gutter_hitbox: &Hitbox,
1147 cx: &mut WindowContext,
1148 ) {
1149 for (ix, fold_indicator) in toggles.iter_mut().enumerate() {
1150 if let Some(fold_indicator) = fold_indicator {
1151 debug_assert!(gutter_settings.folds);
1152 let available_space = size(
1153 AvailableSpace::MinContent,
1154 AvailableSpace::Definite(line_height * 0.55),
1155 );
1156 let fold_indicator_size = fold_indicator.layout_as_root(available_space, cx);
1157
1158 let position = point(
1159 gutter_dimensions.width - gutter_dimensions.right_padding,
1160 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1161 );
1162 let centering_offset = point(
1163 (gutter_dimensions.fold_area_width() - fold_indicator_size.width) / 2.,
1164 (line_height - fold_indicator_size.height) / 2.,
1165 );
1166 let origin = gutter_hitbox.origin + position + centering_offset;
1167 fold_indicator.prepaint_as_root(origin, available_space, cx);
1168 }
1169 }
1170 }
1171
1172 #[allow(clippy::too_many_arguments)]
1173 fn prepaint_crease_trailers(
1174 &self,
1175 trailers: Vec<Option<AnyElement>>,
1176 lines: &[LineWithInvisibles],
1177 line_height: Pixels,
1178 content_origin: gpui::Point<Pixels>,
1179 scroll_pixel_position: gpui::Point<Pixels>,
1180 em_width: Pixels,
1181 cx: &mut WindowContext,
1182 ) -> Vec<Option<CreaseTrailerLayout>> {
1183 trailers
1184 .into_iter()
1185 .enumerate()
1186 .map(|(ix, element)| {
1187 let mut element = element?;
1188 let available_space = size(
1189 AvailableSpace::MinContent,
1190 AvailableSpace::Definite(line_height),
1191 );
1192 let size = element.layout_as_root(available_space, cx);
1193
1194 let line = &lines[ix];
1195 let padding = if line.width == Pixels::ZERO {
1196 Pixels::ZERO
1197 } else {
1198 4. * em_width
1199 };
1200 let position = point(
1201 scroll_pixel_position.x + line.width + padding,
1202 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1203 );
1204 let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1205 let origin = content_origin + position + centering_offset;
1206 element.prepaint_as_root(origin, available_space, cx);
1207 Some(CreaseTrailerLayout {
1208 element,
1209 bounds: Bounds::new(origin, size),
1210 })
1211 })
1212 .collect()
1213 }
1214
1215 // Folds contained in a hunk are ignored apart from shrinking visual size
1216 // If a fold contains any hunks then that fold line is marked as modified
1217 fn layout_git_gutters(
1218 &self,
1219 line_height: Pixels,
1220 gutter_hitbox: &Hitbox,
1221 display_rows: Range<DisplayRow>,
1222 snapshot: &EditorSnapshot,
1223 cx: &mut WindowContext,
1224 ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1225 let buffer_snapshot = &snapshot.buffer_snapshot;
1226
1227 let buffer_start_row = MultiBufferRow(
1228 DisplayPoint::new(display_rows.start, 0)
1229 .to_point(snapshot)
1230 .row,
1231 );
1232 let buffer_end_row = MultiBufferRow(
1233 DisplayPoint::new(display_rows.end, 0)
1234 .to_point(snapshot)
1235 .row,
1236 );
1237
1238 let expanded_hunk_display_rows = self.editor.update(cx, |editor, _| {
1239 editor
1240 .expanded_hunks
1241 .hunks(false)
1242 .map(|expanded_hunk| {
1243 let start_row = expanded_hunk
1244 .hunk_range
1245 .start
1246 .to_display_point(snapshot)
1247 .row();
1248 let end_row = expanded_hunk
1249 .hunk_range
1250 .end
1251 .to_display_point(snapshot)
1252 .row();
1253 (start_row, end_row)
1254 })
1255 .collect::<HashMap<_, _>>()
1256 });
1257
1258 let git_gutter_setting = ProjectSettings::get_global(cx)
1259 .git
1260 .git_gutter
1261 .unwrap_or_default();
1262 buffer_snapshot
1263 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1264 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
1265 .dedup()
1266 .map(|hunk| match git_gutter_setting {
1267 GitGutterSetting::TrackedFiles => {
1268 let hitbox = if let DisplayDiffHunk::Unfolded {
1269 display_row_range, ..
1270 } = &hunk
1271 {
1272 let was_expanded = expanded_hunk_display_rows
1273 .get(&display_row_range.start)
1274 .map(|expanded_end_row| expanded_end_row == &display_row_range.end)
1275 .unwrap_or(false);
1276 if was_expanded {
1277 None
1278 } else {
1279 let hunk_bounds = Self::diff_hunk_bounds(
1280 &snapshot,
1281 line_height,
1282 gutter_hitbox.bounds,
1283 &hunk,
1284 );
1285 Some(cx.insert_hitbox(hunk_bounds, true))
1286 }
1287 } else {
1288 None
1289 };
1290 (hunk, hitbox)
1291 }
1292 GitGutterSetting::Hide => (hunk, None),
1293 })
1294 .collect()
1295 }
1296
1297 #[allow(clippy::too_many_arguments)]
1298 fn layout_inline_blame(
1299 &self,
1300 display_row: DisplayRow,
1301 display_snapshot: &DisplaySnapshot,
1302 line_layout: &LineWithInvisibles,
1303 crease_trailer: Option<&CreaseTrailerLayout>,
1304 em_width: Pixels,
1305 content_origin: gpui::Point<Pixels>,
1306 scroll_pixel_position: gpui::Point<Pixels>,
1307 line_height: Pixels,
1308 cx: &mut WindowContext,
1309 ) -> Option<AnyElement> {
1310 if !self
1311 .editor
1312 .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1313 {
1314 return None;
1315 }
1316
1317 let workspace = self
1318 .editor
1319 .read(cx)
1320 .workspace
1321 .as_ref()
1322 .map(|(w, _)| w.clone());
1323
1324 let display_point = DisplayPoint::new(display_row, 0);
1325 let buffer_row = MultiBufferRow(display_point.to_point(display_snapshot).row);
1326
1327 let blame = self.editor.read(cx).blame.clone()?;
1328 let blame_entry = blame
1329 .update(cx, |blame, cx| {
1330 blame.blame_for_rows([Some(buffer_row)], cx).next()
1331 })
1332 .flatten()?;
1333
1334 let mut element =
1335 render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1336
1337 let start_y = content_origin.y
1338 + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1339
1340 let start_x = {
1341 const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1342
1343 let line_end = if let Some(crease_trailer) = crease_trailer {
1344 crease_trailer.bounds.right()
1345 } else {
1346 content_origin.x - scroll_pixel_position.x + line_layout.width
1347 };
1348 let padded_line_end = line_end + em_width * INLINE_BLAME_PADDING_EM_WIDTHS;
1349
1350 let min_column_in_pixels = ProjectSettings::get_global(cx)
1351 .git
1352 .inline_blame
1353 .and_then(|settings| settings.min_column)
1354 .map(|col| self.column_pixels(col as usize, cx))
1355 .unwrap_or(px(0.));
1356 let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1357
1358 cmp::max(padded_line_end, min_start)
1359 };
1360
1361 let absolute_offset = point(start_x, start_y);
1362 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1363
1364 element.prepaint_as_root(absolute_offset, available_space, cx);
1365
1366 Some(element)
1367 }
1368
1369 #[allow(clippy::too_many_arguments)]
1370 fn layout_blame_entries(
1371 &self,
1372 buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1373 em_width: Pixels,
1374 scroll_position: gpui::Point<f32>,
1375 line_height: Pixels,
1376 gutter_hitbox: &Hitbox,
1377 max_width: Option<Pixels>,
1378 cx: &mut WindowContext,
1379 ) -> Option<Vec<AnyElement>> {
1380 if !self
1381 .editor
1382 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1383 {
1384 return None;
1385 }
1386
1387 let blame = self.editor.read(cx).blame.clone()?;
1388 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1389 blame.blame_for_rows(buffer_rows, cx).collect()
1390 });
1391
1392 let width = if let Some(max_width) = max_width {
1393 AvailableSpace::Definite(max_width)
1394 } else {
1395 AvailableSpace::MaxContent
1396 };
1397 let scroll_top = scroll_position.y * line_height;
1398 let start_x = em_width * 1;
1399
1400 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1401
1402 let shaped_lines = blamed_rows
1403 .into_iter()
1404 .enumerate()
1405 .flat_map(|(ix, blame_entry)| {
1406 if let Some(blame_entry) = blame_entry {
1407 let mut element = render_blame_entry(
1408 ix,
1409 &blame,
1410 blame_entry,
1411 &self.style,
1412 &mut last_used_color,
1413 self.editor.clone(),
1414 cx,
1415 );
1416
1417 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1418 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1419
1420 element.prepaint_as_root(
1421 absolute_offset,
1422 size(width, AvailableSpace::MinContent),
1423 cx,
1424 );
1425
1426 Some(element)
1427 } else {
1428 None
1429 }
1430 })
1431 .collect();
1432
1433 Some(shaped_lines)
1434 }
1435
1436 #[allow(clippy::too_many_arguments)]
1437 fn layout_indent_guides(
1438 &self,
1439 content_origin: gpui::Point<Pixels>,
1440 text_origin: gpui::Point<Pixels>,
1441 visible_buffer_range: Range<MultiBufferRow>,
1442 scroll_pixel_position: gpui::Point<Pixels>,
1443 line_height: Pixels,
1444 snapshot: &DisplaySnapshot,
1445 cx: &mut WindowContext,
1446 ) -> Option<Vec<IndentGuideLayout>> {
1447 let indent_guides = self.editor.update(cx, |editor, cx| {
1448 editor.indent_guides(visible_buffer_range, snapshot, cx)
1449 })?;
1450
1451 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1452 editor
1453 .find_active_indent_guide_indices(&indent_guides, snapshot, cx)
1454 .unwrap_or_default()
1455 });
1456
1457 Some(
1458 indent_guides
1459 .into_iter()
1460 .enumerate()
1461 .filter_map(|(i, indent_guide)| {
1462 let single_indent_width =
1463 self.column_pixels(indent_guide.tab_size as usize, cx);
1464 let total_width = single_indent_width * indent_guide.depth as f32;
1465 let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1466 if start_x >= text_origin.x {
1467 let (offset_y, length) = Self::calculate_indent_guide_bounds(
1468 indent_guide.multibuffer_row_range.clone(),
1469 line_height,
1470 snapshot,
1471 );
1472
1473 let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1474
1475 Some(IndentGuideLayout {
1476 origin: point(start_x, start_y),
1477 length,
1478 single_indent_width,
1479 depth: indent_guide.depth,
1480 active: active_indent_guide_indices.contains(&i),
1481 settings: indent_guide.settings,
1482 })
1483 } else {
1484 None
1485 }
1486 })
1487 .collect(),
1488 )
1489 }
1490
1491 fn calculate_indent_guide_bounds(
1492 row_range: Range<MultiBufferRow>,
1493 line_height: Pixels,
1494 snapshot: &DisplaySnapshot,
1495 ) -> (gpui::Pixels, gpui::Pixels) {
1496 let start_point = Point::new(row_range.start.0, 0);
1497 let end_point = Point::new(row_range.end.0, 0);
1498
1499 let row_range = start_point.to_display_point(snapshot).row()
1500 ..end_point.to_display_point(snapshot).row();
1501
1502 let mut prev_line = start_point;
1503 prev_line.row = prev_line.row.saturating_sub(1);
1504 let prev_line = prev_line.to_display_point(snapshot).row();
1505
1506 let mut cons_line = end_point;
1507 cons_line.row += 1;
1508 let cons_line = cons_line.to_display_point(snapshot).row();
1509
1510 let mut offset_y = row_range.start.0 as f32 * line_height;
1511 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
1512
1513 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
1514 if row_range.end == cons_line {
1515 length += line_height;
1516 }
1517
1518 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
1519 // we want to extend the indent guide to the start of the block.
1520 let mut block_height = 0;
1521 let mut block_offset = 0;
1522 let mut found_excerpt_header = false;
1523 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
1524 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1525 found_excerpt_header = true;
1526 break;
1527 }
1528 block_offset += block.height();
1529 block_height += block.height();
1530 }
1531 if !found_excerpt_header {
1532 offset_y -= block_offset as f32 * line_height;
1533 length += block_height as f32 * line_height;
1534 }
1535
1536 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
1537 // we want to ensure that the indent guide stops before the excerpt header.
1538 let mut block_height = 0;
1539 let mut found_excerpt_header = false;
1540 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
1541 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1542 found_excerpt_header = true;
1543 }
1544 block_height += block.height();
1545 }
1546 if found_excerpt_header {
1547 length -= block_height as f32 * line_height;
1548 }
1549
1550 (offset_y, length)
1551 }
1552
1553 fn layout_run_indicators(
1554 &self,
1555 line_height: Pixels,
1556 scroll_pixel_position: gpui::Point<Pixels>,
1557 gutter_dimensions: &GutterDimensions,
1558 gutter_hitbox: &Hitbox,
1559 snapshot: &EditorSnapshot,
1560 cx: &mut WindowContext,
1561 ) -> Vec<AnyElement> {
1562 self.editor.update(cx, |editor, cx| {
1563 let active_task_indicator_row =
1564 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1565 deployed_from_indicator,
1566 actions,
1567 ..
1568 })) = editor.context_menu.read().as_ref()
1569 {
1570 actions
1571 .tasks
1572 .as_ref()
1573 .map(|tasks| tasks.position.to_display_point(snapshot).row())
1574 .or_else(|| *deployed_from_indicator)
1575 } else {
1576 None
1577 };
1578 editor
1579 .tasks
1580 .iter()
1581 .filter_map(|(_, tasks)| {
1582 let multibuffer_point = tasks.offset.0.to_point(&snapshot.buffer_snapshot);
1583 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
1584 if snapshot.is_line_folded(multibuffer_row) {
1585 return None;
1586 }
1587 let display_row = multibuffer_point.to_display_point(snapshot).row();
1588 let button = editor.render_run_indicator(
1589 &self.style,
1590 Some(display_row) == active_task_indicator_row,
1591 display_row,
1592 cx,
1593 );
1594
1595 let button = prepaint_gutter_button(
1596 button,
1597 display_row,
1598 line_height,
1599 gutter_dimensions,
1600 scroll_pixel_position,
1601 gutter_hitbox,
1602 cx,
1603 );
1604 Some(button)
1605 })
1606 .collect_vec()
1607 })
1608 }
1609
1610 fn layout_code_actions_indicator(
1611 &self,
1612 line_height: Pixels,
1613 newest_selection_head: DisplayPoint,
1614 scroll_pixel_position: gpui::Point<Pixels>,
1615 gutter_dimensions: &GutterDimensions,
1616 gutter_hitbox: &Hitbox,
1617 cx: &mut WindowContext,
1618 ) -> Option<AnyElement> {
1619 let mut active = false;
1620 let mut button = None;
1621 let row = newest_selection_head.row();
1622 self.editor.update(cx, |editor, cx| {
1623 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1624 deployed_from_indicator,
1625 ..
1626 })) = editor.context_menu.read().as_ref()
1627 {
1628 active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1629 };
1630 button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1631 });
1632
1633 let button = prepaint_gutter_button(
1634 button?,
1635 row,
1636 line_height,
1637 gutter_dimensions,
1638 scroll_pixel_position,
1639 gutter_hitbox,
1640 cx,
1641 );
1642
1643 Some(button)
1644 }
1645
1646 fn get_participant_color(
1647 participant_index: Option<ParticipantIndex>,
1648 cx: &WindowContext,
1649 ) -> PlayerColor {
1650 if let Some(index) = participant_index {
1651 cx.theme().players().color_for_participant(index.0)
1652 } else {
1653 cx.theme().players().absent()
1654 }
1655 }
1656
1657 fn calculate_relative_line_numbers(
1658 &self,
1659 snapshot: &EditorSnapshot,
1660 rows: &Range<DisplayRow>,
1661 relative_to: Option<DisplayRow>,
1662 ) -> HashMap<DisplayRow, DisplayRowDelta> {
1663 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
1664 let Some(relative_to) = relative_to else {
1665 return relative_rows;
1666 };
1667
1668 let start = rows.start.min(relative_to);
1669 let end = rows.end.max(relative_to);
1670
1671 let buffer_rows = snapshot
1672 .buffer_rows(start)
1673 .take(1 + end.minus(start) as usize)
1674 .collect::<Vec<_>>();
1675
1676 let head_idx = relative_to.minus(start);
1677 let mut delta = 1;
1678 let mut i = head_idx + 1;
1679 while i < buffer_rows.len() as u32 {
1680 if buffer_rows[i as usize].is_some() {
1681 if rows.contains(&DisplayRow(i + start.0)) {
1682 relative_rows.insert(DisplayRow(i + start.0), delta);
1683 }
1684 delta += 1;
1685 }
1686 i += 1;
1687 }
1688 delta = 1;
1689 i = head_idx.min(buffer_rows.len() as u32 - 1);
1690 while i > 0 && buffer_rows[i as usize].is_none() {
1691 i -= 1;
1692 }
1693
1694 while i > 0 {
1695 i -= 1;
1696 if buffer_rows[i as usize].is_some() {
1697 if rows.contains(&DisplayRow(i + start.0)) {
1698 relative_rows.insert(DisplayRow(i + start.0), delta);
1699 }
1700 delta += 1;
1701 }
1702 }
1703
1704 relative_rows
1705 }
1706
1707 fn layout_line_numbers(
1708 &self,
1709 rows: Range<DisplayRow>,
1710 buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1711 active_rows: &BTreeMap<DisplayRow, bool>,
1712 newest_selection_head: Option<DisplayPoint>,
1713 snapshot: &EditorSnapshot,
1714 cx: &mut WindowContext,
1715 ) -> Vec<Option<ShapedLine>> {
1716 let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
1717 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
1718 });
1719 if !include_line_numbers {
1720 return Vec::new();
1721 }
1722
1723 let editor = self.editor.read(cx);
1724 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1725 let newest = editor.selections.newest::<Point>(cx);
1726 SelectionLayout::new(
1727 newest,
1728 editor.selections.line_mode,
1729 editor.cursor_shape,
1730 &snapshot.display_snapshot,
1731 true,
1732 true,
1733 None,
1734 )
1735 .head
1736 });
1737 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1738
1739 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1740 let relative_to = if is_relative {
1741 Some(newest_selection_head.row())
1742 } else {
1743 None
1744 };
1745 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1746 let mut line_number = String::new();
1747 buffer_rows
1748 .into_iter()
1749 .enumerate()
1750 .map(|(ix, multibuffer_row)| {
1751 let multibuffer_row = multibuffer_row?;
1752 let display_row = DisplayRow(rows.start.0 + ix as u32);
1753 let color = if active_rows.contains_key(&display_row) {
1754 cx.theme().colors().editor_active_line_number
1755 } else {
1756 cx.theme().colors().editor_line_number
1757 };
1758 line_number.clear();
1759 let default_number = multibuffer_row.0 + 1;
1760 let number = relative_rows
1761 .get(&DisplayRow(ix as u32 + rows.start.0))
1762 .unwrap_or(&default_number);
1763 write!(&mut line_number, "{number}").unwrap();
1764 let run = TextRun {
1765 len: line_number.len(),
1766 font: self.style.text.font(),
1767 color,
1768 background_color: None,
1769 underline: None,
1770 strikethrough: None,
1771 };
1772 let shaped_line = cx
1773 .text_system()
1774 .shape_line(line_number.clone().into(), font_size, &[run])
1775 .unwrap();
1776 Some(shaped_line)
1777 })
1778 .collect()
1779 }
1780
1781 fn layout_gutter_fold_toggles(
1782 &self,
1783 rows: Range<DisplayRow>,
1784 buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1785 active_rows: &BTreeMap<DisplayRow, bool>,
1786 snapshot: &EditorSnapshot,
1787 cx: &mut WindowContext,
1788 ) -> Vec<Option<AnyElement>> {
1789 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
1790 && snapshot.mode == EditorMode::Full
1791 && self.editor.read(cx).is_singleton(cx);
1792 if include_fold_statuses {
1793 buffer_rows
1794 .into_iter()
1795 .enumerate()
1796 .map(|(ix, row)| {
1797 if let Some(multibuffer_row) = row {
1798 let display_row = DisplayRow(rows.start.0 + ix as u32);
1799 let active = active_rows.contains_key(&display_row);
1800 snapshot.render_fold_toggle(
1801 multibuffer_row,
1802 active,
1803 self.editor.clone(),
1804 cx,
1805 )
1806 } else {
1807 None
1808 }
1809 })
1810 .collect()
1811 } else {
1812 Vec::new()
1813 }
1814 }
1815
1816 fn layout_crease_trailers(
1817 &self,
1818 buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1819 snapshot: &EditorSnapshot,
1820 cx: &mut WindowContext,
1821 ) -> Vec<Option<AnyElement>> {
1822 buffer_rows
1823 .into_iter()
1824 .map(|row| {
1825 if let Some(multibuffer_row) = row {
1826 snapshot.render_crease_trailer(multibuffer_row, cx)
1827 } else {
1828 None
1829 }
1830 })
1831 .collect()
1832 }
1833
1834 fn layout_lines(
1835 rows: Range<DisplayRow>,
1836 line_number_layouts: &[Option<ShapedLine>],
1837 snapshot: &EditorSnapshot,
1838 style: &EditorStyle,
1839 cx: &mut WindowContext,
1840 ) -> Vec<LineWithInvisibles> {
1841 if rows.start >= rows.end {
1842 return Vec::new();
1843 }
1844
1845 // Show the placeholder when the editor is empty
1846 if snapshot.is_empty() {
1847 let font_size = style.text.font_size.to_pixels(cx.rem_size());
1848 let placeholder_color = cx.theme().colors().text_placeholder;
1849 let placeholder_text = snapshot.placeholder_text();
1850
1851 let placeholder_lines = placeholder_text
1852 .as_ref()
1853 .map_or("", AsRef::as_ref)
1854 .split('\n')
1855 .skip(rows.start.0 as usize)
1856 .chain(iter::repeat(""))
1857 .take(rows.len());
1858 placeholder_lines
1859 .filter_map(move |line| {
1860 let run = TextRun {
1861 len: line.len(),
1862 font: style.text.font(),
1863 color: placeholder_color,
1864 background_color: None,
1865 underline: Default::default(),
1866 strikethrough: None,
1867 };
1868 cx.text_system()
1869 .shape_line(line.to_string().into(), font_size, &[run])
1870 .log_err()
1871 })
1872 .map(|line| LineWithInvisibles {
1873 width: line.width,
1874 len: line.len,
1875 fragments: smallvec![LineFragment::Text(line)],
1876 invisibles: Vec::new(),
1877 font_size,
1878 })
1879 .collect()
1880 } else {
1881 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
1882 LineWithInvisibles::from_chunks(
1883 chunks,
1884 &style.text,
1885 MAX_LINE_LEN,
1886 rows.len(),
1887 line_number_layouts,
1888 snapshot.mode,
1889 cx,
1890 )
1891 }
1892 }
1893
1894 fn prepaint_lines(
1895 &self,
1896 start_row: DisplayRow,
1897 line_layouts: &mut [LineWithInvisibles],
1898 line_height: Pixels,
1899 scroll_pixel_position: gpui::Point<Pixels>,
1900 content_origin: gpui::Point<Pixels>,
1901 cx: &mut WindowContext,
1902 ) -> SmallVec<[AnyElement; 1]> {
1903 let mut line_elements = SmallVec::new();
1904 for (ix, line) in line_layouts.iter_mut().enumerate() {
1905 let row = start_row + DisplayRow(ix as u32);
1906 line.prepaint(
1907 line_height,
1908 scroll_pixel_position,
1909 row,
1910 content_origin,
1911 &mut line_elements,
1912 cx,
1913 );
1914 }
1915 line_elements
1916 }
1917
1918 #[allow(clippy::too_many_arguments)]
1919 fn build_blocks(
1920 &self,
1921 rows: Range<DisplayRow>,
1922 snapshot: &EditorSnapshot,
1923 hitbox: &Hitbox,
1924 text_hitbox: &Hitbox,
1925 scroll_width: &mut Pixels,
1926 gutter_dimensions: &GutterDimensions,
1927 em_width: Pixels,
1928 text_x: Pixels,
1929 line_height: Pixels,
1930 line_layouts: &[LineWithInvisibles],
1931 cx: &mut WindowContext,
1932 ) -> Vec<BlockLayout> {
1933 let mut block_id = 0;
1934 let (fixed_blocks, non_fixed_blocks) = snapshot
1935 .blocks_in_range(rows.clone())
1936 .partition::<Vec<_>, _>(|(_, block)| match block {
1937 TransformBlock::ExcerptHeader { .. } => false,
1938 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1939 TransformBlock::ExcerptFooter { .. } => false,
1940 });
1941
1942 let render_block = |block: &TransformBlock,
1943 available_space: Size<AvailableSpace>,
1944 block_id: usize,
1945 block_row_start: DisplayRow,
1946 cx: &mut WindowContext| {
1947 let mut element = match block {
1948 TransformBlock::Custom(block) => {
1949 let align_to = block
1950 .position()
1951 .to_point(&snapshot.buffer_snapshot)
1952 .to_display_point(snapshot);
1953 let anchor_x = text_x
1954 + if rows.contains(&align_to.row()) {
1955 line_layouts[align_to.row().minus(rows.start) as usize]
1956 .x_for_index(align_to.column() as usize)
1957 } else {
1958 layout_line(align_to.row(), snapshot, &self.style, cx)
1959 .x_for_index(align_to.column() as usize)
1960 };
1961
1962 block.render(&mut BlockContext {
1963 context: cx,
1964 anchor_x,
1965 gutter_dimensions,
1966 line_height,
1967 em_width,
1968 block_id,
1969 max_width: text_hitbox.size.width.max(*scroll_width),
1970 editor_style: &self.style,
1971 })
1972 }
1973
1974 TransformBlock::ExcerptHeader {
1975 buffer,
1976 range,
1977 starts_new_buffer,
1978 height,
1979 id,
1980 show_excerpt_controls,
1981 ..
1982 } => {
1983 let include_root = self
1984 .editor
1985 .read(cx)
1986 .project
1987 .as_ref()
1988 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1989 .unwrap_or_default();
1990
1991 #[derive(Clone)]
1992 struct JumpData {
1993 position: Point,
1994 anchor: text::Anchor,
1995 path: ProjectPath,
1996 line_offset_from_top: u32,
1997 }
1998
1999 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
2000 let jump_path = ProjectPath {
2001 worktree_id: file.worktree_id(cx),
2002 path: file.path.clone(),
2003 };
2004 let jump_anchor = range
2005 .primary
2006 .as_ref()
2007 .map_or(range.context.start, |primary| primary.start);
2008
2009 let excerpt_start = range.context.start;
2010 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2011 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
2012 0
2013 } else {
2014 let excerpt_start_row =
2015 language::ToPoint::to_point(&jump_anchor, buffer).row;
2016 jump_position.row - excerpt_start_row
2017 };
2018
2019 let line_offset_from_top =
2020 block_row_start.0 + *height as u32 + offset_from_excerpt_start
2021 - snapshot
2022 .scroll_anchor
2023 .scroll_position(&snapshot.display_snapshot)
2024 .y as u32;
2025
2026 JumpData {
2027 position: jump_position,
2028 anchor: jump_anchor,
2029 path: jump_path,
2030 line_offset_from_top,
2031 }
2032 });
2033
2034 let icon_offset = gutter_dimensions.width
2035 - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2036
2037 let element = if *starts_new_buffer {
2038 let path = buffer.resolve_file_path(cx, include_root);
2039 let mut filename = None;
2040 let mut parent_path = None;
2041 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2042 if let Some(path) = path {
2043 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2044 parent_path = path
2045 .parent()
2046 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2047 }
2048
2049 let header_padding = px(6.0);
2050
2051 v_flex()
2052 .id(("path excerpt header", block_id))
2053 .size_full()
2054 .p(header_padding)
2055 .child(
2056 h_flex()
2057 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2058 .id("path header block")
2059 .pl(gpui::px(12.))
2060 .pr(gpui::px(8.))
2061 .rounded_md()
2062 .shadow_md()
2063 .border_1()
2064 .border_color(cx.theme().colors().border)
2065 .bg(cx.theme().colors().editor_subheader_background)
2066 .justify_between()
2067 .hover(|style| style.bg(cx.theme().colors().element_hover))
2068 .child(
2069 h_flex().gap_3().child(
2070 h_flex()
2071 .gap_2()
2072 .child(
2073 filename
2074 .map(SharedString::from)
2075 .unwrap_or_else(|| "untitled".into()),
2076 )
2077 .when_some(parent_path, |then, path| {
2078 then.child(
2079 div().child(path).text_color(
2080 cx.theme().colors().text_muted,
2081 ),
2082 )
2083 }),
2084 ),
2085 )
2086 .when_some(jump_data.clone(), |this, jump_data| {
2087 this.cursor_pointer()
2088 .tooltip(|cx| {
2089 Tooltip::for_action(
2090 "Jump to File",
2091 &OpenExcerpts,
2092 cx,
2093 )
2094 })
2095 .on_mouse_down(MouseButton::Left, |_, cx| {
2096 cx.stop_propagation()
2097 })
2098 .on_click(cx.listener_for(&self.editor, {
2099 move |editor, _, cx| {
2100 editor.jump(
2101 jump_data.path.clone(),
2102 jump_data.position,
2103 jump_data.anchor,
2104 jump_data.line_offset_from_top,
2105 cx,
2106 );
2107 }
2108 }))
2109 }),
2110 )
2111 .children(show_excerpt_controls.then(|| {
2112 h_flex()
2113 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.333)))
2114 .pt_1()
2115 .justify_end()
2116 .flex_none()
2117 .w(icon_offset - header_padding)
2118 .child(
2119 ButtonLike::new("expand-icon")
2120 .style(ButtonStyle::Transparent)
2121 .child(
2122 svg()
2123 .path(IconName::ArrowUpFromLine.path())
2124 .size(IconSize::XSmall.rems())
2125 .text_color(
2126 cx.theme().colors().editor_line_number,
2127 )
2128 .group("")
2129 .hover(|style| {
2130 style.text_color(
2131 cx.theme()
2132 .colors()
2133 .editor_active_line_number,
2134 )
2135 }),
2136 )
2137 .on_click(cx.listener_for(&self.editor, {
2138 let id = *id;
2139 move |editor, _, cx| {
2140 editor.expand_excerpt(
2141 id,
2142 multi_buffer::ExpandExcerptDirection::Up,
2143 cx,
2144 );
2145 }
2146 }))
2147 .tooltip({
2148 move |cx| {
2149 Tooltip::for_action(
2150 "Expand Excerpt",
2151 &ExpandExcerpts { lines: 0 },
2152 cx,
2153 )
2154 }
2155 }),
2156 )
2157 }))
2158 } else {
2159 v_flex()
2160 .id(("excerpt header", block_id))
2161 .size_full()
2162 .child(
2163 div()
2164 .flex()
2165 .v_flex()
2166 .justify_start()
2167 .id("jump to collapsed context")
2168 .w(relative(1.0))
2169 .h_full()
2170 .child(
2171 div()
2172 .h_px()
2173 .w_full()
2174 .bg(cx.theme().colors().border_variant)
2175 .group_hover("excerpt-jump-action", |style| {
2176 style.bg(cx.theme().colors().border)
2177 }),
2178 ),
2179 )
2180 .child(
2181 h_flex()
2182 .justify_end()
2183 .flex_none()
2184 .w(icon_offset)
2185 .h_full()
2186 .child(
2187 show_excerpt_controls.then(|| {
2188 ButtonLike::new("expand-icon")
2189 .style(ButtonStyle::Transparent)
2190 .child(
2191 svg()
2192 .path(IconName::ArrowUpFromLine.path())
2193 .size(IconSize::XSmall.rems())
2194 .text_color(
2195 cx.theme().colors().editor_line_number,
2196 )
2197 .group("")
2198 .hover(|style| {
2199 style.text_color(
2200 cx.theme()
2201 .colors()
2202 .editor_active_line_number,
2203 )
2204 }),
2205 )
2206 .on_click(cx.listener_for(&self.editor, {
2207 let id = *id;
2208 move |editor, _, cx| {
2209 editor.expand_excerpt(
2210 id,
2211 multi_buffer::ExpandExcerptDirection::Up,
2212 cx,
2213 );
2214 }
2215 }))
2216 .tooltip({
2217 move |cx| {
2218 Tooltip::for_action(
2219 "Expand Excerpt",
2220 &ExpandExcerpts { lines: 0 },
2221 cx,
2222 )
2223 }
2224 })
2225 }).unwrap_or_else(|| {
2226 ButtonLike::new("jump-icon")
2227 .style(ButtonStyle::Transparent)
2228 .child(
2229 svg()
2230 .path(IconName::ArrowUpRight.path())
2231 .size(IconSize::XSmall.rems())
2232 .text_color(
2233 cx.theme().colors().border_variant,
2234 )
2235 .group("excerpt-jump-action")
2236 .group_hover("excerpt-jump-action", |style| {
2237 style.text_color(
2238 cx.theme().colors().border
2239
2240 )
2241 })
2242 )
2243 .when_some(jump_data.clone(), |this, jump_data| {
2244 this.on_click(cx.listener_for(&self.editor, {
2245 let path = jump_data.path.clone();
2246 move |editor, _, cx| {
2247 cx.stop_propagation();
2248
2249 editor.jump(
2250 path.clone(),
2251 jump_data.position,
2252 jump_data.anchor,
2253 jump_data.line_offset_from_top,
2254 cx,
2255 );
2256 }
2257 }))
2258 .tooltip(move |cx| {
2259 Tooltip::for_action(
2260 format!(
2261 "Jump to {}:L{}",
2262 jump_data.path.path.display(),
2263 jump_data.position.row + 1
2264 ),
2265 &OpenExcerpts,
2266 cx,
2267 )
2268 })
2269 })
2270 })
2271
2272 ),
2273 )
2274 .group("excerpt-jump-action")
2275 .cursor_pointer()
2276 .when_some(jump_data.clone(), |this, jump_data| {
2277 this.on_click(cx.listener_for(&self.editor, {
2278 let path = jump_data.path.clone();
2279 move |editor, _, cx| {
2280 cx.stop_propagation();
2281
2282 editor.jump(
2283 path.clone(),
2284 jump_data.position,
2285 jump_data.anchor,
2286 jump_data.line_offset_from_top,
2287 cx,
2288 );
2289 }
2290 }))
2291 .tooltip(move |cx| {
2292 Tooltip::for_action(
2293 format!(
2294 "Jump to {}:L{}",
2295 jump_data.path.path.display(),
2296 jump_data.position.row + 1
2297 ),
2298 &OpenExcerpts,
2299 cx,
2300 )
2301 })
2302 })
2303 };
2304 element.into_any()
2305 }
2306
2307 TransformBlock::ExcerptFooter { id, .. } => {
2308 let element = v_flex().id(("excerpt footer", block_id)).size_full().child(
2309 h_flex()
2310 .justify_end()
2311 .flex_none()
2312 .w(gutter_dimensions.width
2313 - (gutter_dimensions.left_padding + gutter_dimensions.margin))
2314 .h_full()
2315 .child(
2316 ButtonLike::new("expand-icon")
2317 .style(ButtonStyle::Transparent)
2318 .child(
2319 svg()
2320 .path(IconName::ArrowDownFromLine.path())
2321 .size(IconSize::XSmall.rems())
2322 .text_color(cx.theme().colors().editor_line_number)
2323 .group("")
2324 .hover(|style| {
2325 style.text_color(
2326 cx.theme().colors().editor_active_line_number,
2327 )
2328 }),
2329 )
2330 .on_click(cx.listener_for(&self.editor, {
2331 let id = *id;
2332 move |editor, _, cx| {
2333 editor.expand_excerpt(
2334 id,
2335 multi_buffer::ExpandExcerptDirection::Down,
2336 cx,
2337 );
2338 }
2339 }))
2340 .tooltip({
2341 move |cx| {
2342 Tooltip::for_action(
2343 "Expand Excerpt",
2344 &ExpandExcerpts { lines: 0 },
2345 cx,
2346 )
2347 }
2348 }),
2349 ),
2350 );
2351 element.into_any()
2352 }
2353 };
2354
2355 let size = element.layout_as_root(available_space, cx);
2356 (element, size)
2357 };
2358
2359 let mut fixed_block_max_width = Pixels::ZERO;
2360 let mut blocks = Vec::new();
2361 for (row, block) in fixed_blocks {
2362 let available_space = size(
2363 AvailableSpace::MinContent,
2364 AvailableSpace::Definite(block.height() as f32 * line_height),
2365 );
2366 let (element, element_size) = render_block(block, available_space, block_id, row, cx);
2367 block_id += 1;
2368 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2369 blocks.push(BlockLayout {
2370 row,
2371 element,
2372 available_space,
2373 style: BlockStyle::Fixed,
2374 });
2375 }
2376 for (row, block) in non_fixed_blocks {
2377 let style = match block {
2378 TransformBlock::Custom(block) => block.style(),
2379 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2380 TransformBlock::ExcerptFooter { .. } => BlockStyle::Sticky,
2381 };
2382 let width = match style {
2383 BlockStyle::Sticky => hitbox.size.width,
2384 BlockStyle::Flex => hitbox
2385 .size
2386 .width
2387 .max(fixed_block_max_width)
2388 .max(gutter_dimensions.width + *scroll_width),
2389 BlockStyle::Fixed => unreachable!(),
2390 };
2391 let available_space = size(
2392 AvailableSpace::Definite(width),
2393 AvailableSpace::Definite(block.height() as f32 * line_height),
2394 );
2395 let (element, _) = render_block(block, available_space, block_id, row, cx);
2396 block_id += 1;
2397 blocks.push(BlockLayout {
2398 row,
2399 element,
2400 available_space,
2401 style,
2402 });
2403 }
2404
2405 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2406 blocks
2407 }
2408
2409 fn layout_blocks(
2410 &self,
2411 blocks: &mut Vec<BlockLayout>,
2412 hitbox: &Hitbox,
2413 line_height: Pixels,
2414 scroll_pixel_position: gpui::Point<Pixels>,
2415 cx: &mut WindowContext,
2416 ) {
2417 for block in blocks {
2418 let mut origin = hitbox.origin
2419 + point(
2420 Pixels::ZERO,
2421 block.row.as_f32() * line_height - scroll_pixel_position.y,
2422 );
2423 if !matches!(block.style, BlockStyle::Sticky) {
2424 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2425 }
2426 block
2427 .element
2428 .prepaint_as_root(origin, block.available_space, cx);
2429 }
2430 }
2431
2432 #[allow(clippy::too_many_arguments)]
2433 fn layout_context_menu(
2434 &self,
2435 line_height: Pixels,
2436 hitbox: &Hitbox,
2437 text_hitbox: &Hitbox,
2438 content_origin: gpui::Point<Pixels>,
2439 start_row: DisplayRow,
2440 scroll_pixel_position: gpui::Point<Pixels>,
2441 line_layouts: &[LineWithInvisibles],
2442 newest_selection_head: DisplayPoint,
2443 gutter_overshoot: Pixels,
2444 cx: &mut WindowContext,
2445 ) -> bool {
2446 let max_height = cmp::min(
2447 12. * line_height,
2448 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2449 );
2450 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2451 if editor.context_menu_visible() {
2452 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2453 } else {
2454 None
2455 }
2456 }) else {
2457 return false;
2458 };
2459
2460 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2461 let context_menu_size = context_menu.layout_as_root(available_space, cx);
2462
2463 let (x, y) = match position {
2464 crate::ContextMenuOrigin::EditorPoint(point) => {
2465 let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2466 let x = cursor_row_layout.x_for_index(point.column() as usize)
2467 - scroll_pixel_position.x;
2468 let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2469 (x, y)
2470 }
2471 crate::ContextMenuOrigin::GutterIndicator(row) => {
2472 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the indicator than just a plain first column of the
2473 // text field.
2474 let x = -gutter_overshoot;
2475 let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2476 (x, y)
2477 }
2478 };
2479
2480 let mut list_origin = content_origin + point(x, y);
2481 let list_width = context_menu_size.width;
2482 let list_height = context_menu_size.height;
2483
2484 // Snap the right edge of the list to the right edge of the window if
2485 // its horizontal bounds overflow.
2486 if list_origin.x + list_width > cx.viewport_size().width {
2487 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2488 }
2489
2490 if list_origin.y + list_height > text_hitbox.lower_right().y {
2491 list_origin.y -= line_height + list_height;
2492 }
2493
2494 cx.defer_draw(context_menu, list_origin, 1);
2495 true
2496 }
2497
2498 fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
2499 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
2500 let mut element = deferred(
2501 anchored()
2502 .position(mouse_context_menu.position)
2503 .child(mouse_context_menu.context_menu.clone())
2504 .anchor(AnchorCorner::TopLeft)
2505 .snap_to_window(),
2506 )
2507 .with_priority(1)
2508 .into_any();
2509
2510 element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2511 Some(element)
2512 }
2513
2514 #[allow(clippy::too_many_arguments)]
2515 fn layout_hover_popovers(
2516 &self,
2517 snapshot: &EditorSnapshot,
2518 hitbox: &Hitbox,
2519 text_hitbox: &Hitbox,
2520 visible_display_row_range: Range<DisplayRow>,
2521 content_origin: gpui::Point<Pixels>,
2522 scroll_pixel_position: gpui::Point<Pixels>,
2523 line_layouts: &[LineWithInvisibles],
2524 line_height: Pixels,
2525 em_width: Pixels,
2526 cx: &mut WindowContext,
2527 ) {
2528 struct MeasuredHoverPopover {
2529 element: AnyElement,
2530 size: Size<Pixels>,
2531 horizontal_offset: Pixels,
2532 }
2533
2534 let max_size = size(
2535 (120. * em_width) // Default size
2536 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2537 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2538 (16. * line_height) // Default size
2539 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2540 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2541 );
2542
2543 let hover_popovers = self.editor.update(cx, |editor, cx| {
2544 editor.hover_state.render(
2545 &snapshot,
2546 &self.style,
2547 visible_display_row_range.clone(),
2548 max_size,
2549 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2550 cx,
2551 )
2552 });
2553 let Some((position, hover_popovers)) = hover_popovers else {
2554 return;
2555 };
2556
2557 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2558
2559 // This is safe because we check on layout whether the required row is available
2560 let hovered_row_layout =
2561 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2562
2563 // Compute Hovered Point
2564 let x =
2565 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2566 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2567 let hovered_point = content_origin + point(x, y);
2568
2569 let mut overall_height = Pixels::ZERO;
2570 let mut measured_hover_popovers = Vec::new();
2571 for mut hover_popover in hover_popovers {
2572 let size = hover_popover.layout_as_root(available_space, cx);
2573 let horizontal_offset =
2574 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2575
2576 overall_height += HOVER_POPOVER_GAP + size.height;
2577
2578 measured_hover_popovers.push(MeasuredHoverPopover {
2579 element: hover_popover,
2580 size,
2581 horizontal_offset,
2582 });
2583 }
2584 overall_height += HOVER_POPOVER_GAP;
2585
2586 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2587 let mut occlusion = div()
2588 .size_full()
2589 .occlude()
2590 .on_mouse_move(|_, cx| cx.stop_propagation())
2591 .into_any_element();
2592 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2593 cx.defer_draw(occlusion, origin, 2);
2594 }
2595
2596 if hovered_point.y > overall_height {
2597 // There is enough space above. Render popovers above the hovered point
2598 let mut current_y = hovered_point.y;
2599 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2600 let size = popover.size;
2601 let popover_origin = point(
2602 hovered_point.x + popover.horizontal_offset,
2603 current_y - size.height,
2604 );
2605
2606 cx.defer_draw(popover.element, popover_origin, 2);
2607 if position != itertools::Position::Last {
2608 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2609 draw_occluder(size.width, origin, cx);
2610 }
2611
2612 current_y = popover_origin.y - HOVER_POPOVER_GAP;
2613 }
2614 } else {
2615 // There is not enough space above. Render popovers below the hovered point
2616 let mut current_y = hovered_point.y + line_height;
2617 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2618 let size = popover.size;
2619 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2620
2621 cx.defer_draw(popover.element, popover_origin, 2);
2622 if position != itertools::Position::Last {
2623 let origin = point(popover_origin.x, popover_origin.y + size.height);
2624 draw_occluder(size.width, origin, cx);
2625 }
2626
2627 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2628 }
2629 }
2630 }
2631
2632 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2633 cx.paint_layer(layout.hitbox.bounds, |cx| {
2634 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2635 let gutter_bg = cx.theme().colors().editor_gutter_background;
2636 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2637 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2638
2639 if let EditorMode::Full = layout.mode {
2640 let mut active_rows = layout.active_rows.iter().peekable();
2641 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2642 let mut end_row = start_row.0;
2643 while active_rows
2644 .peek()
2645 .map_or(false, |(active_row, has_selection)| {
2646 active_row.0 == end_row + 1
2647 && *has_selection == contains_non_empty_selection
2648 })
2649 {
2650 active_rows.next().unwrap();
2651 end_row += 1;
2652 }
2653
2654 if !contains_non_empty_selection {
2655 let highlight_h_range =
2656 match layout.position_map.snapshot.current_line_highlight {
2657 CurrentLineHighlight::Gutter => Some(Range {
2658 start: layout.hitbox.left(),
2659 end: layout.gutter_hitbox.right(),
2660 }),
2661 CurrentLineHighlight::Line => Some(Range {
2662 start: layout.text_hitbox.bounds.left(),
2663 end: layout.text_hitbox.bounds.right(),
2664 }),
2665 CurrentLineHighlight::All => Some(Range {
2666 start: layout.hitbox.left(),
2667 end: layout.hitbox.right(),
2668 }),
2669 CurrentLineHighlight::None => None,
2670 };
2671 if let Some(range) = highlight_h_range {
2672 let active_line_bg = cx.theme().colors().editor_active_line_background;
2673 let bounds = Bounds {
2674 origin: point(
2675 range.start,
2676 layout.hitbox.origin.y
2677 + (start_row.as_f32() - scroll_top)
2678 * layout.position_map.line_height,
2679 ),
2680 size: size(
2681 range.end - range.start,
2682 layout.position_map.line_height
2683 * (end_row - start_row.0 + 1) as f32,
2684 ),
2685 };
2686 cx.paint_quad(fill(bounds, active_line_bg));
2687 }
2688 }
2689 }
2690
2691 let mut paint_highlight =
2692 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
2693 let origin = point(
2694 layout.hitbox.origin.x,
2695 layout.hitbox.origin.y
2696 + (highlight_row_start.as_f32() - scroll_top)
2697 * layout.position_map.line_height,
2698 );
2699 let size = size(
2700 layout.hitbox.size.width,
2701 layout.position_map.line_height
2702 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
2703 );
2704 cx.paint_quad(fill(Bounds { origin, size }, color));
2705 };
2706
2707 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
2708 for (&new_row, &new_color) in &layout.highlighted_rows {
2709 match &mut current_paint {
2710 Some((current_color, current_range)) => {
2711 let current_color = *current_color;
2712 let new_range_started = current_color != new_color
2713 || current_range.end.next_row() != new_row;
2714 if new_range_started {
2715 paint_highlight(
2716 current_range.start,
2717 current_range.end,
2718 current_color,
2719 );
2720 current_paint = Some((new_color, new_row..new_row));
2721 continue;
2722 } else {
2723 current_range.end = current_range.end.next_row();
2724 }
2725 }
2726 None => current_paint = Some((new_color, new_row..new_row)),
2727 };
2728 }
2729 if let Some((color, range)) = current_paint {
2730 paint_highlight(range.start, range.end, color);
2731 }
2732
2733 let scroll_left =
2734 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2735
2736 for (wrap_position, active) in layout.wrap_guides.iter() {
2737 let x = (layout.text_hitbox.origin.x
2738 + *wrap_position
2739 + layout.position_map.em_width / 2.)
2740 - scroll_left;
2741
2742 let show_scrollbars = layout
2743 .scrollbar_layout
2744 .as_ref()
2745 .map_or(false, |scrollbar| scrollbar.visible);
2746 if x < layout.text_hitbox.origin.x
2747 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2748 {
2749 continue;
2750 }
2751
2752 let color = if *active {
2753 cx.theme().colors().editor_active_wrap_guide
2754 } else {
2755 cx.theme().colors().editor_wrap_guide
2756 };
2757 cx.paint_quad(fill(
2758 Bounds {
2759 origin: point(x, layout.text_hitbox.origin.y),
2760 size: size(px(1.), layout.text_hitbox.size.height),
2761 },
2762 color,
2763 ));
2764 }
2765 }
2766 })
2767 }
2768
2769 fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2770 let Some(indent_guides) = &layout.indent_guides else {
2771 return;
2772 };
2773
2774 let faded_color = |color: Hsla, alpha: f32| {
2775 let mut faded = color;
2776 faded.a = alpha;
2777 faded
2778 };
2779
2780 for indent_guide in indent_guides {
2781 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
2782 let settings = indent_guide.settings;
2783
2784 // TODO fixed for now, expose them through themes later
2785 const INDENT_AWARE_ALPHA: f32 = 0.2;
2786 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
2787 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
2788 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
2789
2790 let line_color = match (settings.coloring, indent_guide.active) {
2791 (IndentGuideColoring::Disabled, _) => None,
2792 (IndentGuideColoring::Fixed, false) => {
2793 Some(cx.theme().colors().editor_indent_guide)
2794 }
2795 (IndentGuideColoring::Fixed, true) => {
2796 Some(cx.theme().colors().editor_indent_guide_active)
2797 }
2798 (IndentGuideColoring::IndentAware, false) => {
2799 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
2800 }
2801 (IndentGuideColoring::IndentAware, true) => {
2802 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
2803 }
2804 };
2805
2806 let background_color = match (settings.background_coloring, indent_guide.active) {
2807 (IndentGuideBackgroundColoring::Disabled, _) => None,
2808 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
2809 indent_accent_colors,
2810 INDENT_AWARE_BACKGROUND_ALPHA,
2811 )),
2812 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
2813 indent_accent_colors,
2814 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
2815 )),
2816 };
2817
2818 let requested_line_width = if indent_guide.active {
2819 settings.active_line_width
2820 } else {
2821 settings.line_width
2822 }
2823 .clamp(1, 10);
2824 let mut line_indicator_width = 0.;
2825 if let Some(color) = line_color {
2826 cx.paint_quad(fill(
2827 Bounds {
2828 origin: indent_guide.origin,
2829 size: size(px(requested_line_width as f32), indent_guide.length),
2830 },
2831 color,
2832 ));
2833 line_indicator_width = requested_line_width as f32;
2834 }
2835
2836 if let Some(color) = background_color {
2837 let width = indent_guide.single_indent_width - px(line_indicator_width);
2838 cx.paint_quad(fill(
2839 Bounds {
2840 origin: point(
2841 indent_guide.origin.x + px(line_indicator_width),
2842 indent_guide.origin.y,
2843 ),
2844 size: size(width, indent_guide.length),
2845 },
2846 color,
2847 ));
2848 }
2849 }
2850 }
2851
2852 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2853 let line_height = layout.position_map.line_height;
2854 let scroll_position = layout.position_map.snapshot.scroll_position();
2855 let scroll_top = scroll_position.y * line_height;
2856
2857 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2858
2859 for (ix, line) in layout.line_numbers.iter().enumerate() {
2860 if let Some(line) = line {
2861 let line_origin = layout.gutter_hitbox.origin
2862 + point(
2863 layout.gutter_hitbox.size.width
2864 - line.width
2865 - layout.gutter_dimensions.right_padding,
2866 ix as f32 * line_height - (scroll_top % line_height),
2867 );
2868
2869 line.paint(line_origin, line_height, cx).log_err();
2870 }
2871 }
2872 }
2873
2874 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut WindowContext) {
2875 if layout.display_hunks.is_empty() {
2876 return;
2877 }
2878
2879 let line_height = layout.position_map.line_height;
2880 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2881 for (hunk, hitbox) in &layout.display_hunks {
2882 let hunk_to_paint = match hunk {
2883 DisplayDiffHunk::Folded { .. } => {
2884 let hunk_bounds = Self::diff_hunk_bounds(
2885 &layout.position_map.snapshot,
2886 line_height,
2887 layout.gutter_hitbox.bounds,
2888 &hunk,
2889 );
2890 Some((
2891 hunk_bounds,
2892 cx.theme().status().modified,
2893 Corners::all(1. * line_height),
2894 ))
2895 }
2896 DisplayDiffHunk::Unfolded { status, .. } => {
2897 hitbox.as_ref().map(|hunk_hitbox| match status {
2898 DiffHunkStatus::Added => (
2899 hunk_hitbox.bounds,
2900 cx.theme().status().created,
2901 Corners::all(0.05 * line_height),
2902 ),
2903 DiffHunkStatus::Modified => (
2904 hunk_hitbox.bounds,
2905 cx.theme().status().modified,
2906 Corners::all(0.05 * line_height),
2907 ),
2908 DiffHunkStatus::Removed => (
2909 Bounds::new(
2910 point(
2911 hunk_hitbox.origin.x - hunk_hitbox.size.width,
2912 hunk_hitbox.origin.y,
2913 ),
2914 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
2915 ),
2916 cx.theme().status().deleted,
2917 Corners::all(1. * line_height),
2918 ),
2919 })
2920 }
2921 };
2922
2923 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2924 cx.paint_quad(quad(
2925 hunk_bounds,
2926 corner_radii,
2927 background_color,
2928 Edges::default(),
2929 transparent_black(),
2930 ));
2931 }
2932 }
2933 });
2934 }
2935
2936 fn diff_hunk_bounds(
2937 snapshot: &EditorSnapshot,
2938 line_height: Pixels,
2939 bounds: Bounds<Pixels>,
2940 hunk: &DisplayDiffHunk,
2941 ) -> Bounds<Pixels> {
2942 let scroll_position = snapshot.scroll_position();
2943 let scroll_top = scroll_position.y * line_height;
2944
2945 match hunk {
2946 DisplayDiffHunk::Folded { display_row, .. } => {
2947 let start_y = display_row.as_f32() * line_height - scroll_top;
2948 let end_y = start_y + line_height;
2949
2950 let width = 0.275 * line_height;
2951 let highlight_origin = bounds.origin + point(px(0.), start_y);
2952 let highlight_size = size(width, end_y - start_y);
2953 Bounds::new(highlight_origin, highlight_size)
2954 }
2955 DisplayDiffHunk::Unfolded {
2956 display_row_range,
2957 status,
2958 ..
2959 } => match status {
2960 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2961 let start_row = display_row_range.start;
2962 let end_row = display_row_range.end;
2963 // If we're in a multibuffer, row range span might include an
2964 // excerpt header, so if we were to draw the marker straight away,
2965 // the hunk might include the rows of that header.
2966 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2967 // Instead, we simply check whether the range we're dealing with includes
2968 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2969 let end_row_in_current_excerpt = snapshot
2970 .blocks_in_range(start_row..end_row)
2971 .find_map(|(start_row, block)| {
2972 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2973 Some(start_row)
2974 } else {
2975 None
2976 }
2977 })
2978 .unwrap_or(end_row);
2979
2980 let start_y = start_row.as_f32() * line_height - scroll_top;
2981 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
2982
2983 let width = 0.275 * line_height;
2984 let highlight_origin = bounds.origin + point(px(0.), start_y);
2985 let highlight_size = size(width, end_y - start_y);
2986 Bounds::new(highlight_origin, highlight_size)
2987 }
2988 DiffHunkStatus::Removed => {
2989 let row = display_row_range.start;
2990
2991 let offset = line_height / 2.;
2992 let start_y = row.as_f32() * line_height - offset - scroll_top;
2993 let end_y = start_y + line_height;
2994
2995 let width = 0.35 * line_height;
2996 let highlight_origin = bounds.origin + point(px(0.), start_y);
2997 let highlight_size = size(width, end_y - start_y);
2998 Bounds::new(highlight_origin, highlight_size)
2999 }
3000 },
3001 }
3002 }
3003
3004 fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3005 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3006 cx.with_element_namespace("gutter_fold_toggles", |cx| {
3007 for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
3008 fold_indicator.paint(cx);
3009 }
3010 });
3011
3012 for test_indicators in layout.test_indicators.iter_mut() {
3013 test_indicators.paint(cx);
3014 }
3015
3016 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3017 indicator.paint(cx);
3018 }
3019 });
3020 }
3021
3022 fn paint_gutter_highlights(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3023 for (_, hunk_hitbox) in &layout.display_hunks {
3024 if let Some(hunk_hitbox) = hunk_hitbox {
3025 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3026 }
3027 }
3028
3029 let show_git_gutter = layout
3030 .position_map
3031 .snapshot
3032 .show_git_diff_gutter
3033 .unwrap_or_else(|| {
3034 matches!(
3035 ProjectSettings::get_global(cx).git.git_gutter,
3036 Some(GitGutterSetting::TrackedFiles)
3037 )
3038 });
3039 if show_git_gutter {
3040 Self::paint_diff_hunks(layout, cx)
3041 }
3042
3043 let highlight_width = 0.275 * layout.position_map.line_height;
3044 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3045 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3046 for (range, color) in &layout.highlighted_gutter_ranges {
3047 let start_row = if range.start.row() < layout.visible_display_row_range.start {
3048 layout.visible_display_row_range.start - DisplayRow(1)
3049 } else {
3050 range.start.row()
3051 };
3052 let end_row = if range.end.row() > layout.visible_display_row_range.end {
3053 layout.visible_display_row_range.end + DisplayRow(1)
3054 } else {
3055 range.end.row()
3056 };
3057
3058 let start_y = layout.gutter_hitbox.top()
3059 + start_row.0 as f32 * layout.position_map.line_height
3060 - layout.position_map.scroll_pixel_position.y;
3061 let end_y = layout.gutter_hitbox.top()
3062 + (end_row.0 + 1) as f32 * layout.position_map.line_height
3063 - layout.position_map.scroll_pixel_position.y;
3064 let bounds = Bounds::from_corners(
3065 point(layout.gutter_hitbox.left(), start_y),
3066 point(layout.gutter_hitbox.left() + highlight_width, end_y),
3067 );
3068 cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3069 }
3070 });
3071 }
3072
3073 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3074 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3075 return;
3076 };
3077
3078 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3079 for mut blame_element in blamed_display_rows.into_iter() {
3080 blame_element.paint(cx);
3081 }
3082 })
3083 }
3084
3085 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3086 cx.with_content_mask(
3087 Some(ContentMask {
3088 bounds: layout.text_hitbox.bounds,
3089 }),
3090 |cx| {
3091 let cursor_style = if self
3092 .editor
3093 .read(cx)
3094 .hovered_link_state
3095 .as_ref()
3096 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3097 {
3098 CursorStyle::PointingHand
3099 } else {
3100 CursorStyle::IBeam
3101 };
3102 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3103
3104 let invisible_display_ranges = self.paint_highlights(layout, cx);
3105 self.paint_lines(&invisible_display_ranges, layout, cx);
3106 self.paint_redactions(layout, cx);
3107 self.paint_cursors(layout, cx);
3108 self.paint_inline_blame(layout, cx);
3109 cx.with_element_namespace("crease_trailers", |cx| {
3110 for trailer in layout.crease_trailers.iter_mut().flatten() {
3111 trailer.element.paint(cx);
3112 }
3113 });
3114 },
3115 )
3116 }
3117
3118 fn paint_highlights(
3119 &mut self,
3120 layout: &mut EditorLayout,
3121 cx: &mut WindowContext,
3122 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3123 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3124 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3125 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3126 for (range, color) in &layout.highlighted_ranges {
3127 self.paint_highlighted_range(
3128 range.clone(),
3129 *color,
3130 Pixels::ZERO,
3131 line_end_overshoot,
3132 layout,
3133 cx,
3134 );
3135 }
3136
3137 let corner_radius = 0.15 * layout.position_map.line_height;
3138
3139 for (player_color, selections) in &layout.selections {
3140 for selection in selections.into_iter() {
3141 self.paint_highlighted_range(
3142 selection.range.clone(),
3143 player_color.selection,
3144 corner_radius,
3145 corner_radius * 2.,
3146 layout,
3147 cx,
3148 );
3149
3150 if selection.is_local && !selection.range.is_empty() {
3151 invisible_display_ranges.push(selection.range.clone());
3152 }
3153 }
3154 }
3155 invisible_display_ranges
3156 })
3157 }
3158
3159 fn paint_lines(
3160 &mut self,
3161 invisible_display_ranges: &[Range<DisplayPoint>],
3162 layout: &mut EditorLayout,
3163 cx: &mut WindowContext,
3164 ) {
3165 let whitespace_setting = self
3166 .editor
3167 .read(cx)
3168 .buffer
3169 .read(cx)
3170 .settings_at(0, cx)
3171 .show_whitespaces;
3172
3173 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3174 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3175 line_with_invisibles.draw(
3176 layout,
3177 row,
3178 layout.content_origin,
3179 whitespace_setting,
3180 invisible_display_ranges,
3181 cx,
3182 )
3183 }
3184
3185 for line_element in &mut layout.line_elements {
3186 line_element.paint(cx);
3187 }
3188 }
3189
3190 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3191 if layout.redacted_ranges.is_empty() {
3192 return;
3193 }
3194
3195 let line_end_overshoot = layout.line_end_overshoot();
3196
3197 // A softer than perfect black
3198 let redaction_color = gpui::rgb(0x0e1111);
3199
3200 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3201 for range in layout.redacted_ranges.iter() {
3202 self.paint_highlighted_range(
3203 range.clone(),
3204 redaction_color.into(),
3205 Pixels::ZERO,
3206 line_end_overshoot,
3207 layout,
3208 cx,
3209 );
3210 }
3211 });
3212 }
3213
3214 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3215 for cursor in &mut layout.visible_cursors {
3216 cursor.paint(layout.content_origin, cx);
3217 }
3218 }
3219
3220 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3221 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3222 return;
3223 };
3224
3225 let thumb_bounds = scrollbar_layout.thumb_bounds();
3226 if scrollbar_layout.visible {
3227 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3228 cx.paint_quad(quad(
3229 scrollbar_layout.hitbox.bounds,
3230 Corners::default(),
3231 cx.theme().colors().scrollbar_track_background,
3232 Edges {
3233 top: Pixels::ZERO,
3234 right: Pixels::ZERO,
3235 bottom: Pixels::ZERO,
3236 left: ScrollbarLayout::BORDER_WIDTH,
3237 },
3238 cx.theme().colors().scrollbar_track_border,
3239 ));
3240
3241 let fast_markers =
3242 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3243 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3244 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3245
3246 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3247 for marker in markers.iter().chain(&fast_markers) {
3248 let mut marker = marker.clone();
3249 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3250 cx.paint_quad(marker);
3251 }
3252
3253 cx.paint_quad(quad(
3254 thumb_bounds,
3255 Corners::default(),
3256 cx.theme().colors().scrollbar_thumb_background,
3257 Edges {
3258 top: Pixels::ZERO,
3259 right: Pixels::ZERO,
3260 bottom: Pixels::ZERO,
3261 left: ScrollbarLayout::BORDER_WIDTH,
3262 },
3263 cx.theme().colors().scrollbar_thumb_border,
3264 ));
3265 });
3266 }
3267
3268 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3269
3270 let row_height = scrollbar_layout.row_height;
3271 let row_range = scrollbar_layout.visible_row_range.clone();
3272
3273 cx.on_mouse_event({
3274 let editor = self.editor.clone();
3275 let hitbox = scrollbar_layout.hitbox.clone();
3276 let mut mouse_position = cx.mouse_position();
3277 move |event: &MouseMoveEvent, phase, cx| {
3278 if phase == DispatchPhase::Capture {
3279 return;
3280 }
3281
3282 editor.update(cx, |editor, cx| {
3283 if event.pressed_button == Some(MouseButton::Left)
3284 && editor.scroll_manager.is_dragging_scrollbar()
3285 {
3286 let y = mouse_position.y;
3287 let new_y = event.position.y;
3288 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3289 let mut position = editor.scroll_position(cx);
3290 position.y += (new_y - y) / row_height;
3291 if position.y < 0.0 {
3292 position.y = 0.0;
3293 }
3294 editor.set_scroll_position(position, cx);
3295 }
3296
3297 cx.stop_propagation();
3298 } else {
3299 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3300 if hitbox.is_hovered(cx) {
3301 editor.scroll_manager.show_scrollbar(cx);
3302 }
3303 }
3304 mouse_position = event.position;
3305 })
3306 }
3307 });
3308
3309 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3310 cx.on_mouse_event({
3311 let editor = self.editor.clone();
3312 move |_: &MouseUpEvent, phase, cx| {
3313 if phase == DispatchPhase::Capture {
3314 return;
3315 }
3316
3317 editor.update(cx, |editor, cx| {
3318 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3319 cx.stop_propagation();
3320 });
3321 }
3322 });
3323 } else {
3324 cx.on_mouse_event({
3325 let editor = self.editor.clone();
3326 let hitbox = scrollbar_layout.hitbox.clone();
3327 move |event: &MouseDownEvent, phase, cx| {
3328 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3329 return;
3330 }
3331
3332 editor.update(cx, |editor, cx| {
3333 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3334
3335 let y = event.position.y;
3336 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3337 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3338 let top_row = center_row
3339 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3340 let mut position = editor.scroll_position(cx);
3341 position.y = top_row as f32;
3342 editor.set_scroll_position(position, cx);
3343 } else {
3344 editor.scroll_manager.show_scrollbar(cx);
3345 }
3346
3347 cx.stop_propagation();
3348 });
3349 }
3350 });
3351 }
3352 }
3353
3354 fn collect_fast_scrollbar_markers(
3355 &self,
3356 layout: &EditorLayout,
3357 scrollbar_layout: &ScrollbarLayout,
3358 cx: &mut WindowContext,
3359 ) -> Vec<PaintQuad> {
3360 const LIMIT: usize = 100;
3361 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3362 return vec![];
3363 }
3364 let cursor_ranges = layout
3365 .cursors
3366 .iter()
3367 .map(|(point, color)| ColoredRange {
3368 start: point.row(),
3369 end: point.row(),
3370 color: *color,
3371 })
3372 .collect_vec();
3373 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3374 }
3375
3376 fn refresh_slow_scrollbar_markers(
3377 &self,
3378 layout: &EditorLayout,
3379 scrollbar_layout: &ScrollbarLayout,
3380 cx: &mut WindowContext,
3381 ) {
3382 self.editor.update(cx, |editor, cx| {
3383 if !editor.is_singleton(cx)
3384 || !editor
3385 .scrollbar_marker_state
3386 .should_refresh(scrollbar_layout.hitbox.size)
3387 {
3388 return;
3389 }
3390
3391 let scrollbar_layout = scrollbar_layout.clone();
3392 let background_highlights = editor.background_highlights.clone();
3393 let snapshot = layout.position_map.snapshot.clone();
3394 let theme = cx.theme().clone();
3395 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3396
3397 editor.scrollbar_marker_state.dirty = false;
3398 editor.scrollbar_marker_state.pending_refresh =
3399 Some(cx.spawn(|editor, mut cx| async move {
3400 let scrollbar_size = scrollbar_layout.hitbox.size;
3401 let scrollbar_markers = cx
3402 .background_executor()
3403 .spawn(async move {
3404 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3405 let mut marker_quads = Vec::new();
3406 if scrollbar_settings.git_diff {
3407 let marker_row_ranges = snapshot
3408 .buffer_snapshot
3409 .git_diff_hunks_in_range(
3410 MultiBufferRow::MIN..MultiBufferRow::MAX,
3411 )
3412 .map(|hunk| {
3413 let start_display_row =
3414 MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3415 .to_display_point(&snapshot.display_snapshot)
3416 .row();
3417 let mut end_display_row =
3418 MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3419 .to_display_point(&snapshot.display_snapshot)
3420 .row();
3421 if end_display_row != start_display_row {
3422 end_display_row.0 -= 1;
3423 }
3424 let color = match hunk_status(&hunk) {
3425 DiffHunkStatus::Added => theme.status().created,
3426 DiffHunkStatus::Modified => theme.status().modified,
3427 DiffHunkStatus::Removed => theme.status().deleted,
3428 };
3429 ColoredRange {
3430 start: start_display_row,
3431 end: end_display_row,
3432 color,
3433 }
3434 });
3435
3436 marker_quads.extend(
3437 scrollbar_layout
3438 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3439 );
3440 }
3441
3442 for (background_highlight_id, (_, background_ranges)) in
3443 background_highlights.iter()
3444 {
3445 let is_search_highlights = *background_highlight_id
3446 == TypeId::of::<BufferSearchHighlights>();
3447 let is_symbol_occurrences = *background_highlight_id
3448 == TypeId::of::<DocumentHighlightRead>()
3449 || *background_highlight_id
3450 == TypeId::of::<DocumentHighlightWrite>();
3451 if (is_search_highlights && scrollbar_settings.search_results)
3452 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3453 {
3454 let mut color = theme.status().info;
3455 if is_symbol_occurrences {
3456 color.fade_out(0.5);
3457 }
3458 let marker_row_ranges =
3459 background_ranges.into_iter().map(|range| {
3460 let display_start = range
3461 .start
3462 .to_display_point(&snapshot.display_snapshot);
3463 let display_end = range
3464 .end
3465 .to_display_point(&snapshot.display_snapshot);
3466 ColoredRange {
3467 start: display_start.row(),
3468 end: display_end.row(),
3469 color,
3470 }
3471 });
3472 marker_quads.extend(
3473 scrollbar_layout
3474 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3475 );
3476 }
3477 }
3478
3479 if scrollbar_settings.diagnostics {
3480 let diagnostics = snapshot
3481 .buffer_snapshot
3482 .diagnostics_in_range::<_, Point>(
3483 Point::zero()..max_point,
3484 false,
3485 )
3486 // We want to sort by severity, in order to paint the most severe diagnostics last.
3487 .sorted_by_key(|diagnostic| {
3488 std::cmp::Reverse(diagnostic.diagnostic.severity)
3489 });
3490
3491 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3492 let start_display = diagnostic
3493 .range
3494 .start
3495 .to_display_point(&snapshot.display_snapshot);
3496 let end_display = diagnostic
3497 .range
3498 .end
3499 .to_display_point(&snapshot.display_snapshot);
3500 let color = match diagnostic.diagnostic.severity {
3501 DiagnosticSeverity::ERROR => theme.status().error,
3502 DiagnosticSeverity::WARNING => theme.status().warning,
3503 DiagnosticSeverity::INFORMATION => theme.status().info,
3504 _ => theme.status().hint,
3505 };
3506 ColoredRange {
3507 start: start_display.row(),
3508 end: end_display.row(),
3509 color,
3510 }
3511 });
3512 marker_quads.extend(
3513 scrollbar_layout
3514 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3515 );
3516 }
3517
3518 Arc::from(marker_quads)
3519 })
3520 .await;
3521
3522 editor.update(&mut cx, |editor, cx| {
3523 editor.scrollbar_marker_state.markers = scrollbar_markers;
3524 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3525 editor.scrollbar_marker_state.pending_refresh = None;
3526 cx.notify();
3527 })?;
3528
3529 Ok(())
3530 }));
3531 });
3532 }
3533
3534 #[allow(clippy::too_many_arguments)]
3535 fn paint_highlighted_range(
3536 &self,
3537 range: Range<DisplayPoint>,
3538 color: Hsla,
3539 corner_radius: Pixels,
3540 line_end_overshoot: Pixels,
3541 layout: &EditorLayout,
3542 cx: &mut WindowContext,
3543 ) {
3544 let start_row = layout.visible_display_row_range.start;
3545 let end_row = layout.visible_display_row_range.end;
3546 if range.start != range.end {
3547 let row_range = if range.end.column() == 0 {
3548 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3549 } else {
3550 cmp::max(range.start.row(), start_row)
3551 ..cmp::min(range.end.row().next_row(), end_row)
3552 };
3553
3554 let highlighted_range = HighlightedRange {
3555 color,
3556 line_height: layout.position_map.line_height,
3557 corner_radius,
3558 start_y: layout.content_origin.y
3559 + row_range.start.as_f32() * layout.position_map.line_height
3560 - layout.position_map.scroll_pixel_position.y,
3561 lines: row_range
3562 .iter_rows()
3563 .map(|row| {
3564 let line_layout =
3565 &layout.position_map.line_layouts[row.minus(start_row) as usize];
3566 HighlightedRangeLine {
3567 start_x: if row == range.start.row() {
3568 layout.content_origin.x
3569 + line_layout.x_for_index(range.start.column() as usize)
3570 - layout.position_map.scroll_pixel_position.x
3571 } else {
3572 layout.content_origin.x
3573 - layout.position_map.scroll_pixel_position.x
3574 },
3575 end_x: if row == range.end.row() {
3576 layout.content_origin.x
3577 + line_layout.x_for_index(range.end.column() as usize)
3578 - layout.position_map.scroll_pixel_position.x
3579 } else {
3580 layout.content_origin.x + line_layout.width + line_end_overshoot
3581 - layout.position_map.scroll_pixel_position.x
3582 },
3583 }
3584 })
3585 .collect(),
3586 };
3587
3588 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3589 }
3590 }
3591
3592 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3593 if let Some(mut inline_blame) = layout.inline_blame.take() {
3594 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3595 inline_blame.paint(cx);
3596 })
3597 }
3598 }
3599
3600 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3601 for mut block in layout.blocks.drain(..) {
3602 block.element.paint(cx);
3603 }
3604 }
3605
3606 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3607 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3608 mouse_context_menu.paint(cx);
3609 }
3610 }
3611
3612 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3613 cx.on_mouse_event({
3614 let position_map = layout.position_map.clone();
3615 let editor = self.editor.clone();
3616 let hitbox = layout.hitbox.clone();
3617 let mut delta = ScrollDelta::default();
3618
3619 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3620 // accidentally turn off their scrolling.
3621 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3622
3623 move |event: &ScrollWheelEvent, phase, cx| {
3624 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3625 delta = delta.coalesce(event.delta);
3626 editor.update(cx, |editor, cx| {
3627 let position_map: &PositionMap = &position_map;
3628
3629 let line_height = position_map.line_height;
3630 let max_glyph_width = position_map.em_width;
3631 let (delta, axis) = match delta {
3632 gpui::ScrollDelta::Pixels(mut pixels) => {
3633 //Trackpad
3634 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3635 (pixels, axis)
3636 }
3637
3638 gpui::ScrollDelta::Lines(lines) => {
3639 //Not trackpad
3640 let pixels =
3641 point(lines.x * max_glyph_width, lines.y * line_height);
3642 (pixels, None)
3643 }
3644 };
3645
3646 let current_scroll_position = position_map.snapshot.scroll_position();
3647 let x = (current_scroll_position.x * max_glyph_width
3648 - (delta.x * scroll_sensitivity))
3649 / max_glyph_width;
3650 let y = (current_scroll_position.y * line_height
3651 - (delta.y * scroll_sensitivity))
3652 / line_height;
3653 let mut scroll_position =
3654 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3655 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3656 if forbid_vertical_scroll {
3657 scroll_position.y = current_scroll_position.y;
3658 }
3659
3660 if scroll_position != current_scroll_position {
3661 editor.scroll(scroll_position, axis, cx);
3662 cx.stop_propagation();
3663 } else if y < 0. {
3664 // Due to clamping, we may fail to detect cases of overscroll to the top;
3665 // We want the scroll manager to get an update in such cases and detect the change of direction
3666 // on the next frame.
3667 cx.notify();
3668 }
3669 });
3670 }
3671 }
3672 });
3673 }
3674
3675 fn paint_mouse_listeners(
3676 &mut self,
3677 layout: &EditorLayout,
3678 hovered_hunk: Option<HunkToExpand>,
3679 cx: &mut WindowContext,
3680 ) {
3681 self.paint_scroll_wheel_listener(layout, cx);
3682
3683 cx.on_mouse_event({
3684 let position_map = layout.position_map.clone();
3685 let editor = self.editor.clone();
3686 let text_hitbox = layout.text_hitbox.clone();
3687 let gutter_hitbox = layout.gutter_hitbox.clone();
3688
3689 move |event: &MouseDownEvent, phase, cx| {
3690 if phase == DispatchPhase::Bubble {
3691 match event.button {
3692 MouseButton::Left => editor.update(cx, |editor, cx| {
3693 Self::mouse_left_down(
3694 editor,
3695 event,
3696 hovered_hunk.as_ref(),
3697 &position_map,
3698 &text_hitbox,
3699 &gutter_hitbox,
3700 cx,
3701 );
3702 }),
3703 MouseButton::Right => editor.update(cx, |editor, cx| {
3704 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3705 }),
3706 MouseButton::Middle => editor.update(cx, |editor, cx| {
3707 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3708 }),
3709 _ => {}
3710 };
3711 }
3712 }
3713 });
3714
3715 cx.on_mouse_event({
3716 let editor = self.editor.clone();
3717 let position_map = layout.position_map.clone();
3718 let text_hitbox = layout.text_hitbox.clone();
3719
3720 move |event: &MouseUpEvent, phase, cx| {
3721 if phase == DispatchPhase::Bubble {
3722 editor.update(cx, |editor, cx| {
3723 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3724 });
3725 }
3726 }
3727 });
3728 cx.on_mouse_event({
3729 let position_map = layout.position_map.clone();
3730 let editor = self.editor.clone();
3731 let text_hitbox = layout.text_hitbox.clone();
3732 let gutter_hitbox = layout.gutter_hitbox.clone();
3733
3734 move |event: &MouseMoveEvent, phase, cx| {
3735 if phase == DispatchPhase::Bubble {
3736 editor.update(cx, |editor, cx| {
3737 if event.pressed_button == Some(MouseButton::Left)
3738 || event.pressed_button == Some(MouseButton::Middle)
3739 {
3740 Self::mouse_dragged(
3741 editor,
3742 event,
3743 &position_map,
3744 text_hitbox.bounds,
3745 cx,
3746 )
3747 }
3748
3749 Self::mouse_moved(
3750 editor,
3751 event,
3752 &position_map,
3753 &text_hitbox,
3754 &gutter_hitbox,
3755 cx,
3756 )
3757 });
3758 }
3759 }
3760 });
3761 }
3762
3763 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3764 bounds.upper_right().x - self.style.scrollbar_width
3765 }
3766
3767 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3768 let style = &self.style;
3769 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3770 let layout = cx
3771 .text_system()
3772 .shape_line(
3773 SharedString::from(" ".repeat(column)),
3774 font_size,
3775 &[TextRun {
3776 len: column,
3777 font: style.text.font(),
3778 color: Hsla::default(),
3779 background_color: None,
3780 underline: None,
3781 strikethrough: None,
3782 }],
3783 )
3784 .unwrap();
3785
3786 layout.width
3787 }
3788
3789 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3790 let digit_count = snapshot
3791 .max_buffer_row()
3792 .next_row()
3793 .as_f32()
3794 .log10()
3795 .floor() as usize
3796 + 1;
3797 self.column_pixels(digit_count, cx)
3798 }
3799}
3800
3801fn prepaint_gutter_button(
3802 button: IconButton,
3803 row: DisplayRow,
3804 line_height: Pixels,
3805 gutter_dimensions: &GutterDimensions,
3806 scroll_pixel_position: gpui::Point<Pixels>,
3807 gutter_hitbox: &Hitbox,
3808 cx: &mut WindowContext<'_>,
3809) -> AnyElement {
3810 let mut button = button.into_any_element();
3811 let available_space = size(
3812 AvailableSpace::MinContent,
3813 AvailableSpace::Definite(line_height),
3814 );
3815 let indicator_size = button.layout_as_root(available_space, cx);
3816
3817 let blame_width = gutter_dimensions
3818 .git_blame_entries_width
3819 .unwrap_or(Pixels::ZERO);
3820
3821 let mut x = blame_width;
3822 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3823 - indicator_size.width
3824 - blame_width;
3825 x += available_width / 2.;
3826
3827 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3828 y += (line_height - indicator_size.height) / 2.;
3829
3830 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3831 button
3832}
3833
3834fn render_inline_blame_entry(
3835 blame: &gpui::Model<GitBlame>,
3836 blame_entry: BlameEntry,
3837 style: &EditorStyle,
3838 workspace: Option<WeakView<Workspace>>,
3839 cx: &mut WindowContext<'_>,
3840) -> AnyElement {
3841 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3842
3843 let author = blame_entry.author.as_deref().unwrap_or_default();
3844 let text = format!("{}, {}", author, relative_timestamp);
3845
3846 let details = blame.read(cx).details_for_entry(&blame_entry);
3847
3848 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3849
3850 h_flex()
3851 .id("inline-blame")
3852 .w_full()
3853 .font_family(style.text.font().family)
3854 .text_color(cx.theme().status().hint)
3855 .line_height(style.text.line_height)
3856 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3857 .child(text)
3858 .gap_2()
3859 .hoverable_tooltip(move |_| tooltip.clone().into())
3860 .into_any()
3861}
3862
3863fn render_blame_entry(
3864 ix: usize,
3865 blame: &gpui::Model<GitBlame>,
3866 blame_entry: BlameEntry,
3867 style: &EditorStyle,
3868 last_used_color: &mut Option<(PlayerColor, Oid)>,
3869 editor: View<Editor>,
3870 cx: &mut WindowContext<'_>,
3871) -> AnyElement {
3872 let mut sha_color = cx
3873 .theme()
3874 .players()
3875 .color_for_participant(blame_entry.sha.into());
3876 // If the last color we used is the same as the one we get for this line, but
3877 // the commit SHAs are different, then we try again to get a different color.
3878 match *last_used_color {
3879 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3880 let index: u32 = blame_entry.sha.into();
3881 sha_color = cx.theme().players().color_for_participant(index + 1);
3882 }
3883 _ => {}
3884 };
3885 last_used_color.replace((sha_color, blame_entry.sha));
3886
3887 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3888
3889 let short_commit_id = blame_entry.sha.display_short();
3890
3891 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3892 let name = util::truncate_and_trailoff(author_name, 20);
3893
3894 let details = blame.read(cx).details_for_entry(&blame_entry);
3895
3896 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3897
3898 let tooltip = cx.new_view(|_| {
3899 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3900 });
3901
3902 h_flex()
3903 .w_full()
3904 .font_family(style.text.font().family)
3905 .line_height(style.text.line_height)
3906 .id(("blame", ix))
3907 .children([
3908 div()
3909 .text_color(sha_color.cursor)
3910 .child(short_commit_id)
3911 .mr_2(),
3912 div()
3913 .w_full()
3914 .h_flex()
3915 .justify_between()
3916 .text_color(cx.theme().status().hint)
3917 .child(name)
3918 .child(relative_timestamp),
3919 ])
3920 .on_mouse_down(MouseButton::Right, {
3921 let blame_entry = blame_entry.clone();
3922 let details = details.clone();
3923 move |event, cx| {
3924 deploy_blame_entry_context_menu(
3925 &blame_entry,
3926 details.as_ref(),
3927 editor.clone(),
3928 event.position,
3929 cx,
3930 );
3931 }
3932 })
3933 .hover(|style| style.bg(cx.theme().colors().element_hover))
3934 .when_some(
3935 details.and_then(|details| details.permalink),
3936 |this, url| {
3937 let url = url.clone();
3938 this.cursor_pointer().on_click(move |_, cx| {
3939 cx.stop_propagation();
3940 cx.open_url(url.as_str())
3941 })
3942 },
3943 )
3944 .hoverable_tooltip(move |_| tooltip.clone().into())
3945 .into_any()
3946}
3947
3948fn deploy_blame_entry_context_menu(
3949 blame_entry: &BlameEntry,
3950 details: Option<&CommitDetails>,
3951 editor: View<Editor>,
3952 position: gpui::Point<Pixels>,
3953 cx: &mut WindowContext<'_>,
3954) {
3955 let context_menu = ContextMenu::build(cx, move |this, _| {
3956 let sha = format!("{}", blame_entry.sha);
3957 this.entry("Copy commit SHA", None, move |cx| {
3958 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3959 })
3960 .when_some(
3961 details.and_then(|details| details.permalink.clone()),
3962 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
3963 )
3964 });
3965
3966 editor.update(cx, move |editor, cx| {
3967 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3968 cx.notify();
3969 });
3970}
3971
3972#[derive(Debug)]
3973pub(crate) struct LineWithInvisibles {
3974 fragments: SmallVec<[LineFragment; 1]>,
3975 invisibles: Vec<Invisible>,
3976 len: usize,
3977 width: Pixels,
3978 font_size: Pixels,
3979}
3980
3981#[allow(clippy::large_enum_variant)]
3982enum LineFragment {
3983 Text(ShapedLine),
3984 Element {
3985 element: Option<AnyElement>,
3986 size: Size<Pixels>,
3987 len: usize,
3988 },
3989}
3990
3991impl fmt::Debug for LineFragment {
3992 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3993 match self {
3994 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
3995 LineFragment::Element { size, len, .. } => f
3996 .debug_struct("Element")
3997 .field("size", size)
3998 .field("len", len)
3999 .finish(),
4000 }
4001 }
4002}
4003
4004impl LineWithInvisibles {
4005 fn from_chunks<'a>(
4006 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4007 text_style: &TextStyle,
4008 max_line_len: usize,
4009 max_line_count: usize,
4010 line_number_layouts: &[Option<ShapedLine>],
4011 editor_mode: EditorMode,
4012 cx: &mut WindowContext,
4013 ) -> Vec<Self> {
4014 let mut layouts = Vec::with_capacity(max_line_count);
4015 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4016 let mut line = String::new();
4017 let mut invisibles = Vec::new();
4018 let mut width = Pixels::ZERO;
4019 let mut len = 0;
4020 let mut styles = Vec::new();
4021 let mut non_whitespace_added = false;
4022 let mut row = 0;
4023 let mut line_exceeded_max_len = false;
4024 let font_size = text_style.font_size.to_pixels(cx.rem_size());
4025
4026 let ellipsis = SharedString::from("⋯");
4027
4028 for highlighted_chunk in chunks.chain([HighlightedChunk {
4029 text: "\n",
4030 style: None,
4031 is_tab: false,
4032 renderer: None,
4033 }]) {
4034 if let Some(renderer) = highlighted_chunk.renderer {
4035 if !line.is_empty() {
4036 let shaped_line = cx
4037 .text_system()
4038 .shape_line(line.clone().into(), font_size, &styles)
4039 .unwrap();
4040 width += shaped_line.width;
4041 len += shaped_line.len;
4042 fragments.push(LineFragment::Text(shaped_line));
4043 line.clear();
4044 styles.clear();
4045 }
4046
4047 let available_width = if renderer.constrain_width {
4048 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4049 ellipsis.clone()
4050 } else {
4051 SharedString::from(Arc::from(highlighted_chunk.text))
4052 };
4053 let shaped_line = cx
4054 .text_system()
4055 .shape_line(
4056 chunk,
4057 font_size,
4058 &[text_style.to_run(highlighted_chunk.text.len())],
4059 )
4060 .unwrap();
4061 AvailableSpace::Definite(shaped_line.width)
4062 } else {
4063 AvailableSpace::MinContent
4064 };
4065
4066 let mut element = (renderer.render)(cx);
4067 let line_height = text_style.line_height_in_pixels(cx.rem_size());
4068 let size = element.layout_as_root(
4069 size(available_width, AvailableSpace::Definite(line_height)),
4070 cx,
4071 );
4072
4073 width += size.width;
4074 len += highlighted_chunk.text.len();
4075 fragments.push(LineFragment::Element {
4076 element: Some(element),
4077 size,
4078 len: highlighted_chunk.text.len(),
4079 });
4080 } else {
4081 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4082 if ix > 0 {
4083 let shaped_line = cx
4084 .text_system()
4085 .shape_line(line.clone().into(), font_size, &styles)
4086 .unwrap();
4087 width += shaped_line.width;
4088 len += shaped_line.len;
4089 fragments.push(LineFragment::Text(shaped_line));
4090 layouts.push(Self {
4091 width: mem::take(&mut width),
4092 len: mem::take(&mut len),
4093 fragments: mem::take(&mut fragments),
4094 invisibles: std::mem::take(&mut invisibles),
4095 font_size,
4096 });
4097
4098 line.clear();
4099 styles.clear();
4100 row += 1;
4101 line_exceeded_max_len = false;
4102 non_whitespace_added = false;
4103 if row == max_line_count {
4104 return layouts;
4105 }
4106 }
4107
4108 if !line_chunk.is_empty() && !line_exceeded_max_len {
4109 let text_style = if let Some(style) = highlighted_chunk.style {
4110 Cow::Owned(text_style.clone().highlight(style))
4111 } else {
4112 Cow::Borrowed(text_style)
4113 };
4114
4115 if line.len() + line_chunk.len() > max_line_len {
4116 let mut chunk_len = max_line_len - line.len();
4117 while !line_chunk.is_char_boundary(chunk_len) {
4118 chunk_len -= 1;
4119 }
4120 line_chunk = &line_chunk[..chunk_len];
4121 line_exceeded_max_len = true;
4122 }
4123
4124 styles.push(TextRun {
4125 len: line_chunk.len(),
4126 font: text_style.font(),
4127 color: text_style.color,
4128 background_color: text_style.background_color,
4129 underline: text_style.underline,
4130 strikethrough: text_style.strikethrough,
4131 });
4132
4133 if editor_mode == EditorMode::Full {
4134 // Line wrap pads its contents with fake whitespaces,
4135 // avoid printing them
4136 let inside_wrapped_string = line_number_layouts
4137 .get(row)
4138 .and_then(|layout| layout.as_ref())
4139 .is_none();
4140 if highlighted_chunk.is_tab {
4141 if non_whitespace_added || !inside_wrapped_string {
4142 invisibles.push(Invisible::Tab {
4143 line_start_offset: line.len(),
4144 line_end_offset: line.len() + line_chunk.len(),
4145 });
4146 }
4147 } else {
4148 invisibles.extend(
4149 line_chunk
4150 .bytes()
4151 .enumerate()
4152 .filter(|(_, line_byte)| {
4153 let is_whitespace =
4154 (*line_byte as char).is_whitespace();
4155 non_whitespace_added |= !is_whitespace;
4156 is_whitespace
4157 && (non_whitespace_added || !inside_wrapped_string)
4158 })
4159 .map(|(whitespace_index, _)| Invisible::Whitespace {
4160 line_offset: line.len() + whitespace_index,
4161 }),
4162 )
4163 }
4164 }
4165
4166 line.push_str(line_chunk);
4167 }
4168 }
4169 }
4170 }
4171
4172 layouts
4173 }
4174
4175 fn prepaint(
4176 &mut self,
4177 line_height: Pixels,
4178 scroll_pixel_position: gpui::Point<Pixels>,
4179 row: DisplayRow,
4180 content_origin: gpui::Point<Pixels>,
4181 line_elements: &mut SmallVec<[AnyElement; 1]>,
4182 cx: &mut WindowContext,
4183 ) {
4184 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4185 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4186 for fragment in &mut self.fragments {
4187 match fragment {
4188 LineFragment::Text(line) => {
4189 fragment_origin.x += line.width;
4190 }
4191 LineFragment::Element { element, size, .. } => {
4192 let mut element = element
4193 .take()
4194 .expect("you can't prepaint LineWithInvisibles twice");
4195
4196 // Center the element vertically within the line.
4197 let mut element_origin = fragment_origin;
4198 element_origin.y += (line_height - size.height) / 2.;
4199 element.prepaint_at(element_origin, cx);
4200 line_elements.push(element);
4201
4202 fragment_origin.x += size.width;
4203 }
4204 }
4205 }
4206 }
4207
4208 fn draw(
4209 &self,
4210 layout: &EditorLayout,
4211 row: DisplayRow,
4212 content_origin: gpui::Point<Pixels>,
4213 whitespace_setting: ShowWhitespaceSetting,
4214 selection_ranges: &[Range<DisplayPoint>],
4215 cx: &mut WindowContext,
4216 ) {
4217 let line_height = layout.position_map.line_height;
4218 let line_y = line_height
4219 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4220
4221 let mut fragment_origin =
4222 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4223
4224 for fragment in &self.fragments {
4225 match fragment {
4226 LineFragment::Text(line) => {
4227 line.paint(fragment_origin, line_height, cx).log_err();
4228 fragment_origin.x += line.width;
4229 }
4230 LineFragment::Element { size, .. } => {
4231 fragment_origin.x += size.width;
4232 }
4233 }
4234 }
4235
4236 self.draw_invisibles(
4237 &selection_ranges,
4238 layout,
4239 content_origin,
4240 line_y,
4241 row,
4242 line_height,
4243 whitespace_setting,
4244 cx,
4245 );
4246 }
4247
4248 #[allow(clippy::too_many_arguments)]
4249 fn draw_invisibles(
4250 &self,
4251 selection_ranges: &[Range<DisplayPoint>],
4252 layout: &EditorLayout,
4253 content_origin: gpui::Point<Pixels>,
4254 line_y: Pixels,
4255 row: DisplayRow,
4256 line_height: Pixels,
4257 whitespace_setting: ShowWhitespaceSetting,
4258 cx: &mut WindowContext,
4259 ) {
4260 let extract_whitespace_info = |invisible: &Invisible| {
4261 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4262 Invisible::Tab {
4263 line_start_offset,
4264 line_end_offset,
4265 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4266 Invisible::Whitespace { line_offset } => {
4267 (*line_offset, line_offset + 1, &layout.space_invisible)
4268 }
4269 };
4270
4271 let x_offset = self.x_for_index(token_offset);
4272 let invisible_offset =
4273 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4274 let origin = content_origin
4275 + gpui::point(
4276 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4277 line_y,
4278 );
4279
4280 (
4281 [token_offset, token_end_offset],
4282 Box::new(move |cx: &mut WindowContext| {
4283 invisible_symbol.paint(origin, line_height, cx).log_err();
4284 }),
4285 )
4286 };
4287
4288 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4289 match whitespace_setting {
4290 ShowWhitespaceSetting::None => return,
4291 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4292 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4293 let invisible_point = DisplayPoint::new(row, start as u32);
4294 if !selection_ranges
4295 .iter()
4296 .any(|region| region.start <= invisible_point && invisible_point < region.end)
4297 {
4298 return;
4299 }
4300
4301 paint(cx);
4302 }),
4303
4304 // For a whitespace to be on a boundary, any of the following conditions need to be met:
4305 // - It is a tab
4306 // - It is adjacent to an edge (start or end)
4307 // - It is adjacent to a whitespace (left or right)
4308 ShowWhitespaceSetting::Boundary => {
4309 // We'll need to keep track of the last invisible we've seen and then check if we are adjacent to it for some of
4310 // the above cases.
4311 // Note: We zip in the original `invisibles` to check for tab equality
4312 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4313 for (([start, end], paint), invisible) in
4314 invisible_iter.zip_eq(self.invisibles.iter())
4315 {
4316 let should_render = match (&last_seen, invisible) {
4317 (_, Invisible::Tab { .. }) => true,
4318 (Some((_, last_end, _)), _) => *last_end == start,
4319 _ => false,
4320 };
4321
4322 if should_render || start == 0 || end == self.len {
4323 paint(cx);
4324
4325 // Since we are scanning from the left, we will skip over the first available whitespace that is part
4326 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4327 if let Some((should_render_last, last_end, paint_last)) = last_seen {
4328 // Note that we need to make sure that the last one is actually adjacent
4329 if !should_render_last && last_end == start {
4330 paint_last(cx);
4331 }
4332 }
4333 }
4334
4335 // Manually render anything within a selection
4336 let invisible_point = DisplayPoint::new(row, start as u32);
4337 if selection_ranges.iter().any(|region| {
4338 region.start <= invisible_point && invisible_point < region.end
4339 }) {
4340 paint(cx);
4341 }
4342
4343 last_seen = Some((should_render, end, paint));
4344 }
4345 }
4346 };
4347 }
4348
4349 pub fn x_for_index(&self, index: usize) -> Pixels {
4350 let mut fragment_start_x = Pixels::ZERO;
4351 let mut fragment_start_index = 0;
4352
4353 for fragment in &self.fragments {
4354 match fragment {
4355 LineFragment::Text(shaped_line) => {
4356 let fragment_end_index = fragment_start_index + shaped_line.len;
4357 if index < fragment_end_index {
4358 return fragment_start_x
4359 + shaped_line.x_for_index(index - fragment_start_index);
4360 }
4361 fragment_start_x += shaped_line.width;
4362 fragment_start_index = fragment_end_index;
4363 }
4364 LineFragment::Element { len, size, .. } => {
4365 let fragment_end_index = fragment_start_index + len;
4366 if index < fragment_end_index {
4367 return fragment_start_x;
4368 }
4369 fragment_start_x += size.width;
4370 fragment_start_index = fragment_end_index;
4371 }
4372 }
4373 }
4374
4375 fragment_start_x
4376 }
4377
4378 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4379 let mut fragment_start_x = Pixels::ZERO;
4380 let mut fragment_start_index = 0;
4381
4382 for fragment in &self.fragments {
4383 match fragment {
4384 LineFragment::Text(shaped_line) => {
4385 let fragment_end_x = fragment_start_x + shaped_line.width;
4386 if x < fragment_end_x {
4387 return Some(
4388 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4389 );
4390 }
4391 fragment_start_x = fragment_end_x;
4392 fragment_start_index += shaped_line.len;
4393 }
4394 LineFragment::Element { len, size, .. } => {
4395 let fragment_end_x = fragment_start_x + size.width;
4396 if x < fragment_end_x {
4397 return Some(fragment_start_index);
4398 }
4399 fragment_start_index += len;
4400 fragment_start_x = fragment_end_x;
4401 }
4402 }
4403 }
4404
4405 None
4406 }
4407
4408 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4409 let mut fragment_start_index = 0;
4410
4411 for fragment in &self.fragments {
4412 match fragment {
4413 LineFragment::Text(shaped_line) => {
4414 let fragment_end_index = fragment_start_index + shaped_line.len;
4415 if index < fragment_end_index {
4416 return shaped_line.font_id_for_index(index - fragment_start_index);
4417 }
4418 fragment_start_index = fragment_end_index;
4419 }
4420 LineFragment::Element { len, .. } => {
4421 let fragment_end_index = fragment_start_index + len;
4422 if index < fragment_end_index {
4423 return None;
4424 }
4425 fragment_start_index = fragment_end_index;
4426 }
4427 }
4428 }
4429
4430 None
4431 }
4432}
4433
4434#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4435enum Invisible {
4436 /// A tab character
4437 ///
4438 /// A tab character is internally represented by spaces (configured by the user's tab width)
4439 /// aligned to the nearest column, so it's necessary to store the start and end offset for
4440 /// adjacency checks.
4441 Tab {
4442 line_start_offset: usize,
4443 line_end_offset: usize,
4444 },
4445 Whitespace {
4446 line_offset: usize,
4447 },
4448}
4449
4450impl EditorElement {
4451 /// Returns the rem size to use when rendering the [`EditorElement`].
4452 ///
4453 /// This allows UI elements to scale based on the `buffer_font_size`.
4454 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4455 match self.editor.read(cx).mode {
4456 EditorMode::Full => {
4457 let buffer_font_size = self.style.text.font_size;
4458 match buffer_font_size {
4459 AbsoluteLength::Pixels(pixels) => {
4460 let rem_size_scale = {
4461 // Our default UI font size is 14px on a 16px base scale.
4462 // This means the default UI font size is 0.875rems.
4463 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4464
4465 // We then determine the delta between a single rem and the default font
4466 // size scale.
4467 let default_font_size_delta = 1. - default_font_size_scale;
4468
4469 // Finally, we add this delta to 1rem to get the scale factor that
4470 // should be used to scale up the UI.
4471 1. + default_font_size_delta
4472 };
4473
4474 Some(pixels * rem_size_scale)
4475 }
4476 AbsoluteLength::Rems(rems) => {
4477 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4478 }
4479 }
4480 }
4481 // We currently use single-line and auto-height editors in UI contexts,
4482 // so we don't want to scale everything with the buffer font size, as it
4483 // ends up looking off.
4484 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
4485 }
4486 }
4487}
4488
4489impl Element for EditorElement {
4490 type RequestLayoutState = ();
4491 type PrepaintState = EditorLayout;
4492
4493 fn id(&self) -> Option<ElementId> {
4494 None
4495 }
4496
4497 fn request_layout(
4498 &mut self,
4499 _: Option<&GlobalElementId>,
4500 cx: &mut WindowContext,
4501 ) -> (gpui::LayoutId, ()) {
4502 let rem_size = self.rem_size(cx);
4503 cx.with_rem_size(rem_size, |cx| {
4504 self.editor.update(cx, |editor, cx| {
4505 editor.set_style(self.style.clone(), cx);
4506
4507 let layout_id = match editor.mode {
4508 EditorMode::SingleLine { auto_width } => {
4509 let rem_size = cx.rem_size();
4510
4511 let height = self.style.text.line_height_in_pixels(rem_size);
4512 if auto_width {
4513 let editor_handle = cx.view().clone();
4514 let style = self.style.clone();
4515 cx.request_measured_layout(Style::default(), move |_, _, cx| {
4516 let editor_snapshot =
4517 editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
4518 let line = Self::layout_lines(
4519 DisplayRow(0)..DisplayRow(1),
4520 &[],
4521 &editor_snapshot,
4522 &style,
4523 cx,
4524 )
4525 .pop()
4526 .unwrap();
4527
4528 let font_id = cx.text_system().resolve_font(&style.text.font());
4529 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4530 let em_width = cx
4531 .text_system()
4532 .typographic_bounds(font_id, font_size, 'm')
4533 .unwrap()
4534 .size
4535 .width;
4536
4537 size(line.width + em_width, height)
4538 })
4539 } else {
4540 let mut style = Style::default();
4541 style.size.height = height.into();
4542 style.size.width = relative(1.).into();
4543 cx.request_layout(style, None)
4544 }
4545 }
4546 EditorMode::AutoHeight { max_lines } => {
4547 let editor_handle = cx.view().clone();
4548 let max_line_number_width =
4549 self.max_line_number_width(&editor.snapshot(cx), cx);
4550 cx.request_measured_layout(
4551 Style::default(),
4552 move |known_dimensions, available_space, cx| {
4553 editor_handle
4554 .update(cx, |editor, cx| {
4555 compute_auto_height_layout(
4556 editor,
4557 max_lines,
4558 max_line_number_width,
4559 known_dimensions,
4560 available_space.width,
4561 cx,
4562 )
4563 })
4564 .unwrap_or_default()
4565 },
4566 )
4567 }
4568 EditorMode::Full => {
4569 let mut style = Style::default();
4570 style.size.width = relative(1.).into();
4571 style.size.height = relative(1.).into();
4572 cx.request_layout(style, None)
4573 }
4574 };
4575
4576 (layout_id, ())
4577 })
4578 })
4579 }
4580
4581 fn prepaint(
4582 &mut self,
4583 _: Option<&GlobalElementId>,
4584 bounds: Bounds<Pixels>,
4585 _: &mut Self::RequestLayoutState,
4586 cx: &mut WindowContext,
4587 ) -> Self::PrepaintState {
4588 let text_style = TextStyleRefinement {
4589 font_size: Some(self.style.text.font_size),
4590 line_height: Some(self.style.text.line_height),
4591 ..Default::default()
4592 };
4593 cx.set_view_id(self.editor.entity_id());
4594
4595 let rem_size = self.rem_size(cx);
4596 cx.with_rem_size(rem_size, |cx| {
4597 cx.with_text_style(Some(text_style), |cx| {
4598 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4599 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4600 let style = self.style.clone();
4601
4602 let font_id = cx.text_system().resolve_font(&style.text.font());
4603 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4604 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4605 let em_width = cx
4606 .text_system()
4607 .typographic_bounds(font_id, font_size, 'm')
4608 .unwrap()
4609 .size
4610 .width;
4611 let em_advance = cx
4612 .text_system()
4613 .advance(font_id, font_size, 'm')
4614 .unwrap()
4615 .width;
4616
4617 let gutter_dimensions = snapshot.gutter_dimensions(
4618 font_id,
4619 font_size,
4620 em_width,
4621 self.max_line_number_width(&snapshot, cx),
4622 cx,
4623 );
4624 let text_width = bounds.size.width - gutter_dimensions.width;
4625
4626 let right_margin = if snapshot.mode == EditorMode::Full {
4627 EditorElement::SCROLLBAR_WIDTH
4628 } else {
4629 px(0.)
4630 };
4631 let overscroll = size(em_width + right_margin, px(0.));
4632
4633 snapshot = self.editor.update(cx, |editor, cx| {
4634 editor.last_bounds = Some(bounds);
4635 editor.gutter_dimensions = gutter_dimensions;
4636 editor.set_visible_line_count(bounds.size.height / line_height, cx);
4637
4638 let editor_width =
4639 text_width - gutter_dimensions.margin - overscroll.width - em_width;
4640 let wrap_width = match editor.soft_wrap_mode(cx) {
4641 SoftWrap::None => None,
4642 SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4643 SoftWrap::EditorWidth => Some(editor_width),
4644 SoftWrap::Column(column) => {
4645 Some(editor_width.min(column as f32 * em_advance))
4646 }
4647 };
4648
4649 if editor.set_wrap_width(wrap_width, cx) {
4650 editor.snapshot(cx)
4651 } else {
4652 snapshot
4653 }
4654 });
4655
4656 let wrap_guides = self
4657 .editor
4658 .read(cx)
4659 .wrap_guides(cx)
4660 .iter()
4661 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4662 .collect::<SmallVec<[_; 2]>>();
4663
4664 let hitbox = cx.insert_hitbox(bounds, false);
4665 let gutter_hitbox = cx.insert_hitbox(
4666 Bounds {
4667 origin: bounds.origin,
4668 size: size(gutter_dimensions.width, bounds.size.height),
4669 },
4670 false,
4671 );
4672 let text_hitbox = cx.insert_hitbox(
4673 Bounds {
4674 origin: gutter_hitbox.upper_right(),
4675 size: size(text_width, bounds.size.height),
4676 },
4677 false,
4678 );
4679 // Offset the content_bounds from the text_bounds by the gutter margin (which
4680 // is roughly half a character wide) to make hit testing work more like how we want.
4681 let content_origin =
4682 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4683
4684 let height_in_lines = bounds.size.height / line_height;
4685 let max_row = snapshot.max_point().row().as_f32();
4686 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
4687 (max_row - height_in_lines + 1.).max(0.)
4688 } else {
4689 let settings = EditorSettings::get_global(cx);
4690 match settings.scroll_beyond_last_line {
4691 ScrollBeyondLastLine::OnePage => max_row,
4692 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
4693 ScrollBeyondLastLine::VerticalScrollMargin => {
4694 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
4695 .max(0.)
4696 }
4697 }
4698 };
4699
4700 let mut autoscroll_containing_element = false;
4701 let mut autoscroll_horizontally = false;
4702 self.editor.update(cx, |editor, cx| {
4703 autoscroll_containing_element =
4704 editor.autoscroll_requested() || editor.has_pending_selection();
4705 autoscroll_horizontally =
4706 editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
4707 snapshot = editor.snapshot(cx);
4708 });
4709
4710 let mut scroll_position = snapshot.scroll_position();
4711 // The scroll position is a fractional point, the whole number of which represents
4712 // the top of the window in terms of display rows.
4713 let start_row = DisplayRow(scroll_position.y as u32);
4714 let max_row = snapshot.max_point().row();
4715 let end_row = cmp::min(
4716 (scroll_position.y + height_in_lines).ceil() as u32,
4717 max_row.next_row().0,
4718 );
4719 let end_row = DisplayRow(end_row);
4720
4721 let buffer_rows = snapshot
4722 .buffer_rows(start_row)
4723 .take((start_row..end_row).len())
4724 .collect::<Vec<_>>();
4725
4726 let start_anchor = if start_row == Default::default() {
4727 Anchor::min()
4728 } else {
4729 snapshot.buffer_snapshot.anchor_before(
4730 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4731 )
4732 };
4733 let end_anchor = if end_row > max_row {
4734 Anchor::max()
4735 } else {
4736 snapshot.buffer_snapshot.anchor_before(
4737 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4738 )
4739 };
4740
4741 let highlighted_rows = self
4742 .editor
4743 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4744 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4745 start_anchor..end_anchor,
4746 &snapshot.display_snapshot,
4747 cx.theme().colors(),
4748 );
4749 let highlighted_gutter_ranges =
4750 self.editor.read(cx).gutter_highlights_in_range(
4751 start_anchor..end_anchor,
4752 &snapshot.display_snapshot,
4753 cx,
4754 );
4755
4756 let redacted_ranges = self.editor.read(cx).redacted_ranges(
4757 start_anchor..end_anchor,
4758 &snapshot.display_snapshot,
4759 cx,
4760 );
4761
4762 let (selections, active_rows, newest_selection_head) = self.layout_selections(
4763 start_anchor,
4764 end_anchor,
4765 &snapshot,
4766 start_row,
4767 end_row,
4768 cx,
4769 );
4770
4771 let line_numbers = self.layout_line_numbers(
4772 start_row..end_row,
4773 buffer_rows.iter().copied(),
4774 &active_rows,
4775 newest_selection_head,
4776 &snapshot,
4777 cx,
4778 );
4779
4780 let mut gutter_fold_toggles =
4781 cx.with_element_namespace("gutter_fold_toggles", |cx| {
4782 self.layout_gutter_fold_toggles(
4783 start_row..end_row,
4784 buffer_rows.iter().copied(),
4785 &active_rows,
4786 &snapshot,
4787 cx,
4788 )
4789 });
4790 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4791 self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4792 });
4793
4794 let display_hunks = self.layout_git_gutters(
4795 line_height,
4796 &gutter_hitbox,
4797 start_row..end_row,
4798 &snapshot,
4799 cx,
4800 );
4801
4802 let mut max_visible_line_width = Pixels::ZERO;
4803 let mut line_layouts = Self::layout_lines(
4804 start_row..end_row,
4805 &line_numbers,
4806 &snapshot,
4807 &self.style,
4808 cx,
4809 );
4810 for line_with_invisibles in &line_layouts {
4811 if line_with_invisibles.width > max_visible_line_width {
4812 max_visible_line_width = line_with_invisibles.width;
4813 }
4814 }
4815
4816 let longest_line_width =
4817 layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4818 let mut scroll_width =
4819 longest_line_width.max(max_visible_line_width) + overscroll.width;
4820
4821 let mut blocks = cx.with_element_namespace("blocks", |cx| {
4822 self.build_blocks(
4823 start_row..end_row,
4824 &snapshot,
4825 &hitbox,
4826 &text_hitbox,
4827 &mut scroll_width,
4828 &gutter_dimensions,
4829 em_width,
4830 gutter_dimensions.full_width(),
4831 line_height,
4832 &line_layouts,
4833 cx,
4834 )
4835 });
4836
4837 let start_buffer_row =
4838 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4839 let end_buffer_row =
4840 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4841
4842 let scroll_max = point(
4843 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4844 max_row.as_f32(),
4845 );
4846
4847 self.editor.update(cx, |editor, cx| {
4848 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4849
4850 let autoscrolled = if autoscroll_horizontally {
4851 editor.autoscroll_horizontally(
4852 start_row,
4853 text_hitbox.size.width,
4854 scroll_width,
4855 em_width,
4856 &line_layouts,
4857 cx,
4858 )
4859 } else {
4860 false
4861 };
4862
4863 if clamped || autoscrolled {
4864 snapshot = editor.snapshot(cx);
4865 scroll_position = snapshot.scroll_position();
4866 }
4867 });
4868
4869 let scroll_pixel_position = point(
4870 scroll_position.x * em_width,
4871 scroll_position.y * line_height,
4872 );
4873
4874 let indent_guides = self.layout_indent_guides(
4875 content_origin,
4876 text_hitbox.origin,
4877 start_buffer_row..end_buffer_row,
4878 scroll_pixel_position,
4879 line_height,
4880 &snapshot,
4881 cx,
4882 );
4883
4884 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
4885 self.prepaint_crease_trailers(
4886 crease_trailers,
4887 &line_layouts,
4888 line_height,
4889 content_origin,
4890 scroll_pixel_position,
4891 em_width,
4892 cx,
4893 )
4894 });
4895
4896 let mut inline_blame = None;
4897 if let Some(newest_selection_head) = newest_selection_head {
4898 let display_row = newest_selection_head.row();
4899 if (start_row..end_row).contains(&display_row) {
4900 let line_ix = display_row.minus(start_row) as usize;
4901 let line_layout = &line_layouts[line_ix];
4902 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
4903 inline_blame = self.layout_inline_blame(
4904 display_row,
4905 &snapshot.display_snapshot,
4906 line_layout,
4907 crease_trailer_layout,
4908 em_width,
4909 content_origin,
4910 scroll_pixel_position,
4911 line_height,
4912 cx,
4913 );
4914 }
4915 }
4916
4917 let blamed_display_rows = self.layout_blame_entries(
4918 buffer_rows.into_iter(),
4919 em_width,
4920 scroll_position,
4921 line_height,
4922 &gutter_hitbox,
4923 gutter_dimensions.git_blame_entries_width,
4924 cx,
4925 );
4926
4927 let scroll_max = point(
4928 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4929 max_scroll_top,
4930 );
4931
4932 self.editor.update(cx, |editor, cx| {
4933 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4934
4935 let autoscrolled = if autoscroll_horizontally {
4936 editor.autoscroll_horizontally(
4937 start_row,
4938 text_hitbox.size.width,
4939 scroll_width,
4940 em_width,
4941 &line_layouts,
4942 cx,
4943 )
4944 } else {
4945 false
4946 };
4947
4948 if clamped || autoscrolled {
4949 snapshot = editor.snapshot(cx);
4950 scroll_position = snapshot.scroll_position();
4951 }
4952 });
4953
4954 let line_elements = self.prepaint_lines(
4955 start_row,
4956 &mut line_layouts,
4957 line_height,
4958 scroll_pixel_position,
4959 content_origin,
4960 cx,
4961 );
4962
4963 cx.with_element_namespace("blocks", |cx| {
4964 self.layout_blocks(
4965 &mut blocks,
4966 &hitbox,
4967 line_height,
4968 scroll_pixel_position,
4969 cx,
4970 );
4971 });
4972
4973 let cursors = self.collect_cursors(&snapshot, cx);
4974 let visible_row_range = start_row..end_row;
4975 let non_visible_cursors = cursors
4976 .iter()
4977 .any(move |c| !visible_row_range.contains(&c.0.row()));
4978
4979 let visible_cursors = self.layout_visible_cursors(
4980 &snapshot,
4981 &selections,
4982 start_row..end_row,
4983 &line_layouts,
4984 &text_hitbox,
4985 content_origin,
4986 scroll_position,
4987 scroll_pixel_position,
4988 line_height,
4989 em_width,
4990 autoscroll_containing_element,
4991 cx,
4992 );
4993
4994 let scrollbar_layout = self.layout_scrollbar(
4995 &snapshot,
4996 bounds,
4997 scroll_position,
4998 height_in_lines,
4999 non_visible_cursors,
5000 cx,
5001 );
5002
5003 let gutter_settings = EditorSettings::get_global(cx).gutter;
5004
5005 let mut _context_menu_visible = false;
5006 let mut code_actions_indicator = None;
5007 if let Some(newest_selection_head) = newest_selection_head {
5008 if (start_row..end_row).contains(&newest_selection_head.row()) {
5009 _context_menu_visible = self.layout_context_menu(
5010 line_height,
5011 &hitbox,
5012 &text_hitbox,
5013 content_origin,
5014 start_row,
5015 scroll_pixel_position,
5016 &line_layouts,
5017 newest_selection_head,
5018 gutter_dimensions.width - gutter_dimensions.left_padding,
5019 cx,
5020 );
5021
5022 let show_code_actions = snapshot
5023 .show_code_actions
5024 .unwrap_or_else(|| gutter_settings.code_actions);
5025 if show_code_actions {
5026 let newest_selection_point =
5027 newest_selection_head.to_point(&snapshot.display_snapshot);
5028 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5029 MultiBufferRow(newest_selection_point.row),
5030 );
5031 if let Some((buffer, range)) = buffer {
5032 let buffer_id = buffer.remote_id();
5033 let row = range.start.row;
5034 let has_test_indicator =
5035 self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
5036
5037 if !has_test_indicator {
5038 code_actions_indicator = self
5039 .layout_code_actions_indicator(
5040 line_height,
5041 newest_selection_head,
5042 scroll_pixel_position,
5043 &gutter_dimensions,
5044 &gutter_hitbox,
5045 cx,
5046 );
5047 }
5048 }
5049 }
5050 }
5051 }
5052
5053 let test_indicators = if gutter_settings.runnables {
5054 self.layout_run_indicators(
5055 line_height,
5056 scroll_pixel_position,
5057 &gutter_dimensions,
5058 &gutter_hitbox,
5059 &snapshot,
5060 cx,
5061 )
5062 } else {
5063 vec![]
5064 };
5065
5066 if !cx.has_active_drag() {
5067 self.layout_hover_popovers(
5068 &snapshot,
5069 &hitbox,
5070 &text_hitbox,
5071 start_row..end_row,
5072 content_origin,
5073 scroll_pixel_position,
5074 &line_layouts,
5075 line_height,
5076 em_width,
5077 cx,
5078 );
5079 }
5080
5081 let mouse_context_menu = self.layout_mouse_context_menu(cx);
5082
5083 cx.with_element_namespace("gutter_fold_toggles", |cx| {
5084 self.prepaint_gutter_fold_toggles(
5085 &mut gutter_fold_toggles,
5086 line_height,
5087 &gutter_dimensions,
5088 gutter_settings,
5089 scroll_pixel_position,
5090 &gutter_hitbox,
5091 cx,
5092 )
5093 });
5094
5095 let invisible_symbol_font_size = font_size / 2.;
5096 let tab_invisible = cx
5097 .text_system()
5098 .shape_line(
5099 "→".into(),
5100 invisible_symbol_font_size,
5101 &[TextRun {
5102 len: "→".len(),
5103 font: self.style.text.font(),
5104 color: cx.theme().colors().editor_invisible,
5105 background_color: None,
5106 underline: None,
5107 strikethrough: None,
5108 }],
5109 )
5110 .unwrap();
5111 let space_invisible = cx
5112 .text_system()
5113 .shape_line(
5114 "•".into(),
5115 invisible_symbol_font_size,
5116 &[TextRun {
5117 len: "•".len(),
5118 font: self.style.text.font(),
5119 color: cx.theme().colors().editor_invisible,
5120 background_color: None,
5121 underline: None,
5122 strikethrough: None,
5123 }],
5124 )
5125 .unwrap();
5126
5127 EditorLayout {
5128 mode: snapshot.mode,
5129 position_map: Arc::new(PositionMap {
5130 size: bounds.size,
5131 scroll_pixel_position,
5132 scroll_max,
5133 line_layouts,
5134 line_height,
5135 em_width,
5136 em_advance,
5137 snapshot,
5138 }),
5139 visible_display_row_range: start_row..end_row,
5140 wrap_guides,
5141 indent_guides,
5142 hitbox,
5143 text_hitbox,
5144 gutter_hitbox,
5145 gutter_dimensions,
5146 content_origin,
5147 scrollbar_layout,
5148 active_rows,
5149 highlighted_rows,
5150 highlighted_ranges,
5151 highlighted_gutter_ranges,
5152 redacted_ranges,
5153 line_elements,
5154 line_numbers,
5155 display_hunks,
5156 blamed_display_rows,
5157 inline_blame,
5158 blocks,
5159 cursors,
5160 visible_cursors,
5161 selections,
5162 mouse_context_menu,
5163 test_indicators,
5164 code_actions_indicator,
5165 gutter_fold_toggles,
5166 crease_trailers,
5167 tab_invisible,
5168 space_invisible,
5169 }
5170 })
5171 })
5172 })
5173 }
5174
5175 fn paint(
5176 &mut self,
5177 _: Option<&GlobalElementId>,
5178 bounds: Bounds<gpui::Pixels>,
5179 _: &mut Self::RequestLayoutState,
5180 layout: &mut Self::PrepaintState,
5181 cx: &mut WindowContext,
5182 ) {
5183 let focus_handle = self.editor.focus_handle(cx);
5184 let key_context = self.editor.read(cx).key_context(cx);
5185 cx.set_focus_handle(&focus_handle);
5186 cx.set_key_context(key_context);
5187 cx.handle_input(
5188 &focus_handle,
5189 ElementInputHandler::new(bounds, self.editor.clone()),
5190 );
5191 self.register_actions(cx);
5192 self.register_key_listeners(cx, layout);
5193
5194 let text_style = TextStyleRefinement {
5195 font_size: Some(self.style.text.font_size),
5196 line_height: Some(self.style.text.line_height),
5197 ..Default::default()
5198 };
5199 let mouse_position = cx.mouse_position();
5200 let hovered_hunk = layout
5201 .display_hunks
5202 .iter()
5203 .find_map(|(hunk, hunk_hitbox)| match hunk {
5204 DisplayDiffHunk::Folded { .. } => None,
5205 DisplayDiffHunk::Unfolded {
5206 diff_base_byte_range,
5207 multi_buffer_range,
5208 status,
5209 ..
5210 } => {
5211 if hunk_hitbox
5212 .as_ref()
5213 .map(|hitbox| hitbox.contains(&mouse_position))
5214 .unwrap_or(false)
5215 {
5216 Some(HunkToExpand {
5217 status: *status,
5218 multi_buffer_range: multi_buffer_range.clone(),
5219 diff_base_byte_range: diff_base_byte_range.clone(),
5220 })
5221 } else {
5222 None
5223 }
5224 }
5225 });
5226 let rem_size = self.rem_size(cx);
5227 cx.with_rem_size(rem_size, |cx| {
5228 cx.with_text_style(Some(text_style), |cx| {
5229 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5230 self.paint_mouse_listeners(layout, hovered_hunk, cx);
5231 self.paint_background(layout, cx);
5232 self.paint_indent_guides(layout, cx);
5233
5234 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5235 self.paint_blamed_display_rows(layout, cx);
5236 self.paint_line_numbers(layout, cx);
5237 }
5238
5239 self.paint_text(layout, cx);
5240
5241 if !layout.blocks.is_empty() {
5242 cx.with_element_namespace("blocks", |cx| {
5243 self.paint_blocks(layout, cx);
5244 });
5245 }
5246
5247 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5248 self.paint_gutter_highlights(layout, cx);
5249 self.paint_gutter_indicators(layout, cx);
5250 }
5251
5252 self.paint_scrollbar(layout, cx);
5253 self.paint_mouse_context_menu(layout, cx);
5254 });
5255 })
5256 })
5257 }
5258}
5259
5260impl IntoElement for EditorElement {
5261 type Element = Self;
5262
5263 fn into_element(self) -> Self::Element {
5264 self
5265 }
5266}
5267
5268pub struct EditorLayout {
5269 position_map: Arc<PositionMap>,
5270 hitbox: Hitbox,
5271 text_hitbox: Hitbox,
5272 gutter_hitbox: Hitbox,
5273 gutter_dimensions: GutterDimensions,
5274 content_origin: gpui::Point<Pixels>,
5275 scrollbar_layout: Option<ScrollbarLayout>,
5276 mode: EditorMode,
5277 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5278 indent_guides: Option<Vec<IndentGuideLayout>>,
5279 visible_display_row_range: Range<DisplayRow>,
5280 active_rows: BTreeMap<DisplayRow, bool>,
5281 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5282 line_elements: SmallVec<[AnyElement; 1]>,
5283 line_numbers: Vec<Option<ShapedLine>>,
5284 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5285 blamed_display_rows: Option<Vec<AnyElement>>,
5286 inline_blame: Option<AnyElement>,
5287 blocks: Vec<BlockLayout>,
5288 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5289 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5290 redacted_ranges: Vec<Range<DisplayPoint>>,
5291 cursors: Vec<(DisplayPoint, Hsla)>,
5292 visible_cursors: Vec<CursorLayout>,
5293 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5294 code_actions_indicator: Option<AnyElement>,
5295 test_indicators: Vec<AnyElement>,
5296 gutter_fold_toggles: Vec<Option<AnyElement>>,
5297 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5298 mouse_context_menu: Option<AnyElement>,
5299 tab_invisible: ShapedLine,
5300 space_invisible: ShapedLine,
5301}
5302
5303impl EditorLayout {
5304 fn line_end_overshoot(&self) -> Pixels {
5305 0.15 * self.position_map.line_height
5306 }
5307}
5308
5309struct ColoredRange<T> {
5310 start: T,
5311 end: T,
5312 color: Hsla,
5313}
5314
5315#[derive(Clone)]
5316struct ScrollbarLayout {
5317 hitbox: Hitbox,
5318 visible_row_range: Range<f32>,
5319 visible: bool,
5320 row_height: Pixels,
5321 thumb_height: Pixels,
5322}
5323
5324impl ScrollbarLayout {
5325 const BORDER_WIDTH: Pixels = px(1.0);
5326 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5327 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5328 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5329
5330 fn thumb_bounds(&self) -> Bounds<Pixels> {
5331 let thumb_top = self.y_for_row(self.visible_row_range.start);
5332 let thumb_bottom = thumb_top + self.thumb_height;
5333 Bounds::from_corners(
5334 point(self.hitbox.left(), thumb_top),
5335 point(self.hitbox.right(), thumb_bottom),
5336 )
5337 }
5338
5339 fn y_for_row(&self, row: f32) -> Pixels {
5340 self.hitbox.top() + row * self.row_height
5341 }
5342
5343 fn marker_quads_for_ranges(
5344 &self,
5345 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5346 column: Option<usize>,
5347 ) -> Vec<PaintQuad> {
5348 struct MinMax {
5349 min: Pixels,
5350 max: Pixels,
5351 }
5352 let (x_range, height_limit) = if let Some(column) = column {
5353 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5354 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5355 let end = start + column_width;
5356 (
5357 Range { start, end },
5358 MinMax {
5359 min: Self::MIN_MARKER_HEIGHT,
5360 max: px(f32::MAX),
5361 },
5362 )
5363 } else {
5364 (
5365 Range {
5366 start: Self::BORDER_WIDTH,
5367 end: self.hitbox.size.width,
5368 },
5369 MinMax {
5370 min: Self::LINE_MARKER_HEIGHT,
5371 max: Self::LINE_MARKER_HEIGHT,
5372 },
5373 )
5374 };
5375
5376 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5377 let mut pixel_ranges = row_ranges
5378 .into_iter()
5379 .map(|range| {
5380 let start_y = row_to_y(range.start);
5381 let end_y = row_to_y(range.end)
5382 + self.row_height.max(height_limit.min).min(height_limit.max);
5383 ColoredRange {
5384 start: start_y,
5385 end: end_y,
5386 color: range.color,
5387 }
5388 })
5389 .peekable();
5390
5391 let mut quads = Vec::new();
5392 while let Some(mut pixel_range) = pixel_ranges.next() {
5393 while let Some(next_pixel_range) = pixel_ranges.peek() {
5394 if pixel_range.end >= next_pixel_range.start - px(1.0)
5395 && pixel_range.color == next_pixel_range.color
5396 {
5397 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5398 pixel_ranges.next();
5399 } else {
5400 break;
5401 }
5402 }
5403
5404 let bounds = Bounds::from_corners(
5405 point(x_range.start, pixel_range.start),
5406 point(x_range.end, pixel_range.end),
5407 );
5408 quads.push(quad(
5409 bounds,
5410 Corners::default(),
5411 pixel_range.color,
5412 Edges::default(),
5413 Hsla::transparent_black(),
5414 ));
5415 }
5416
5417 quads
5418 }
5419}
5420
5421struct CreaseTrailerLayout {
5422 element: AnyElement,
5423 bounds: Bounds<Pixels>,
5424}
5425
5426struct PositionMap {
5427 size: Size<Pixels>,
5428 line_height: Pixels,
5429 scroll_pixel_position: gpui::Point<Pixels>,
5430 scroll_max: gpui::Point<f32>,
5431 em_width: Pixels,
5432 em_advance: Pixels,
5433 line_layouts: Vec<LineWithInvisibles>,
5434 snapshot: EditorSnapshot,
5435}
5436
5437#[derive(Debug, Copy, Clone)]
5438pub struct PointForPosition {
5439 pub previous_valid: DisplayPoint,
5440 pub next_valid: DisplayPoint,
5441 pub exact_unclipped: DisplayPoint,
5442 pub column_overshoot_after_line_end: u32,
5443}
5444
5445impl PointForPosition {
5446 pub fn as_valid(&self) -> Option<DisplayPoint> {
5447 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5448 Some(self.previous_valid)
5449 } else {
5450 None
5451 }
5452 }
5453}
5454
5455impl PositionMap {
5456 fn point_for_position(
5457 &self,
5458 text_bounds: Bounds<Pixels>,
5459 position: gpui::Point<Pixels>,
5460 ) -> PointForPosition {
5461 let scroll_position = self.snapshot.scroll_position();
5462 let position = position - text_bounds.origin;
5463 let y = position.y.max(px(0.)).min(self.size.height);
5464 let x = position.x + (scroll_position.x * self.em_width);
5465 let row = ((y / self.line_height) + scroll_position.y) as u32;
5466
5467 let (column, x_overshoot_after_line_end) = if let Some(line) = self
5468 .line_layouts
5469 .get(row as usize - scroll_position.y as usize)
5470 {
5471 if let Some(ix) = line.index_for_x(x) {
5472 (ix as u32, px(0.))
5473 } else {
5474 (line.len as u32, px(0.).max(x - line.width))
5475 }
5476 } else {
5477 (0, x)
5478 };
5479
5480 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5481 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5482 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5483
5484 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5485 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5486 PointForPosition {
5487 previous_valid,
5488 next_valid,
5489 exact_unclipped,
5490 column_overshoot_after_line_end,
5491 }
5492 }
5493}
5494
5495struct BlockLayout {
5496 row: DisplayRow,
5497 element: AnyElement,
5498 available_space: Size<AvailableSpace>,
5499 style: BlockStyle,
5500}
5501
5502fn layout_line(
5503 row: DisplayRow,
5504 snapshot: &EditorSnapshot,
5505 style: &EditorStyle,
5506 cx: &mut WindowContext,
5507) -> LineWithInvisibles {
5508 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5509 LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5510 .pop()
5511 .unwrap()
5512}
5513
5514#[derive(Debug)]
5515pub struct IndentGuideLayout {
5516 origin: gpui::Point<Pixels>,
5517 length: Pixels,
5518 single_indent_width: Pixels,
5519 depth: u32,
5520 active: bool,
5521 settings: IndentGuideSettings,
5522}
5523
5524pub struct CursorLayout {
5525 origin: gpui::Point<Pixels>,
5526 block_width: Pixels,
5527 line_height: Pixels,
5528 color: Hsla,
5529 shape: CursorShape,
5530 block_text: Option<ShapedLine>,
5531 cursor_name: Option<AnyElement>,
5532}
5533
5534#[derive(Debug)]
5535pub struct CursorName {
5536 string: SharedString,
5537 color: Hsla,
5538 is_top_row: bool,
5539}
5540
5541impl CursorLayout {
5542 pub fn new(
5543 origin: gpui::Point<Pixels>,
5544 block_width: Pixels,
5545 line_height: Pixels,
5546 color: Hsla,
5547 shape: CursorShape,
5548 block_text: Option<ShapedLine>,
5549 ) -> CursorLayout {
5550 CursorLayout {
5551 origin,
5552 block_width,
5553 line_height,
5554 color,
5555 shape,
5556 block_text,
5557 cursor_name: None,
5558 }
5559 }
5560
5561 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5562 Bounds {
5563 origin: self.origin + origin,
5564 size: size(self.block_width, self.line_height),
5565 }
5566 }
5567
5568 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5569 match self.shape {
5570 CursorShape::Bar => Bounds {
5571 origin: self.origin + origin,
5572 size: size(px(2.0), self.line_height),
5573 },
5574 CursorShape::Block | CursorShape::Hollow => Bounds {
5575 origin: self.origin + origin,
5576 size: size(self.block_width, self.line_height),
5577 },
5578 CursorShape::Underscore => Bounds {
5579 origin: self.origin
5580 + origin
5581 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5582 size: size(self.block_width, px(2.0)),
5583 },
5584 }
5585 }
5586
5587 pub fn layout(
5588 &mut self,
5589 origin: gpui::Point<Pixels>,
5590 cursor_name: Option<CursorName>,
5591 cx: &mut WindowContext,
5592 ) {
5593 if let Some(cursor_name) = cursor_name {
5594 let bounds = self.bounds(origin);
5595 let text_size = self.line_height / 1.5;
5596
5597 let name_origin = if cursor_name.is_top_row {
5598 point(bounds.right() - px(1.), bounds.top())
5599 } else {
5600 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5601 };
5602 let mut name_element = div()
5603 .bg(self.color)
5604 .text_size(text_size)
5605 .px_0p5()
5606 .line_height(text_size + px(2.))
5607 .text_color(cursor_name.color)
5608 .child(cursor_name.string.clone())
5609 .into_any_element();
5610
5611 name_element.prepaint_as_root(
5612 name_origin,
5613 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5614 cx,
5615 );
5616
5617 self.cursor_name = Some(name_element);
5618 }
5619 }
5620
5621 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5622 let bounds = self.bounds(origin);
5623
5624 //Draw background or border quad
5625 let cursor = if matches!(self.shape, CursorShape::Hollow) {
5626 outline(bounds, self.color)
5627 } else {
5628 fill(bounds, self.color)
5629 };
5630
5631 if let Some(name) = &mut self.cursor_name {
5632 name.paint(cx);
5633 }
5634
5635 cx.paint_quad(cursor);
5636
5637 if let Some(block_text) = &self.block_text {
5638 block_text
5639 .paint(self.origin + origin, self.line_height, cx)
5640 .log_err();
5641 }
5642 }
5643
5644 pub fn shape(&self) -> CursorShape {
5645 self.shape
5646 }
5647}
5648
5649#[derive(Debug)]
5650pub struct HighlightedRange {
5651 pub start_y: Pixels,
5652 pub line_height: Pixels,
5653 pub lines: Vec<HighlightedRangeLine>,
5654 pub color: Hsla,
5655 pub corner_radius: Pixels,
5656}
5657
5658#[derive(Debug)]
5659pub struct HighlightedRangeLine {
5660 pub start_x: Pixels,
5661 pub end_x: Pixels,
5662}
5663
5664impl HighlightedRange {
5665 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5666 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5667 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5668 self.paint_lines(
5669 self.start_y + self.line_height,
5670 &self.lines[1..],
5671 bounds,
5672 cx,
5673 );
5674 } else {
5675 self.paint_lines(self.start_y, &self.lines, bounds, cx);
5676 }
5677 }
5678
5679 fn paint_lines(
5680 &self,
5681 start_y: Pixels,
5682 lines: &[HighlightedRangeLine],
5683 _bounds: Bounds<Pixels>,
5684 cx: &mut WindowContext,
5685 ) {
5686 if lines.is_empty() {
5687 return;
5688 }
5689
5690 let first_line = lines.first().unwrap();
5691 let last_line = lines.last().unwrap();
5692
5693 let first_top_left = point(first_line.start_x, start_y);
5694 let first_top_right = point(first_line.end_x, start_y);
5695
5696 let curve_height = point(Pixels::ZERO, self.corner_radius);
5697 let curve_width = |start_x: Pixels, end_x: Pixels| {
5698 let max = (end_x - start_x) / 2.;
5699 let width = if max < self.corner_radius {
5700 max
5701 } else {
5702 self.corner_radius
5703 };
5704
5705 point(width, Pixels::ZERO)
5706 };
5707
5708 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5709 let mut path = gpui::Path::new(first_top_right - top_curve_width);
5710 path.curve_to(first_top_right + curve_height, first_top_right);
5711
5712 let mut iter = lines.iter().enumerate().peekable();
5713 while let Some((ix, line)) = iter.next() {
5714 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5715
5716 if let Some((_, next_line)) = iter.peek() {
5717 let next_top_right = point(next_line.end_x, bottom_right.y);
5718
5719 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5720 Ordering::Equal => {
5721 path.line_to(bottom_right);
5722 }
5723 Ordering::Less => {
5724 let curve_width = curve_width(next_top_right.x, bottom_right.x);
5725 path.line_to(bottom_right - curve_height);
5726 if self.corner_radius > Pixels::ZERO {
5727 path.curve_to(bottom_right - curve_width, bottom_right);
5728 }
5729 path.line_to(next_top_right + curve_width);
5730 if self.corner_radius > Pixels::ZERO {
5731 path.curve_to(next_top_right + curve_height, next_top_right);
5732 }
5733 }
5734 Ordering::Greater => {
5735 let curve_width = curve_width(bottom_right.x, next_top_right.x);
5736 path.line_to(bottom_right - curve_height);
5737 if self.corner_radius > Pixels::ZERO {
5738 path.curve_to(bottom_right + curve_width, bottom_right);
5739 }
5740 path.line_to(next_top_right - curve_width);
5741 if self.corner_radius > Pixels::ZERO {
5742 path.curve_to(next_top_right + curve_height, next_top_right);
5743 }
5744 }
5745 }
5746 } else {
5747 let curve_width = curve_width(line.start_x, line.end_x);
5748 path.line_to(bottom_right - curve_height);
5749 if self.corner_radius > Pixels::ZERO {
5750 path.curve_to(bottom_right - curve_width, bottom_right);
5751 }
5752
5753 let bottom_left = point(line.start_x, bottom_right.y);
5754 path.line_to(bottom_left + curve_width);
5755 if self.corner_radius > Pixels::ZERO {
5756 path.curve_to(bottom_left - curve_height, bottom_left);
5757 }
5758 }
5759 }
5760
5761 if first_line.start_x > last_line.start_x {
5762 let curve_width = curve_width(last_line.start_x, first_line.start_x);
5763 let second_top_left = point(last_line.start_x, start_y + self.line_height);
5764 path.line_to(second_top_left + curve_height);
5765 if self.corner_radius > Pixels::ZERO {
5766 path.curve_to(second_top_left + curve_width, second_top_left);
5767 }
5768 let first_bottom_left = point(first_line.start_x, second_top_left.y);
5769 path.line_to(first_bottom_left - curve_width);
5770 if self.corner_radius > Pixels::ZERO {
5771 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5772 }
5773 }
5774
5775 path.line_to(first_top_left + curve_height);
5776 if self.corner_radius > Pixels::ZERO {
5777 path.curve_to(first_top_left + top_curve_width, first_top_left);
5778 }
5779 path.line_to(first_top_right - top_curve_width);
5780
5781 cx.paint_path(path, self.color);
5782 }
5783}
5784
5785pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5786 (delta.pow(1.5) / 100.0).into()
5787}
5788
5789fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5790 (delta.pow(1.2) / 300.0).into()
5791}
5792
5793#[cfg(test)]
5794mod tests {
5795 use super::*;
5796 use crate::{
5797 display_map::{BlockDisposition, BlockProperties},
5798 editor_tests::{init_test, update_test_language_settings},
5799 Editor, MultiBuffer,
5800 };
5801 use gpui::{TestAppContext, VisualTestContext};
5802 use language::language_settings;
5803 use log::info;
5804 use std::num::NonZeroU32;
5805 use ui::Context;
5806 use util::test::sample_text;
5807
5808 #[gpui::test]
5809 fn test_shape_line_numbers(cx: &mut TestAppContext) {
5810 init_test(cx, |_| {});
5811 let window = cx.add_window(|cx| {
5812 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5813 Editor::new(EditorMode::Full, buffer, None, true, cx)
5814 });
5815
5816 let editor = window.root(cx).unwrap();
5817 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5818 let element = EditorElement::new(&editor, style);
5819 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5820
5821 let layouts = cx
5822 .update_window(*window, |_, cx| {
5823 element.layout_line_numbers(
5824 DisplayRow(0)..DisplayRow(6),
5825 (0..6).map(MultiBufferRow).map(Some),
5826 &Default::default(),
5827 Some(DisplayPoint::new(DisplayRow(0), 0)),
5828 &snapshot,
5829 cx,
5830 )
5831 })
5832 .unwrap();
5833 assert_eq!(layouts.len(), 6);
5834
5835 let relative_rows = window
5836 .update(cx, |editor, cx| {
5837 let snapshot = editor.snapshot(cx);
5838 element.calculate_relative_line_numbers(
5839 &snapshot,
5840 &(DisplayRow(0)..DisplayRow(6)),
5841 Some(DisplayRow(3)),
5842 )
5843 })
5844 .unwrap();
5845 assert_eq!(relative_rows[&DisplayRow(0)], 3);
5846 assert_eq!(relative_rows[&DisplayRow(1)], 2);
5847 assert_eq!(relative_rows[&DisplayRow(2)], 1);
5848 // current line has no relative number
5849 assert_eq!(relative_rows[&DisplayRow(4)], 1);
5850 assert_eq!(relative_rows[&DisplayRow(5)], 2);
5851
5852 // works if cursor is before screen
5853 let relative_rows = window
5854 .update(cx, |editor, cx| {
5855 let snapshot = editor.snapshot(cx);
5856 element.calculate_relative_line_numbers(
5857 &snapshot,
5858 &(DisplayRow(3)..DisplayRow(6)),
5859 Some(DisplayRow(1)),
5860 )
5861 })
5862 .unwrap();
5863 assert_eq!(relative_rows.len(), 3);
5864 assert_eq!(relative_rows[&DisplayRow(3)], 2);
5865 assert_eq!(relative_rows[&DisplayRow(4)], 3);
5866 assert_eq!(relative_rows[&DisplayRow(5)], 4);
5867
5868 // works if cursor is after screen
5869 let relative_rows = window
5870 .update(cx, |editor, cx| {
5871 let snapshot = editor.snapshot(cx);
5872 element.calculate_relative_line_numbers(
5873 &snapshot,
5874 &(DisplayRow(0)..DisplayRow(3)),
5875 Some(DisplayRow(6)),
5876 )
5877 })
5878 .unwrap();
5879 assert_eq!(relative_rows.len(), 3);
5880 assert_eq!(relative_rows[&DisplayRow(0)], 5);
5881 assert_eq!(relative_rows[&DisplayRow(1)], 4);
5882 assert_eq!(relative_rows[&DisplayRow(2)], 3);
5883 }
5884
5885 #[gpui::test]
5886 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5887 init_test(cx, |_| {});
5888
5889 let window = cx.add_window(|cx| {
5890 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5891 Editor::new(EditorMode::Full, buffer, None, true, cx)
5892 });
5893 let cx = &mut VisualTestContext::from_window(*window, cx);
5894 let editor = window.root(cx).unwrap();
5895 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5896
5897 window
5898 .update(cx, |editor, cx| {
5899 editor.cursor_shape = CursorShape::Block;
5900 editor.change_selections(None, cx, |s| {
5901 s.select_ranges([
5902 Point::new(0, 0)..Point::new(1, 0),
5903 Point::new(3, 2)..Point::new(3, 3),
5904 Point::new(5, 6)..Point::new(6, 0),
5905 ]);
5906 });
5907 })
5908 .unwrap();
5909
5910 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5911 EditorElement::new(&editor, style)
5912 });
5913
5914 assert_eq!(state.selections.len(), 1);
5915 let local_selections = &state.selections[0].1;
5916 assert_eq!(local_selections.len(), 3);
5917 // moves cursor back one line
5918 assert_eq!(
5919 local_selections[0].head,
5920 DisplayPoint::new(DisplayRow(0), 6)
5921 );
5922 assert_eq!(
5923 local_selections[0].range,
5924 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
5925 );
5926
5927 // moves cursor back one column
5928 assert_eq!(
5929 local_selections[1].range,
5930 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
5931 );
5932 assert_eq!(
5933 local_selections[1].head,
5934 DisplayPoint::new(DisplayRow(3), 2)
5935 );
5936
5937 // leaves cursor on the max point
5938 assert_eq!(
5939 local_selections[2].range,
5940 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
5941 );
5942 assert_eq!(
5943 local_selections[2].head,
5944 DisplayPoint::new(DisplayRow(6), 0)
5945 );
5946
5947 // active lines does not include 1 (even though the range of the selection does)
5948 assert_eq!(
5949 state.active_rows.keys().cloned().collect::<Vec<_>>(),
5950 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
5951 );
5952
5953 // multi-buffer support
5954 // in DisplayPoint coordinates, this is what we're dealing with:
5955 // 0: [[file
5956 // 1: header
5957 // 2: section]]
5958 // 3: aaaaaa
5959 // 4: bbbbbb
5960 // 5: cccccc
5961 // 6:
5962 // 7: [[footer]]
5963 // 8: [[header]]
5964 // 9: ffffff
5965 // 10: gggggg
5966 // 11: hhhhhh
5967 // 12:
5968 // 13: [[footer]]
5969 // 14: [[file
5970 // 15: header
5971 // 16: section]]
5972 // 17: bbbbbb
5973 // 18: cccccc
5974 // 19: dddddd
5975 // 20: [[footer]]
5976 let window = cx.add_window(|cx| {
5977 let buffer = MultiBuffer::build_multi(
5978 [
5979 (
5980 &(sample_text(8, 6, 'a') + "\n"),
5981 vec![
5982 Point::new(0, 0)..Point::new(3, 0),
5983 Point::new(4, 0)..Point::new(7, 0),
5984 ],
5985 ),
5986 (
5987 &(sample_text(8, 6, 'a') + "\n"),
5988 vec![Point::new(1, 0)..Point::new(3, 0)],
5989 ),
5990 ],
5991 cx,
5992 );
5993 Editor::new(EditorMode::Full, buffer, None, true, cx)
5994 });
5995 let editor = window.root(cx).unwrap();
5996 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5997 let _state = window.update(cx, |editor, cx| {
5998 editor.cursor_shape = CursorShape::Block;
5999 editor.change_selections(None, cx, |s| {
6000 s.select_display_ranges([
6001 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6002 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6003 ]);
6004 });
6005 });
6006
6007 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6008 EditorElement::new(&editor, style)
6009 });
6010 assert_eq!(state.selections.len(), 1);
6011 let local_selections = &state.selections[0].1;
6012 assert_eq!(local_selections.len(), 2);
6013
6014 // moves cursor on excerpt boundary back a line
6015 // and doesn't allow selection to bleed through
6016 assert_eq!(
6017 local_selections[0].range,
6018 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6019 );
6020 assert_eq!(
6021 local_selections[0].head,
6022 DisplayPoint::new(DisplayRow(6), 0)
6023 );
6024 // moves cursor on buffer boundary back two lines
6025 // and doesn't allow selection to bleed through
6026 assert_eq!(
6027 local_selections[1].range,
6028 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6029 );
6030 assert_eq!(
6031 local_selections[1].head,
6032 DisplayPoint::new(DisplayRow(12), 0)
6033 );
6034 }
6035
6036 #[gpui::test]
6037 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6038 init_test(cx, |_| {});
6039
6040 let window = cx.add_window(|cx| {
6041 let buffer = MultiBuffer::build_simple("", cx);
6042 Editor::new(EditorMode::Full, buffer, None, true, cx)
6043 });
6044 let cx = &mut VisualTestContext::from_window(*window, cx);
6045 let editor = window.root(cx).unwrap();
6046 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6047 window
6048 .update(cx, |editor, cx| {
6049 editor.set_placeholder_text("hello", cx);
6050 editor.insert_blocks(
6051 [BlockProperties {
6052 style: BlockStyle::Fixed,
6053 disposition: BlockDisposition::Above,
6054 height: 3,
6055 position: Anchor::min(),
6056 render: Box::new(|_| div().into_any()),
6057 }],
6058 None,
6059 cx,
6060 );
6061
6062 // Blur the editor so that it displays placeholder text.
6063 cx.blur();
6064 })
6065 .unwrap();
6066
6067 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6068 EditorElement::new(&editor, style)
6069 });
6070 assert_eq!(state.position_map.line_layouts.len(), 4);
6071 assert_eq!(
6072 state
6073 .line_numbers
6074 .iter()
6075 .map(Option::is_some)
6076 .collect::<Vec<_>>(),
6077 &[false, false, false, true]
6078 );
6079 }
6080
6081 #[gpui::test]
6082 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6083 const TAB_SIZE: u32 = 4;
6084
6085 let input_text = "\t \t|\t| a b";
6086 let expected_invisibles = vec![
6087 Invisible::Tab {
6088 line_start_offset: 0,
6089 line_end_offset: TAB_SIZE as usize,
6090 },
6091 Invisible::Whitespace {
6092 line_offset: TAB_SIZE as usize,
6093 },
6094 Invisible::Tab {
6095 line_start_offset: TAB_SIZE as usize + 1,
6096 line_end_offset: TAB_SIZE as usize * 2,
6097 },
6098 Invisible::Tab {
6099 line_start_offset: TAB_SIZE as usize * 2 + 1,
6100 line_end_offset: TAB_SIZE as usize * 3,
6101 },
6102 Invisible::Whitespace {
6103 line_offset: TAB_SIZE as usize * 3 + 1,
6104 },
6105 Invisible::Whitespace {
6106 line_offset: TAB_SIZE as usize * 3 + 3,
6107 },
6108 ];
6109 assert_eq!(
6110 expected_invisibles.len(),
6111 input_text
6112 .chars()
6113 .filter(|initial_char| initial_char.is_whitespace())
6114 .count(),
6115 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6116 );
6117
6118 init_test(cx, |s| {
6119 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6120 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6121 });
6122
6123 let actual_invisibles =
6124 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
6125
6126 assert_eq!(expected_invisibles, actual_invisibles);
6127 }
6128
6129 #[gpui::test]
6130 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6131 init_test(cx, |s| {
6132 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6133 s.defaults.tab_size = NonZeroU32::new(4);
6134 });
6135
6136 for editor_mode_without_invisibles in [
6137 EditorMode::SingleLine { auto_width: false },
6138 EditorMode::AutoHeight { max_lines: 100 },
6139 ] {
6140 let invisibles = collect_invisibles_from_new_editor(
6141 cx,
6142 editor_mode_without_invisibles,
6143 "\t\t\t| | a b",
6144 px(500.0),
6145 );
6146 assert!(invisibles.is_empty(),
6147 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6148 }
6149 }
6150
6151 #[gpui::test]
6152 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6153 let tab_size = 4;
6154 let input_text = "a\tbcd ".repeat(9);
6155 let repeated_invisibles = [
6156 Invisible::Tab {
6157 line_start_offset: 1,
6158 line_end_offset: tab_size as usize,
6159 },
6160 Invisible::Whitespace {
6161 line_offset: tab_size as usize + 3,
6162 },
6163 Invisible::Whitespace {
6164 line_offset: tab_size as usize + 4,
6165 },
6166 Invisible::Whitespace {
6167 line_offset: tab_size as usize + 5,
6168 },
6169 Invisible::Whitespace {
6170 line_offset: tab_size as usize + 6,
6171 },
6172 Invisible::Whitespace {
6173 line_offset: tab_size as usize + 7,
6174 },
6175 ];
6176 let expected_invisibles = std::iter::once(repeated_invisibles)
6177 .cycle()
6178 .take(9)
6179 .flatten()
6180 .collect::<Vec<_>>();
6181 assert_eq!(
6182 expected_invisibles.len(),
6183 input_text
6184 .chars()
6185 .filter(|initial_char| initial_char.is_whitespace())
6186 .count(),
6187 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6188 );
6189 info!("Expected invisibles: {expected_invisibles:?}");
6190
6191 init_test(cx, |_| {});
6192
6193 // Put the same string with repeating whitespace pattern into editors of various size,
6194 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6195 let resize_step = 10.0;
6196 let mut editor_width = 200.0;
6197 while editor_width <= 1000.0 {
6198 update_test_language_settings(cx, |s| {
6199 s.defaults.tab_size = NonZeroU32::new(tab_size);
6200 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6201 s.defaults.preferred_line_length = Some(editor_width as u32);
6202 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6203 });
6204
6205 let actual_invisibles = collect_invisibles_from_new_editor(
6206 cx,
6207 EditorMode::Full,
6208 &input_text,
6209 px(editor_width),
6210 );
6211
6212 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6213 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6214 let mut i = 0;
6215 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6216 i = actual_index;
6217 match expected_invisibles.get(i) {
6218 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6219 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6220 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6221 _ => {
6222 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6223 }
6224 },
6225 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6226 }
6227 }
6228 let missing_expected_invisibles = &expected_invisibles[i + 1..];
6229 assert!(
6230 missing_expected_invisibles.is_empty(),
6231 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6232 );
6233
6234 editor_width += resize_step;
6235 }
6236 }
6237
6238 fn collect_invisibles_from_new_editor(
6239 cx: &mut TestAppContext,
6240 editor_mode: EditorMode,
6241 input_text: &str,
6242 editor_width: Pixels,
6243 ) -> Vec<Invisible> {
6244 info!(
6245 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6246 editor_width.0
6247 );
6248 let window = cx.add_window(|cx| {
6249 let buffer = MultiBuffer::build_simple(&input_text, cx);
6250 Editor::new(editor_mode, buffer, None, true, cx)
6251 });
6252 let cx = &mut VisualTestContext::from_window(*window, cx);
6253 let editor = window.root(cx).unwrap();
6254 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6255 window
6256 .update(cx, |editor, cx| {
6257 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6258 editor.set_wrap_width(Some(editor_width), cx);
6259 })
6260 .unwrap();
6261 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6262 EditorElement::new(&editor, style)
6263 });
6264 state
6265 .position_map
6266 .line_layouts
6267 .iter()
6268 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6269 .cloned()
6270 .collect()
6271 }
6272}
6273
6274pub fn register_action<T: Action>(
6275 view: &View<Editor>,
6276 cx: &mut WindowContext,
6277 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6278) {
6279 let view = view.clone();
6280 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6281 let action = action.downcast_ref().unwrap();
6282 if phase == DispatchPhase::Bubble {
6283 view.update(cx, |editor, cx| {
6284 listener(editor, action, cx);
6285 })
6286 }
6287 })
6288}
6289
6290fn compute_auto_height_layout(
6291 editor: &mut Editor,
6292 max_lines: usize,
6293 max_line_number_width: Pixels,
6294 known_dimensions: Size<Option<Pixels>>,
6295 available_width: AvailableSpace,
6296 cx: &mut ViewContext<Editor>,
6297) -> Option<Size<Pixels>> {
6298 let width = known_dimensions.width.or_else(|| {
6299 if let AvailableSpace::Definite(available_width) = available_width {
6300 Some(available_width)
6301 } else {
6302 None
6303 }
6304 })?;
6305 if let Some(height) = known_dimensions.height {
6306 return Some(size(width, height));
6307 }
6308
6309 let style = editor.style.as_ref().unwrap();
6310 let font_id = cx.text_system().resolve_font(&style.text.font());
6311 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6312 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6313 let em_width = cx
6314 .text_system()
6315 .typographic_bounds(font_id, font_size, 'm')
6316 .unwrap()
6317 .size
6318 .width;
6319
6320 let mut snapshot = editor.snapshot(cx);
6321 let gutter_dimensions =
6322 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6323
6324 editor.gutter_dimensions = gutter_dimensions;
6325 let text_width = width - gutter_dimensions.width;
6326 let overscroll = size(em_width, px(0.));
6327
6328 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6329 if editor.set_wrap_width(Some(editor_width), cx) {
6330 snapshot = editor.snapshot(cx);
6331 }
6332
6333 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6334 let height = scroll_height
6335 .max(line_height)
6336 .min(line_height * max_lines as f32);
6337
6338 Some(size(width, height))
6339}