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