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