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