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