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