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