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