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