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