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