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