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