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