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