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