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