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