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