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