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