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