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