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