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