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