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