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