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