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