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, svg, 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 #[derive(Clone)]
1394 struct JumpData {
1395 position: Point,
1396 anchor: text::Anchor,
1397 path: ProjectPath,
1398 }
1399
1400 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1401 let jump_path = ProjectPath {
1402 worktree_id: file.worktree_id(cx),
1403 path: file.path.clone(),
1404 };
1405 let jump_anchor = range
1406 .primary
1407 .as_ref()
1408 .map_or(range.context.start, |primary| primary.start);
1409 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1410
1411 JumpData {
1412 position: jump_position,
1413 anchor: jump_anchor,
1414 path: jump_path,
1415 }
1416 });
1417
1418 let element = if *starts_new_buffer {
1419 let path = buffer.resolve_file_path(cx, include_root);
1420 let mut filename = None;
1421 let mut parent_path = None;
1422 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1423 if let Some(path) = path {
1424 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1425 parent_path = path
1426 .parent()
1427 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1428 }
1429
1430 v_flex()
1431 .id(("path header container", block_id))
1432 .size_full()
1433 .justify_center()
1434 .p(gpui::px(6.))
1435 .child(
1436 h_flex()
1437 .id("path header block")
1438 .size_full()
1439 .pl(gpui::px(12.))
1440 .pr(gpui::px(8.))
1441 .rounded_md()
1442 .shadow_md()
1443 .border()
1444 .border_color(cx.theme().colors().border)
1445 .bg(cx.theme().colors().editor_subheader_background)
1446 .justify_between()
1447 .hover(|style| style.bg(cx.theme().colors().element_hover))
1448 .child(
1449 h_flex().gap_3().child(
1450 h_flex()
1451 .gap_2()
1452 .child(
1453 filename
1454 .map(SharedString::from)
1455 .unwrap_or_else(|| "untitled".into()),
1456 )
1457 .when_some(parent_path, |then, path| {
1458 then.child(
1459 div().child(path).text_color(
1460 cx.theme().colors().text_muted,
1461 ),
1462 )
1463 }),
1464 ),
1465 )
1466 .when_some(jump_data.clone(), |this, jump_data| {
1467 this.cursor_pointer()
1468 .tooltip(|cx| {
1469 Tooltip::for_action(
1470 "Jump to File",
1471 &OpenExcerpts,
1472 cx,
1473 )
1474 })
1475 .on_mouse_down(MouseButton::Left, |_, cx| {
1476 cx.stop_propagation()
1477 })
1478 .on_click(cx.listener_for(&self.editor, {
1479 move |editor, _, cx| {
1480 editor.jump(
1481 jump_data.path.clone(),
1482 jump_data.position,
1483 jump_data.anchor,
1484 cx,
1485 );
1486 }
1487 }))
1488 }),
1489 )
1490 } else {
1491 v_flex()
1492 .id(("collapsed context", block_id))
1493 .size_full()
1494 .child(
1495 div()
1496 .flex()
1497 .v_flex()
1498 .justify_start()
1499 .id("jump to collapsed context")
1500 .group("")
1501 .w(relative(1.0))
1502 .h_full()
1503 .cursor_pointer()
1504 .child(
1505 div()
1506 .h_px()
1507 .w_full()
1508 .bg(cx.theme().colors().border_variant)
1509 .group_hover("", |style| {
1510 style.bg(cx.theme().colors().border)
1511 }),
1512 )
1513 .when_some(jump_data.clone(), |this, jump_data| {
1514 this.on_click(cx.listener_for(&self.editor, {
1515 let path = jump_data.path.clone();
1516 move |editor, _, cx| {
1517 cx.stop_propagation();
1518
1519 editor.jump(
1520 path.clone(),
1521 jump_data.position,
1522 jump_data.anchor,
1523 cx,
1524 );
1525 }
1526 }))
1527 .tooltip(
1528 move |cx| {
1529 Tooltip::for_action(
1530 format!(
1531 "Jump to {}:L{}",
1532 jump_data.path.path.display(),
1533 jump_data.position.row + 1
1534 ),
1535 &OpenExcerpts,
1536 cx,
1537 )
1538 },
1539 )
1540 }),
1541 )
1542 .child(
1543 h_flex()
1544 .justify_end()
1545 .flex_none()
1546 .w(
1547 gutter_dimensions.width - (gutter_dimensions.left_padding), // + gutter_dimensions.right_padding)
1548 )
1549 .h_full()
1550 .child(
1551 ButtonLike::new("jump-icon")
1552 .style(ButtonStyle::Transparent)
1553 .child(
1554 svg()
1555 .path(IconName::ArrowUpRight.path())
1556 .size(IconSize::XSmall.rems())
1557 .text_color(cx.theme().colors().border)
1558 .group_hover("", |style| {
1559 style.text_color(
1560 cx.theme().colors().editor_line_number,
1561 )
1562 }),
1563 )
1564 .when_some(jump_data.clone(), |this, jump_data| {
1565 this.on_click(cx.listener_for(&self.editor, {
1566 let path = jump_data.path.clone();
1567 move |editor, _, cx| {
1568 editor.jump(
1569 path.clone(),
1570 jump_data.position,
1571 jump_data.anchor,
1572 cx,
1573 );
1574 }
1575 }))
1576 .tooltip({
1577 move |cx| {
1578 Tooltip::for_action(
1579 format!(
1580 "Jump to {}:L{}",
1581 jump_data.path.path.display(),
1582 jump_data.position.row + 1
1583 ),
1584 &OpenExcerpts,
1585 cx,
1586 )
1587 }
1588 })
1589 }),
1590 ),
1591 )
1592 };
1593 element.into_any()
1594 }
1595 };
1596
1597 let size = element.measure(available_space, cx);
1598 (element, size)
1599 };
1600
1601 let mut fixed_block_max_width = Pixels::ZERO;
1602 let mut blocks = Vec::new();
1603 for (row, block) in fixed_blocks {
1604 let available_space = size(
1605 AvailableSpace::MinContent,
1606 AvailableSpace::Definite(block.height() as f32 * line_height),
1607 );
1608 let (element, element_size) = render_block(block, available_space, block_id, cx);
1609 block_id += 1;
1610 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1611 blocks.push(BlockLayout {
1612 row,
1613 element,
1614 available_space,
1615 style: BlockStyle::Fixed,
1616 });
1617 }
1618 for (row, block) in non_fixed_blocks {
1619 let style = match block {
1620 TransformBlock::Custom(block) => block.style(),
1621 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1622 };
1623 let width = match style {
1624 BlockStyle::Sticky => hitbox.size.width,
1625 BlockStyle::Flex => hitbox
1626 .size
1627 .width
1628 .max(fixed_block_max_width)
1629 .max(gutter_dimensions.width + *scroll_width),
1630 BlockStyle::Fixed => unreachable!(),
1631 };
1632 let available_space = size(
1633 AvailableSpace::Definite(width),
1634 AvailableSpace::Definite(block.height() as f32 * line_height),
1635 );
1636 let (element, _) = render_block(block, available_space, block_id, cx);
1637 block_id += 1;
1638 blocks.push(BlockLayout {
1639 row,
1640 element,
1641 available_space,
1642 style,
1643 });
1644 }
1645
1646 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1647 blocks
1648 }
1649
1650 fn layout_blocks(
1651 &self,
1652 blocks: &mut Vec<BlockLayout>,
1653 hitbox: &Hitbox,
1654 line_height: Pixels,
1655 scroll_pixel_position: gpui::Point<Pixels>,
1656 cx: &mut ElementContext,
1657 ) {
1658 for block in blocks {
1659 let mut origin = hitbox.origin
1660 + point(
1661 Pixels::ZERO,
1662 block.row as f32 * line_height - scroll_pixel_position.y,
1663 );
1664 if !matches!(block.style, BlockStyle::Sticky) {
1665 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1666 }
1667 block.element.layout(origin, block.available_space, cx);
1668 }
1669 }
1670
1671 #[allow(clippy::too_many_arguments)]
1672 fn layout_context_menu(
1673 &self,
1674 line_height: Pixels,
1675 hitbox: &Hitbox,
1676 text_hitbox: &Hitbox,
1677 content_origin: gpui::Point<Pixels>,
1678 start_row: u32,
1679 scroll_pixel_position: gpui::Point<Pixels>,
1680 line_layouts: &[LineWithInvisibles],
1681 newest_selection_head: DisplayPoint,
1682 cx: &mut ElementContext,
1683 ) -> bool {
1684 let max_height = cmp::min(
1685 12. * line_height,
1686 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1687 );
1688 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1689 if editor.context_menu_visible() {
1690 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1691 } else {
1692 None
1693 }
1694 }) else {
1695 return false;
1696 };
1697
1698 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1699 let context_menu_size = context_menu.measure(available_space, cx);
1700
1701 let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1702 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1703 let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1704 let mut list_origin = content_origin + point(x, y);
1705 let list_width = context_menu_size.width;
1706 let list_height = context_menu_size.height;
1707
1708 // Snap the right edge of the list to the right edge of the window if
1709 // its horizontal bounds overflow.
1710 if list_origin.x + list_width > cx.viewport_size().width {
1711 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1712 }
1713
1714 if list_origin.y + list_height > text_hitbox.lower_right().y {
1715 list_origin.y -= line_height + list_height;
1716 }
1717
1718 cx.defer_draw(context_menu, list_origin, 1);
1719 true
1720 }
1721
1722 fn layout_mouse_context_menu(&self, cx: &mut ElementContext) -> Option<AnyElement> {
1723 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1724 let mut element = overlay()
1725 .position(mouse_context_menu.position)
1726 .child(mouse_context_menu.context_menu.clone())
1727 .anchor(AnchorCorner::TopLeft)
1728 .snap_to_window()
1729 .into_any();
1730 element.layout(gpui::Point::default(), AvailableSpace::min_size(), cx);
1731 Some(element)
1732 }
1733
1734 #[allow(clippy::too_many_arguments)]
1735 fn layout_hover_popovers(
1736 &self,
1737 snapshot: &EditorSnapshot,
1738 hitbox: &Hitbox,
1739 text_hitbox: &Hitbox,
1740 visible_display_row_range: Range<u32>,
1741 content_origin: gpui::Point<Pixels>,
1742 scroll_pixel_position: gpui::Point<Pixels>,
1743 line_layouts: &[LineWithInvisibles],
1744 line_height: Pixels,
1745 em_width: Pixels,
1746 cx: &mut ElementContext,
1747 ) {
1748 struct MeasuredHoverPopover {
1749 element: AnyElement,
1750 size: Size<Pixels>,
1751 horizontal_offset: Pixels,
1752 }
1753
1754 let max_size = size(
1755 (120. * em_width) // Default size
1756 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
1757 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1758 (16. * line_height) // Default size
1759 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
1760 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1761 );
1762
1763 let hover_popovers = self.editor.update(cx, |editor, cx| {
1764 editor.hover_state.render(
1765 &snapshot,
1766 &self.style,
1767 visible_display_row_range.clone(),
1768 max_size,
1769 editor.workspace.as_ref().map(|(w, _)| w.clone()),
1770 cx,
1771 )
1772 });
1773 let Some((position, hover_popovers)) = hover_popovers else {
1774 return;
1775 };
1776
1777 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1778
1779 // This is safe because we check on layout whether the required row is available
1780 let hovered_row_layout =
1781 &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
1782
1783 // Compute Hovered Point
1784 let x =
1785 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1786 let y = position.row() as f32 * line_height - scroll_pixel_position.y;
1787 let hovered_point = content_origin + point(x, y);
1788
1789 let mut overall_height = Pixels::ZERO;
1790 let mut measured_hover_popovers = Vec::new();
1791 for mut hover_popover in hover_popovers {
1792 let size = hover_popover.measure(available_space, cx);
1793 let horizontal_offset =
1794 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
1795
1796 overall_height += HOVER_POPOVER_GAP + size.height;
1797
1798 measured_hover_popovers.push(MeasuredHoverPopover {
1799 element: hover_popover,
1800 size,
1801 horizontal_offset,
1802 });
1803 }
1804 overall_height += HOVER_POPOVER_GAP;
1805
1806 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
1807 let mut occlusion = div()
1808 .size_full()
1809 .occlude()
1810 .on_mouse_move(|_, cx| cx.stop_propagation())
1811 .into_any_element();
1812 occlusion.measure(size(width, HOVER_POPOVER_GAP).into(), cx);
1813 cx.defer_draw(occlusion, origin, 2);
1814 }
1815
1816 if hovered_point.y > overall_height {
1817 // There is enough space above. Render popovers above the hovered point
1818 let mut current_y = hovered_point.y;
1819 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1820 let size = popover.size;
1821 let popover_origin = point(
1822 hovered_point.x + popover.horizontal_offset,
1823 current_y - size.height,
1824 );
1825
1826 cx.defer_draw(popover.element, popover_origin, 2);
1827 if position != itertools::Position::Last {
1828 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
1829 draw_occluder(size.width, origin, cx);
1830 }
1831
1832 current_y = popover_origin.y - HOVER_POPOVER_GAP;
1833 }
1834 } else {
1835 // There is not enough space above. Render popovers below the hovered point
1836 let mut current_y = hovered_point.y + line_height;
1837 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1838 let size = popover.size;
1839 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
1840
1841 cx.defer_draw(popover.element, popover_origin, 2);
1842 if position != itertools::Position::Last {
1843 let origin = point(popover_origin.x, popover_origin.y + size.height);
1844 draw_occluder(size.width, origin, cx);
1845 }
1846
1847 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
1848 }
1849 }
1850 }
1851
1852 fn paint_background(&self, layout: &EditorLayout, cx: &mut ElementContext) {
1853 cx.paint_layer(layout.hitbox.bounds, |cx| {
1854 let scroll_top = layout.position_map.snapshot.scroll_position().y;
1855 let gutter_bg = cx.theme().colors().editor_gutter_background;
1856 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
1857 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
1858
1859 if let EditorMode::Full = layout.mode {
1860 let mut active_rows = layout.active_rows.iter().peekable();
1861 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
1862 let mut end_row = *start_row;
1863 while active_rows.peek().map_or(false, |r| {
1864 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
1865 }) {
1866 active_rows.next().unwrap();
1867 end_row += 1;
1868 }
1869
1870 if !contains_non_empty_selection {
1871 let origin = point(
1872 layout.hitbox.origin.x,
1873 layout.hitbox.origin.y
1874 + (*start_row as f32 - scroll_top)
1875 * layout.position_map.line_height,
1876 );
1877 let size = size(
1878 layout.hitbox.size.width,
1879 layout.position_map.line_height * (end_row - start_row + 1) as f32,
1880 );
1881 let active_line_bg = cx.theme().colors().editor_active_line_background;
1882 cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
1883 }
1884 }
1885
1886 let mut paint_highlight =
1887 |highlight_row_start: u32, highlight_row_end: u32, color| {
1888 let origin = point(
1889 layout.hitbox.origin.x,
1890 layout.hitbox.origin.y
1891 + (highlight_row_start as f32 - scroll_top)
1892 * layout.position_map.line_height,
1893 );
1894 let size = size(
1895 layout.hitbox.size.width,
1896 layout.position_map.line_height
1897 * (highlight_row_end + 1 - highlight_row_start) as f32,
1898 );
1899 cx.paint_quad(fill(Bounds { origin, size }, color));
1900 };
1901
1902 let mut last_row = None;
1903 let mut highlight_row_start = 0u32;
1904 let mut highlight_row_end = 0u32;
1905 for (&row, &color) in &layout.highlighted_rows {
1906 let paint = last_row.map_or(false, |(last_row, last_color)| {
1907 last_color != color || last_row + 1 < row
1908 });
1909
1910 if paint {
1911 let paint_range_is_unfinished = highlight_row_end == 0;
1912 if paint_range_is_unfinished {
1913 highlight_row_end = row;
1914 last_row = None;
1915 }
1916 paint_highlight(highlight_row_start, highlight_row_end, color);
1917 highlight_row_start = 0;
1918 highlight_row_end = 0;
1919 if !paint_range_is_unfinished {
1920 highlight_row_start = row;
1921 last_row = Some((row, color));
1922 }
1923 } else {
1924 if last_row.is_none() {
1925 highlight_row_start = row;
1926 } else {
1927 highlight_row_end = row;
1928 }
1929 last_row = Some((row, color));
1930 }
1931 }
1932 if let Some((row, hsla)) = last_row {
1933 highlight_row_end = row;
1934 paint_highlight(highlight_row_start, highlight_row_end, hsla);
1935 }
1936
1937 let scroll_left =
1938 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
1939
1940 for (wrap_position, active) in layout.wrap_guides.iter() {
1941 let x = (layout.text_hitbox.origin.x
1942 + *wrap_position
1943 + layout.position_map.em_width / 2.)
1944 - scroll_left;
1945
1946 let show_scrollbars = layout
1947 .scrollbar_layout
1948 .as_ref()
1949 .map_or(false, |scrollbar| scrollbar.visible);
1950 if x < layout.text_hitbox.origin.x
1951 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
1952 {
1953 continue;
1954 }
1955
1956 let color = if *active {
1957 cx.theme().colors().editor_active_wrap_guide
1958 } else {
1959 cx.theme().colors().editor_wrap_guide
1960 };
1961 cx.paint_quad(fill(
1962 Bounds {
1963 origin: point(x, layout.text_hitbox.origin.y),
1964 size: size(px(1.), layout.text_hitbox.size.height),
1965 },
1966 color,
1967 ));
1968 }
1969 }
1970 })
1971 }
1972
1973 fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
1974 let line_height = layout.position_map.line_height;
1975
1976 let scroll_position = layout.position_map.snapshot.scroll_position();
1977 let scroll_top = scroll_position.y * line_height;
1978
1979 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
1980
1981 let show_git_gutter = matches!(
1982 ProjectSettings::get_global(cx).git.git_gutter,
1983 Some(GitGutterSetting::TrackedFiles)
1984 );
1985
1986 if show_git_gutter {
1987 Self::paint_diff_hunks(layout, cx);
1988 }
1989
1990 for (ix, line) in layout.line_numbers.iter().enumerate() {
1991 if let Some(line) = line {
1992 let line_origin = layout.gutter_hitbox.origin
1993 + point(
1994 layout.gutter_hitbox.size.width
1995 - line.width
1996 - layout.gutter_dimensions.right_padding,
1997 ix as f32 * line_height - (scroll_top % line_height),
1998 );
1999
2000 line.paint(line_origin, line_height, cx).log_err();
2001 }
2002 }
2003
2004 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2005 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2006 for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2007 fold_indicator.paint(cx);
2008 }
2009 });
2010
2011 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2012 indicator.paint(cx);
2013 }
2014 })
2015 }
2016
2017 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut ElementContext) {
2018 if layout.display_hunks.is_empty() {
2019 return;
2020 }
2021
2022 let line_height = layout.position_map.line_height;
2023
2024 let scroll_position = layout.position_map.snapshot.scroll_position();
2025 let scroll_top = scroll_position.y * line_height;
2026
2027 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2028 for hunk in &layout.display_hunks {
2029 let (display_row_range, status) = match hunk {
2030 //TODO: This rendering is entirely a horrible hack
2031 &DisplayDiffHunk::Folded { display_row: row } => {
2032 let start_y = row as f32 * line_height - scroll_top;
2033 let end_y = start_y + line_height;
2034
2035 let width = 0.275 * line_height;
2036 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2037 let highlight_size = size(width * 2., end_y - start_y);
2038 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2039 cx.paint_quad(quad(
2040 highlight_bounds,
2041 Corners::all(1. * line_height),
2042 cx.theme().status().modified,
2043 Edges::default(),
2044 transparent_black(),
2045 ));
2046
2047 continue;
2048 }
2049
2050 DisplayDiffHunk::Unfolded {
2051 display_row_range,
2052 status,
2053 } => (display_row_range, status),
2054 };
2055
2056 let color = match status {
2057 DiffHunkStatus::Added => cx.theme().status().created,
2058 DiffHunkStatus::Modified => cx.theme().status().modified,
2059
2060 //TODO: This rendering is entirely a horrible hack
2061 DiffHunkStatus::Removed => {
2062 let row = display_row_range.start;
2063
2064 let offset = line_height / 2.;
2065 let start_y = row as f32 * line_height - offset - scroll_top;
2066 let end_y = start_y + line_height;
2067
2068 let width = 0.275 * line_height;
2069 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2070 let highlight_size = size(width * 2., end_y - start_y);
2071 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2072 cx.paint_quad(quad(
2073 highlight_bounds,
2074 Corners::all(1. * line_height),
2075 cx.theme().status().deleted,
2076 Edges::default(),
2077 transparent_black(),
2078 ));
2079
2080 continue;
2081 }
2082 };
2083
2084 let start_row = display_row_range.start;
2085 let end_row = display_row_range.end;
2086 // If we're in a multibuffer, row range span might include an
2087 // excerpt header, so if we were to draw the marker straight away,
2088 // the hunk might include the rows of that header.
2089 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2090 // Instead, we simply check whether the range we're dealing with includes
2091 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2092 let end_row_in_current_excerpt = layout
2093 .position_map
2094 .snapshot
2095 .blocks_in_range(start_row..end_row)
2096 .find_map(|(start_row, block)| {
2097 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2098 Some(start_row)
2099 } else {
2100 None
2101 }
2102 })
2103 .unwrap_or(end_row);
2104
2105 let start_y = start_row as f32 * line_height - scroll_top;
2106 let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2107
2108 let width = 0.275 * line_height;
2109 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2110 let highlight_size = size(width * 2., end_y - start_y);
2111 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2112 cx.paint_quad(quad(
2113 highlight_bounds,
2114 Corners::all(0.05 * line_height),
2115 color,
2116 Edges::default(),
2117 transparent_black(),
2118 ));
2119 }
2120 })
2121 }
2122
2123 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2124 cx.with_content_mask(
2125 Some(ContentMask {
2126 bounds: layout.text_hitbox.bounds,
2127 }),
2128 |cx| {
2129 let cursor_style = if self
2130 .editor
2131 .read(cx)
2132 .hovered_link_state
2133 .as_ref()
2134 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2135 {
2136 CursorStyle::PointingHand
2137 } else {
2138 CursorStyle::IBeam
2139 };
2140 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2141
2142 cx.with_element_id(Some("folds"), |cx| self.paint_folds(layout, cx));
2143 let invisible_display_ranges = self.paint_highlights(layout, cx);
2144 self.paint_lines(&invisible_display_ranges, layout, cx);
2145 self.paint_redactions(layout, cx);
2146 self.paint_cursors(layout, cx);
2147 },
2148 )
2149 }
2150
2151 fn paint_highlights(
2152 &mut self,
2153 layout: &mut EditorLayout,
2154 cx: &mut ElementContext,
2155 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2156 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2157 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2158 let line_end_overshoot = 0.15 * layout.position_map.line_height;
2159 for (range, color) in &layout.highlighted_ranges {
2160 self.paint_highlighted_range(
2161 range.clone(),
2162 *color,
2163 Pixels::ZERO,
2164 line_end_overshoot,
2165 layout,
2166 cx,
2167 );
2168 }
2169
2170 let corner_radius = 0.15 * layout.position_map.line_height;
2171
2172 for (player_color, selections) in &layout.selections {
2173 for selection in selections.into_iter() {
2174 self.paint_highlighted_range(
2175 selection.range.clone(),
2176 player_color.selection,
2177 corner_radius,
2178 corner_radius * 2.,
2179 layout,
2180 cx,
2181 );
2182
2183 if selection.is_local && !selection.range.is_empty() {
2184 invisible_display_ranges.push(selection.range.clone());
2185 }
2186 }
2187 }
2188 invisible_display_ranges
2189 })
2190 }
2191
2192 fn paint_lines(
2193 &mut self,
2194 invisible_display_ranges: &[Range<DisplayPoint>],
2195 layout: &EditorLayout,
2196 cx: &mut ElementContext,
2197 ) {
2198 let whitespace_setting = self
2199 .editor
2200 .read(cx)
2201 .buffer
2202 .read(cx)
2203 .settings_at(0, cx)
2204 .show_whitespaces;
2205
2206 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2207 let row = layout.visible_display_row_range.start + ix as u32;
2208 line_with_invisibles.draw(
2209 layout,
2210 row,
2211 layout.content_origin,
2212 whitespace_setting,
2213 invisible_display_ranges,
2214 cx,
2215 )
2216 }
2217 }
2218
2219 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2220 if layout.redacted_ranges.is_empty() {
2221 return;
2222 }
2223
2224 let line_end_overshoot = layout.line_end_overshoot();
2225
2226 // A softer than perfect black
2227 let redaction_color = gpui::rgb(0x0e1111);
2228
2229 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2230 for range in layout.redacted_ranges.iter() {
2231 self.paint_highlighted_range(
2232 range.clone(),
2233 redaction_color.into(),
2234 Pixels::ZERO,
2235 line_end_overshoot,
2236 layout,
2237 cx,
2238 );
2239 }
2240 });
2241 }
2242
2243 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2244 for cursor in &mut layout.cursors {
2245 cursor.paint(layout.content_origin, cx);
2246 }
2247 }
2248
2249 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2250 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2251 return;
2252 };
2253
2254 let thumb_bounds = scrollbar_layout.thumb_bounds();
2255 if scrollbar_layout.visible {
2256 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2257 cx.paint_quad(quad(
2258 scrollbar_layout.hitbox.bounds,
2259 Corners::default(),
2260 cx.theme().colors().scrollbar_track_background,
2261 Edges {
2262 top: Pixels::ZERO,
2263 right: Pixels::ZERO,
2264 bottom: Pixels::ZERO,
2265 left: ScrollbarLayout::BORDER_WIDTH,
2266 },
2267 cx.theme().colors().scrollbar_track_border,
2268 ));
2269 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2270 let is_singleton = self.editor.read(cx).is_singleton(cx);
2271 let left = scrollbar_layout.hitbox.left();
2272 let right = scrollbar_layout.hitbox.right();
2273 let column_width =
2274 px(((right - left - ScrollbarLayout::BORDER_WIDTH).0 / 3.0).floor());
2275 if is_singleton && scrollbar_settings.selections {
2276 let start_anchor = Anchor::min();
2277 let end_anchor = Anchor::max();
2278 let background_ranges = self
2279 .editor
2280 .read(cx)
2281 .background_highlight_row_ranges::<BufferSearchHighlights>(
2282 start_anchor..end_anchor,
2283 &layout.position_map.snapshot,
2284 50000,
2285 );
2286 let left_x = left + ScrollbarLayout::BORDER_WIDTH + column_width;
2287 let right_x = left_x + column_width;
2288 for range in background_ranges {
2289 let (start_y, end_y) =
2290 scrollbar_layout.ys_for_marker(range.start().row(), range.end().row());
2291 let bounds =
2292 Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2293 cx.paint_quad(quad(
2294 bounds,
2295 Corners::default(),
2296 cx.theme().status().info,
2297 Edges::default(),
2298 cx.theme().colors().scrollbar_thumb_border,
2299 ));
2300 }
2301 }
2302
2303 if is_singleton && scrollbar_settings.symbols_selections {
2304 let selection_ranges = self.editor.read(cx).background_highlights_in_range(
2305 Anchor::min()..Anchor::max(),
2306 &layout.position_map.snapshot,
2307 cx.theme().colors(),
2308 );
2309 let left_x = left + ScrollbarLayout::BORDER_WIDTH + column_width;
2310 let right_x = left_x + column_width;
2311 for hunk in selection_ranges {
2312 let start_display = Point::new(hunk.0.start.row(), 0)
2313 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2314 let end_display = Point::new(hunk.0.end.row(), 0)
2315 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2316 let (start_y, end_y) =
2317 scrollbar_layout.ys_for_marker(start_display.row(), end_display.row());
2318 let bounds =
2319 Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2320 cx.paint_quad(quad(
2321 bounds,
2322 Corners::default(),
2323 cx.theme().status().info,
2324 Edges::default(),
2325 cx.theme().colors().scrollbar_thumb_border,
2326 ));
2327 }
2328 }
2329
2330 if is_singleton && scrollbar_settings.git_diff {
2331 let left_x = left + ScrollbarLayout::BORDER_WIDTH;
2332 let right_x = left_x + column_width;
2333 for hunk in layout
2334 .position_map
2335 .snapshot
2336 .buffer_snapshot
2337 .git_diff_hunks_in_range(0..layout.max_row)
2338 {
2339 let start_display_row = Point::new(hunk.associated_range.start, 0)
2340 .to_display_point(&layout.position_map.snapshot.display_snapshot)
2341 .row();
2342 let mut end_display_row = Point::new(hunk.associated_range.end, 0)
2343 .to_display_point(&layout.position_map.snapshot.display_snapshot)
2344 .row();
2345 if end_display_row != start_display_row {
2346 end_display_row -= 1;
2347 }
2348 let (start_y, end_y) =
2349 scrollbar_layout.ys_for_marker(start_display_row, end_display_row);
2350 let bounds =
2351 Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2352 let color = match hunk.status() {
2353 DiffHunkStatus::Added => cx.theme().status().created,
2354 DiffHunkStatus::Modified => cx.theme().status().modified,
2355 DiffHunkStatus::Removed => cx.theme().status().deleted,
2356 };
2357 cx.paint_quad(quad(
2358 bounds,
2359 Corners::default(),
2360 color,
2361 Edges::default(),
2362 cx.theme().colors().scrollbar_thumb_border,
2363 ));
2364 }
2365 }
2366
2367 if is_singleton && scrollbar_settings.diagnostics {
2368 let max_point = layout
2369 .position_map
2370 .snapshot
2371 .display_snapshot
2372 .buffer_snapshot
2373 .max_point();
2374
2375 let diagnostics = layout
2376 .position_map
2377 .snapshot
2378 .buffer_snapshot
2379 .diagnostics_in_range::<_, Point>(Point::zero()..max_point, false)
2380 // We want to sort by severity, in order to paint the most severe diagnostics last.
2381 .sorted_by_key(|diagnostic| {
2382 std::cmp::Reverse(diagnostic.diagnostic.severity)
2383 });
2384
2385 let left_x = left + ScrollbarLayout::BORDER_WIDTH + 2.0 * column_width;
2386 for diagnostic in diagnostics {
2387 let start_display = diagnostic
2388 .range
2389 .start
2390 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2391 let end_display = diagnostic
2392 .range
2393 .end
2394 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2395 let (start_y, end_y) =
2396 scrollbar_layout.ys_for_marker(start_display.row(), end_display.row());
2397 let bounds =
2398 Bounds::from_corners(point(left_x, start_y), point(right, end_y));
2399 let color = match diagnostic.diagnostic.severity {
2400 DiagnosticSeverity::ERROR => cx.theme().status().error,
2401 DiagnosticSeverity::WARNING => cx.theme().status().warning,
2402 DiagnosticSeverity::INFORMATION => cx.theme().status().info,
2403 _ => cx.theme().status().hint,
2404 };
2405 cx.paint_quad(quad(
2406 bounds,
2407 Corners::default(),
2408 color,
2409 Edges::default(),
2410 cx.theme().colors().scrollbar_thumb_border,
2411 ));
2412 }
2413 }
2414
2415 cx.paint_quad(quad(
2416 thumb_bounds,
2417 Corners::default(),
2418 cx.theme().colors().scrollbar_thumb_background,
2419 Edges {
2420 top: Pixels::ZERO,
2421 right: Pixels::ZERO,
2422 bottom: Pixels::ZERO,
2423 left: ScrollbarLayout::BORDER_WIDTH,
2424 },
2425 cx.theme().colors().scrollbar_thumb_border,
2426 ));
2427 });
2428 }
2429
2430 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2431
2432 let scroll_height = scrollbar_layout.scroll_height;
2433 let height = scrollbar_layout.height;
2434 let row_range = scrollbar_layout.visible_row_range.clone();
2435
2436 cx.on_mouse_event({
2437 let editor = self.editor.clone();
2438 let hitbox = scrollbar_layout.hitbox.clone();
2439 let mut mouse_position = cx.mouse_position();
2440 move |event: &MouseMoveEvent, phase, cx| {
2441 if phase == DispatchPhase::Capture {
2442 return;
2443 }
2444
2445 editor.update(cx, |editor, cx| {
2446 if event.pressed_button == Some(MouseButton::Left)
2447 && editor.scroll_manager.is_dragging_scrollbar()
2448 {
2449 let y = mouse_position.y;
2450 let new_y = event.position.y;
2451 if (hitbox.top()..hitbox.bottom()).contains(&y) {
2452 let mut position = editor.scroll_position(cx);
2453 position.y += (new_y - y) * scroll_height / height;
2454 if position.y < 0.0 {
2455 position.y = 0.0;
2456 }
2457 editor.set_scroll_position(position, cx);
2458 }
2459
2460 mouse_position = event.position;
2461 cx.stop_propagation();
2462 } else {
2463 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2464 if hitbox.is_hovered(cx) {
2465 editor.scroll_manager.show_scrollbar(cx);
2466 }
2467 }
2468 })
2469 }
2470 });
2471
2472 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2473 cx.on_mouse_event({
2474 let editor = self.editor.clone();
2475 move |_: &MouseUpEvent, phase, cx| {
2476 if phase == DispatchPhase::Capture {
2477 return;
2478 }
2479
2480 editor.update(cx, |editor, cx| {
2481 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2482 cx.stop_propagation();
2483 });
2484 }
2485 });
2486 } else {
2487 cx.on_mouse_event({
2488 let editor = self.editor.clone();
2489 let hitbox = scrollbar_layout.hitbox.clone();
2490 move |event: &MouseDownEvent, phase, cx| {
2491 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2492 return;
2493 }
2494
2495 editor.update(cx, |editor, cx| {
2496 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2497
2498 let y = event.position.y;
2499 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2500 let center_row =
2501 ((y - hitbox.top()) * scroll_height / height).round() as u32;
2502 let top_row = center_row
2503 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2504 let mut position = editor.scroll_position(cx);
2505 position.y = top_row as f32;
2506 editor.set_scroll_position(position, cx);
2507 } else {
2508 editor.scroll_manager.show_scrollbar(cx);
2509 }
2510
2511 cx.stop_propagation();
2512 });
2513 }
2514 });
2515 }
2516 }
2517
2518 #[allow(clippy::too_many_arguments)]
2519 fn paint_highlighted_range(
2520 &self,
2521 range: Range<DisplayPoint>,
2522 color: Hsla,
2523 corner_radius: Pixels,
2524 line_end_overshoot: Pixels,
2525 layout: &EditorLayout,
2526 cx: &mut ElementContext,
2527 ) {
2528 let start_row = layout.visible_display_row_range.start;
2529 let end_row = layout.visible_display_row_range.end;
2530 if range.start != range.end {
2531 let row_range = if range.end.column() == 0 {
2532 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2533 } else {
2534 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2535 };
2536
2537 let highlighted_range = HighlightedRange {
2538 color,
2539 line_height: layout.position_map.line_height,
2540 corner_radius,
2541 start_y: layout.content_origin.y
2542 + row_range.start as f32 * layout.position_map.line_height
2543 - layout.position_map.scroll_pixel_position.y,
2544 lines: row_range
2545 .into_iter()
2546 .map(|row| {
2547 let line_layout =
2548 &layout.position_map.line_layouts[(row - start_row) as usize].line;
2549 HighlightedRangeLine {
2550 start_x: if row == range.start.row() {
2551 layout.content_origin.x
2552 + line_layout.x_for_index(range.start.column() as usize)
2553 - layout.position_map.scroll_pixel_position.x
2554 } else {
2555 layout.content_origin.x
2556 - layout.position_map.scroll_pixel_position.x
2557 },
2558 end_x: if row == range.end.row() {
2559 layout.content_origin.x
2560 + line_layout.x_for_index(range.end.column() as usize)
2561 - layout.position_map.scroll_pixel_position.x
2562 } else {
2563 layout.content_origin.x + line_layout.width + line_end_overshoot
2564 - layout.position_map.scroll_pixel_position.x
2565 },
2566 }
2567 })
2568 .collect(),
2569 };
2570
2571 highlighted_range.paint(layout.text_hitbox.bounds, cx);
2572 }
2573 }
2574
2575 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2576 if layout.folds.is_empty() {
2577 return;
2578 }
2579
2580 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2581 let fold_corner_radius = 0.15 * layout.position_map.line_height;
2582 for mut fold in mem::take(&mut layout.folds) {
2583 fold.hover_element.paint(cx);
2584
2585 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2586 let fold_background = if hover_element.interactivity().active.unwrap() {
2587 cx.theme().colors().ghost_element_active
2588 } else if hover_element.interactivity().hovered.unwrap() {
2589 cx.theme().colors().ghost_element_hover
2590 } else {
2591 cx.theme().colors().ghost_element_background
2592 };
2593
2594 self.paint_highlighted_range(
2595 fold.display_range.clone(),
2596 fold_background,
2597 fold_corner_radius,
2598 fold_corner_radius * 2.,
2599 layout,
2600 cx,
2601 );
2602 }
2603 })
2604 }
2605
2606 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2607 for mut block in layout.blocks.drain(..) {
2608 block.element.paint(cx);
2609 }
2610 }
2611
2612 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2613 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2614 mouse_context_menu.paint(cx);
2615 }
2616 }
2617
2618 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2619 cx.on_mouse_event({
2620 let position_map = layout.position_map.clone();
2621 let editor = self.editor.clone();
2622 let hitbox = layout.hitbox.clone();
2623 let mut delta = ScrollDelta::default();
2624
2625 move |event: &ScrollWheelEvent, phase, cx| {
2626 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2627 delta = delta.coalesce(event.delta);
2628 editor.update(cx, |editor, cx| {
2629 let position_map: &PositionMap = &position_map;
2630
2631 let line_height = position_map.line_height;
2632 let max_glyph_width = position_map.em_width;
2633 let (delta, axis) = match delta {
2634 gpui::ScrollDelta::Pixels(mut pixels) => {
2635 //Trackpad
2636 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2637 (pixels, axis)
2638 }
2639
2640 gpui::ScrollDelta::Lines(lines) => {
2641 //Not trackpad
2642 let pixels =
2643 point(lines.x * max_glyph_width, lines.y * line_height);
2644 (pixels, None)
2645 }
2646 };
2647
2648 let scroll_position = position_map.snapshot.scroll_position();
2649 let x = (scroll_position.x * max_glyph_width - delta.x) / max_glyph_width;
2650 let y = (scroll_position.y * line_height - delta.y) / line_height;
2651 let scroll_position =
2652 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2653 editor.scroll(scroll_position, axis, cx);
2654 cx.stop_propagation();
2655 });
2656 }
2657 }
2658 });
2659 }
2660
2661 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2662 self.paint_scroll_wheel_listener(layout, cx);
2663
2664 cx.on_mouse_event({
2665 let position_map = layout.position_map.clone();
2666 let editor = self.editor.clone();
2667 let text_hitbox = layout.text_hitbox.clone();
2668 let gutter_hitbox = layout.gutter_hitbox.clone();
2669
2670 move |event: &MouseDownEvent, phase, cx| {
2671 if phase == DispatchPhase::Bubble {
2672 match event.button {
2673 MouseButton::Left => editor.update(cx, |editor, cx| {
2674 Self::mouse_left_down(
2675 editor,
2676 event,
2677 &position_map,
2678 &text_hitbox,
2679 &gutter_hitbox,
2680 cx,
2681 );
2682 }),
2683 MouseButton::Right => editor.update(cx, |editor, cx| {
2684 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2685 }),
2686 _ => {}
2687 };
2688 }
2689 }
2690 });
2691
2692 cx.on_mouse_event({
2693 let editor = self.editor.clone();
2694 let position_map = layout.position_map.clone();
2695 let text_hitbox = layout.text_hitbox.clone();
2696
2697 move |event: &MouseUpEvent, phase, cx| {
2698 if phase == DispatchPhase::Bubble {
2699 editor.update(cx, |editor, cx| {
2700 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2701 });
2702 }
2703 }
2704 });
2705 cx.on_mouse_event({
2706 let position_map = layout.position_map.clone();
2707 let editor = self.editor.clone();
2708 let text_hitbox = layout.text_hitbox.clone();
2709 let gutter_hitbox = layout.gutter_hitbox.clone();
2710
2711 move |event: &MouseMoveEvent, phase, cx| {
2712 if phase == DispatchPhase::Bubble {
2713 editor.update(cx, |editor, cx| {
2714 if event.pressed_button == Some(MouseButton::Left) {
2715 Self::mouse_dragged(
2716 editor,
2717 event,
2718 &position_map,
2719 text_hitbox.bounds,
2720 cx,
2721 )
2722 }
2723
2724 Self::mouse_moved(
2725 editor,
2726 event,
2727 &position_map,
2728 &text_hitbox,
2729 &gutter_hitbox,
2730 cx,
2731 )
2732 });
2733 }
2734 }
2735 });
2736 }
2737
2738 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2739 bounds.upper_right().x - self.style.scrollbar_width
2740 }
2741
2742 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2743 let style = &self.style;
2744 let font_size = style.text.font_size.to_pixels(cx.rem_size());
2745 let layout = cx
2746 .text_system()
2747 .shape_line(
2748 SharedString::from(" ".repeat(column)),
2749 font_size,
2750 &[TextRun {
2751 len: column,
2752 font: style.text.font(),
2753 color: Hsla::default(),
2754 background_color: None,
2755 underline: None,
2756 strikethrough: None,
2757 }],
2758 )
2759 .unwrap();
2760
2761 layout.width
2762 }
2763
2764 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2765 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2766 self.column_pixels(digit_count, cx)
2767 }
2768}
2769
2770#[derive(Debug)]
2771pub(crate) struct LineWithInvisibles {
2772 pub line: ShapedLine,
2773 invisibles: Vec<Invisible>,
2774}
2775
2776impl LineWithInvisibles {
2777 fn from_chunks<'a>(
2778 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2779 text_style: &TextStyle,
2780 max_line_len: usize,
2781 max_line_count: usize,
2782 line_number_layouts: &[Option<ShapedLine>],
2783 editor_mode: EditorMode,
2784 cx: &WindowContext,
2785 ) -> Vec<Self> {
2786 let mut layouts = Vec::with_capacity(max_line_count);
2787 let mut line = String::new();
2788 let mut invisibles = Vec::new();
2789 let mut styles = Vec::new();
2790 let mut non_whitespace_added = false;
2791 let mut row = 0;
2792 let mut line_exceeded_max_len = false;
2793 let font_size = text_style.font_size.to_pixels(cx.rem_size());
2794
2795 for highlighted_chunk in chunks.chain([HighlightedChunk {
2796 chunk: "\n",
2797 style: None,
2798 is_tab: false,
2799 }]) {
2800 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2801 if ix > 0 {
2802 let shaped_line = cx
2803 .text_system()
2804 .shape_line(line.clone().into(), font_size, &styles)
2805 .unwrap();
2806 layouts.push(Self {
2807 line: shaped_line,
2808 invisibles: std::mem::take(&mut invisibles),
2809 });
2810
2811 line.clear();
2812 styles.clear();
2813 row += 1;
2814 line_exceeded_max_len = false;
2815 non_whitespace_added = false;
2816 if row == max_line_count {
2817 return layouts;
2818 }
2819 }
2820
2821 if !line_chunk.is_empty() && !line_exceeded_max_len {
2822 let text_style = if let Some(style) = highlighted_chunk.style {
2823 Cow::Owned(text_style.clone().highlight(style))
2824 } else {
2825 Cow::Borrowed(text_style)
2826 };
2827
2828 if line.len() + line_chunk.len() > max_line_len {
2829 let mut chunk_len = max_line_len - line.len();
2830 while !line_chunk.is_char_boundary(chunk_len) {
2831 chunk_len -= 1;
2832 }
2833 line_chunk = &line_chunk[..chunk_len];
2834 line_exceeded_max_len = true;
2835 }
2836
2837 styles.push(TextRun {
2838 len: line_chunk.len(),
2839 font: text_style.font(),
2840 color: text_style.color,
2841 background_color: text_style.background_color,
2842 underline: text_style.underline,
2843 strikethrough: text_style.strikethrough,
2844 });
2845
2846 if editor_mode == EditorMode::Full {
2847 // Line wrap pads its contents with fake whitespaces,
2848 // avoid printing them
2849 let inside_wrapped_string = line_number_layouts
2850 .get(row)
2851 .and_then(|layout| layout.as_ref())
2852 .is_none();
2853 if highlighted_chunk.is_tab {
2854 if non_whitespace_added || !inside_wrapped_string {
2855 invisibles.push(Invisible::Tab {
2856 line_start_offset: line.len(),
2857 });
2858 }
2859 } else {
2860 invisibles.extend(
2861 line_chunk
2862 .chars()
2863 .enumerate()
2864 .filter(|(_, line_char)| {
2865 let is_whitespace = line_char.is_whitespace();
2866 non_whitespace_added |= !is_whitespace;
2867 is_whitespace
2868 && (non_whitespace_added || !inside_wrapped_string)
2869 })
2870 .map(|(whitespace_index, _)| Invisible::Whitespace {
2871 line_offset: line.len() + whitespace_index,
2872 }),
2873 )
2874 }
2875 }
2876
2877 line.push_str(line_chunk);
2878 }
2879 }
2880 }
2881
2882 layouts
2883 }
2884
2885 fn draw(
2886 &self,
2887 layout: &EditorLayout,
2888 row: u32,
2889 content_origin: gpui::Point<Pixels>,
2890 whitespace_setting: ShowWhitespaceSetting,
2891 selection_ranges: &[Range<DisplayPoint>],
2892 cx: &mut ElementContext,
2893 ) {
2894 let line_height = layout.position_map.line_height;
2895 let line_y =
2896 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
2897
2898 self.line
2899 .paint(
2900 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y),
2901 line_height,
2902 cx,
2903 )
2904 .log_err();
2905
2906 self.draw_invisibles(
2907 &selection_ranges,
2908 layout,
2909 content_origin,
2910 line_y,
2911 row,
2912 line_height,
2913 whitespace_setting,
2914 cx,
2915 );
2916 }
2917
2918 #[allow(clippy::too_many_arguments)]
2919 fn draw_invisibles(
2920 &self,
2921 selection_ranges: &[Range<DisplayPoint>],
2922 layout: &EditorLayout,
2923 content_origin: gpui::Point<Pixels>,
2924 line_y: Pixels,
2925 row: u32,
2926 line_height: Pixels,
2927 whitespace_setting: ShowWhitespaceSetting,
2928 cx: &mut ElementContext,
2929 ) {
2930 let allowed_invisibles_regions = match whitespace_setting {
2931 ShowWhitespaceSetting::None => return,
2932 ShowWhitespaceSetting::Selection => Some(selection_ranges),
2933 ShowWhitespaceSetting::All => None,
2934 };
2935
2936 for invisible in &self.invisibles {
2937 let (&token_offset, invisible_symbol) = match invisible {
2938 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2939 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2940 };
2941
2942 let x_offset = self.line.x_for_index(token_offset);
2943 let invisible_offset =
2944 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2945 let origin = content_origin
2946 + gpui::point(
2947 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
2948 line_y,
2949 );
2950
2951 if let Some(allowed_regions) = allowed_invisibles_regions {
2952 let invisible_point = DisplayPoint::new(row, token_offset as u32);
2953 if !allowed_regions
2954 .iter()
2955 .any(|region| region.start <= invisible_point && invisible_point < region.end)
2956 {
2957 continue;
2958 }
2959 }
2960 invisible_symbol.paint(origin, line_height, cx).log_err();
2961 }
2962 }
2963}
2964
2965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2966enum Invisible {
2967 Tab { line_start_offset: usize },
2968 Whitespace { line_offset: usize },
2969}
2970
2971impl Element for EditorElement {
2972 type BeforeLayout = ();
2973 type AfterLayout = EditorLayout;
2974
2975 fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
2976 self.editor.update(cx, |editor, cx| {
2977 editor.set_style(self.style.clone(), cx);
2978
2979 let layout_id = match editor.mode {
2980 EditorMode::SingleLine => {
2981 let rem_size = cx.rem_size();
2982 let mut style = Style::default();
2983 style.size.width = relative(1.).into();
2984 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
2985 cx.with_element_context(|cx| cx.request_layout(&style, None))
2986 }
2987 EditorMode::AutoHeight { max_lines } => {
2988 let editor_handle = cx.view().clone();
2989 let max_line_number_width =
2990 self.max_line_number_width(&editor.snapshot(cx), cx);
2991 cx.with_element_context(|cx| {
2992 cx.request_measured_layout(
2993 Style::default(),
2994 move |known_dimensions, _, cx| {
2995 editor_handle
2996 .update(cx, |editor, cx| {
2997 compute_auto_height_layout(
2998 editor,
2999 max_lines,
3000 max_line_number_width,
3001 known_dimensions,
3002 cx,
3003 )
3004 })
3005 .unwrap_or_default()
3006 },
3007 )
3008 })
3009 }
3010 EditorMode::Full => {
3011 let mut style = Style::default();
3012 style.size.width = relative(1.).into();
3013 style.size.height = relative(1.).into();
3014 cx.with_element_context(|cx| cx.request_layout(&style, None))
3015 }
3016 };
3017
3018 (layout_id, ())
3019 })
3020 }
3021
3022 fn after_layout(
3023 &mut self,
3024 bounds: Bounds<Pixels>,
3025 _: &mut Self::BeforeLayout,
3026 cx: &mut ElementContext,
3027 ) -> Self::AfterLayout {
3028 let text_style = TextStyleRefinement {
3029 font_size: Some(self.style.text.font_size),
3030 line_height: Some(self.style.text.line_height),
3031 ..Default::default()
3032 };
3033 cx.with_text_style(Some(text_style), |cx| {
3034 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3035 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3036 let style = self.style.clone();
3037
3038 let font_id = cx.text_system().resolve_font(&style.text.font());
3039 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3040 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3041 let em_width = cx
3042 .text_system()
3043 .typographic_bounds(font_id, font_size, 'm')
3044 .unwrap()
3045 .size
3046 .width;
3047 let em_advance = cx
3048 .text_system()
3049 .advance(font_id, font_size, 'm')
3050 .unwrap()
3051 .width;
3052
3053 let gutter_dimensions = snapshot.gutter_dimensions(
3054 font_id,
3055 font_size,
3056 em_width,
3057 self.max_line_number_width(&snapshot, cx),
3058 cx,
3059 );
3060 let text_width = bounds.size.width - gutter_dimensions.width;
3061 let overscroll = size(em_width, px(0.));
3062
3063 snapshot = self.editor.update(cx, |editor, cx| {
3064 editor.gutter_width = gutter_dimensions.width;
3065 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3066
3067 let editor_width =
3068 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3069 let wrap_width = match editor.soft_wrap_mode(cx) {
3070 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3071 SoftWrap::EditorWidth => editor_width,
3072 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3073 };
3074
3075 if editor.set_wrap_width(Some(wrap_width), cx) {
3076 editor.snapshot(cx)
3077 } else {
3078 snapshot
3079 }
3080 });
3081
3082 let wrap_guides = self
3083 .editor
3084 .read(cx)
3085 .wrap_guides(cx)
3086 .iter()
3087 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3088 .collect::<SmallVec<[_; 2]>>();
3089
3090 let hitbox = cx.insert_hitbox(bounds, false);
3091 let gutter_hitbox = cx.insert_hitbox(
3092 Bounds {
3093 origin: bounds.origin,
3094 size: size(gutter_dimensions.width, bounds.size.height),
3095 },
3096 false,
3097 );
3098 let text_hitbox = cx.insert_hitbox(
3099 Bounds {
3100 origin: gutter_hitbox.upper_right(),
3101 size: size(text_width, bounds.size.height),
3102 },
3103 false,
3104 );
3105 // Offset the content_bounds from the text_bounds by the gutter margin (which
3106 // is roughly half a character wide) to make hit testing work more like how we want.
3107 let content_origin =
3108 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3109
3110 let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
3111 let autoscroll_horizontally =
3112 editor.autoscroll_vertically(bounds.size.height, line_height, cx);
3113 snapshot = editor.snapshot(cx);
3114 autoscroll_horizontally
3115 });
3116
3117 let mut scroll_position = snapshot.scroll_position();
3118 // The scroll position is a fractional point, the whole number of which represents
3119 // the top of the window in terms of display rows.
3120 let start_row = scroll_position.y as u32;
3121 let height_in_lines = bounds.size.height / line_height;
3122 let max_row = snapshot.max_point().row();
3123
3124 // Add 1 to ensure selections bleed off screen
3125 let end_row =
3126 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3127
3128 let start_anchor = if start_row == 0 {
3129 Anchor::min()
3130 } else {
3131 snapshot.buffer_snapshot.anchor_before(
3132 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3133 )
3134 };
3135 let end_anchor = if end_row > max_row {
3136 Anchor::max()
3137 } else {
3138 snapshot.buffer_snapshot.anchor_before(
3139 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3140 )
3141 };
3142
3143 let highlighted_rows = self
3144 .editor
3145 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3146 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3147 start_anchor..end_anchor,
3148 &snapshot.display_snapshot,
3149 cx.theme().colors(),
3150 );
3151
3152 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3153 start_anchor..end_anchor,
3154 &snapshot.display_snapshot,
3155 cx,
3156 );
3157
3158 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3159 start_anchor,
3160 end_anchor,
3161 &snapshot,
3162 start_row,
3163 end_row,
3164 cx,
3165 );
3166
3167 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3168 start_row..end_row,
3169 &active_rows,
3170 newest_selection_head,
3171 &snapshot,
3172 cx,
3173 );
3174
3175 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3176
3177 let mut max_visible_line_width = Pixels::ZERO;
3178 let line_layouts =
3179 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3180 for line_with_invisibles in &line_layouts {
3181 if line_with_invisibles.line.width > max_visible_line_width {
3182 max_visible_line_width = line_with_invisibles.line.width;
3183 }
3184 }
3185
3186 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3187 .unwrap()
3188 .width;
3189 let mut scroll_width =
3190 longest_line_width.max(max_visible_line_width) + overscroll.width;
3191 let mut blocks = self.build_blocks(
3192 start_row..end_row,
3193 &snapshot,
3194 &hitbox,
3195 &text_hitbox,
3196 &mut scroll_width,
3197 &gutter_dimensions,
3198 em_width,
3199 gutter_dimensions.width + gutter_dimensions.margin,
3200 line_height,
3201 &line_layouts,
3202 cx,
3203 );
3204
3205 let scroll_max = point(
3206 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3207 max_row as f32,
3208 );
3209
3210 self.editor.update(cx, |editor, cx| {
3211 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3212
3213 let autoscrolled = if autoscroll_horizontally {
3214 editor.autoscroll_horizontally(
3215 start_row,
3216 text_hitbox.size.width,
3217 scroll_width,
3218 em_width,
3219 &line_layouts,
3220 cx,
3221 )
3222 } else {
3223 false
3224 };
3225
3226 if clamped || autoscrolled {
3227 snapshot = editor.snapshot(cx);
3228 scroll_position = snapshot.scroll_position();
3229 }
3230 });
3231
3232 let scroll_pixel_position = point(
3233 scroll_position.x * em_width,
3234 scroll_position.y * line_height,
3235 );
3236
3237 cx.with_element_id(Some("blocks"), |cx| {
3238 self.layout_blocks(
3239 &mut blocks,
3240 &hitbox,
3241 line_height,
3242 scroll_pixel_position,
3243 cx,
3244 );
3245 });
3246
3247 let cursors = self.layout_cursors(
3248 &snapshot,
3249 &selections,
3250 start_row..end_row,
3251 &line_layouts,
3252 &text_hitbox,
3253 content_origin,
3254 scroll_pixel_position,
3255 line_height,
3256 em_width,
3257 cx,
3258 );
3259
3260 let scrollbar_layout = self.layout_scrollbar(
3261 &snapshot,
3262 bounds,
3263 scroll_position,
3264 line_height,
3265 height_in_lines,
3266 cx,
3267 );
3268
3269 let folds = cx.with_element_id(Some("folds"), |cx| {
3270 self.layout_folds(
3271 &snapshot,
3272 content_origin,
3273 start_anchor..end_anchor,
3274 start_row..end_row,
3275 scroll_pixel_position,
3276 line_height,
3277 &line_layouts,
3278 cx,
3279 )
3280 });
3281
3282 let gutter_settings = EditorSettings::get_global(cx).gutter;
3283
3284 let mut context_menu_visible = false;
3285 let mut code_actions_indicator = None;
3286 if let Some(newest_selection_head) = newest_selection_head {
3287 if (start_row..end_row).contains(&newest_selection_head.row()) {
3288 context_menu_visible = self.layout_context_menu(
3289 line_height,
3290 &hitbox,
3291 &text_hitbox,
3292 content_origin,
3293 start_row,
3294 scroll_pixel_position,
3295 &line_layouts,
3296 newest_selection_head,
3297 cx,
3298 );
3299 if gutter_settings.code_actions {
3300 code_actions_indicator = self.layout_code_actions_indicator(
3301 line_height,
3302 newest_selection_head,
3303 scroll_pixel_position,
3304 &gutter_dimensions,
3305 &gutter_hitbox,
3306 cx,
3307 );
3308 }
3309 }
3310 }
3311
3312 if !context_menu_visible && !cx.has_active_drag() {
3313 self.layout_hover_popovers(
3314 &snapshot,
3315 &hitbox,
3316 &text_hitbox,
3317 start_row..end_row,
3318 content_origin,
3319 scroll_pixel_position,
3320 &line_layouts,
3321 line_height,
3322 em_width,
3323 cx,
3324 );
3325 }
3326
3327 let mouse_context_menu = self.layout_mouse_context_menu(cx);
3328
3329 let fold_indicators = if gutter_settings.folds {
3330 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3331 self.layout_gutter_fold_indicators(
3332 fold_statuses,
3333 line_height,
3334 &gutter_dimensions,
3335 gutter_settings,
3336 scroll_pixel_position,
3337 &gutter_hitbox,
3338 cx,
3339 )
3340 })
3341 } else {
3342 Vec::new()
3343 };
3344
3345 let invisible_symbol_font_size = font_size / 2.;
3346 let tab_invisible = cx
3347 .text_system()
3348 .shape_line(
3349 "→".into(),
3350 invisible_symbol_font_size,
3351 &[TextRun {
3352 len: "→".len(),
3353 font: self.style.text.font(),
3354 color: cx.theme().colors().editor_invisible,
3355 background_color: None,
3356 underline: None,
3357 strikethrough: None,
3358 }],
3359 )
3360 .unwrap();
3361 let space_invisible = cx
3362 .text_system()
3363 .shape_line(
3364 "•".into(),
3365 invisible_symbol_font_size,
3366 &[TextRun {
3367 len: "•".len(),
3368 font: self.style.text.font(),
3369 color: cx.theme().colors().editor_invisible,
3370 background_color: None,
3371 underline: None,
3372 strikethrough: None,
3373 }],
3374 )
3375 .unwrap();
3376
3377 EditorLayout {
3378 mode: snapshot.mode,
3379 position_map: Arc::new(PositionMap {
3380 size: bounds.size,
3381 scroll_pixel_position,
3382 scroll_max,
3383 line_layouts,
3384 line_height,
3385 em_width,
3386 em_advance,
3387 snapshot,
3388 }),
3389 visible_display_row_range: start_row..end_row,
3390 wrap_guides,
3391 hitbox,
3392 text_hitbox,
3393 gutter_hitbox,
3394 gutter_dimensions,
3395 content_origin,
3396 scrollbar_layout,
3397 max_row,
3398 active_rows,
3399 highlighted_rows,
3400 highlighted_ranges,
3401 redacted_ranges,
3402 line_numbers,
3403 display_hunks,
3404 folds,
3405 blocks,
3406 cursors,
3407 selections,
3408 mouse_context_menu,
3409 code_actions_indicator,
3410 fold_indicators,
3411 tab_invisible,
3412 space_invisible,
3413 }
3414 })
3415 })
3416 }
3417
3418 fn paint(
3419 &mut self,
3420 bounds: Bounds<gpui::Pixels>,
3421 _: &mut Self::BeforeLayout,
3422 layout: &mut Self::AfterLayout,
3423 cx: &mut ElementContext,
3424 ) {
3425 let focus_handle = self.editor.focus_handle(cx);
3426 let key_context = self.editor.read(cx).key_context(cx);
3427 cx.set_focus_handle(&focus_handle);
3428 cx.set_key_context(key_context);
3429 cx.set_view_id(self.editor.entity_id());
3430 cx.handle_input(
3431 &focus_handle,
3432 ElementInputHandler::new(bounds, self.editor.clone()),
3433 );
3434 self.register_actions(cx);
3435 self.register_key_listeners(cx, layout);
3436
3437 let text_style = TextStyleRefinement {
3438 font_size: Some(self.style.text.font_size),
3439 line_height: Some(self.style.text.line_height),
3440 ..Default::default()
3441 };
3442 cx.with_text_style(Some(text_style), |cx| {
3443 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3444 self.paint_mouse_listeners(layout, cx);
3445
3446 self.paint_background(layout, cx);
3447 if layout.gutter_hitbox.size.width > Pixels::ZERO {
3448 self.paint_gutter(layout, cx);
3449 }
3450 self.paint_text(layout, cx);
3451
3452 if !layout.blocks.is_empty() {
3453 cx.with_element_id(Some("blocks"), |cx| {
3454 self.paint_blocks(layout, cx);
3455 });
3456 }
3457
3458 self.paint_scrollbar(layout, cx);
3459 self.paint_mouse_context_menu(layout, cx);
3460 });
3461 })
3462 }
3463}
3464
3465impl IntoElement for EditorElement {
3466 type Element = Self;
3467
3468 fn into_element(self) -> Self::Element {
3469 self
3470 }
3471}
3472
3473type BufferRow = u32;
3474
3475pub struct EditorLayout {
3476 position_map: Arc<PositionMap>,
3477 hitbox: Hitbox,
3478 text_hitbox: Hitbox,
3479 gutter_hitbox: Hitbox,
3480 gutter_dimensions: GutterDimensions,
3481 content_origin: gpui::Point<Pixels>,
3482 scrollbar_layout: Option<ScrollbarLayout>,
3483 mode: EditorMode,
3484 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3485 visible_display_row_range: Range<u32>,
3486 active_rows: BTreeMap<u32, bool>,
3487 highlighted_rows: BTreeMap<u32, Hsla>,
3488 line_numbers: Vec<Option<ShapedLine>>,
3489 display_hunks: Vec<DisplayDiffHunk>,
3490 folds: Vec<FoldLayout>,
3491 blocks: Vec<BlockLayout>,
3492 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3493 redacted_ranges: Vec<Range<DisplayPoint>>,
3494 cursors: Vec<CursorLayout>,
3495 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3496 max_row: u32,
3497 code_actions_indicator: Option<AnyElement>,
3498 fold_indicators: Vec<Option<AnyElement>>,
3499 mouse_context_menu: Option<AnyElement>,
3500 tab_invisible: ShapedLine,
3501 space_invisible: ShapedLine,
3502}
3503
3504impl EditorLayout {
3505 fn line_end_overshoot(&self) -> Pixels {
3506 0.15 * self.position_map.line_height
3507 }
3508}
3509
3510struct ScrollbarLayout {
3511 hitbox: Hitbox,
3512 visible_row_range: Range<f32>,
3513 visible: bool,
3514 height: Pixels,
3515 scroll_height: f32,
3516 first_row_y_offset: Pixels,
3517 row_height: Pixels,
3518}
3519
3520impl ScrollbarLayout {
3521 const BORDER_WIDTH: Pixels = px(1.0);
3522 const MIN_MARKER_HEIGHT: Pixels = px(2.0);
3523
3524 fn thumb_bounds(&self) -> Bounds<Pixels> {
3525 let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
3526 let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
3527 Bounds::from_corners(
3528 point(self.hitbox.left(), thumb_top),
3529 point(self.hitbox.right(), thumb_bottom),
3530 )
3531 }
3532
3533 fn y_for_row(&self, row: f32) -> Pixels {
3534 self.hitbox.top() + self.first_row_y_offset + row * self.row_height
3535 }
3536
3537 fn ys_for_marker(&self, start_row: u32, end_row: u32) -> (Pixels, Pixels) {
3538 let start_y = self.y_for_row(start_row as f32);
3539 let mut end_y = self.y_for_row((end_row + 1) as f32);
3540 if end_y - start_y < Self::MIN_MARKER_HEIGHT {
3541 end_y = start_y + Self::MIN_MARKER_HEIGHT;
3542 }
3543 (start_y, end_y)
3544 }
3545}
3546
3547struct FoldLayout {
3548 display_range: Range<DisplayPoint>,
3549 hover_element: AnyElement,
3550}
3551
3552struct PositionMap {
3553 size: Size<Pixels>,
3554 line_height: Pixels,
3555 scroll_pixel_position: gpui::Point<Pixels>,
3556 scroll_max: gpui::Point<f32>,
3557 em_width: Pixels,
3558 em_advance: Pixels,
3559 line_layouts: Vec<LineWithInvisibles>,
3560 snapshot: EditorSnapshot,
3561}
3562
3563#[derive(Debug, Copy, Clone)]
3564pub struct PointForPosition {
3565 pub previous_valid: DisplayPoint,
3566 pub next_valid: DisplayPoint,
3567 pub exact_unclipped: DisplayPoint,
3568 pub column_overshoot_after_line_end: u32,
3569}
3570
3571impl PointForPosition {
3572 pub fn as_valid(&self) -> Option<DisplayPoint> {
3573 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3574 Some(self.previous_valid)
3575 } else {
3576 None
3577 }
3578 }
3579}
3580
3581impl PositionMap {
3582 fn point_for_position(
3583 &self,
3584 text_bounds: Bounds<Pixels>,
3585 position: gpui::Point<Pixels>,
3586 ) -> PointForPosition {
3587 let scroll_position = self.snapshot.scroll_position();
3588 let position = position - text_bounds.origin;
3589 let y = position.y.max(px(0.)).min(self.size.height);
3590 let x = position.x + (scroll_position.x * self.em_width);
3591 let row = ((y / self.line_height) + scroll_position.y) as u32;
3592
3593 let (column, x_overshoot_after_line_end) = if let Some(line) = self
3594 .line_layouts
3595 .get(row as usize - scroll_position.y as usize)
3596 .map(|LineWithInvisibles { line, .. }| line)
3597 {
3598 if let Some(ix) = line.index_for_x(x) {
3599 (ix as u32, px(0.))
3600 } else {
3601 (line.len as u32, px(0.).max(x - line.width))
3602 }
3603 } else {
3604 (0, x)
3605 };
3606
3607 let mut exact_unclipped = DisplayPoint::new(row, column);
3608 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3609 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3610
3611 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3612 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3613 PointForPosition {
3614 previous_valid,
3615 next_valid,
3616 exact_unclipped,
3617 column_overshoot_after_line_end,
3618 }
3619 }
3620}
3621
3622struct BlockLayout {
3623 row: u32,
3624 element: AnyElement,
3625 available_space: Size<AvailableSpace>,
3626 style: BlockStyle,
3627}
3628
3629fn layout_line(
3630 row: u32,
3631 snapshot: &EditorSnapshot,
3632 style: &EditorStyle,
3633 cx: &WindowContext,
3634) -> Result<ShapedLine> {
3635 let mut line = snapshot.line(row);
3636
3637 if line.len() > MAX_LINE_LEN {
3638 let mut len = MAX_LINE_LEN;
3639 while !line.is_char_boundary(len) {
3640 len -= 1;
3641 }
3642
3643 line.truncate(len);
3644 }
3645
3646 cx.text_system().shape_line(
3647 line.into(),
3648 style.text.font_size.to_pixels(cx.rem_size()),
3649 &[TextRun {
3650 len: snapshot.line_len(row) as usize,
3651 font: style.text.font(),
3652 color: Hsla::default(),
3653 background_color: None,
3654 underline: None,
3655 strikethrough: None,
3656 }],
3657 )
3658}
3659
3660pub struct CursorLayout {
3661 origin: gpui::Point<Pixels>,
3662 block_width: Pixels,
3663 line_height: Pixels,
3664 color: Hsla,
3665 shape: CursorShape,
3666 block_text: Option<ShapedLine>,
3667 cursor_name: Option<AnyElement>,
3668}
3669
3670#[derive(Debug)]
3671pub struct CursorName {
3672 string: SharedString,
3673 color: Hsla,
3674 is_top_row: bool,
3675}
3676
3677impl CursorLayout {
3678 pub fn new(
3679 origin: gpui::Point<Pixels>,
3680 block_width: Pixels,
3681 line_height: Pixels,
3682 color: Hsla,
3683 shape: CursorShape,
3684 block_text: Option<ShapedLine>,
3685 ) -> CursorLayout {
3686 CursorLayout {
3687 origin,
3688 block_width,
3689 line_height,
3690 color,
3691 shape,
3692 block_text,
3693 cursor_name: None,
3694 }
3695 }
3696
3697 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3698 Bounds {
3699 origin: self.origin + origin,
3700 size: size(self.block_width, self.line_height),
3701 }
3702 }
3703
3704 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3705 match self.shape {
3706 CursorShape::Bar => Bounds {
3707 origin: self.origin + origin,
3708 size: size(px(2.0), self.line_height),
3709 },
3710 CursorShape::Block | CursorShape::Hollow => Bounds {
3711 origin: self.origin + origin,
3712 size: size(self.block_width, self.line_height),
3713 },
3714 CursorShape::Underscore => Bounds {
3715 origin: self.origin
3716 + origin
3717 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3718 size: size(self.block_width, px(2.0)),
3719 },
3720 }
3721 }
3722
3723 pub fn layout(
3724 &mut self,
3725 origin: gpui::Point<Pixels>,
3726 cursor_name: Option<CursorName>,
3727 cx: &mut ElementContext,
3728 ) {
3729 if let Some(cursor_name) = cursor_name {
3730 let bounds = self.bounds(origin);
3731 let text_size = self.line_height / 1.5;
3732
3733 let name_origin = if cursor_name.is_top_row {
3734 point(bounds.right() - px(1.), bounds.top())
3735 } else {
3736 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
3737 };
3738 let mut name_element = div()
3739 .bg(self.color)
3740 .text_size(text_size)
3741 .px_0p5()
3742 .line_height(text_size + px(2.))
3743 .text_color(cursor_name.color)
3744 .child(cursor_name.string.clone())
3745 .into_any_element();
3746
3747 name_element.layout(
3748 name_origin,
3749 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
3750 cx,
3751 );
3752
3753 self.cursor_name = Some(name_element);
3754 }
3755 }
3756
3757 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
3758 let bounds = self.bounds(origin);
3759
3760 //Draw background or border quad
3761 let cursor = if matches!(self.shape, CursorShape::Hollow) {
3762 outline(bounds, self.color)
3763 } else {
3764 fill(bounds, self.color)
3765 };
3766
3767 if let Some(name) = &mut self.cursor_name {
3768 name.paint(cx);
3769 }
3770
3771 cx.paint_quad(cursor);
3772
3773 if let Some(block_text) = &self.block_text {
3774 block_text
3775 .paint(self.origin + origin, self.line_height, cx)
3776 .log_err();
3777 }
3778 }
3779
3780 pub fn shape(&self) -> CursorShape {
3781 self.shape
3782 }
3783}
3784
3785#[derive(Debug)]
3786pub struct HighlightedRange {
3787 pub start_y: Pixels,
3788 pub line_height: Pixels,
3789 pub lines: Vec<HighlightedRangeLine>,
3790 pub color: Hsla,
3791 pub corner_radius: Pixels,
3792}
3793
3794#[derive(Debug)]
3795pub struct HighlightedRangeLine {
3796 pub start_x: Pixels,
3797 pub end_x: Pixels,
3798}
3799
3800impl HighlightedRange {
3801 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
3802 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3803 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3804 self.paint_lines(
3805 self.start_y + self.line_height,
3806 &self.lines[1..],
3807 bounds,
3808 cx,
3809 );
3810 } else {
3811 self.paint_lines(self.start_y, &self.lines, bounds, cx);
3812 }
3813 }
3814
3815 fn paint_lines(
3816 &self,
3817 start_y: Pixels,
3818 lines: &[HighlightedRangeLine],
3819 _bounds: Bounds<Pixels>,
3820 cx: &mut ElementContext,
3821 ) {
3822 if lines.is_empty() {
3823 return;
3824 }
3825
3826 let first_line = lines.first().unwrap();
3827 let last_line = lines.last().unwrap();
3828
3829 let first_top_left = point(first_line.start_x, start_y);
3830 let first_top_right = point(first_line.end_x, start_y);
3831
3832 let curve_height = point(Pixels::ZERO, self.corner_radius);
3833 let curve_width = |start_x: Pixels, end_x: Pixels| {
3834 let max = (end_x - start_x) / 2.;
3835 let width = if max < self.corner_radius {
3836 max
3837 } else {
3838 self.corner_radius
3839 };
3840
3841 point(width, Pixels::ZERO)
3842 };
3843
3844 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3845 let mut path = gpui::Path::new(first_top_right - top_curve_width);
3846 path.curve_to(first_top_right + curve_height, first_top_right);
3847
3848 let mut iter = lines.iter().enumerate().peekable();
3849 while let Some((ix, line)) = iter.next() {
3850 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3851
3852 if let Some((_, next_line)) = iter.peek() {
3853 let next_top_right = point(next_line.end_x, bottom_right.y);
3854
3855 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3856 Ordering::Equal => {
3857 path.line_to(bottom_right);
3858 }
3859 Ordering::Less => {
3860 let curve_width = curve_width(next_top_right.x, bottom_right.x);
3861 path.line_to(bottom_right - curve_height);
3862 if self.corner_radius > Pixels::ZERO {
3863 path.curve_to(bottom_right - curve_width, bottom_right);
3864 }
3865 path.line_to(next_top_right + curve_width);
3866 if self.corner_radius > Pixels::ZERO {
3867 path.curve_to(next_top_right + curve_height, next_top_right);
3868 }
3869 }
3870 Ordering::Greater => {
3871 let curve_width = curve_width(bottom_right.x, next_top_right.x);
3872 path.line_to(bottom_right - curve_height);
3873 if self.corner_radius > Pixels::ZERO {
3874 path.curve_to(bottom_right + curve_width, bottom_right);
3875 }
3876 path.line_to(next_top_right - curve_width);
3877 if self.corner_radius > Pixels::ZERO {
3878 path.curve_to(next_top_right + curve_height, next_top_right);
3879 }
3880 }
3881 }
3882 } else {
3883 let curve_width = curve_width(line.start_x, line.end_x);
3884 path.line_to(bottom_right - curve_height);
3885 if self.corner_radius > Pixels::ZERO {
3886 path.curve_to(bottom_right - curve_width, bottom_right);
3887 }
3888
3889 let bottom_left = point(line.start_x, bottom_right.y);
3890 path.line_to(bottom_left + curve_width);
3891 if self.corner_radius > Pixels::ZERO {
3892 path.curve_to(bottom_left - curve_height, bottom_left);
3893 }
3894 }
3895 }
3896
3897 if first_line.start_x > last_line.start_x {
3898 let curve_width = curve_width(last_line.start_x, first_line.start_x);
3899 let second_top_left = point(last_line.start_x, start_y + self.line_height);
3900 path.line_to(second_top_left + curve_height);
3901 if self.corner_radius > Pixels::ZERO {
3902 path.curve_to(second_top_left + curve_width, second_top_left);
3903 }
3904 let first_bottom_left = point(first_line.start_x, second_top_left.y);
3905 path.line_to(first_bottom_left - curve_width);
3906 if self.corner_radius > Pixels::ZERO {
3907 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3908 }
3909 }
3910
3911 path.line_to(first_top_left + curve_height);
3912 if self.corner_radius > Pixels::ZERO {
3913 path.curve_to(first_top_left + top_curve_width, first_top_left);
3914 }
3915 path.line_to(first_top_right - top_curve_width);
3916
3917 cx.paint_path(path, self.color);
3918 }
3919}
3920
3921pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3922 (delta.pow(1.5) / 100.0).into()
3923}
3924
3925fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3926 (delta.pow(1.2) / 300.0).into()
3927}
3928
3929#[cfg(test)]
3930mod tests {
3931 use super::*;
3932 use crate::{
3933 display_map::{BlockDisposition, BlockProperties},
3934 editor_tests::{init_test, update_test_language_settings},
3935 Editor, MultiBuffer,
3936 };
3937 use gpui::TestAppContext;
3938 use language::language_settings;
3939 use log::info;
3940 use std::{num::NonZeroU32, sync::Arc};
3941 use util::test::sample_text;
3942
3943 #[gpui::test]
3944 fn test_shape_line_numbers(cx: &mut TestAppContext) {
3945 init_test(cx, |_| {});
3946 let window = cx.add_window(|cx| {
3947 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3948 Editor::new(EditorMode::Full, buffer, None, cx)
3949 });
3950
3951 let editor = window.root(cx).unwrap();
3952 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3953 let element = EditorElement::new(&editor, style);
3954 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
3955
3956 let layouts = cx
3957 .update_window(*window, |_, cx| {
3958 cx.with_element_context(|cx| {
3959 element
3960 .layout_line_numbers(
3961 0..6,
3962 &Default::default(),
3963 Some(DisplayPoint::new(0, 0)),
3964 &snapshot,
3965 cx,
3966 )
3967 .0
3968 })
3969 })
3970 .unwrap();
3971 assert_eq!(layouts.len(), 6);
3972
3973 let relative_rows = window
3974 .update(cx, |editor, cx| {
3975 let snapshot = editor.snapshot(cx);
3976 element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3977 })
3978 .unwrap();
3979 assert_eq!(relative_rows[&0], 3);
3980 assert_eq!(relative_rows[&1], 2);
3981 assert_eq!(relative_rows[&2], 1);
3982 // current line has no relative number
3983 assert_eq!(relative_rows[&4], 1);
3984 assert_eq!(relative_rows[&5], 2);
3985
3986 // works if cursor is before screen
3987 let relative_rows = window
3988 .update(cx, |editor, cx| {
3989 let snapshot = editor.snapshot(cx);
3990
3991 element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3992 })
3993 .unwrap();
3994 assert_eq!(relative_rows.len(), 3);
3995 assert_eq!(relative_rows[&3], 2);
3996 assert_eq!(relative_rows[&4], 3);
3997 assert_eq!(relative_rows[&5], 4);
3998
3999 // works if cursor is after screen
4000 let relative_rows = window
4001 .update(cx, |editor, cx| {
4002 let snapshot = editor.snapshot(cx);
4003
4004 element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
4005 })
4006 .unwrap();
4007 assert_eq!(relative_rows.len(), 3);
4008 assert_eq!(relative_rows[&0], 5);
4009 assert_eq!(relative_rows[&1], 4);
4010 assert_eq!(relative_rows[&2], 3);
4011 }
4012
4013 #[gpui::test]
4014 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4015 init_test(cx, |_| {});
4016
4017 let window = cx.add_window(|cx| {
4018 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4019 Editor::new(EditorMode::Full, buffer, None, cx)
4020 });
4021 let editor = window.root(cx).unwrap();
4022 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4023 let mut element = EditorElement::new(&editor, style);
4024
4025 window
4026 .update(cx, |editor, cx| {
4027 editor.cursor_shape = CursorShape::Block;
4028 editor.change_selections(None, cx, |s| {
4029 s.select_ranges([
4030 Point::new(0, 0)..Point::new(1, 0),
4031 Point::new(3, 2)..Point::new(3, 3),
4032 Point::new(5, 6)..Point::new(6, 0),
4033 ]);
4034 });
4035 })
4036 .unwrap();
4037 let state = cx
4038 .update_window(window.into(), |_view, cx| {
4039 cx.with_element_context(|cx| {
4040 element.after_layout(
4041 Bounds {
4042 origin: point(px(500.), px(500.)),
4043 size: size(px(500.), px(500.)),
4044 },
4045 &mut (),
4046 cx,
4047 )
4048 })
4049 })
4050 .unwrap();
4051
4052 assert_eq!(state.selections.len(), 1);
4053 let local_selections = &state.selections[0].1;
4054 assert_eq!(local_selections.len(), 3);
4055 // moves cursor back one line
4056 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4057 assert_eq!(
4058 local_selections[0].range,
4059 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4060 );
4061
4062 // moves cursor back one column
4063 assert_eq!(
4064 local_selections[1].range,
4065 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4066 );
4067 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4068
4069 // leaves cursor on the max point
4070 assert_eq!(
4071 local_selections[2].range,
4072 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4073 );
4074 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4075
4076 // active lines does not include 1 (even though the range of the selection does)
4077 assert_eq!(
4078 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4079 vec![0, 3, 5, 6]
4080 );
4081
4082 // multi-buffer support
4083 // in DisplayPoint coordinates, this is what we're dealing with:
4084 // 0: [[file
4085 // 1: header]]
4086 // 2: aaaaaa
4087 // 3: bbbbbb
4088 // 4: cccccc
4089 // 5:
4090 // 6: ...
4091 // 7: ffffff
4092 // 8: gggggg
4093 // 9: hhhhhh
4094 // 10:
4095 // 11: [[file
4096 // 12: header]]
4097 // 13: bbbbbb
4098 // 14: cccccc
4099 // 15: dddddd
4100 let window = cx.add_window(|cx| {
4101 let buffer = MultiBuffer::build_multi(
4102 [
4103 (
4104 &(sample_text(8, 6, 'a') + "\n"),
4105 vec![
4106 Point::new(0, 0)..Point::new(3, 0),
4107 Point::new(4, 0)..Point::new(7, 0),
4108 ],
4109 ),
4110 (
4111 &(sample_text(8, 6, 'a') + "\n"),
4112 vec![Point::new(1, 0)..Point::new(3, 0)],
4113 ),
4114 ],
4115 cx,
4116 );
4117 Editor::new(EditorMode::Full, buffer, None, cx)
4118 });
4119 let editor = window.root(cx).unwrap();
4120 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4121 let mut element = EditorElement::new(&editor, style);
4122 let _state = window.update(cx, |editor, cx| {
4123 editor.cursor_shape = CursorShape::Block;
4124 editor.change_selections(None, cx, |s| {
4125 s.select_display_ranges([
4126 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4127 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4128 ]);
4129 });
4130 });
4131
4132 let state = cx
4133 .update_window(window.into(), |_view, cx| {
4134 cx.with_element_context(|cx| {
4135 element.after_layout(
4136 Bounds {
4137 origin: point(px(500.), px(500.)),
4138 size: size(px(500.), px(500.)),
4139 },
4140 &mut (),
4141 cx,
4142 )
4143 })
4144 })
4145 .unwrap();
4146 assert_eq!(state.selections.len(), 1);
4147 let local_selections = &state.selections[0].1;
4148 assert_eq!(local_selections.len(), 2);
4149
4150 // moves cursor on excerpt boundary back a line
4151 // and doesn't allow selection to bleed through
4152 assert_eq!(
4153 local_selections[0].range,
4154 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4155 );
4156 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4157 // moves cursor on buffer boundary back two lines
4158 // and doesn't allow selection to bleed through
4159 assert_eq!(
4160 local_selections[1].range,
4161 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4162 );
4163 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4164 }
4165
4166 #[gpui::test]
4167 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4168 init_test(cx, |_| {});
4169
4170 let window = cx.add_window(|cx| {
4171 let buffer = MultiBuffer::build_simple("", cx);
4172 Editor::new(EditorMode::Full, buffer, None, cx)
4173 });
4174 let editor = window.root(cx).unwrap();
4175 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4176 window
4177 .update(cx, |editor, cx| {
4178 editor.set_placeholder_text("hello", cx);
4179 editor.insert_blocks(
4180 [BlockProperties {
4181 style: BlockStyle::Fixed,
4182 disposition: BlockDisposition::Above,
4183 height: 3,
4184 position: Anchor::min(),
4185 render: Arc::new(|_| div().into_any()),
4186 }],
4187 None,
4188 cx,
4189 );
4190
4191 // Blur the editor so that it displays placeholder text.
4192 cx.blur();
4193 })
4194 .unwrap();
4195
4196 let mut element = EditorElement::new(&editor, style);
4197 let state = cx
4198 .update_window(window.into(), |_view, cx| {
4199 cx.with_element_context(|cx| {
4200 element.after_layout(
4201 Bounds {
4202 origin: point(px(500.), px(500.)),
4203 size: size(px(500.), px(500.)),
4204 },
4205 &mut (),
4206 cx,
4207 )
4208 })
4209 })
4210 .unwrap();
4211
4212 assert_eq!(state.position_map.line_layouts.len(), 4);
4213 assert_eq!(
4214 state
4215 .line_numbers
4216 .iter()
4217 .map(Option::is_some)
4218 .collect::<Vec<_>>(),
4219 &[false, false, false, true]
4220 );
4221 }
4222
4223 #[gpui::test]
4224 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4225 const TAB_SIZE: u32 = 4;
4226
4227 let input_text = "\t \t|\t| a b";
4228 let expected_invisibles = vec![
4229 Invisible::Tab {
4230 line_start_offset: 0,
4231 },
4232 Invisible::Whitespace {
4233 line_offset: TAB_SIZE as usize,
4234 },
4235 Invisible::Tab {
4236 line_start_offset: TAB_SIZE as usize + 1,
4237 },
4238 Invisible::Tab {
4239 line_start_offset: TAB_SIZE as usize * 2 + 1,
4240 },
4241 Invisible::Whitespace {
4242 line_offset: TAB_SIZE as usize * 3 + 1,
4243 },
4244 Invisible::Whitespace {
4245 line_offset: TAB_SIZE as usize * 3 + 3,
4246 },
4247 ];
4248 assert_eq!(
4249 expected_invisibles.len(),
4250 input_text
4251 .chars()
4252 .filter(|initial_char| initial_char.is_whitespace())
4253 .count(),
4254 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4255 );
4256
4257 init_test(cx, |s| {
4258 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4259 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4260 });
4261
4262 let actual_invisibles =
4263 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4264
4265 assert_eq!(expected_invisibles, actual_invisibles);
4266 }
4267
4268 #[gpui::test]
4269 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4270 init_test(cx, |s| {
4271 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4272 s.defaults.tab_size = NonZeroU32::new(4);
4273 });
4274
4275 for editor_mode_without_invisibles in [
4276 EditorMode::SingleLine,
4277 EditorMode::AutoHeight { max_lines: 100 },
4278 ] {
4279 let invisibles = collect_invisibles_from_new_editor(
4280 cx,
4281 editor_mode_without_invisibles,
4282 "\t\t\t| | a b",
4283 px(500.0),
4284 );
4285 assert!(invisibles.is_empty(),
4286 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4287 }
4288 }
4289
4290 #[gpui::test]
4291 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4292 let tab_size = 4;
4293 let input_text = "a\tbcd ".repeat(9);
4294 let repeated_invisibles = [
4295 Invisible::Tab {
4296 line_start_offset: 1,
4297 },
4298 Invisible::Whitespace {
4299 line_offset: tab_size as usize + 3,
4300 },
4301 Invisible::Whitespace {
4302 line_offset: tab_size as usize + 4,
4303 },
4304 Invisible::Whitespace {
4305 line_offset: tab_size as usize + 5,
4306 },
4307 ];
4308 let expected_invisibles = std::iter::once(repeated_invisibles)
4309 .cycle()
4310 .take(9)
4311 .flatten()
4312 .collect::<Vec<_>>();
4313 assert_eq!(
4314 expected_invisibles.len(),
4315 input_text
4316 .chars()
4317 .filter(|initial_char| initial_char.is_whitespace())
4318 .count(),
4319 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4320 );
4321 info!("Expected invisibles: {expected_invisibles:?}");
4322
4323 init_test(cx, |_| {});
4324
4325 // Put the same string with repeating whitespace pattern into editors of various size,
4326 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4327 let resize_step = 10.0;
4328 let mut editor_width = 200.0;
4329 while editor_width <= 1000.0 {
4330 update_test_language_settings(cx, |s| {
4331 s.defaults.tab_size = NonZeroU32::new(tab_size);
4332 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4333 s.defaults.preferred_line_length = Some(editor_width as u32);
4334 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4335 });
4336
4337 let actual_invisibles = collect_invisibles_from_new_editor(
4338 cx,
4339 EditorMode::Full,
4340 &input_text,
4341 px(editor_width),
4342 );
4343
4344 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4345 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4346 let mut i = 0;
4347 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4348 i = actual_index;
4349 match expected_invisibles.get(i) {
4350 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4351 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4352 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4353 _ => {
4354 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4355 }
4356 },
4357 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4358 }
4359 }
4360 let missing_expected_invisibles = &expected_invisibles[i + 1..];
4361 assert!(
4362 missing_expected_invisibles.is_empty(),
4363 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4364 );
4365
4366 editor_width += resize_step;
4367 }
4368 }
4369
4370 fn collect_invisibles_from_new_editor(
4371 cx: &mut TestAppContext,
4372 editor_mode: EditorMode,
4373 input_text: &str,
4374 editor_width: Pixels,
4375 ) -> Vec<Invisible> {
4376 info!(
4377 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4378 editor_width.0
4379 );
4380 let window = cx.add_window(|cx| {
4381 let buffer = MultiBuffer::build_simple(&input_text, cx);
4382 Editor::new(editor_mode, buffer, None, cx)
4383 });
4384 let editor = window.root(cx).unwrap();
4385 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4386 let mut element = EditorElement::new(&editor, style);
4387 window
4388 .update(cx, |editor, cx| {
4389 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4390 editor.set_wrap_width(Some(editor_width), cx);
4391 })
4392 .unwrap();
4393 let layout_state = cx
4394 .update_window(window.into(), |_, cx| {
4395 cx.with_element_context(|cx| {
4396 element.after_layout(
4397 Bounds {
4398 origin: point(px(500.), px(500.)),
4399 size: size(px(500.), px(500.)),
4400 },
4401 &mut (),
4402 cx,
4403 )
4404 })
4405 })
4406 .unwrap();
4407
4408 layout_state
4409 .position_map
4410 .line_layouts
4411 .iter()
4412 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4413 .cloned()
4414 .collect()
4415 }
4416}
4417
4418pub fn register_action<T: Action>(
4419 view: &View<Editor>,
4420 cx: &mut WindowContext,
4421 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4422) {
4423 let view = view.clone();
4424 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4425 let action = action.downcast_ref().unwrap();
4426 if phase == DispatchPhase::Bubble {
4427 view.update(cx, |editor, cx| {
4428 listener(editor, action, cx);
4429 })
4430 }
4431 })
4432}
4433
4434fn compute_auto_height_layout(
4435 editor: &mut Editor,
4436 max_lines: usize,
4437 max_line_number_width: Pixels,
4438 known_dimensions: Size<Option<Pixels>>,
4439 cx: &mut ViewContext<Editor>,
4440) -> Option<Size<Pixels>> {
4441 let width = known_dimensions.width?;
4442 if let Some(height) = known_dimensions.height {
4443 return Some(size(width, height));
4444 }
4445
4446 let style = editor.style.as_ref().unwrap();
4447 let font_id = cx.text_system().resolve_font(&style.text.font());
4448 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4449 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4450 let em_width = cx
4451 .text_system()
4452 .typographic_bounds(font_id, font_size, 'm')
4453 .unwrap()
4454 .size
4455 .width;
4456
4457 let mut snapshot = editor.snapshot(cx);
4458 let gutter_dimensions =
4459 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
4460
4461 editor.gutter_width = gutter_dimensions.width;
4462 let text_width = width - gutter_dimensions.width;
4463 let overscroll = size(em_width, px(0.));
4464
4465 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
4466 if editor.set_wrap_width(Some(editor_width), cx) {
4467 snapshot = editor.snapshot(cx);
4468 }
4469
4470 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
4471 let height = scroll_height
4472 .max(line_height)
4473 .min(line_height * max_lines as f32);
4474
4475 Some(size(width, height))
4476}