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