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