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