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