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
882 for fold in snapshot.folds_in_range(layout.visible_anchor_range.clone()) {
883 let fold_range = fold.range.clone();
884 let display_range = fold.range.start.to_display_point(&snapshot)
885 ..fold.range.end.to_display_point(&snapshot);
886 debug_assert_eq!(display_range.start.row(), display_range.end.row());
887 let row = display_range.start.row();
888 debug_assert!(row < layout.visible_display_row_range.end);
889 let Some(line_layout) = &layout
890 .position_map
891 .line_layouts
892 .get((row - layout.visible_display_row_range.start) as usize)
893 .map(|l| &l.line)
894 else {
895 continue;
896 };
897
898 let start_x = content_origin.x
899 + line_layout.x_for_index(display_range.start.column() as usize)
900 - layout.position_map.scroll_position.x;
901 let start_y = content_origin.y
902 + row as f32 * layout.position_map.line_height
903 - layout.position_map.scroll_position.y;
904 let end_x = content_origin.x
905 + line_layout.x_for_index(display_range.end.column() as usize)
906 - layout.position_map.scroll_position.x;
907
908 let fold_bounds = Bounds {
909 origin: point(start_x, start_y),
910 size: size(end_x - start_x, layout.position_map.line_height),
911 };
912
913 let fold_background = cx.with_z_index(1, |cx| {
914 div()
915 .id(fold.id)
916 .size_full()
917 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
918 .on_click(cx.listener_for(
919 &self.editor,
920 move |editor: &mut Editor, _, cx| {
921 editor.unfold_ranges(
922 [fold_range.start..fold_range.end],
923 true,
924 false,
925 cx,
926 );
927 cx.stop_propagation();
928 },
929 ))
930 .draw_and_update_state(
931 fold_bounds.origin,
932 fold_bounds.size,
933 cx,
934 |fold_element_state, cx| {
935 if fold_element_state.is_active() {
936 cx.theme().colors().ghost_element_active
937 } else if fold_bounds.contains(&cx.mouse_position()) {
938 cx.theme().colors().ghost_element_hover
939 } else {
940 cx.theme().colors().ghost_element_background
941 }
942 },
943 )
944 });
945
946 self.paint_highlighted_range(
947 display_range.clone(),
948 fold_background,
949 fold_corner_radius,
950 fold_corner_radius * 2.,
951 layout,
952 content_origin,
953 text_bounds,
954 cx,
955 );
956 }
957 });
958
959 for (range, color) in &layout.highlighted_ranges {
960 self.paint_highlighted_range(
961 range.clone(),
962 *color,
963 Pixels::ZERO,
964 line_end_overshoot,
965 layout,
966 content_origin,
967 text_bounds,
968 cx,
969 );
970 }
971
972 let mut cursors = SmallVec::<[Cursor; 32]>::new();
973 let corner_radius = 0.15 * layout.position_map.line_height;
974 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
975
976 for (selection_style, selections) in &layout.selections {
977 for selection in selections {
978 self.paint_highlighted_range(
979 selection.range.clone(),
980 selection_style.selection,
981 corner_radius,
982 corner_radius * 2.,
983 layout,
984 content_origin,
985 text_bounds,
986 cx,
987 );
988
989 if selection.is_local && !selection.range.is_empty() {
990 invisible_display_ranges.push(selection.range.clone());
991 }
992
993 if !selection.is_local || self.editor.read(cx).show_local_cursors(cx) {
994 let cursor_position = selection.head;
995 if layout
996 .visible_display_row_range
997 .contains(&cursor_position.row())
998 {
999 let cursor_row_layout = &layout.position_map.line_layouts
1000 [(cursor_position.row() - start_row) as usize]
1001 .line;
1002 let cursor_column = cursor_position.column() as usize;
1003
1004 let cursor_character_x =
1005 cursor_row_layout.x_for_index(cursor_column);
1006 let mut block_width = cursor_row_layout
1007 .x_for_index(cursor_column + 1)
1008 - cursor_character_x;
1009 if block_width == Pixels::ZERO {
1010 block_width = layout.position_map.em_width;
1011 }
1012 let block_text = if let CursorShape::Block = selection.cursor_shape
1013 {
1014 layout
1015 .position_map
1016 .snapshot
1017 .chars_at(cursor_position)
1018 .next()
1019 .and_then(|(character, _)| {
1020 let text = if character == '\n' {
1021 SharedString::from(" ")
1022 } else {
1023 SharedString::from(character.to_string())
1024 };
1025 let len = text.len();
1026 cx.text_system()
1027 .shape_line(
1028 text,
1029 cursor_row_layout.font_size,
1030 &[TextRun {
1031 len,
1032 font: self.style.text.font(),
1033 color: self.style.background,
1034 background_color: None,
1035 underline: None,
1036 }],
1037 )
1038 .log_err()
1039 })
1040 } else {
1041 None
1042 };
1043
1044 let x = cursor_character_x - layout.position_map.scroll_position.x;
1045 let y = cursor_position.row() as f32
1046 * layout.position_map.line_height
1047 - layout.position_map.scroll_position.y;
1048 if selection.is_newest {
1049 self.editor.update(cx, |editor, _| {
1050 editor.pixel_position_of_newest_cursor = Some(point(
1051 text_bounds.origin.x + x + block_width / 2.,
1052 text_bounds.origin.y
1053 + y
1054 + layout.position_map.line_height / 2.,
1055 ))
1056 });
1057 }
1058 cursors.push(Cursor {
1059 color: selection_style.cursor,
1060 block_width,
1061 origin: point(x, y),
1062 line_height: layout.position_map.line_height,
1063 shape: selection.cursor_shape,
1064 block_text,
1065 });
1066 }
1067 }
1068 }
1069 }
1070
1071 for (ix, line_with_invisibles) in
1072 layout.position_map.line_layouts.iter().enumerate()
1073 {
1074 let row = start_row + ix as u32;
1075 line_with_invisibles.draw(
1076 layout,
1077 row,
1078 content_origin,
1079 whitespace_setting,
1080 &invisible_display_ranges,
1081 cx,
1082 )
1083 }
1084
1085 cx.with_z_index(0, |cx| {
1086 for cursor in cursors {
1087 cursor.paint(content_origin, cx);
1088 }
1089 });
1090 },
1091 )
1092 }
1093
1094 fn paint_overlays(
1095 &mut self,
1096 text_bounds: Bounds<Pixels>,
1097 layout: &mut LayoutState,
1098 cx: &mut WindowContext,
1099 ) {
1100 let content_origin = text_bounds.origin + point(layout.gutter_margin, Pixels::ZERO);
1101 let start_row = layout.visible_display_row_range.start;
1102 if let Some((position, mut context_menu)) = layout.context_menu.take() {
1103 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1104 let context_menu_size = context_menu.measure(available_space, cx);
1105
1106 let cursor_row_layout =
1107 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
1108 let x = cursor_row_layout.x_for_index(position.column() as usize)
1109 - layout.position_map.scroll_position.x;
1110 let y = (position.row() + 1) as f32 * layout.position_map.line_height
1111 - layout.position_map.scroll_position.y;
1112 let mut list_origin = content_origin + point(x, y);
1113 let list_width = context_menu_size.width;
1114 let list_height = context_menu_size.height;
1115
1116 // Snap the right edge of the list to the right edge of the window if
1117 // its horizontal bounds overflow.
1118 if list_origin.x + list_width > cx.viewport_size().width {
1119 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1120 }
1121
1122 if list_origin.y + list_height > text_bounds.lower_right().y {
1123 list_origin.y -= layout.position_map.line_height + list_height;
1124 }
1125
1126 cx.break_content_mask(|cx| context_menu.draw(list_origin, available_space, cx));
1127 }
1128
1129 if let Some((position, mut hover_popovers)) = layout.hover_popovers.take() {
1130 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1131
1132 // This is safe because we check on layout whether the required row is available
1133 let hovered_row_layout =
1134 &layout.position_map.line_layouts[(position.row() - start_row) as usize].line;
1135
1136 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
1137 // height. This is the size we will use to decide whether to render popovers above or below
1138 // the hovered line.
1139 let first_size = hover_popovers[0].measure(available_space, cx);
1140 let height_to_reserve =
1141 first_size.height + 1.5 * MIN_POPOVER_LINE_HEIGHT * layout.position_map.line_height;
1142
1143 // Compute Hovered Point
1144 let x = hovered_row_layout.x_for_index(position.column() as usize)
1145 - layout.position_map.scroll_position.x;
1146 let y = position.row() as f32 * layout.position_map.line_height
1147 - layout.position_map.scroll_position.y;
1148 let hovered_point = content_origin + point(x, y);
1149
1150 if hovered_point.y - height_to_reserve > Pixels::ZERO {
1151 // There is enough space above. Render popovers above the hovered point
1152 let mut current_y = hovered_point.y;
1153 for mut hover_popover in hover_popovers {
1154 let size = hover_popover.measure(available_space, cx);
1155 let mut popover_origin = point(hovered_point.x, current_y - size.height);
1156
1157 let x_out_of_bounds =
1158 text_bounds.upper_right().x - (popover_origin.x + size.width);
1159 if x_out_of_bounds < Pixels::ZERO {
1160 popover_origin.x = popover_origin.x + x_out_of_bounds;
1161 }
1162
1163 cx.break_content_mask(|cx| {
1164 hover_popover.draw(popover_origin, available_space, cx)
1165 });
1166
1167 current_y = popover_origin.y - HOVER_POPOVER_GAP;
1168 }
1169 } else {
1170 // There is not enough space above. Render popovers below the hovered point
1171 let mut current_y = hovered_point.y + layout.position_map.line_height;
1172 for mut hover_popover in hover_popovers {
1173 let size = hover_popover.measure(available_space, cx);
1174 let mut popover_origin = point(hovered_point.x, current_y);
1175
1176 let x_out_of_bounds =
1177 text_bounds.upper_right().x - (popover_origin.x + size.width);
1178 if x_out_of_bounds < Pixels::ZERO {
1179 popover_origin.x = popover_origin.x + x_out_of_bounds;
1180 }
1181
1182 hover_popover.draw(popover_origin, available_space, cx);
1183
1184 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
1185 }
1186 }
1187 }
1188
1189 if let Some(mouse_context_menu) = self.editor.read(cx).mouse_context_menu.as_ref() {
1190 let element = overlay()
1191 .position(mouse_context_menu.position)
1192 .child(mouse_context_menu.context_menu.clone())
1193 .anchor(AnchorCorner::TopLeft)
1194 .snap_to_window();
1195 element.into_any().draw(
1196 gpui::Point::default(),
1197 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
1198 cx,
1199 );
1200 }
1201 }
1202
1203 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
1204 bounds.upper_right().x - self.style.scrollbar_width
1205 }
1206
1207 fn paint_scrollbar(
1208 &mut self,
1209 bounds: Bounds<Pixels>,
1210 layout: &mut LayoutState,
1211 cx: &mut WindowContext,
1212 ) {
1213 if layout.mode != EditorMode::Full {
1214 return;
1215 }
1216
1217 // If a drag took place after we started dragging the scrollbar,
1218 // cancel the scrollbar drag.
1219 if cx.has_active_drag() {
1220 self.editor.update(cx, |editor, cx| {
1221 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1222 });
1223 }
1224
1225 let top = bounds.origin.y;
1226 let bottom = bounds.lower_left().y;
1227 let right = bounds.lower_right().x;
1228 let left = self.scrollbar_left(&bounds);
1229 let row_range = layout.scrollbar_row_range.clone();
1230 let max_row = layout.max_row as f32 + (row_range.end - row_range.start);
1231
1232 let mut height = bounds.size.height;
1233 let mut first_row_y_offset = px(0.0);
1234
1235 // Impose a minimum height on the scrollbar thumb
1236 let row_height = height / max_row;
1237 let min_thumb_height = layout.position_map.line_height;
1238 let thumb_height = (row_range.end - row_range.start) * row_height;
1239 if thumb_height < min_thumb_height {
1240 first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
1241 height -= min_thumb_height - thumb_height;
1242 }
1243
1244 let y_for_row = |row: f32| -> Pixels { top + first_row_y_offset + row * row_height };
1245
1246 let thumb_top = y_for_row(row_range.start) - first_row_y_offset;
1247 let thumb_bottom = y_for_row(row_range.end) + first_row_y_offset;
1248 let track_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
1249 let thumb_bounds = Bounds::from_corners(point(left, thumb_top), point(right, thumb_bottom));
1250
1251 if layout.show_scrollbars {
1252 cx.paint_quad(quad(
1253 track_bounds,
1254 Corners::default(),
1255 cx.theme().colors().scrollbar_track_background,
1256 Edges {
1257 top: Pixels::ZERO,
1258 right: Pixels::ZERO,
1259 bottom: Pixels::ZERO,
1260 left: px(1.),
1261 },
1262 cx.theme().colors().scrollbar_track_border,
1263 ));
1264 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1265 if layout.is_singleton && scrollbar_settings.selections {
1266 let start_anchor = Anchor::min();
1267 let end_anchor = Anchor::max();
1268 let background_ranges = self
1269 .editor
1270 .read(cx)
1271 .background_highlight_row_ranges::<BufferSearchHighlights>(
1272 start_anchor..end_anchor,
1273 &layout.position_map.snapshot,
1274 50000,
1275 );
1276 for range in background_ranges {
1277 let start_y = y_for_row(range.start().row() as f32);
1278 let mut end_y = y_for_row(range.end().row() as f32);
1279 if end_y - start_y < px(1.) {
1280 end_y = start_y + px(1.);
1281 }
1282 let bounds = Bounds::from_corners(point(left, start_y), point(right, end_y));
1283 cx.paint_quad(quad(
1284 bounds,
1285 Corners::default(),
1286 cx.theme().status().info,
1287 Edges {
1288 top: Pixels::ZERO,
1289 right: px(1.),
1290 bottom: Pixels::ZERO,
1291 left: px(1.),
1292 },
1293 cx.theme().colors().scrollbar_thumb_border,
1294 ));
1295 }
1296 }
1297
1298 if layout.is_singleton && scrollbar_settings.git_diff {
1299 for hunk in layout
1300 .position_map
1301 .snapshot
1302 .buffer_snapshot
1303 .git_diff_hunks_in_range(0..(max_row.floor() as u32))
1304 {
1305 let start_display = Point::new(hunk.buffer_range.start, 0)
1306 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1307 let end_display = Point::new(hunk.buffer_range.end, 0)
1308 .to_display_point(&layout.position_map.snapshot.display_snapshot);
1309 let start_y = y_for_row(start_display.row() as f32);
1310 let mut end_y = if hunk.buffer_range.start == hunk.buffer_range.end {
1311 y_for_row((end_display.row() + 1) as f32)
1312 } else {
1313 y_for_row((end_display.row()) as f32)
1314 };
1315
1316 if end_y - start_y < px(1.) {
1317 end_y = start_y + px(1.);
1318 }
1319 let bounds = Bounds::from_corners(point(left, start_y), point(right, end_y));
1320
1321 let color = match hunk.status() {
1322 DiffHunkStatus::Added => cx.theme().status().created,
1323 DiffHunkStatus::Modified => cx.theme().status().modified,
1324 DiffHunkStatus::Removed => cx.theme().status().deleted,
1325 };
1326 cx.paint_quad(quad(
1327 bounds,
1328 Corners::default(),
1329 color,
1330 Edges {
1331 top: Pixels::ZERO,
1332 right: px(1.),
1333 bottom: Pixels::ZERO,
1334 left: px(1.),
1335 },
1336 cx.theme().colors().scrollbar_thumb_border,
1337 ));
1338 }
1339 }
1340
1341 cx.paint_quad(quad(
1342 thumb_bounds,
1343 Corners::default(),
1344 cx.theme().colors().scrollbar_thumb_background,
1345 Edges {
1346 top: Pixels::ZERO,
1347 right: px(1.),
1348 bottom: Pixels::ZERO,
1349 left: px(1.),
1350 },
1351 cx.theme().colors().scrollbar_thumb_border,
1352 ));
1353 }
1354
1355 let interactive_track_bounds = InteractiveBounds {
1356 bounds: track_bounds,
1357 stacking_order: cx.stacking_order().clone(),
1358 };
1359 let mut mouse_position = cx.mouse_position();
1360 if interactive_track_bounds.visibly_contains(&mouse_position, cx) {
1361 cx.set_cursor_style(CursorStyle::Arrow);
1362 }
1363
1364 cx.on_mouse_event({
1365 let editor = self.editor.clone();
1366 move |event: &MouseMoveEvent, phase, cx| {
1367 if phase == DispatchPhase::Capture {
1368 return;
1369 }
1370
1371 editor.update(cx, |editor, cx| {
1372 if event.pressed_button == Some(MouseButton::Left)
1373 && editor.scroll_manager.is_dragging_scrollbar()
1374 {
1375 let y = mouse_position.y;
1376 let new_y = event.position.y;
1377 if (track_bounds.top()..track_bounds.bottom()).contains(&y) {
1378 let mut position = editor.scroll_position(cx);
1379 position.y += (new_y - y) * (max_row as f32) / height;
1380 if position.y < 0.0 {
1381 position.y = 0.0;
1382 }
1383 editor.set_scroll_position(position, cx);
1384 }
1385
1386 mouse_position = event.position;
1387 cx.stop_propagation();
1388 } else {
1389 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1390 if interactive_track_bounds.visibly_contains(&event.position, cx) {
1391 editor.scroll_manager.show_scrollbar(cx);
1392 }
1393 }
1394 })
1395 }
1396 });
1397
1398 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
1399 cx.on_mouse_event({
1400 let editor = self.editor.clone();
1401 move |_: &MouseUpEvent, phase, cx| {
1402 if phase == DispatchPhase::Capture {
1403 return;
1404 }
1405
1406 editor.update(cx, |editor, cx| {
1407 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1408 cx.stop_propagation();
1409 });
1410 }
1411 });
1412 } else {
1413 cx.on_mouse_event({
1414 let editor = self.editor.clone();
1415 move |event: &MouseDownEvent, phase, cx| {
1416 if phase == DispatchPhase::Capture {
1417 return;
1418 }
1419
1420 editor.update(cx, |editor, cx| {
1421 if track_bounds.contains(&event.position) {
1422 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
1423
1424 let y = event.position.y;
1425 if y < thumb_top || thumb_bottom < y {
1426 let center_row =
1427 ((y - top) * max_row as f32 / height).round() as u32;
1428 let top_row = center_row
1429 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
1430 let mut position = editor.scroll_position(cx);
1431 position.y = top_row as f32;
1432 editor.set_scroll_position(position, cx);
1433 } else {
1434 editor.scroll_manager.show_scrollbar(cx);
1435 }
1436
1437 cx.stop_propagation();
1438 }
1439 });
1440 }
1441 });
1442 }
1443 }
1444
1445 #[allow(clippy::too_many_arguments)]
1446 fn paint_highlighted_range(
1447 &self,
1448 range: Range<DisplayPoint>,
1449 color: Hsla,
1450 corner_radius: Pixels,
1451 line_end_overshoot: Pixels,
1452 layout: &LayoutState,
1453 content_origin: gpui::Point<Pixels>,
1454 bounds: Bounds<Pixels>,
1455 cx: &mut WindowContext,
1456 ) {
1457 let start_row = layout.visible_display_row_range.start;
1458 let end_row = layout.visible_display_row_range.end;
1459 if range.start != range.end {
1460 let row_range = if range.end.column() == 0 {
1461 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
1462 } else {
1463 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
1464 };
1465
1466 let highlighted_range = HighlightedRange {
1467 color,
1468 line_height: layout.position_map.line_height,
1469 corner_radius,
1470 start_y: content_origin.y
1471 + row_range.start as f32 * layout.position_map.line_height
1472 - layout.position_map.scroll_position.y,
1473 lines: row_range
1474 .into_iter()
1475 .map(|row| {
1476 let line_layout =
1477 &layout.position_map.line_layouts[(row - start_row) as usize].line;
1478 HighlightedRangeLine {
1479 start_x: if row == range.start.row() {
1480 content_origin.x
1481 + line_layout.x_for_index(range.start.column() as usize)
1482 - layout.position_map.scroll_position.x
1483 } else {
1484 content_origin.x - layout.position_map.scroll_position.x
1485 },
1486 end_x: if row == range.end.row() {
1487 content_origin.x
1488 + line_layout.x_for_index(range.end.column() as usize)
1489 - layout.position_map.scroll_position.x
1490 } else {
1491 content_origin.x + line_layout.width + line_end_overshoot
1492 - layout.position_map.scroll_position.x
1493 },
1494 }
1495 })
1496 .collect(),
1497 };
1498
1499 highlighted_range.paint(bounds, cx);
1500 }
1501 }
1502
1503 fn paint_blocks(
1504 &mut self,
1505 bounds: Bounds<Pixels>,
1506 layout: &mut LayoutState,
1507 cx: &mut WindowContext,
1508 ) {
1509 let scroll_position = layout.position_map.snapshot.scroll_position();
1510 let scroll_left = scroll_position.x * layout.position_map.em_width;
1511 let scroll_top = scroll_position.y * layout.position_map.line_height;
1512
1513 for mut block in layout.blocks.drain(..) {
1514 let mut origin = bounds.origin
1515 + point(
1516 Pixels::ZERO,
1517 block.row as f32 * layout.position_map.line_height - scroll_top,
1518 );
1519 if !matches!(block.style, BlockStyle::Sticky) {
1520 origin += point(-scroll_left, Pixels::ZERO);
1521 }
1522 block.element.draw(origin, block.available_space, cx);
1523 }
1524 }
1525
1526 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
1527 let style = &self.style;
1528 let font_size = style.text.font_size.to_pixels(cx.rem_size());
1529 let layout = cx
1530 .text_system()
1531 .shape_line(
1532 SharedString::from(" ".repeat(column)),
1533 font_size,
1534 &[TextRun {
1535 len: column,
1536 font: style.text.font(),
1537 color: Hsla::default(),
1538 background_color: None,
1539 underline: None,
1540 }],
1541 )
1542 .unwrap();
1543
1544 layout.width
1545 }
1546
1547 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
1548 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
1549 self.column_pixels(digit_count, cx)
1550 }
1551
1552 //Folds contained in a hunk are ignored apart from shrinking visual size
1553 //If a fold contains any hunks then that fold line is marked as modified
1554 fn layout_git_gutters(
1555 &self,
1556 display_rows: Range<u32>,
1557 snapshot: &EditorSnapshot,
1558 ) -> Vec<DisplayDiffHunk> {
1559 let buffer_snapshot = &snapshot.buffer_snapshot;
1560
1561 let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1562 .to_point(snapshot)
1563 .row;
1564 let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1565 .to_point(snapshot)
1566 .row;
1567
1568 buffer_snapshot
1569 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1570 .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1571 .dedup()
1572 .collect()
1573 }
1574
1575 fn calculate_relative_line_numbers(
1576 &self,
1577 snapshot: &EditorSnapshot,
1578 rows: &Range<u32>,
1579 relative_to: Option<u32>,
1580 ) -> HashMap<u32, u32> {
1581 let mut relative_rows: HashMap<u32, u32> = Default::default();
1582 let Some(relative_to) = relative_to else {
1583 return relative_rows;
1584 };
1585
1586 let start = rows.start.min(relative_to);
1587 let end = rows.end.max(relative_to);
1588
1589 let buffer_rows = snapshot
1590 .buffer_rows(start)
1591 .take(1 + (end - start) as usize)
1592 .collect::<Vec<_>>();
1593
1594 let head_idx = relative_to - start;
1595 let mut delta = 1;
1596 let mut i = head_idx + 1;
1597 while i < buffer_rows.len() as u32 {
1598 if buffer_rows[i as usize].is_some() {
1599 if rows.contains(&(i + start)) {
1600 relative_rows.insert(i + start, delta);
1601 }
1602 delta += 1;
1603 }
1604 i += 1;
1605 }
1606 delta = 1;
1607 i = head_idx.min(buffer_rows.len() as u32 - 1);
1608 while i > 0 && buffer_rows[i as usize].is_none() {
1609 i -= 1;
1610 }
1611
1612 while i > 0 {
1613 i -= 1;
1614 if buffer_rows[i as usize].is_some() {
1615 if rows.contains(&(i + start)) {
1616 relative_rows.insert(i + start, delta);
1617 }
1618 delta += 1;
1619 }
1620 }
1621
1622 relative_rows
1623 }
1624
1625 fn shape_line_numbers(
1626 &self,
1627 rows: Range<u32>,
1628 active_rows: &BTreeMap<u32, bool>,
1629 newest_selection_head: DisplayPoint,
1630 is_singleton: bool,
1631 snapshot: &EditorSnapshot,
1632 cx: &ViewContext<Editor>,
1633 ) -> (
1634 Vec<Option<ShapedLine>>,
1635 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1636 ) {
1637 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1638 let include_line_numbers = snapshot.mode == EditorMode::Full;
1639 let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1640 let mut fold_statuses = Vec::with_capacity(rows.len());
1641 let mut line_number = String::new();
1642 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1643 let relative_to = if is_relative {
1644 Some(newest_selection_head.row())
1645 } else {
1646 None
1647 };
1648
1649 let relative_rows = self.calculate_relative_line_numbers(&snapshot, &rows, relative_to);
1650
1651 for (ix, row) in snapshot
1652 .buffer_rows(rows.start)
1653 .take((rows.end - rows.start) as usize)
1654 .enumerate()
1655 {
1656 let display_row = rows.start + ix as u32;
1657 let (active, color) = if active_rows.contains_key(&display_row) {
1658 (true, cx.theme().colors().editor_active_line_number)
1659 } else {
1660 (false, cx.theme().colors().editor_line_number)
1661 };
1662 if let Some(buffer_row) = row {
1663 if include_line_numbers {
1664 line_number.clear();
1665 let default_number = buffer_row + 1;
1666 let number = relative_rows
1667 .get(&(ix as u32 + rows.start))
1668 .unwrap_or(&default_number);
1669 write!(&mut line_number, "{}", number).unwrap();
1670 let run = TextRun {
1671 len: line_number.len(),
1672 font: self.style.text.font(),
1673 color,
1674 background_color: None,
1675 underline: None,
1676 };
1677 let shaped_line = cx
1678 .text_system()
1679 .shape_line(line_number.clone().into(), font_size, &[run])
1680 .unwrap();
1681 shaped_line_numbers.push(Some(shaped_line));
1682 fold_statuses.push(
1683 is_singleton
1684 .then(|| {
1685 snapshot
1686 .fold_for_line(buffer_row)
1687 .map(|fold_status| (fold_status, buffer_row, active))
1688 })
1689 .flatten(),
1690 )
1691 }
1692 } else {
1693 fold_statuses.push(None);
1694 shaped_line_numbers.push(None);
1695 }
1696 }
1697
1698 (shaped_line_numbers, fold_statuses)
1699 }
1700
1701 fn layout_lines(
1702 &self,
1703 rows: Range<u32>,
1704 line_number_layouts: &[Option<ShapedLine>],
1705 snapshot: &EditorSnapshot,
1706 cx: &ViewContext<Editor>,
1707 ) -> Vec<LineWithInvisibles> {
1708 if rows.start >= rows.end {
1709 return Vec::new();
1710 }
1711
1712 // Show the placeholder when the editor is empty
1713 if snapshot.is_empty() {
1714 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1715 let placeholder_color = cx.theme().colors().text_placeholder;
1716 let placeholder_text = snapshot.placeholder_text();
1717
1718 let placeholder_lines = placeholder_text
1719 .as_ref()
1720 .map_or("", AsRef::as_ref)
1721 .split('\n')
1722 .skip(rows.start as usize)
1723 .chain(iter::repeat(""))
1724 .take(rows.len());
1725 placeholder_lines
1726 .filter_map(move |line| {
1727 let run = TextRun {
1728 len: line.len(),
1729 font: self.style.text.font(),
1730 color: placeholder_color,
1731 background_color: None,
1732 underline: Default::default(),
1733 };
1734 cx.text_system()
1735 .shape_line(line.to_string().into(), font_size, &[run])
1736 .log_err()
1737 })
1738 .map(|line| LineWithInvisibles {
1739 line,
1740 invisibles: Vec::new(),
1741 })
1742 .collect()
1743 } else {
1744 let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1745 LineWithInvisibles::from_chunks(
1746 chunks,
1747 &self.style.text,
1748 MAX_LINE_LEN,
1749 rows.len() as usize,
1750 line_number_layouts,
1751 snapshot.mode,
1752 cx,
1753 )
1754 }
1755 }
1756
1757 fn compute_layout(&mut self, bounds: Bounds<Pixels>, cx: &mut WindowContext) -> LayoutState {
1758 self.editor.update(cx, |editor, cx| {
1759 let snapshot = editor.snapshot(cx);
1760 let style = self.style.clone();
1761
1762 let font_id = cx.text_system().resolve_font(&style.text.font());
1763 let font_size = style.text.font_size.to_pixels(cx.rem_size());
1764 let line_height = style.text.line_height_in_pixels(cx.rem_size());
1765 let em_width = cx
1766 .text_system()
1767 .typographic_bounds(font_id, font_size, 'm')
1768 .unwrap()
1769 .size
1770 .width;
1771 let em_advance = cx
1772 .text_system()
1773 .advance(font_id, font_size, 'm')
1774 .unwrap()
1775 .width;
1776
1777 let gutter_padding;
1778 let gutter_width;
1779 let gutter_margin;
1780 if snapshot.show_gutter {
1781 let descent = cx.text_system().descent(font_id, font_size);
1782
1783 let gutter_padding_factor = 3.5;
1784 gutter_padding = (em_width * gutter_padding_factor).round();
1785 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1786 gutter_margin = -descent;
1787 } else {
1788 gutter_padding = Pixels::ZERO;
1789 gutter_width = Pixels::ZERO;
1790 gutter_margin = Pixels::ZERO;
1791 };
1792
1793 editor.gutter_width = gutter_width;
1794
1795 let text_width = bounds.size.width - gutter_width;
1796 let overscroll = size(em_width, px(0.));
1797 let _snapshot = {
1798 editor.set_visible_line_count((bounds.size.height / line_height).into(), cx);
1799
1800 let editor_width = text_width - gutter_margin - overscroll.width - em_width;
1801 let wrap_width = match editor.soft_wrap_mode(cx) {
1802 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
1803 SoftWrap::EditorWidth => editor_width,
1804 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
1805 };
1806
1807 if editor.set_wrap_width(Some(wrap_width), cx) {
1808 editor.snapshot(cx)
1809 } else {
1810 snapshot
1811 }
1812 };
1813
1814 let wrap_guides = editor
1815 .wrap_guides(cx)
1816 .iter()
1817 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
1818 .collect::<SmallVec<[_; 2]>>();
1819
1820 let gutter_size = size(gutter_width, bounds.size.height);
1821 let text_size = size(text_width, bounds.size.height);
1822
1823 let autoscroll_horizontally =
1824 editor.autoscroll_vertically(bounds.size.height, line_height, cx);
1825 let mut snapshot = editor.snapshot(cx);
1826
1827 let scroll_position = snapshot.scroll_position();
1828 // The scroll position is a fractional point, the whole number of which represents
1829 // the top of the window in terms of display rows.
1830 let start_row = scroll_position.y as u32;
1831 let height_in_lines = f32::from(bounds.size.height / line_height);
1832 let max_row = snapshot.max_point().row();
1833
1834 // Add 1 to ensure selections bleed off screen
1835 let end_row = 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
1836
1837 let start_anchor = if start_row == 0 {
1838 Anchor::min()
1839 } else {
1840 snapshot
1841 .buffer_snapshot
1842 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1843 };
1844 let end_anchor = if end_row > max_row {
1845 Anchor::max()
1846 } else {
1847 snapshot
1848 .buffer_snapshot
1849 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1850 };
1851
1852 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1853 let mut active_rows = BTreeMap::new();
1854 let is_singleton = editor.is_singleton(cx);
1855
1856 let highlighted_rows = editor.highlighted_rows();
1857 let highlighted_ranges = editor.background_highlights_in_range(
1858 start_anchor..end_anchor,
1859 &snapshot.display_snapshot,
1860 cx.theme().colors(),
1861 );
1862
1863 let mut newest_selection_head = None;
1864
1865 if editor.show_local_selections {
1866 let mut local_selections: Vec<Selection<Point>> = editor
1867 .selections
1868 .disjoint_in_range(start_anchor..end_anchor, cx);
1869 local_selections.extend(editor.selections.pending(cx));
1870 let mut layouts = Vec::new();
1871 let newest = editor.selections.newest(cx);
1872 for selection in local_selections.drain(..) {
1873 let is_empty = selection.start == selection.end;
1874 let is_newest = selection == newest;
1875
1876 let layout = SelectionLayout::new(
1877 selection,
1878 editor.selections.line_mode,
1879 editor.cursor_shape,
1880 &snapshot.display_snapshot,
1881 is_newest,
1882 true,
1883 );
1884 if is_newest {
1885 newest_selection_head = Some(layout.head);
1886 }
1887
1888 for row in cmp::max(layout.active_rows.start, start_row)
1889 ..=cmp::min(layout.active_rows.end, end_row)
1890 {
1891 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1892 *contains_non_empty_selection |= !is_empty;
1893 }
1894 layouts.push(layout);
1895 }
1896
1897 let player = if editor.read_only(cx) {
1898 cx.theme().players().read_only()
1899 } else {
1900 style.local_player
1901 };
1902
1903 selections.push((player, layouts));
1904 }
1905
1906 if let Some(collaboration_hub) = &editor.collaboration_hub {
1907 // When following someone, render the local selections in their color.
1908 if let Some(leader_id) = editor.leader_peer_id {
1909 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
1910 if let Some(participant_index) = collaboration_hub
1911 .user_participant_indices(cx)
1912 .get(&collaborator.user_id)
1913 {
1914 if let Some((local_selection_style, _)) = selections.first_mut() {
1915 *local_selection_style = cx
1916 .theme()
1917 .players()
1918 .color_for_participant(participant_index.0);
1919 }
1920 }
1921 }
1922 }
1923
1924 let mut remote_selections = HashMap::default();
1925 for selection in snapshot.remote_selections_in_range(
1926 &(start_anchor..end_anchor),
1927 collaboration_hub.as_ref(),
1928 cx,
1929 ) {
1930 let selection_style = if let Some(participant_index) = selection.participant_index {
1931 cx.theme()
1932 .players()
1933 .color_for_participant(participant_index.0)
1934 } else {
1935 cx.theme().players().absent()
1936 };
1937
1938 // Don't re-render the leader's selections, since the local selections
1939 // match theirs.
1940 if Some(selection.peer_id) == editor.leader_peer_id {
1941 continue;
1942 }
1943
1944 remote_selections
1945 .entry(selection.replica_id)
1946 .or_insert((selection_style, Vec::new()))
1947 .1
1948 .push(SelectionLayout::new(
1949 selection.selection,
1950 selection.line_mode,
1951 selection.cursor_shape,
1952 &snapshot.display_snapshot,
1953 false,
1954 false,
1955 ));
1956 }
1957
1958 selections.extend(remote_selections.into_values());
1959 }
1960
1961 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1962 let show_scrollbars = match scrollbar_settings.show {
1963 ShowScrollbar::Auto => {
1964 // Git
1965 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1966 ||
1967 // Selections
1968 (is_singleton && scrollbar_settings.selections && editor.has_background_highlights::<BufferSearchHighlights>())
1969 // Scrollmanager
1970 || editor.scroll_manager.scrollbars_visible()
1971 }
1972 ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
1973 ShowScrollbar::Always => true,
1974 ShowScrollbar::Never => false,
1975 };
1976
1977 let head_for_relative = newest_selection_head.unwrap_or_else(|| {
1978 let newest = editor.selections.newest::<Point>(cx);
1979 SelectionLayout::new(
1980 newest,
1981 editor.selections.line_mode,
1982 editor.cursor_shape,
1983 &snapshot.display_snapshot,
1984 true,
1985 true,
1986 )
1987 .head
1988 });
1989
1990 let (line_numbers, fold_statuses) = self.shape_line_numbers(
1991 start_row..end_row,
1992 &active_rows,
1993 head_for_relative,
1994 is_singleton,
1995 &snapshot,
1996 cx,
1997 );
1998
1999 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2000
2001 let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2002
2003 let mut max_visible_line_width = Pixels::ZERO;
2004 let line_layouts = self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
2005 for line_with_invisibles in &line_layouts {
2006 if line_with_invisibles.line.width > max_visible_line_width {
2007 max_visible_line_width = line_with_invisibles.line.width;
2008 }
2009 }
2010
2011 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
2012 .unwrap()
2013 .width;
2014 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
2015
2016 let (scroll_width, blocks) = cx.with_element_id(Some("editor_blocks"), |cx| {
2017 self.layout_blocks(
2018 start_row..end_row,
2019 &snapshot,
2020 bounds.size.width,
2021 scroll_width,
2022 gutter_padding,
2023 gutter_width,
2024 em_width,
2025 gutter_width + gutter_margin,
2026 line_height,
2027 &style,
2028 &line_layouts,
2029 editor,
2030 cx,
2031 )
2032 });
2033
2034 let scroll_max = point(
2035 f32::from((scroll_width - text_size.width) / em_width).max(0.0),
2036 max_row as f32,
2037 );
2038
2039 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
2040
2041 let autoscrolled = if autoscroll_horizontally {
2042 editor.autoscroll_horizontally(
2043 start_row,
2044 text_size.width,
2045 scroll_width,
2046 em_width,
2047 &line_layouts,
2048 cx,
2049 )
2050 } else {
2051 false
2052 };
2053
2054 if clamped || autoscrolled {
2055 snapshot = editor.snapshot(cx);
2056 }
2057
2058 let mut context_menu = None;
2059 let mut code_actions_indicator = None;
2060 if let Some(newest_selection_head) = newest_selection_head {
2061 if (start_row..end_row).contains(&newest_selection_head.row()) {
2062 if editor.context_menu_visible() {
2063 let max_height = (12. * line_height).min((bounds.size.height - line_height) / 2.);
2064 context_menu =
2065 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx);
2066 }
2067
2068 let active = matches!(
2069 editor.context_menu.read().as_ref(),
2070 Some(crate::ContextMenu::CodeActions(_))
2071 );
2072
2073 code_actions_indicator = editor
2074 .render_code_actions_indicator(&style, active, cx)
2075 .map(|element| CodeActionsIndicator {
2076 row: newest_selection_head.row(),
2077 button: element,
2078 });
2079 }
2080 }
2081
2082 let visible_rows = start_row..start_row + line_layouts.len() as u32;
2083 let max_size = size(
2084 (120. * em_width) // Default size
2085 .min(bounds.size.width / 2.) // Shrink to half of the editor width
2086 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2087 (16. * line_height) // Default size
2088 .min(bounds.size.height / 2.) // Shrink to half of the editor height
2089 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2090 );
2091
2092 let hover = editor.hover_state.render(
2093 &snapshot,
2094 &style,
2095 visible_rows,
2096 max_size,
2097 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2098 cx,
2099 );
2100
2101 let fold_indicators = cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2102 editor.render_fold_indicators(
2103 fold_statuses,
2104 &style,
2105 editor.gutter_hovered,
2106 line_height,
2107 gutter_margin,
2108 cx,
2109 )
2110 });
2111
2112 let invisible_symbol_font_size = font_size / 2.;
2113 let tab_invisible = cx
2114 .text_system()
2115 .shape_line(
2116 "→".into(),
2117 invisible_symbol_font_size,
2118 &[TextRun {
2119 len: "→".len(),
2120 font: self.style.text.font(),
2121 color: cx.theme().colors().editor_invisible,
2122 background_color: None,
2123 underline: None,
2124 }],
2125 )
2126 .unwrap();
2127 let space_invisible = cx
2128 .text_system()
2129 .shape_line(
2130 "•".into(),
2131 invisible_symbol_font_size,
2132 &[TextRun {
2133 len: "•".len(),
2134 font: self.style.text.font(),
2135 color: cx.theme().colors().editor_invisible,
2136 background_color: None,
2137 underline: None,
2138 }],
2139 )
2140 .unwrap();
2141
2142 LayoutState {
2143 mode: snapshot.mode,
2144 position_map: Arc::new(PositionMap {
2145 size: bounds.size,
2146 scroll_position: point(
2147 scroll_position.x * em_width,
2148 scroll_position.y * line_height,
2149 ),
2150 scroll_max,
2151 line_layouts,
2152 line_height,
2153 em_width,
2154 em_advance,
2155 snapshot,
2156 }),
2157 visible_anchor_range: start_anchor..end_anchor,
2158 visible_display_row_range: start_row..end_row,
2159 wrap_guides,
2160 gutter_size,
2161 gutter_padding,
2162 text_size,
2163 scrollbar_row_range,
2164 show_scrollbars,
2165 is_singleton,
2166 max_row,
2167 gutter_margin,
2168 active_rows,
2169 highlighted_rows,
2170 highlighted_ranges,
2171 line_numbers,
2172 display_hunks,
2173 blocks,
2174 selections,
2175 context_menu,
2176 code_actions_indicator,
2177 fold_indicators,
2178 tab_invisible,
2179 space_invisible,
2180 hover_popovers: hover,
2181 }
2182 })
2183 }
2184
2185 #[allow(clippy::too_many_arguments)]
2186 fn layout_blocks(
2187 &self,
2188 rows: Range<u32>,
2189 snapshot: &EditorSnapshot,
2190 editor_width: Pixels,
2191 scroll_width: Pixels,
2192 gutter_padding: Pixels,
2193 gutter_width: Pixels,
2194 em_width: Pixels,
2195 text_x: Pixels,
2196 line_height: Pixels,
2197 style: &EditorStyle,
2198 line_layouts: &[LineWithInvisibles],
2199 editor: &mut Editor,
2200 cx: &mut ViewContext<Editor>,
2201 ) -> (Pixels, Vec<BlockLayout>) {
2202 let mut block_id = 0;
2203 let (fixed_blocks, non_fixed_blocks) = snapshot
2204 .blocks_in_range(rows.clone())
2205 .partition::<Vec<_>, _>(|(_, block)| match block {
2206 TransformBlock::ExcerptHeader { .. } => false,
2207 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
2208 });
2209
2210 let render_block = |block: &TransformBlock,
2211 available_space: Size<AvailableSpace>,
2212 block_id: usize,
2213 editor: &mut Editor,
2214 cx: &mut ViewContext<Editor>| {
2215 let mut element = match block {
2216 TransformBlock::Custom(block) => {
2217 let align_to = block
2218 .position()
2219 .to_point(&snapshot.buffer_snapshot)
2220 .to_display_point(snapshot);
2221 let anchor_x = text_x
2222 + if rows.contains(&align_to.row()) {
2223 line_layouts[(align_to.row() - rows.start) as usize]
2224 .line
2225 .x_for_index(align_to.column() as usize)
2226 } else {
2227 layout_line(align_to.row(), snapshot, style, cx)
2228 .unwrap()
2229 .x_for_index(align_to.column() as usize)
2230 };
2231
2232 block.render(&mut BlockContext {
2233 view_context: cx,
2234 anchor_x,
2235 gutter_padding,
2236 line_height,
2237 gutter_width,
2238 em_width,
2239 block_id,
2240 editor_style: &self.style,
2241 })
2242 }
2243
2244 TransformBlock::ExcerptHeader {
2245 buffer,
2246 range,
2247 starts_new_buffer,
2248 ..
2249 } => {
2250 let include_root = editor
2251 .project
2252 .as_ref()
2253 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2254 .unwrap_or_default();
2255
2256 let jump_handler = project::File::from_dyn(buffer.file()).map(|file| {
2257 let jump_path = ProjectPath {
2258 worktree_id: file.worktree_id(cx),
2259 path: file.path.clone(),
2260 };
2261 let jump_anchor = range
2262 .primary
2263 .as_ref()
2264 .map_or(range.context.start, |primary| primary.start);
2265 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2266
2267 let jump_handler = cx.listener_for(&self.editor, move |editor, _, cx| {
2268 editor.jump(jump_path.clone(), jump_position, jump_anchor, cx);
2269 });
2270
2271 jump_handler
2272 });
2273
2274 let element = if *starts_new_buffer {
2275 let path = buffer.resolve_file_path(cx, include_root);
2276 let mut filename = None;
2277 let mut parent_path = None;
2278 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2279 if let Some(path) = path {
2280 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2281 parent_path = path
2282 .parent()
2283 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2284 }
2285
2286 div()
2287 .id(("path header container", block_id))
2288 .size_full()
2289 .p_1p5()
2290 .child(
2291 h_stack()
2292 .id("path header block")
2293 .py_1p5()
2294 .pl_3()
2295 .pr_2()
2296 .rounded_lg()
2297 .shadow_md()
2298 .border()
2299 .border_color(cx.theme().colors().border)
2300 .bg(cx.theme().colors().editor_subheader_background)
2301 .justify_between()
2302 .hover(|style| style.bg(cx.theme().colors().element_hover))
2303 .child(
2304 h_stack().gap_3().child(
2305 h_stack()
2306 .gap_2()
2307 .child(
2308 filename
2309 .map(SharedString::from)
2310 .unwrap_or_else(|| "untitled".into()),
2311 )
2312 .when_some(parent_path, |then, path| {
2313 then.child(
2314 div().child(path).text_color(
2315 cx.theme().colors().text_muted,
2316 ),
2317 )
2318 }),
2319 ),
2320 )
2321 .when_some(jump_handler, |this, jump_handler| {
2322 this.cursor_pointer()
2323 .tooltip(|cx| {
2324 Tooltip::for_action(
2325 "Jump to Buffer",
2326 &OpenExcerpts,
2327 cx,
2328 )
2329 })
2330 .on_mouse_down(MouseButton::Left, |_, cx| {
2331 cx.stop_propagation()
2332 })
2333 .on_click(jump_handler)
2334 }),
2335 )
2336 } else {
2337 h_stack()
2338 .id(("collapsed context", block_id))
2339 .size_full()
2340 .gap(gutter_padding)
2341 .child(
2342 h_stack()
2343 .justify_end()
2344 .flex_none()
2345 .w(gutter_width - gutter_padding)
2346 .h_full()
2347 .text_buffer(cx)
2348 .text_color(cx.theme().colors().editor_line_number)
2349 .child("..."),
2350 )
2351 .map(|this| {
2352 if let Some(jump_handler) = jump_handler {
2353 this.child(
2354 ButtonLike::new("jump to collapsed context")
2355 .style(ButtonStyle::Transparent)
2356 .full_width()
2357 .on_click(jump_handler)
2358 .tooltip(|cx| {
2359 Tooltip::for_action(
2360 "Jump to Buffer",
2361 &OpenExcerpts,
2362 cx,
2363 )
2364 })
2365 .child(
2366 div()
2367 .h_px()
2368 .w_full()
2369 .bg(cx.theme().colors().border_variant)
2370 .group_hover("", |style| {
2371 style.bg(cx.theme().colors().border)
2372 }),
2373 ),
2374 )
2375 } else {
2376 this.child(div().size_full().bg(gpui::green()))
2377 }
2378 })
2379 };
2380 element.into_any()
2381 }
2382 };
2383
2384 let size = element.measure(available_space, cx);
2385 (element, size)
2386 };
2387
2388 let mut fixed_block_max_width = Pixels::ZERO;
2389 let mut blocks = Vec::new();
2390 for (row, block) in fixed_blocks {
2391 let available_space = size(
2392 AvailableSpace::MinContent,
2393 AvailableSpace::Definite(block.height() as f32 * line_height),
2394 );
2395 let (element, element_size) =
2396 render_block(block, available_space, block_id, editor, cx);
2397 block_id += 1;
2398 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2399 blocks.push(BlockLayout {
2400 row,
2401 element,
2402 available_space,
2403 style: BlockStyle::Fixed,
2404 });
2405 }
2406 for (row, block) in non_fixed_blocks {
2407 let style = match block {
2408 TransformBlock::Custom(block) => block.style(),
2409 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2410 };
2411 let width = match style {
2412 BlockStyle::Sticky => editor_width,
2413 BlockStyle::Flex => editor_width
2414 .max(fixed_block_max_width)
2415 .max(gutter_width + scroll_width),
2416 BlockStyle::Fixed => unreachable!(),
2417 };
2418 let available_space = size(
2419 AvailableSpace::Definite(width),
2420 AvailableSpace::Definite(block.height() as f32 * line_height),
2421 );
2422 let (element, _) = render_block(block, available_space, block_id, editor, cx);
2423 block_id += 1;
2424 blocks.push(BlockLayout {
2425 row,
2426 element,
2427 available_space,
2428 style,
2429 });
2430 }
2431 (
2432 scroll_width.max(fixed_block_max_width - gutter_width),
2433 blocks,
2434 )
2435 }
2436
2437 fn paint_scroll_wheel_listener(
2438 &mut self,
2439 interactive_bounds: &InteractiveBounds,
2440 layout: &LayoutState,
2441 cx: &mut WindowContext,
2442 ) {
2443 cx.on_mouse_event({
2444 let position_map = layout.position_map.clone();
2445 let editor = self.editor.clone();
2446 let interactive_bounds = interactive_bounds.clone();
2447 let mut delta = ScrollDelta::default();
2448
2449 move |event: &ScrollWheelEvent, phase, cx| {
2450 if phase == DispatchPhase::Bubble
2451 && interactive_bounds.visibly_contains(&event.position, cx)
2452 {
2453 delta = delta.coalesce(event.delta);
2454 editor.update(cx, |editor, cx| {
2455 let position = event.position;
2456 let position_map: &PositionMap = &position_map;
2457 let bounds = &interactive_bounds;
2458 if !bounds.visibly_contains(&position, cx) {
2459 return;
2460 }
2461
2462 let line_height = position_map.line_height;
2463 let max_glyph_width = position_map.em_width;
2464 let (delta, axis) = match delta {
2465 gpui::ScrollDelta::Pixels(mut pixels) => {
2466 //Trackpad
2467 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2468 (pixels, axis)
2469 }
2470
2471 gpui::ScrollDelta::Lines(lines) => {
2472 //Not trackpad
2473 let pixels =
2474 point(lines.x * max_glyph_width, lines.y * line_height);
2475 (pixels, None)
2476 }
2477 };
2478
2479 let scroll_position = position_map.snapshot.scroll_position();
2480 let x = f32::from(
2481 (scroll_position.x * max_glyph_width - delta.x) / max_glyph_width,
2482 );
2483 let y =
2484 f32::from((scroll_position.y * line_height - delta.y) / line_height);
2485 let scroll_position =
2486 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2487 editor.scroll(scroll_position, axis, cx);
2488 cx.stop_propagation();
2489 });
2490 }
2491 }
2492 });
2493 }
2494
2495 fn paint_mouse_listeners(
2496 &mut self,
2497 bounds: Bounds<Pixels>,
2498 gutter_bounds: Bounds<Pixels>,
2499 text_bounds: Bounds<Pixels>,
2500 layout: &LayoutState,
2501 cx: &mut WindowContext,
2502 ) {
2503 let interactive_bounds = InteractiveBounds {
2504 bounds: bounds.intersect(&cx.content_mask().bounds),
2505 stacking_order: cx.stacking_order().clone(),
2506 };
2507
2508 self.paint_scroll_wheel_listener(&interactive_bounds, layout, cx);
2509
2510 cx.on_mouse_event({
2511 let position_map = layout.position_map.clone();
2512 let editor = self.editor.clone();
2513 let stacking_order = cx.stacking_order().clone();
2514 let interactive_bounds = interactive_bounds.clone();
2515
2516 move |event: &MouseDownEvent, phase, cx| {
2517 if phase == DispatchPhase::Bubble
2518 && interactive_bounds.visibly_contains(&event.position, cx)
2519 {
2520 match event.button {
2521 MouseButton::Left => editor.update(cx, |editor, cx| {
2522 Self::mouse_left_down(
2523 editor,
2524 event,
2525 &position_map,
2526 text_bounds,
2527 gutter_bounds,
2528 &stacking_order,
2529 cx,
2530 );
2531 }),
2532 MouseButton::Right => editor.update(cx, |editor, cx| {
2533 Self::mouse_right_down(editor, event, &position_map, text_bounds, cx);
2534 }),
2535 _ => {}
2536 };
2537 }
2538 }
2539 });
2540
2541 cx.on_mouse_event({
2542 let position_map = layout.position_map.clone();
2543 let editor = self.editor.clone();
2544 let stacking_order = cx.stacking_order().clone();
2545 let interactive_bounds = interactive_bounds.clone();
2546
2547 move |event: &MouseUpEvent, phase, cx| {
2548 if phase == DispatchPhase::Bubble
2549 && interactive_bounds.visibly_contains(&event.position, cx)
2550 {
2551 editor.update(cx, |editor, cx| {
2552 Self::mouse_up(
2553 editor,
2554 event,
2555 &position_map,
2556 text_bounds,
2557 &stacking_order,
2558 cx,
2559 )
2560 });
2561 }
2562 }
2563 });
2564 cx.on_mouse_event({
2565 let position_map = layout.position_map.clone();
2566 let editor = self.editor.clone();
2567 let stacking_order = cx.stacking_order().clone();
2568
2569 move |event: &MouseMoveEvent, phase, cx| {
2570 // if editor.has_pending_selection() && event.pressed_button == Some(MouseButton::Left) {
2571
2572 if phase == DispatchPhase::Bubble {
2573 editor.update(cx, |editor, cx| {
2574 if event.pressed_button == Some(MouseButton::Left) {
2575 Self::mouse_dragged(
2576 editor,
2577 event,
2578 &position_map,
2579 text_bounds,
2580 gutter_bounds,
2581 &stacking_order,
2582 cx,
2583 )
2584 }
2585
2586 if interactive_bounds.visibly_contains(&event.position, cx) {
2587 Self::mouse_moved(
2588 editor,
2589 event,
2590 &position_map,
2591 text_bounds,
2592 gutter_bounds,
2593 &stacking_order,
2594 cx,
2595 )
2596 }
2597 });
2598 }
2599 }
2600 });
2601 }
2602}
2603
2604#[derive(Debug)]
2605pub struct LineWithInvisibles {
2606 pub line: ShapedLine,
2607 invisibles: Vec<Invisible>,
2608}
2609
2610impl LineWithInvisibles {
2611 fn from_chunks<'a>(
2612 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2613 text_style: &TextStyle,
2614 max_line_len: usize,
2615 max_line_count: usize,
2616 line_number_layouts: &[Option<ShapedLine>],
2617 editor_mode: EditorMode,
2618 cx: &WindowContext,
2619 ) -> Vec<Self> {
2620 let mut layouts = Vec::with_capacity(max_line_count);
2621 let mut line = String::new();
2622 let mut invisibles = Vec::new();
2623 let mut styles = Vec::new();
2624 let mut non_whitespace_added = false;
2625 let mut row = 0;
2626 let mut line_exceeded_max_len = false;
2627 let font_size = text_style.font_size.to_pixels(cx.rem_size());
2628
2629 for highlighted_chunk in chunks.chain([HighlightedChunk {
2630 chunk: "\n",
2631 style: None,
2632 is_tab: false,
2633 }]) {
2634 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2635 if ix > 0 {
2636 let shaped_line = cx
2637 .text_system()
2638 .shape_line(line.clone().into(), font_size, &styles)
2639 .unwrap();
2640 layouts.push(Self {
2641 line: shaped_line,
2642 invisibles: invisibles.drain(..).collect(),
2643 });
2644
2645 line.clear();
2646 styles.clear();
2647 row += 1;
2648 line_exceeded_max_len = false;
2649 non_whitespace_added = false;
2650 if row == max_line_count {
2651 return layouts;
2652 }
2653 }
2654
2655 if !line_chunk.is_empty() && !line_exceeded_max_len {
2656 let text_style = if let Some(style) = highlighted_chunk.style {
2657 Cow::Owned(text_style.clone().highlight(style))
2658 } else {
2659 Cow::Borrowed(text_style)
2660 };
2661
2662 if line.len() + line_chunk.len() > max_line_len {
2663 let mut chunk_len = max_line_len - line.len();
2664 while !line_chunk.is_char_boundary(chunk_len) {
2665 chunk_len -= 1;
2666 }
2667 line_chunk = &line_chunk[..chunk_len];
2668 line_exceeded_max_len = true;
2669 }
2670
2671 styles.push(TextRun {
2672 len: line_chunk.len(),
2673 font: text_style.font(),
2674 color: text_style.color,
2675 background_color: text_style.background_color,
2676 underline: text_style.underline,
2677 });
2678
2679 if editor_mode == EditorMode::Full {
2680 // Line wrap pads its contents with fake whitespaces,
2681 // avoid printing them
2682 let inside_wrapped_string = line_number_layouts
2683 .get(row)
2684 .and_then(|layout| layout.as_ref())
2685 .is_none();
2686 if highlighted_chunk.is_tab {
2687 if non_whitespace_added || !inside_wrapped_string {
2688 invisibles.push(Invisible::Tab {
2689 line_start_offset: line.len(),
2690 });
2691 }
2692 } else {
2693 invisibles.extend(
2694 line_chunk
2695 .chars()
2696 .enumerate()
2697 .filter(|(_, line_char)| {
2698 let is_whitespace = line_char.is_whitespace();
2699 non_whitespace_added |= !is_whitespace;
2700 is_whitespace
2701 && (non_whitespace_added || !inside_wrapped_string)
2702 })
2703 .map(|(whitespace_index, _)| Invisible::Whitespace {
2704 line_offset: line.len() + whitespace_index,
2705 }),
2706 )
2707 }
2708 }
2709
2710 line.push_str(line_chunk);
2711 }
2712 }
2713 }
2714
2715 layouts
2716 }
2717
2718 fn draw(
2719 &self,
2720 layout: &LayoutState,
2721 row: u32,
2722 content_origin: gpui::Point<Pixels>,
2723 whitespace_setting: ShowWhitespaceSetting,
2724 selection_ranges: &[Range<DisplayPoint>],
2725 cx: &mut WindowContext,
2726 ) {
2727 let line_height = layout.position_map.line_height;
2728 let line_y = line_height * row as f32 - layout.position_map.scroll_position.y;
2729
2730 self.line
2731 .paint(
2732 content_origin + gpui::point(-layout.position_map.scroll_position.x, line_y),
2733 line_height,
2734 cx,
2735 )
2736 .log_err();
2737
2738 self.draw_invisibles(
2739 &selection_ranges,
2740 layout,
2741 content_origin,
2742 line_y,
2743 row,
2744 line_height,
2745 whitespace_setting,
2746 cx,
2747 );
2748 }
2749
2750 fn draw_invisibles(
2751 &self,
2752 selection_ranges: &[Range<DisplayPoint>],
2753 layout: &LayoutState,
2754 content_origin: gpui::Point<Pixels>,
2755 line_y: Pixels,
2756 row: u32,
2757 line_height: Pixels,
2758 whitespace_setting: ShowWhitespaceSetting,
2759 cx: &mut WindowContext,
2760 ) {
2761 let allowed_invisibles_regions = match whitespace_setting {
2762 ShowWhitespaceSetting::None => return,
2763 ShowWhitespaceSetting::Selection => Some(selection_ranges),
2764 ShowWhitespaceSetting::All => None,
2765 };
2766
2767 for invisible in &self.invisibles {
2768 let (&token_offset, invisible_symbol) = match invisible {
2769 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2770 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2771 };
2772
2773 let x_offset = self.line.x_for_index(token_offset);
2774 let invisible_offset =
2775 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2776 let origin = content_origin
2777 + gpui::point(
2778 x_offset + invisible_offset - layout.position_map.scroll_position.x,
2779 line_y,
2780 );
2781
2782 if let Some(allowed_regions) = allowed_invisibles_regions {
2783 let invisible_point = DisplayPoint::new(row, token_offset as u32);
2784 if !allowed_regions
2785 .iter()
2786 .any(|region| region.start <= invisible_point && invisible_point < region.end)
2787 {
2788 continue;
2789 }
2790 }
2791 invisible_symbol.paint(origin, line_height, cx).log_err();
2792 }
2793 }
2794}
2795
2796#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2797enum Invisible {
2798 Tab { line_start_offset: usize },
2799 Whitespace { line_offset: usize },
2800}
2801
2802impl Element for EditorElement {
2803 type State = ();
2804
2805 fn request_layout(
2806 &mut self,
2807 _element_state: Option<Self::State>,
2808 cx: &mut gpui::WindowContext,
2809 ) -> (gpui::LayoutId, Self::State) {
2810 self.editor.update(cx, |editor, cx| {
2811 editor.set_style(self.style.clone(), cx);
2812
2813 let layout_id = match editor.mode {
2814 EditorMode::SingleLine => {
2815 let rem_size = cx.rem_size();
2816 let mut style = Style::default();
2817 style.size.width = relative(1.).into();
2818 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
2819 cx.request_layout(&style, None)
2820 }
2821 EditorMode::AutoHeight { max_lines } => {
2822 let editor_handle = cx.view().clone();
2823 let max_line_number_width =
2824 self.max_line_number_width(&editor.snapshot(cx), cx);
2825 cx.request_measured_layout(Style::default(), move |known_dimensions, _, cx| {
2826 editor_handle
2827 .update(cx, |editor, cx| {
2828 compute_auto_height_layout(
2829 editor,
2830 max_lines,
2831 max_line_number_width,
2832 known_dimensions,
2833 cx,
2834 )
2835 })
2836 .unwrap_or_default()
2837 })
2838 }
2839 EditorMode::Full => {
2840 let mut style = Style::default();
2841 style.size.width = relative(1.).into();
2842 style.size.height = relative(1.).into();
2843 cx.request_layout(&style, None)
2844 }
2845 };
2846
2847 (layout_id, ())
2848 })
2849 }
2850
2851 fn paint(
2852 &mut self,
2853 bounds: Bounds<gpui::Pixels>,
2854 _element_state: &mut Self::State,
2855 cx: &mut gpui::WindowContext,
2856 ) {
2857 let editor = self.editor.clone();
2858
2859 cx.with_text_style(
2860 Some(gpui::TextStyleRefinement {
2861 font_size: Some(self.style.text.font_size),
2862 ..Default::default()
2863 }),
2864 |cx| {
2865 let mut layout = self.compute_layout(bounds, cx);
2866 let gutter_bounds = Bounds {
2867 origin: bounds.origin,
2868 size: layout.gutter_size,
2869 };
2870 let text_bounds = Bounds {
2871 origin: gutter_bounds.upper_right(),
2872 size: layout.text_size,
2873 };
2874
2875 let focus_handle = editor.focus_handle(cx);
2876 let key_context = self.editor.read(cx).key_context(cx);
2877 cx.with_key_dispatch(Some(key_context), Some(focus_handle.clone()), |_, cx| {
2878 self.register_actions(cx);
2879 self.register_key_listeners(cx);
2880
2881 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
2882 let input_handler =
2883 ElementInputHandler::new(bounds, self.editor.clone(), cx);
2884 cx.handle_input(&focus_handle, input_handler);
2885
2886 self.paint_background(gutter_bounds, text_bounds, &layout, cx);
2887 if layout.gutter_size.width > Pixels::ZERO {
2888 self.paint_gutter(gutter_bounds, &mut layout, cx);
2889 }
2890 self.paint_text(text_bounds, &mut layout, cx);
2891
2892 cx.with_z_index(0, |cx| {
2893 self.paint_mouse_listeners(
2894 bounds,
2895 gutter_bounds,
2896 text_bounds,
2897 &layout,
2898 cx,
2899 );
2900 });
2901 if !layout.blocks.is_empty() {
2902 cx.with_z_index(0, |cx| {
2903 cx.with_element_id(Some("editor_blocks"), |cx| {
2904 self.paint_blocks(bounds, &mut layout, cx);
2905 });
2906 })
2907 }
2908
2909 cx.with_z_index(1, |cx| {
2910 self.paint_overlays(text_bounds, &mut layout, cx);
2911 });
2912
2913 cx.with_z_index(2, |cx| self.paint_scrollbar(bounds, &mut layout, cx));
2914 });
2915 })
2916 },
2917 );
2918 }
2919}
2920
2921impl IntoElement for EditorElement {
2922 type Element = Self;
2923
2924 fn element_id(&self) -> Option<gpui::ElementId> {
2925 self.editor.element_id()
2926 }
2927
2928 fn into_element(self) -> Self::Element {
2929 self
2930 }
2931}
2932
2933type BufferRow = u32;
2934
2935pub struct LayoutState {
2936 position_map: Arc<PositionMap>,
2937 gutter_size: Size<Pixels>,
2938 gutter_padding: Pixels,
2939 gutter_margin: Pixels,
2940 text_size: gpui::Size<Pixels>,
2941 mode: EditorMode,
2942 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
2943 visible_anchor_range: Range<Anchor>,
2944 visible_display_row_range: Range<u32>,
2945 active_rows: BTreeMap<u32, bool>,
2946 highlighted_rows: Option<Range<u32>>,
2947 line_numbers: Vec<Option<ShapedLine>>,
2948 display_hunks: Vec<DisplayDiffHunk>,
2949 blocks: Vec<BlockLayout>,
2950 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
2951 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
2952 scrollbar_row_range: Range<f32>,
2953 show_scrollbars: bool,
2954 is_singleton: bool,
2955 max_row: u32,
2956 context_menu: Option<(DisplayPoint, AnyElement)>,
2957 code_actions_indicator: Option<CodeActionsIndicator>,
2958 hover_popovers: Option<(DisplayPoint, Vec<AnyElement>)>,
2959 fold_indicators: Vec<Option<IconButton>>,
2960 tab_invisible: ShapedLine,
2961 space_invisible: ShapedLine,
2962}
2963
2964struct CodeActionsIndicator {
2965 row: u32,
2966 button: IconButton,
2967}
2968
2969struct PositionMap {
2970 size: Size<Pixels>,
2971 line_height: Pixels,
2972 scroll_position: gpui::Point<Pixels>,
2973 scroll_max: gpui::Point<f32>,
2974 em_width: Pixels,
2975 em_advance: Pixels,
2976 line_layouts: Vec<LineWithInvisibles>,
2977 snapshot: EditorSnapshot,
2978}
2979
2980#[derive(Debug, Copy, Clone)]
2981pub struct PointForPosition {
2982 pub previous_valid: DisplayPoint,
2983 pub next_valid: DisplayPoint,
2984 pub exact_unclipped: DisplayPoint,
2985 pub column_overshoot_after_line_end: u32,
2986}
2987
2988impl PointForPosition {
2989 #[cfg(test)]
2990 pub fn valid(valid: DisplayPoint) -> Self {
2991 Self {
2992 previous_valid: valid,
2993 next_valid: valid,
2994 exact_unclipped: valid,
2995 column_overshoot_after_line_end: 0,
2996 }
2997 }
2998
2999 pub fn as_valid(&self) -> Option<DisplayPoint> {
3000 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3001 Some(self.previous_valid)
3002 } else {
3003 None
3004 }
3005 }
3006}
3007
3008impl PositionMap {
3009 fn point_for_position(
3010 &self,
3011 text_bounds: Bounds<Pixels>,
3012 position: gpui::Point<Pixels>,
3013 ) -> PointForPosition {
3014 let scroll_position = self.snapshot.scroll_position();
3015 let position = position - text_bounds.origin;
3016 let y = position.y.max(px(0.)).min(self.size.height);
3017 let x = position.x + (scroll_position.x * self.em_width);
3018 let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3019
3020 let (column, x_overshoot_after_line_end) = if let Some(line) = self
3021 .line_layouts
3022 .get(row as usize - scroll_position.y as usize)
3023 .map(|&LineWithInvisibles { ref line, .. }| line)
3024 {
3025 if let Some(ix) = line.index_for_x(x) {
3026 (ix as u32, px(0.))
3027 } else {
3028 (line.len as u32, px(0.).max(x - line.width))
3029 }
3030 } else {
3031 (0, x)
3032 };
3033
3034 let mut exact_unclipped = DisplayPoint::new(row, column);
3035 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3036 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3037
3038 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3039 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3040 PointForPosition {
3041 previous_valid,
3042 next_valid,
3043 exact_unclipped,
3044 column_overshoot_after_line_end,
3045 }
3046 }
3047}
3048
3049struct BlockLayout {
3050 row: u32,
3051 element: AnyElement,
3052 available_space: Size<AvailableSpace>,
3053 style: BlockStyle,
3054}
3055
3056fn layout_line(
3057 row: u32,
3058 snapshot: &EditorSnapshot,
3059 style: &EditorStyle,
3060 cx: &WindowContext,
3061) -> Result<ShapedLine> {
3062 let mut line = snapshot.line(row);
3063
3064 if line.len() > MAX_LINE_LEN {
3065 let mut len = MAX_LINE_LEN;
3066 while !line.is_char_boundary(len) {
3067 len -= 1;
3068 }
3069
3070 line.truncate(len);
3071 }
3072
3073 cx.text_system().shape_line(
3074 line.into(),
3075 style.text.font_size.to_pixels(cx.rem_size()),
3076 &[TextRun {
3077 len: snapshot.line_len(row) as usize,
3078 font: style.text.font(),
3079 color: Hsla::default(),
3080 background_color: None,
3081 underline: None,
3082 }],
3083 )
3084}
3085
3086#[derive(Debug)]
3087pub struct Cursor {
3088 origin: gpui::Point<Pixels>,
3089 block_width: Pixels,
3090 line_height: Pixels,
3091 color: Hsla,
3092 shape: CursorShape,
3093 block_text: Option<ShapedLine>,
3094}
3095
3096impl Cursor {
3097 pub fn new(
3098 origin: gpui::Point<Pixels>,
3099 block_width: Pixels,
3100 line_height: Pixels,
3101 color: Hsla,
3102 shape: CursorShape,
3103 block_text: Option<ShapedLine>,
3104 ) -> Cursor {
3105 Cursor {
3106 origin,
3107 block_width,
3108 line_height,
3109 color,
3110 shape,
3111 block_text,
3112 }
3113 }
3114
3115 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3116 Bounds {
3117 origin: self.origin + origin,
3118 size: size(self.block_width, self.line_height),
3119 }
3120 }
3121
3122 pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3123 let bounds = match self.shape {
3124 CursorShape::Bar => Bounds {
3125 origin: self.origin + origin,
3126 size: size(px(2.0), self.line_height),
3127 },
3128 CursorShape::Block | CursorShape::Hollow => Bounds {
3129 origin: self.origin + origin,
3130 size: size(self.block_width, self.line_height),
3131 },
3132 CursorShape::Underscore => Bounds {
3133 origin: self.origin
3134 + origin
3135 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3136 size: size(self.block_width, px(2.0)),
3137 },
3138 };
3139
3140 //Draw background or border quad
3141 let cursor = if matches!(self.shape, CursorShape::Hollow) {
3142 outline(bounds, self.color)
3143 } else {
3144 fill(bounds, self.color)
3145 };
3146
3147 cx.paint_quad(cursor);
3148
3149 if let Some(block_text) = &self.block_text {
3150 block_text
3151 .paint(self.origin + origin, self.line_height, cx)
3152 .log_err();
3153 }
3154 }
3155
3156 pub fn shape(&self) -> CursorShape {
3157 self.shape
3158 }
3159}
3160
3161#[derive(Debug)]
3162pub struct HighlightedRange {
3163 pub start_y: Pixels,
3164 pub line_height: Pixels,
3165 pub lines: Vec<HighlightedRangeLine>,
3166 pub color: Hsla,
3167 pub corner_radius: Pixels,
3168}
3169
3170#[derive(Debug)]
3171pub struct HighlightedRangeLine {
3172 pub start_x: Pixels,
3173 pub end_x: Pixels,
3174}
3175
3176impl HighlightedRange {
3177 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
3178 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3179 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3180 self.paint_lines(
3181 self.start_y + self.line_height,
3182 &self.lines[1..],
3183 bounds,
3184 cx,
3185 );
3186 } else {
3187 self.paint_lines(self.start_y, &self.lines, bounds, cx);
3188 }
3189 }
3190
3191 fn paint_lines(
3192 &self,
3193 start_y: Pixels,
3194 lines: &[HighlightedRangeLine],
3195 _bounds: Bounds<Pixels>,
3196 cx: &mut WindowContext,
3197 ) {
3198 if lines.is_empty() {
3199 return;
3200 }
3201
3202 let first_line = lines.first().unwrap();
3203 let last_line = lines.last().unwrap();
3204
3205 let first_top_left = point(first_line.start_x, start_y);
3206 let first_top_right = point(first_line.end_x, start_y);
3207
3208 let curve_height = point(Pixels::ZERO, self.corner_radius);
3209 let curve_width = |start_x: Pixels, end_x: Pixels| {
3210 let max = (end_x - start_x) / 2.;
3211 let width = if max < self.corner_radius {
3212 max
3213 } else {
3214 self.corner_radius
3215 };
3216
3217 point(width, Pixels::ZERO)
3218 };
3219
3220 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3221 let mut path = gpui::Path::new(first_top_right - top_curve_width);
3222 path.curve_to(first_top_right + curve_height, first_top_right);
3223
3224 let mut iter = lines.iter().enumerate().peekable();
3225 while let Some((ix, line)) = iter.next() {
3226 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3227
3228 if let Some((_, next_line)) = iter.peek() {
3229 let next_top_right = point(next_line.end_x, bottom_right.y);
3230
3231 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3232 Ordering::Equal => {
3233 path.line_to(bottom_right);
3234 }
3235 Ordering::Less => {
3236 let curve_width = curve_width(next_top_right.x, bottom_right.x);
3237 path.line_to(bottom_right - curve_height);
3238 if self.corner_radius > Pixels::ZERO {
3239 path.curve_to(bottom_right - curve_width, bottom_right);
3240 }
3241 path.line_to(next_top_right + curve_width);
3242 if self.corner_radius > Pixels::ZERO {
3243 path.curve_to(next_top_right + curve_height, next_top_right);
3244 }
3245 }
3246 Ordering::Greater => {
3247 let curve_width = curve_width(bottom_right.x, next_top_right.x);
3248 path.line_to(bottom_right - curve_height);
3249 if self.corner_radius > Pixels::ZERO {
3250 path.curve_to(bottom_right + curve_width, bottom_right);
3251 }
3252 path.line_to(next_top_right - curve_width);
3253 if self.corner_radius > Pixels::ZERO {
3254 path.curve_to(next_top_right + curve_height, next_top_right);
3255 }
3256 }
3257 }
3258 } else {
3259 let curve_width = curve_width(line.start_x, line.end_x);
3260 path.line_to(bottom_right - curve_height);
3261 if self.corner_radius > Pixels::ZERO {
3262 path.curve_to(bottom_right - curve_width, bottom_right);
3263 }
3264
3265 let bottom_left = point(line.start_x, bottom_right.y);
3266 path.line_to(bottom_left + curve_width);
3267 if self.corner_radius > Pixels::ZERO {
3268 path.curve_to(bottom_left - curve_height, bottom_left);
3269 }
3270 }
3271 }
3272
3273 if first_line.start_x > last_line.start_x {
3274 let curve_width = curve_width(last_line.start_x, first_line.start_x);
3275 let second_top_left = point(last_line.start_x, start_y + self.line_height);
3276 path.line_to(second_top_left + curve_height);
3277 if self.corner_radius > Pixels::ZERO {
3278 path.curve_to(second_top_left + curve_width, second_top_left);
3279 }
3280 let first_bottom_left = point(first_line.start_x, second_top_left.y);
3281 path.line_to(first_bottom_left - curve_width);
3282 if self.corner_radius > Pixels::ZERO {
3283 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3284 }
3285 }
3286
3287 path.line_to(first_top_left + curve_height);
3288 if self.corner_radius > Pixels::ZERO {
3289 path.curve_to(first_top_left + top_curve_width, first_top_left);
3290 }
3291 path.line_to(first_top_right - top_curve_width);
3292
3293 cx.paint_path(path, self.color);
3294 }
3295}
3296
3297pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3298 (delta.pow(1.5) / 100.0).into()
3299}
3300
3301fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3302 (delta.pow(1.2) / 300.0).into()
3303}
3304
3305#[cfg(test)]
3306mod tests {
3307 use super::*;
3308 use crate::{
3309 display_map::{BlockDisposition, BlockProperties},
3310 editor_tests::{init_test, update_test_language_settings},
3311 Editor, MultiBuffer,
3312 };
3313 use gpui::TestAppContext;
3314 use language::language_settings;
3315 use log::info;
3316 use std::{num::NonZeroU32, sync::Arc};
3317 use util::test::sample_text;
3318
3319 #[gpui::test]
3320 fn test_shape_line_numbers(cx: &mut TestAppContext) {
3321 init_test(cx, |_| {});
3322 let window = cx.add_window(|cx| {
3323 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3324 Editor::new(EditorMode::Full, buffer, None, cx)
3325 });
3326
3327 let editor = window.root(cx).unwrap();
3328 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3329 let element = EditorElement::new(&editor, style);
3330
3331 let layouts = window
3332 .update(cx, |editor, cx| {
3333 let snapshot = editor.snapshot(cx);
3334 element
3335 .shape_line_numbers(
3336 0..6,
3337 &Default::default(),
3338 DisplayPoint::new(0, 0),
3339 false,
3340 &snapshot,
3341 cx,
3342 )
3343 .0
3344 })
3345 .unwrap();
3346 assert_eq!(layouts.len(), 6);
3347
3348 let relative_rows = window
3349 .update(cx, |editor, cx| {
3350 let snapshot = editor.snapshot(cx);
3351 element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3352 })
3353 .unwrap();
3354 assert_eq!(relative_rows[&0], 3);
3355 assert_eq!(relative_rows[&1], 2);
3356 assert_eq!(relative_rows[&2], 1);
3357 // current line has no relative number
3358 assert_eq!(relative_rows[&4], 1);
3359 assert_eq!(relative_rows[&5], 2);
3360
3361 // works if cursor is before screen
3362 let relative_rows = window
3363 .update(cx, |editor, cx| {
3364 let snapshot = editor.snapshot(cx);
3365
3366 element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3367 })
3368 .unwrap();
3369 assert_eq!(relative_rows.len(), 3);
3370 assert_eq!(relative_rows[&3], 2);
3371 assert_eq!(relative_rows[&4], 3);
3372 assert_eq!(relative_rows[&5], 4);
3373
3374 // works if cursor is after screen
3375 let relative_rows = window
3376 .update(cx, |editor, cx| {
3377 let snapshot = editor.snapshot(cx);
3378
3379 element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3380 })
3381 .unwrap();
3382 assert_eq!(relative_rows.len(), 3);
3383 assert_eq!(relative_rows[&0], 5);
3384 assert_eq!(relative_rows[&1], 4);
3385 assert_eq!(relative_rows[&2], 3);
3386 }
3387
3388 #[gpui::test]
3389 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3390 init_test(cx, |_| {});
3391
3392 let window = cx.add_window(|cx| {
3393 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3394 Editor::new(EditorMode::Full, buffer, None, cx)
3395 });
3396 let editor = window.root(cx).unwrap();
3397 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3398 let mut element = EditorElement::new(&editor, style);
3399
3400 window
3401 .update(cx, |editor, cx| {
3402 editor.cursor_shape = CursorShape::Block;
3403 editor.change_selections(None, cx, |s| {
3404 s.select_ranges([
3405 Point::new(0, 0)..Point::new(1, 0),
3406 Point::new(3, 2)..Point::new(3, 3),
3407 Point::new(5, 6)..Point::new(6, 0),
3408 ]);
3409 });
3410 })
3411 .unwrap();
3412 let state = cx
3413 .update_window(window.into(), |_, cx| {
3414 element.compute_layout(
3415 Bounds {
3416 origin: point(px(500.), px(500.)),
3417 size: size(px(500.), px(500.)),
3418 },
3419 cx,
3420 )
3421 })
3422 .unwrap();
3423
3424 assert_eq!(state.selections.len(), 1);
3425 let local_selections = &state.selections[0].1;
3426 assert_eq!(local_selections.len(), 3);
3427 // moves cursor back one line
3428 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3429 assert_eq!(
3430 local_selections[0].range,
3431 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3432 );
3433
3434 // moves cursor back one column
3435 assert_eq!(
3436 local_selections[1].range,
3437 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3438 );
3439 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3440
3441 // leaves cursor on the max point
3442 assert_eq!(
3443 local_selections[2].range,
3444 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3445 );
3446 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3447
3448 // active lines does not include 1 (even though the range of the selection does)
3449 assert_eq!(
3450 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3451 vec![0, 3, 5, 6]
3452 );
3453
3454 // multi-buffer support
3455 // in DisplayPoint co-ordinates, this is what we're dealing with:
3456 // 0: [[file
3457 // 1: header]]
3458 // 2: aaaaaa
3459 // 3: bbbbbb
3460 // 4: cccccc
3461 // 5:
3462 // 6: ...
3463 // 7: ffffff
3464 // 8: gggggg
3465 // 9: hhhhhh
3466 // 10:
3467 // 11: [[file
3468 // 12: header]]
3469 // 13: bbbbbb
3470 // 14: cccccc
3471 // 15: dddddd
3472 let window = cx.add_window(|cx| {
3473 let buffer = MultiBuffer::build_multi(
3474 [
3475 (
3476 &(sample_text(8, 6, 'a') + "\n"),
3477 vec![
3478 Point::new(0, 0)..Point::new(3, 0),
3479 Point::new(4, 0)..Point::new(7, 0),
3480 ],
3481 ),
3482 (
3483 &(sample_text(8, 6, 'a') + "\n"),
3484 vec![Point::new(1, 0)..Point::new(3, 0)],
3485 ),
3486 ],
3487 cx,
3488 );
3489 Editor::new(EditorMode::Full, buffer, None, cx)
3490 });
3491 let editor = window.root(cx).unwrap();
3492 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3493 let mut element = EditorElement::new(&editor, style);
3494 let _state = window.update(cx, |editor, cx| {
3495 editor.cursor_shape = CursorShape::Block;
3496 editor.change_selections(None, cx, |s| {
3497 s.select_display_ranges([
3498 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3499 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3500 ]);
3501 });
3502 });
3503
3504 let state = cx
3505 .update_window(window.into(), |_, cx| {
3506 element.compute_layout(
3507 Bounds {
3508 origin: point(px(500.), px(500.)),
3509 size: size(px(500.), px(500.)),
3510 },
3511 cx,
3512 )
3513 })
3514 .unwrap();
3515 assert_eq!(state.selections.len(), 1);
3516 let local_selections = &state.selections[0].1;
3517 assert_eq!(local_selections.len(), 2);
3518
3519 // moves cursor on excerpt boundary back a line
3520 // and doesn't allow selection to bleed through
3521 assert_eq!(
3522 local_selections[0].range,
3523 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3524 );
3525 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3526 // moves cursor on buffer boundary back two lines
3527 // and doesn't allow selection to bleed through
3528 assert_eq!(
3529 local_selections[1].range,
3530 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3531 );
3532 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3533 }
3534
3535 #[gpui::test]
3536 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3537 init_test(cx, |_| {});
3538
3539 let window = cx.add_window(|cx| {
3540 let buffer = MultiBuffer::build_simple("", cx);
3541 Editor::new(EditorMode::Full, buffer, None, cx)
3542 });
3543 let editor = window.root(cx).unwrap();
3544 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3545 window
3546 .update(cx, |editor, cx| {
3547 editor.set_placeholder_text("hello", cx);
3548 editor.insert_blocks(
3549 [BlockProperties {
3550 style: BlockStyle::Fixed,
3551 disposition: BlockDisposition::Above,
3552 height: 3,
3553 position: Anchor::min(),
3554 render: Arc::new(|_| div().into_any()),
3555 }],
3556 None,
3557 cx,
3558 );
3559
3560 // Blur the editor so that it displays placeholder text.
3561 cx.blur();
3562 })
3563 .unwrap();
3564
3565 let mut element = EditorElement::new(&editor, style);
3566 let state = cx
3567 .update_window(window.into(), |_, cx| {
3568 element.compute_layout(
3569 Bounds {
3570 origin: point(px(500.), px(500.)),
3571 size: size(px(500.), px(500.)),
3572 },
3573 cx,
3574 )
3575 })
3576 .unwrap();
3577 let size = state.position_map.size;
3578
3579 assert_eq!(state.position_map.line_layouts.len(), 4);
3580 assert_eq!(
3581 state
3582 .line_numbers
3583 .iter()
3584 .map(Option::is_some)
3585 .collect::<Vec<_>>(),
3586 &[false, false, false, true]
3587 );
3588
3589 // Don't panic.
3590 let bounds = Bounds::<Pixels>::new(Default::default(), size);
3591 cx.update_window(window.into(), |_, cx| {
3592 element.paint(bounds, &mut (), cx);
3593 })
3594 .unwrap()
3595 }
3596
3597 #[gpui::test]
3598 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3599 const TAB_SIZE: u32 = 4;
3600
3601 let input_text = "\t \t|\t| a b";
3602 let expected_invisibles = vec![
3603 Invisible::Tab {
3604 line_start_offset: 0,
3605 },
3606 Invisible::Whitespace {
3607 line_offset: TAB_SIZE as usize,
3608 },
3609 Invisible::Tab {
3610 line_start_offset: TAB_SIZE as usize + 1,
3611 },
3612 Invisible::Tab {
3613 line_start_offset: TAB_SIZE as usize * 2 + 1,
3614 },
3615 Invisible::Whitespace {
3616 line_offset: TAB_SIZE as usize * 3 + 1,
3617 },
3618 Invisible::Whitespace {
3619 line_offset: TAB_SIZE as usize * 3 + 3,
3620 },
3621 ];
3622 assert_eq!(
3623 expected_invisibles.len(),
3624 input_text
3625 .chars()
3626 .filter(|initial_char| initial_char.is_whitespace())
3627 .count(),
3628 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3629 );
3630
3631 init_test(cx, |s| {
3632 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3633 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3634 });
3635
3636 let actual_invisibles =
3637 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
3638
3639 assert_eq!(expected_invisibles, actual_invisibles);
3640 }
3641
3642 #[gpui::test]
3643 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3644 init_test(cx, |s| {
3645 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3646 s.defaults.tab_size = NonZeroU32::new(4);
3647 });
3648
3649 for editor_mode_without_invisibles in [
3650 EditorMode::SingleLine,
3651 EditorMode::AutoHeight { max_lines: 100 },
3652 ] {
3653 let invisibles = collect_invisibles_from_new_editor(
3654 cx,
3655 editor_mode_without_invisibles,
3656 "\t\t\t| | a b",
3657 px(500.0),
3658 );
3659 assert!(invisibles.is_empty(),
3660 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3661 }
3662 }
3663
3664 #[gpui::test]
3665 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
3666 let tab_size = 4;
3667 let input_text = "a\tbcd ".repeat(9);
3668 let repeated_invisibles = [
3669 Invisible::Tab {
3670 line_start_offset: 1,
3671 },
3672 Invisible::Whitespace {
3673 line_offset: tab_size as usize + 3,
3674 },
3675 Invisible::Whitespace {
3676 line_offset: tab_size as usize + 4,
3677 },
3678 Invisible::Whitespace {
3679 line_offset: tab_size as usize + 5,
3680 },
3681 ];
3682 let expected_invisibles = std::iter::once(repeated_invisibles)
3683 .cycle()
3684 .take(9)
3685 .flatten()
3686 .collect::<Vec<_>>();
3687 assert_eq!(
3688 expected_invisibles.len(),
3689 input_text
3690 .chars()
3691 .filter(|initial_char| initial_char.is_whitespace())
3692 .count(),
3693 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3694 );
3695 info!("Expected invisibles: {expected_invisibles:?}");
3696
3697 init_test(cx, |_| {});
3698
3699 // Put the same string with repeating whitespace pattern into editors of various size,
3700 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
3701 let resize_step = 10.0;
3702 let mut editor_width = 200.0;
3703 while editor_width <= 1000.0 {
3704 update_test_language_settings(cx, |s| {
3705 s.defaults.tab_size = NonZeroU32::new(tab_size);
3706 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3707 s.defaults.preferred_line_length = Some(editor_width as u32);
3708 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
3709 });
3710
3711 let actual_invisibles = collect_invisibles_from_new_editor(
3712 cx,
3713 EditorMode::Full,
3714 &input_text,
3715 px(editor_width),
3716 );
3717
3718 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
3719 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
3720 let mut i = 0;
3721 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
3722 i = actual_index;
3723 match expected_invisibles.get(i) {
3724 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
3725 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
3726 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
3727 _ => {
3728 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
3729 }
3730 },
3731 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
3732 }
3733 }
3734 let missing_expected_invisibles = &expected_invisibles[i + 1..];
3735 assert!(
3736 missing_expected_invisibles.is_empty(),
3737 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
3738 );
3739
3740 editor_width += resize_step;
3741 }
3742 }
3743
3744 fn collect_invisibles_from_new_editor(
3745 cx: &mut TestAppContext,
3746 editor_mode: EditorMode,
3747 input_text: &str,
3748 editor_width: Pixels,
3749 ) -> Vec<Invisible> {
3750 info!(
3751 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
3752 editor_width.0
3753 );
3754 let window = cx.add_window(|cx| {
3755 let buffer = MultiBuffer::build_simple(&input_text, cx);
3756 Editor::new(editor_mode, buffer, None, cx)
3757 });
3758 let editor = window.root(cx).unwrap();
3759 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3760 let mut element = EditorElement::new(&editor, style);
3761 window
3762 .update(cx, |editor, cx| {
3763 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
3764 editor.set_wrap_width(Some(editor_width), cx);
3765 })
3766 .unwrap();
3767 let layout_state = cx
3768 .update_window(window.into(), |_, cx| {
3769 element.compute_layout(
3770 Bounds {
3771 origin: point(px(500.), px(500.)),
3772 size: size(px(500.), px(500.)),
3773 },
3774 cx,
3775 )
3776 })
3777 .unwrap();
3778
3779 layout_state
3780 .position_map
3781 .line_layouts
3782 .iter()
3783 .map(|line_with_invisibles| &line_with_invisibles.invisibles)
3784 .flatten()
3785 .cloned()
3786 .collect()
3787 }
3788}
3789
3790pub fn register_action<T: Action>(
3791 view: &View<Editor>,
3792 cx: &mut WindowContext,
3793 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
3794) {
3795 let view = view.clone();
3796 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
3797 let action = action.downcast_ref().unwrap();
3798 if phase == DispatchPhase::Bubble {
3799 view.update(cx, |editor, cx| {
3800 listener(editor, action, cx);
3801 })
3802 }
3803 })
3804}
3805
3806fn compute_auto_height_layout(
3807 editor: &mut Editor,
3808 max_lines: usize,
3809 max_line_number_width: Pixels,
3810 known_dimensions: Size<Option<Pixels>>,
3811 cx: &mut ViewContext<Editor>,
3812) -> Option<Size<Pixels>> {
3813 let width = known_dimensions.width?;
3814 if let Some(height) = known_dimensions.height {
3815 return Some(size(width, height));
3816 }
3817
3818 let style = editor.style.as_ref().unwrap();
3819 let font_id = cx.text_system().resolve_font(&style.text.font());
3820 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3821 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3822 let em_width = cx
3823 .text_system()
3824 .typographic_bounds(font_id, font_size, 'm')
3825 .unwrap()
3826 .size
3827 .width;
3828
3829 let mut snapshot = editor.snapshot(cx);
3830 let gutter_width;
3831 let gutter_margin;
3832 if snapshot.show_gutter {
3833 let descent = cx.text_system().descent(font_id, font_size);
3834 let gutter_padding_factor = 3.5;
3835 let gutter_padding = (em_width * gutter_padding_factor).round();
3836 gutter_width = max_line_number_width + gutter_padding * 2.0;
3837 gutter_margin = -descent;
3838 } else {
3839 gutter_width = Pixels::ZERO;
3840 gutter_margin = Pixels::ZERO;
3841 };
3842
3843 editor.gutter_width = gutter_width;
3844 let text_width = width - gutter_width;
3845 let overscroll = size(em_width, px(0.));
3846
3847 let editor_width = text_width - gutter_margin - overscroll.width - em_width;
3848 if editor.set_wrap_width(Some(editor_width), cx) {
3849 snapshot = editor.snapshot(cx);
3850 }
3851
3852 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
3853 let height = scroll_height
3854 .max(line_height)
3855 .min(line_height * max_lines as f32);
3856
3857 Some(size(width, height))
3858}