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