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