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