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