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 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 todo!()
1676 // size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
1677 }
1678 // todo!()
1679 // else if size.y.is_infinite() {
1680 // // size.set_y(scroll_height);
1681 // }
1682 //
1683 let gutter_size = size(gutter_width, bounds.size.height);
1684 let text_size = size(text_width, bounds.size.height);
1685
1686 let autoscroll_horizontally =
1687 editor.autoscroll_vertically(bounds.size.height, line_height, cx);
1688 let mut snapshot = editor.snapshot(cx);
1689
1690 let scroll_position = snapshot.scroll_position();
1691 // The scroll position is a fractional point, the whole number of which represents
1692 // the top of the window in terms of display rows.
1693 let start_row = scroll_position.y as u32;
1694 let height_in_lines = f32::from(bounds.size.height / line_height);
1695 let max_row = snapshot.max_point().row();
1696
1697 // Add 1 to ensure selections bleed off screen
1698 let end_row = 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
1699
1700 let start_anchor = if start_row == 0 {
1701 Anchor::min()
1702 } else {
1703 snapshot
1704 .buffer_snapshot
1705 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1706 };
1707 let end_anchor = if end_row > max_row {
1708 Anchor::max()
1709 } else {
1710 snapshot
1711 .buffer_snapshot
1712 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1713 };
1714
1715 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1716 let mut active_rows = BTreeMap::new();
1717 let mut fold_ranges = Vec::new();
1718 let is_singleton = editor.is_singleton(cx);
1719
1720 let highlighted_rows = editor.highlighted_rows();
1721 let highlighted_ranges = editor.background_highlights_in_range(
1722 start_anchor..end_anchor,
1723 &snapshot.display_snapshot,
1724 cx.theme().colors(),
1725 );
1726
1727 fold_ranges.extend(
1728 snapshot
1729 .folds_in_range(start_anchor..end_anchor)
1730 .map(|anchor| {
1731 let start = anchor.start.to_point(&snapshot.buffer_snapshot);
1732 (
1733 start.row,
1734 start.to_display_point(&snapshot.display_snapshot)
1735 ..anchor.end.to_display_point(&snapshot),
1736 )
1737 }),
1738 );
1739
1740 let mut newest_selection_head = None;
1741
1742 if editor.show_local_selections {
1743 let mut local_selections: Vec<Selection<Point>> = editor
1744 .selections
1745 .disjoint_in_range(start_anchor..end_anchor, cx);
1746 local_selections.extend(editor.selections.pending(cx));
1747 let mut layouts = Vec::new();
1748 let newest = editor.selections.newest(cx);
1749 for selection in local_selections.drain(..) {
1750 let is_empty = selection.start == selection.end;
1751 let is_newest = selection == newest;
1752
1753 let layout = SelectionLayout::new(
1754 selection,
1755 editor.selections.line_mode,
1756 editor.cursor_shape,
1757 &snapshot.display_snapshot,
1758 is_newest,
1759 true,
1760 );
1761 if is_newest {
1762 newest_selection_head = Some(layout.head);
1763 }
1764
1765 for row in cmp::max(layout.active_rows.start, start_row)
1766 ..=cmp::min(layout.active_rows.end, end_row)
1767 {
1768 let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
1769 *contains_non_empty_selection |= !is_empty;
1770 }
1771 layouts.push(layout);
1772 }
1773
1774 selections.push((style.local_player, layouts));
1775 }
1776
1777 if let Some(collaboration_hub) = &editor.collaboration_hub {
1778 // When following someone, render the local selections in their color.
1779 if let Some(leader_id) = editor.leader_peer_id {
1780 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
1781 if let Some(participant_index) = collaboration_hub
1782 .user_participant_indices(cx)
1783 .get(&collaborator.user_id)
1784 {
1785 if let Some((local_selection_style, _)) = selections.first_mut() {
1786 *local_selection_style = cx
1787 .theme()
1788 .players()
1789 .color_for_participant(participant_index.0);
1790 }
1791 }
1792 }
1793 }
1794
1795 let mut remote_selections = HashMap::default();
1796 for selection in snapshot.remote_selections_in_range(
1797 &(start_anchor..end_anchor),
1798 collaboration_hub.as_ref(),
1799 cx,
1800 ) {
1801 let selection_style = if let Some(participant_index) = selection.participant_index {
1802 cx.theme()
1803 .players()
1804 .color_for_participant(participant_index.0)
1805 } else {
1806 cx.theme().players().absent()
1807 };
1808
1809 // Don't re-render the leader's selections, since the local selections
1810 // match theirs.
1811 if Some(selection.peer_id) == editor.leader_peer_id {
1812 continue;
1813 }
1814
1815 remote_selections
1816 .entry(selection.replica_id)
1817 .or_insert((selection_style, Vec::new()))
1818 .1
1819 .push(SelectionLayout::new(
1820 selection.selection,
1821 selection.line_mode,
1822 selection.cursor_shape,
1823 &snapshot.display_snapshot,
1824 false,
1825 false,
1826 ));
1827 }
1828
1829 selections.extend(remote_selections.into_values());
1830 }
1831
1832 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1833 let show_scrollbars = match scrollbar_settings.show {
1834 ShowScrollbar::Auto => {
1835 // Git
1836 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1837 ||
1838 // Selections
1839 (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty())
1840 // Scrollmanager
1841 || editor.scroll_manager.scrollbars_visible()
1842 }
1843 ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
1844 ShowScrollbar::Always => true,
1845 ShowScrollbar::Never => false,
1846 };
1847
1848 let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)> = fold_ranges
1849 .into_iter()
1850 .map(|(id, fold)| {
1851 todo!("folds!")
1852 // let color = self
1853 // .style
1854 // .folds
1855 // .ellipses
1856 // .background
1857 // .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
1858 // .color;
1859
1860 // (id, fold, color)
1861 })
1862 .collect();
1863
1864 let head_for_relative = newest_selection_head.unwrap_or_else(|| {
1865 let newest = editor.selections.newest::<Point>(cx);
1866 SelectionLayout::new(
1867 newest,
1868 editor.selections.line_mode,
1869 editor.cursor_shape,
1870 &snapshot.display_snapshot,
1871 true,
1872 true,
1873 )
1874 .head
1875 });
1876
1877 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
1878 start_row..end_row,
1879 &active_rows,
1880 head_for_relative,
1881 is_singleton,
1882 &snapshot,
1883 cx,
1884 );
1885
1886 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1887
1888 let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
1889
1890 let mut max_visible_line_width = Pixels::ZERO;
1891 let line_layouts =
1892 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
1893 for line_with_invisibles in &line_layouts {
1894 if line_with_invisibles.line.width > max_visible_line_width {
1895 max_visible_line_width = line_with_invisibles.line.width;
1896 }
1897 }
1898
1899 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
1900 .unwrap()
1901 .width;
1902 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
1903 // todo!("blocks")
1904 // let (scroll_width, blocks) = self.layout_blocks(
1905 // start_row..end_row,
1906 // &snapshot,
1907 // size.x,
1908 // scroll_width,
1909 // gutter_padding,
1910 // gutter_width,
1911 // em_width,
1912 // gutter_width + gutter_margin,
1913 // line_height,
1914 // &style,
1915 // &line_layouts,
1916 // editor,
1917 // cx,
1918 // );
1919
1920 let scroll_max = point(
1921 f32::from((scroll_width - text_size.width) / em_width).max(0.0),
1922 max_row as f32,
1923 );
1924
1925 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
1926
1927 let autoscrolled = if autoscroll_horizontally {
1928 editor.autoscroll_horizontally(
1929 start_row,
1930 text_size.width,
1931 scroll_width,
1932 em_width,
1933 &line_layouts,
1934 cx,
1935 )
1936 } else {
1937 false
1938 };
1939
1940 if clamped || autoscrolled {
1941 snapshot = editor.snapshot(cx);
1942 }
1943
1944 // todo!("context menu")
1945 // let mut context_menu = None;
1946 // let mut code_actions_indicator = None;
1947 // if let Some(newest_selection_head) = newest_selection_head {
1948 // if (start_row..end_row).contains(&newest_selection_head.row()) {
1949 // if editor.context_menu_visible() {
1950 // context_menu =
1951 // editor.render_context_menu(newest_selection_head, style.clone(), cx);
1952 // }
1953
1954 // let active = matches!(
1955 // editor.context_menu.read().as_ref(),
1956 // Some(crate::ContextMenu::CodeActions(_))
1957 // );
1958
1959 // code_actions_indicator = editor
1960 // .render_code_actions_indicator(&style, active, cx)
1961 // .map(|indicator| (newest_selection_head.row(), indicator));
1962 // }
1963 // }
1964
1965 let visible_rows = start_row..start_row + line_layouts.len() as u32;
1966 // todo!("hover")
1967 // let mut hover = editor.hover_state.render(
1968 // &snapshot,
1969 // &style,
1970 // visible_rows,
1971 // editor.workspace.as_ref().map(|(w, _)| w.clone()),
1972 // cx,
1973 // );
1974 // let mode = editor.mode;
1975
1976 // todo!("fold_indicators")
1977 // let mut fold_indicators = editor.render_fold_indicators(
1978 // fold_statuses,
1979 // &style,
1980 // editor.gutter_hovered,
1981 // line_height,
1982 // gutter_margin,
1983 // cx,
1984 // );
1985
1986 // todo!("context_menu")
1987 // if let Some((_, context_menu)) = context_menu.as_mut() {
1988 // context_menu.layout(
1989 // SizeConstraint {
1990 // min: gpui::Point::<Pixels>::zero(),
1991 // max: point(
1992 // cx.window_size().x * 0.7,
1993 // (12. * line_height).min((size.y - line_height) / 2.),
1994 // ),
1995 // },
1996 // editor,
1997 // cx,
1998 // );
1999 // }
2000
2001 // todo!("code actions")
2002 // if let Some((_, indicator)) = code_actions_indicator.as_mut() {
2003 // indicator.layout(
2004 // SizeConstraint::strict_along(
2005 // Axis::Vertical,
2006 // line_height * style.code_actions.vertical_scale,
2007 // ),
2008 // editor,
2009 // cx,
2010 // );
2011 // }
2012
2013 // todo!("fold indicators")
2014 // for fold_indicator in fold_indicators.iter_mut() {
2015 // if let Some(indicator) = fold_indicator.as_mut() {
2016 // indicator.layout(
2017 // SizeConstraint::strict_along(
2018 // Axis::Vertical,
2019 // line_height * style.code_actions.vertical_scale,
2020 // ),
2021 // editor,
2022 // cx,
2023 // );
2024 // }
2025 // }
2026
2027 // todo!("hover popovers")
2028 // if let Some((_, hover_popovers)) = hover.as_mut() {
2029 // for hover_popover in hover_popovers.iter_mut() {
2030 // hover_popover.layout(
2031 // SizeConstraint {
2032 // min: gpui::Point::<Pixels>::zero(),
2033 // max: point(
2034 // (120. * em_width) // Default size
2035 // .min(size.x / 2.) // Shrink to half of the editor width
2036 // .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2037 // (16. * line_height) // Default size
2038 // .min(size.y / 2.) // Shrink to half of the editor height
2039 // .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2040 // ),
2041 // },
2042 // editor,
2043 // cx,
2044 // );
2045 // }
2046 // }
2047
2048 let invisible_symbol_font_size = font_size / 2.;
2049 let tab_invisible = cx
2050 .text_system()
2051 .layout_text(
2052 "→",
2053 invisible_symbol_font_size,
2054 &[TextRun {
2055 len: "→".len(),
2056 font: self.style.text.font(),
2057 color: cx.theme().colors().editor_invisible,
2058 underline: None,
2059 }],
2060 None,
2061 )
2062 .unwrap()
2063 .pop()
2064 .unwrap();
2065 let space_invisible = cx
2066 .text_system()
2067 .layout_text(
2068 "•",
2069 invisible_symbol_font_size,
2070 &[TextRun {
2071 len: "•".len(),
2072 font: self.style.text.font(),
2073 color: cx.theme().colors().editor_invisible,
2074 underline: None,
2075 }],
2076 None,
2077 )
2078 .unwrap()
2079 .pop()
2080 .unwrap();
2081
2082 LayoutState {
2083 mode: editor_mode,
2084 position_map: Arc::new(PositionMap {
2085 size: bounds.size,
2086 scroll_max,
2087 line_layouts,
2088 line_height,
2089 em_width,
2090 em_advance,
2091 snapshot,
2092 }),
2093 visible_display_row_range: start_row..end_row,
2094 wrap_guides,
2095 gutter_size,
2096 gutter_padding,
2097 text_size,
2098 scrollbar_row_range,
2099 show_scrollbars,
2100 is_singleton,
2101 max_row,
2102 gutter_margin,
2103 active_rows,
2104 highlighted_rows,
2105 highlighted_ranges,
2106 fold_ranges,
2107 line_number_layouts,
2108 display_hunks,
2109 // blocks,
2110 selections,
2111 // context_menu,
2112 // code_actions_indicator,
2113 // fold_indicators,
2114 tab_invisible,
2115 space_invisible,
2116 // hover_popovers: hover,
2117 }
2118 }
2119
2120 // #[allow(clippy::too_many_arguments)]
2121 // fn layout_blocks(
2122 // &mut self,
2123 // rows: Range<u32>,
2124 // snapshot: &EditorSnapshot,
2125 // editor_width: f32,
2126 // scroll_width: f32,
2127 // gutter_padding: f32,
2128 // gutter_width: f32,
2129 // em_width: f32,
2130 // text_x: f32,
2131 // line_height: f32,
2132 // style: &EditorStyle,
2133 // line_layouts: &[LineWithInvisibles],
2134 // editor: &mut Editor,
2135 // cx: &mut ViewContext<Editor>,
2136 // ) -> (f32, Vec<BlockLayout>) {
2137 // let mut block_id = 0;
2138 // let scroll_x = snapshot.scroll_anchor.offset.x;
2139 // let (fixed_blocks, non_fixed_blocks) = snapshot
2140 // .blocks_in_range(rows.clone())
2141 // .partition::<Vec<_>, _>(|(_, block)| match block {
2142 // TransformBlock::ExcerptHeader { .. } => false,
2143 // TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
2144 // });
2145 // let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
2146 // let mut element = match block {
2147 // TransformBlock::Custom(block) => {
2148 // let align_to = block
2149 // .position()
2150 // .to_point(&snapshot.buffer_snapshot)
2151 // .to_display_point(snapshot);
2152 // let anchor_x = text_x
2153 // + if rows.contains(&align_to.row()) {
2154 // line_layouts[(align_to.row() - rows.start) as usize]
2155 // .line
2156 // .x_for_index(align_to.column() as usize)
2157 // } else {
2158 // layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
2159 // .x_for_index(align_to.column() as usize)
2160 // };
2161
2162 // block.render(&mut BlockContext {
2163 // view_context: cx,
2164 // anchor_x,
2165 // gutter_padding,
2166 // line_height,
2167 // scroll_x,
2168 // gutter_width,
2169 // em_width,
2170 // block_id,
2171 // })
2172 // }
2173 // TransformBlock::ExcerptHeader {
2174 // id,
2175 // buffer,
2176 // range,
2177 // starts_new_buffer,
2178 // ..
2179 // } => {
2180 // let tooltip_style = theme::current(cx).tooltip.clone();
2181 // let include_root = editor
2182 // .project
2183 // .as_ref()
2184 // .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2185 // .unwrap_or_default();
2186 // let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
2187 // let jump_path = ProjectPath {
2188 // worktree_id: file.worktree_id(cx),
2189 // path: file.path.clone(),
2190 // };
2191 // let jump_anchor = range
2192 // .primary
2193 // .as_ref()
2194 // .map_or(range.context.start, |primary| primary.start);
2195 // let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2196
2197 // enum JumpIcon {}
2198 // MouseEventHandler::new::<JumpIcon, _>((*id).into(), cx, |state, _| {
2199 // let style = style.jump_icon.style_for(state);
2200 // Svg::new("icons/arrow_up_right.svg")
2201 // .with_color(style.color)
2202 // .constrained()
2203 // .with_width(style.icon_width)
2204 // .aligned()
2205 // .contained()
2206 // .with_style(style.container)
2207 // .constrained()
2208 // .with_width(style.button_width)
2209 // .with_height(style.button_width)
2210 // })
2211 // .with_cursor_style(CursorStyle::PointingHand)
2212 // .on_click(MouseButton::Left, move |_, editor, cx| {
2213 // if let Some(workspace) = editor
2214 // .workspace
2215 // .as_ref()
2216 // .and_then(|(workspace, _)| workspace.upgrade(cx))
2217 // {
2218 // workspace.update(cx, |workspace, cx| {
2219 // Editor::jump(
2220 // workspace,
2221 // jump_path.clone(),
2222 // jump_position,
2223 // jump_anchor,
2224 // cx,
2225 // );
2226 // });
2227 // }
2228 // })
2229 // .with_tooltip::<JumpIcon>(
2230 // (*id).into(),
2231 // "Jump to Buffer".to_string(),
2232 // Some(Box::new(crate::OpenExcerpts)),
2233 // tooltip_style.clone(),
2234 // cx,
2235 // )
2236 // .aligned()
2237 // .flex_float()
2238 // });
2239
2240 // if *starts_new_buffer {
2241 // let editor_font_size = style.text.font_size;
2242 // let style = &style.diagnostic_path_header;
2243 // let font_size = (style.text_scale_factor * editor_font_size).round();
2244
2245 // let path = buffer.resolve_file_path(cx, include_root);
2246 // let mut filename = None;
2247 // let mut parent_path = None;
2248 // // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2249 // if let Some(path) = path {
2250 // filename = path.file_name().map(|f| f.to_string_lossy.to_string());
2251 // parent_path =
2252 // path.parent().map(|p| p.to_string_lossy.to_string() + "/");
2253 // }
2254
2255 // Flex::row()
2256 // .with_child(
2257 // Label::new(
2258 // filename.unwrap_or_else(|| "untitled".to_string()),
2259 // style.filename.text.clone().with_font_size(font_size),
2260 // )
2261 // .contained()
2262 // .with_style(style.filename.container)
2263 // .aligned(),
2264 // )
2265 // .with_children(parent_path.map(|path| {
2266 // Label::new(path, style.path.text.clone().with_font_size(font_size))
2267 // .contained()
2268 // .with_style(style.path.container)
2269 // .aligned()
2270 // }))
2271 // .with_children(jump_icon)
2272 // .contained()
2273 // .with_style(style.container)
2274 // .with_padding_left(gutter_padding)
2275 // .with_padding_right(gutter_padding)
2276 // .expanded()
2277 // .into_any_named("path header block")
2278 // } else {
2279 // let text_style = style.text.clone();
2280 // Flex::row()
2281 // .with_child(Label::new("⋯", text_style))
2282 // .with_children(jump_icon)
2283 // .contained()
2284 // .with_padding_left(gutter_padding)
2285 // .with_padding_right(gutter_padding)
2286 // .expanded()
2287 // .into_any_named("collapsed context")
2288 // }
2289 // }
2290 // };
2291
2292 // element.layout(
2293 // SizeConstraint {
2294 // min: gpui::Point::<Pixels>::zero(),
2295 // max: point(width, block.height() as f32 * line_height),
2296 // },
2297 // editor,
2298 // cx,
2299 // );
2300 // element
2301 // };
2302
2303 // let mut fixed_block_max_width = 0f32;
2304 // let mut blocks = Vec::new();
2305 // for (row, block) in fixed_blocks {
2306 // let element = render_block(block, f32::INFINITY, block_id);
2307 // block_id += 1;
2308 // fixed_block_max_width = fixed_block_max_width.max(element.size().x + em_width);
2309 // blocks.push(BlockLayout {
2310 // row,
2311 // element,
2312 // style: BlockStyle::Fixed,
2313 // });
2314 // }
2315 // for (row, block) in non_fixed_blocks {
2316 // let style = match block {
2317 // TransformBlock::Custom(block) => block.style(),
2318 // TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2319 // };
2320 // let width = match style {
2321 // BlockStyle::Sticky => editor_width,
2322 // BlockStyle::Flex => editor_width
2323 // .max(fixed_block_max_width)
2324 // .max(gutter_width + scroll_width),
2325 // BlockStyle::Fixed => unreachable!(),
2326 // };
2327 // let element = render_block(block, width, block_id);
2328 // block_id += 1;
2329 // blocks.push(BlockLayout {
2330 // row,
2331 // element,
2332 // style,
2333 // });
2334 // }
2335 // (
2336 // scroll_width.max(fixed_block_max_width - gutter_width),
2337 // blocks,
2338 // )
2339 // }
2340}
2341
2342#[derive(Debug)]
2343pub struct LineWithInvisibles {
2344 pub line: Line,
2345 invisibles: Vec<Invisible>,
2346}
2347
2348impl LineWithInvisibles {
2349 fn from_chunks<'a>(
2350 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2351 text_style: &TextStyle,
2352 max_line_len: usize,
2353 max_line_count: usize,
2354 line_number_layouts: &[Option<Line>],
2355 editor_mode: EditorMode,
2356 cx: &WindowContext,
2357 ) -> Vec<Self> {
2358 let mut layouts = Vec::with_capacity(max_line_count);
2359 let mut line = String::new();
2360 let mut invisibles = Vec::new();
2361 let mut styles = Vec::new();
2362 let mut non_whitespace_added = false;
2363 let mut row = 0;
2364 let mut line_exceeded_max_len = false;
2365 let font_size = text_style.font_size.to_pixels(cx.rem_size());
2366
2367 for highlighted_chunk in chunks.chain([HighlightedChunk {
2368 chunk: "\n",
2369 style: None,
2370 is_tab: false,
2371 }]) {
2372 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2373 if ix > 0 {
2374 let layout = cx
2375 .text_system()
2376 .layout_text(&line, font_size, &styles, None);
2377 layouts.push(Self {
2378 line: layout.unwrap().pop().unwrap(),
2379 invisibles: invisibles.drain(..).collect(),
2380 });
2381
2382 line.clear();
2383 styles.clear();
2384 row += 1;
2385 line_exceeded_max_len = false;
2386 non_whitespace_added = false;
2387 if row == max_line_count {
2388 return layouts;
2389 }
2390 }
2391
2392 if !line_chunk.is_empty() && !line_exceeded_max_len {
2393 let text_style = if let Some(style) = highlighted_chunk.style {
2394 text_style
2395 .clone()
2396 .highlight(style)
2397 .map(Cow::Owned)
2398 .unwrap_or_else(|_| Cow::Borrowed(text_style))
2399 } else {
2400 Cow::Borrowed(text_style)
2401 };
2402
2403 if line.len() + line_chunk.len() > max_line_len {
2404 let mut chunk_len = max_line_len - line.len();
2405 while !line_chunk.is_char_boundary(chunk_len) {
2406 chunk_len -= 1;
2407 }
2408 line_chunk = &line_chunk[..chunk_len];
2409 line_exceeded_max_len = true;
2410 }
2411
2412 styles.push(TextRun {
2413 len: line_chunk.len(),
2414 font: text_style.font(),
2415 color: text_style.color,
2416 underline: text_style.underline,
2417 });
2418
2419 if editor_mode == EditorMode::Full {
2420 // Line wrap pads its contents with fake whitespaces,
2421 // avoid printing them
2422 let inside_wrapped_string = line_number_layouts
2423 .get(row)
2424 .and_then(|layout| layout.as_ref())
2425 .is_none();
2426 if highlighted_chunk.is_tab {
2427 if non_whitespace_added || !inside_wrapped_string {
2428 invisibles.push(Invisible::Tab {
2429 line_start_offset: line.len(),
2430 });
2431 }
2432 } else {
2433 invisibles.extend(
2434 line_chunk
2435 .chars()
2436 .enumerate()
2437 .filter(|(_, line_char)| {
2438 let is_whitespace = line_char.is_whitespace();
2439 non_whitespace_added |= !is_whitespace;
2440 is_whitespace
2441 && (non_whitespace_added || !inside_wrapped_string)
2442 })
2443 .map(|(whitespace_index, _)| Invisible::Whitespace {
2444 line_offset: line.len() + whitespace_index,
2445 }),
2446 )
2447 }
2448 }
2449
2450 line.push_str(line_chunk);
2451 }
2452 }
2453 }
2454
2455 layouts
2456 }
2457
2458 fn draw(
2459 &self,
2460 layout: &LayoutState,
2461 row: u32,
2462 scroll_top: Pixels,
2463 content_origin: gpui::Point<Pixels>,
2464 scroll_left: Pixels,
2465 whitespace_setting: ShowWhitespaceSetting,
2466 selection_ranges: &[Range<DisplayPoint>],
2467 cx: &mut ViewContext<Editor>,
2468 ) {
2469 let line_height = layout.position_map.line_height;
2470 let line_y = line_height * row as f32 - scroll_top;
2471
2472 self.line.paint(
2473 content_origin + gpui::point(-scroll_left, line_y),
2474 line_height,
2475 cx,
2476 );
2477
2478 self.draw_invisibles(
2479 &selection_ranges,
2480 layout,
2481 content_origin,
2482 scroll_left,
2483 line_y,
2484 row,
2485 line_height,
2486 whitespace_setting,
2487 cx,
2488 );
2489 }
2490
2491 fn draw_invisibles(
2492 &self,
2493 selection_ranges: &[Range<DisplayPoint>],
2494 layout: &LayoutState,
2495 content_origin: gpui::Point<Pixels>,
2496 scroll_left: Pixels,
2497 line_y: Pixels,
2498 row: u32,
2499 line_height: Pixels,
2500 whitespace_setting: ShowWhitespaceSetting,
2501 cx: &mut ViewContext<Editor>,
2502 ) {
2503 let allowed_invisibles_regions = match whitespace_setting {
2504 ShowWhitespaceSetting::None => return,
2505 ShowWhitespaceSetting::Selection => Some(selection_ranges),
2506 ShowWhitespaceSetting::All => None,
2507 };
2508
2509 for invisible in &self.invisibles {
2510 let (&token_offset, invisible_symbol) = match invisible {
2511 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2512 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2513 };
2514
2515 let x_offset = self.line.x_for_index(token_offset);
2516 let invisible_offset =
2517 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2518 let origin =
2519 content_origin + gpui::point(-scroll_left + x_offset + invisible_offset, line_y);
2520
2521 if let Some(allowed_regions) = allowed_invisibles_regions {
2522 let invisible_point = DisplayPoint::new(row, token_offset as u32);
2523 if !allowed_regions
2524 .iter()
2525 .any(|region| region.start <= invisible_point && invisible_point < region.end)
2526 {
2527 continue;
2528 }
2529 }
2530 invisible_symbol.paint(origin, line_height, cx);
2531 }
2532 }
2533}
2534
2535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2536enum Invisible {
2537 Tab { line_start_offset: usize },
2538 Whitespace { line_offset: usize },
2539}
2540
2541impl Element<Editor> for EditorElement {
2542 type ElementState = ();
2543
2544 fn id(&self) -> Option<gpui::ElementId> {
2545 None
2546 }
2547
2548 fn initialize(
2549 &mut self,
2550 editor: &mut Editor,
2551 element_state: Option<Self::ElementState>,
2552 cx: &mut gpui::ViewContext<Editor>,
2553 ) -> Self::ElementState {
2554 editor.style = Some(self.style.clone()); // Long-term, we'd like to eliminate this.
2555
2556 let dispatch_context = editor.dispatch_context(cx);
2557 cx.with_element_id(cx.view().entity_id(), |global_id, cx| {
2558 cx.with_key_dispatch_context(dispatch_context, |cx| {
2559 cx.with_key_listeners(
2560 [
2561 build_action_listener(Editor::move_left),
2562 build_action_listener(Editor::move_right),
2563 build_action_listener(Editor::move_down),
2564 build_action_listener(Editor::move_up),
2565 build_key_listener(
2566 move |editor, key_down: &KeyDownEvent, dispatch_context, phase, cx| {
2567 if phase == DispatchPhase::Bubble {
2568 if let KeyMatch::Some(action) = cx.match_keystroke(
2569 &global_id,
2570 &key_down.keystroke,
2571 dispatch_context,
2572 ) {
2573 return Some(action);
2574 }
2575 }
2576
2577 None
2578 },
2579 ),
2580 ],
2581 |cx| cx.with_focus(editor.focus_handle.clone(), |_| {}),
2582 );
2583 })
2584 });
2585 }
2586
2587 fn layout(
2588 &mut self,
2589 editor: &mut Editor,
2590 element_state: &mut Self::ElementState,
2591 cx: &mut gpui::ViewContext<Editor>,
2592 ) -> gpui::LayoutId {
2593 let rem_size = cx.rem_size();
2594 let mut style = Style::default();
2595 style.size.width = relative(1.).into();
2596 style.size.height = match editor.mode {
2597 EditorMode::SingleLine => self.style.text.line_height_in_pixels(cx.rem_size()).into(),
2598 EditorMode::AutoHeight { .. } => todo!(),
2599 EditorMode::Full => relative(1.).into(),
2600 };
2601 cx.request_layout(&style, None)
2602 }
2603
2604 fn paint(
2605 &mut self,
2606 bounds: Bounds<gpui::Pixels>,
2607 editor: &mut Editor,
2608 element_state: &mut Self::ElementState,
2609 cx: &mut gpui::ViewContext<Editor>,
2610 ) {
2611 let layout = self.compute_layout(editor, cx, bounds);
2612
2613 cx.on_mouse_event({
2614 let position_map = layout.position_map.clone();
2615 move |editor, event: &ScrollWheelEvent, phase, cx| {
2616 if phase != DispatchPhase::Bubble {
2617 return;
2618 }
2619
2620 if Self::scroll(editor, event, &position_map, bounds, cx) {
2621 cx.stop_propagation();
2622 }
2623 }
2624 });
2625
2626 cx.with_content_mask(ContentMask { bounds }, |cx| {
2627 let gutter_bounds = Bounds {
2628 origin: bounds.origin,
2629 size: layout.gutter_size,
2630 };
2631 let text_bounds = Bounds {
2632 origin: gutter_bounds.upper_right(),
2633 size: layout.text_size,
2634 };
2635
2636 self.paint_background(gutter_bounds, text_bounds, &layout, cx);
2637 if layout.gutter_size.width > Pixels::ZERO {
2638 self.paint_gutter(gutter_bounds, &layout, editor, cx);
2639 }
2640 self.paint_text(text_bounds, &layout, editor, cx);
2641 });
2642 }
2643}
2644
2645// impl EditorElement {
2646// type LayoutState = LayoutState;
2647// type PaintState = ();
2648
2649// fn layout(
2650// &mut self,
2651// constraint: SizeConstraint,
2652// editor: &mut Editor,
2653// cx: &mut ViewContext<Editor>,
2654// ) -> (gpui::Point<Pixels>, Self::LayoutState) {
2655// let mut size = constraint.max;
2656// if size.x.is_infinite() {
2657// unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2658// }
2659
2660// let snapshot = editor.snapshot(cx);
2661// let style = self.style.clone();
2662
2663// let line_height = (style.text.font_size * style.line_height_scalar).round();
2664
2665// let gutter_padding;
2666// let gutter_width;
2667// let gutter_margin;
2668// if snapshot.show_gutter {
2669// let em_width = style.text.em_width(cx.font_cache());
2670// gutter_padding = (em_width * style.gutter_padding_factor).round();
2671// gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2672// gutter_margin = -style.text.descent(cx.font_cache());
2673// } else {
2674// gutter_padding = 0.0;
2675// gutter_width = 0.0;
2676// gutter_margin = 0.0;
2677// };
2678
2679// let text_width = size.x - gutter_width;
2680// let em_width = style.text.em_width(cx.font_cache());
2681// let em_advance = style.text.em_advance(cx.font_cache());
2682// let overscroll = point(em_width, 0.);
2683// let snapshot = {
2684// editor.set_visible_line_count(size.y / line_height, cx);
2685
2686// let editor_width = text_width - gutter_margin - overscroll.x - em_width;
2687// let wrap_width = match editor.soft_wrap_mode(cx) {
2688// SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2689// SoftWrap::EditorWidth => editor_width,
2690// SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2691// };
2692
2693// if editor.set_wrap_width(Some(wrap_width), cx) {
2694// editor.snapshot(cx)
2695// } else {
2696// snapshot
2697// }
2698// };
2699
2700// let wrap_guides = editor
2701// .wrap_guides(cx)
2702// .iter()
2703// .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2704// .collect();
2705
2706// let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2707// if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2708// size.set_y(
2709// scroll_height
2710// .min(constraint.max_along(Axis::Vertical))
2711// .max(constraint.min_along(Axis::Vertical))
2712// .max(line_height)
2713// .min(line_height * max_lines as f32),
2714// )
2715// } else if let EditorMode::SingleLine = snapshot.mode {
2716// size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
2717// } else if size.y.is_infinite() {
2718// size.set_y(scroll_height);
2719// }
2720// let gutter_size = point(gutter_width, size.y);
2721// let text_size = point(text_width, size.y);
2722
2723// let autoscroll_horizontally = editor.autoscroll_vertically(size.y, line_height, cx);
2724// let mut snapshot = editor.snapshot(cx);
2725
2726// let scroll_position = snapshot.scroll_position();
2727// // The scroll position is a fractional point, the whole number of which represents
2728// // the top of the window in terms of display rows.
2729// let start_row = scroll_position.y as u32;
2730// let height_in_lines = size.y / line_height;
2731// let max_row = snapshot.max_point().row();
2732
2733// // Add 1 to ensure selections bleed off screen
2734// let end_row = 1 + cmp::min(
2735// (scroll_position.y + height_in_lines).ceil() as u32,
2736// max_row,
2737// );
2738
2739// let start_anchor = if start_row == 0 {
2740// Anchor::min()
2741// } else {
2742// snapshot
2743// .buffer_snapshot
2744// .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2745// };
2746// let end_anchor = if end_row > max_row {
2747// Anchor::max
2748// } else {
2749// snapshot
2750// .buffer_snapshot
2751// .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2752// };
2753
2754// let mut selections: Vec<(SelectionStyle, Vec<SelectionLayout>)> = Vec::new();
2755// let mut active_rows = BTreeMap::new();
2756// let mut fold_ranges = Vec::new();
2757// let is_singleton = editor.is_singleton(cx);
2758
2759// let highlighted_rows = editor.highlighted_rows();
2760// let theme = theme::current(cx);
2761// let highlighted_ranges = editor.background_highlights_in_range(
2762// start_anchor..end_anchor,
2763// &snapshot.display_snapshot,
2764// theme.as_ref(),
2765// );
2766
2767// fold_ranges.extend(
2768// snapshot
2769// .folds_in_range(start_anchor..end_anchor)
2770// .map(|anchor| {
2771// let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2772// (
2773// start.row,
2774// start.to_display_point(&snapshot.display_snapshot)
2775// ..anchor.end.to_display_point(&snapshot),
2776// )
2777// }),
2778// );
2779
2780// let mut newest_selection_head = None;
2781
2782// if editor.show_local_selections {
2783// let mut local_selections: Vec<Selection<Point>> = editor
2784// .selections
2785// .disjoint_in_range(start_anchor..end_anchor, cx);
2786// local_selections.extend(editor.selections.pending(cx));
2787// let mut layouts = Vec::new();
2788// let newest = editor.selections.newest(cx);
2789// for selection in local_selections.drain(..) {
2790// let is_empty = selection.start == selection.end;
2791// let is_newest = selection == newest;
2792
2793// let layout = SelectionLayout::new(
2794// selection,
2795// editor.selections.line_mode,
2796// editor.cursor_shape,
2797// &snapshot.display_snapshot,
2798// is_newest,
2799// true,
2800// );
2801// if is_newest {
2802// newest_selection_head = Some(layout.head);
2803// }
2804
2805// for row in cmp::max(layout.active_rows.start, start_row)
2806// ..=cmp::min(layout.active_rows.end, end_row)
2807// {
2808// let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2809// *contains_non_empty_selection |= !is_empty;
2810// }
2811// layouts.push(layout);
2812// }
2813
2814// selections.push((style.selection, layouts));
2815// }
2816
2817// if let Some(collaboration_hub) = &editor.collaboration_hub {
2818// // When following someone, render the local selections in their color.
2819// if let Some(leader_id) = editor.leader_peer_id {
2820// if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
2821// if let Some(participant_index) = collaboration_hub
2822// .user_participant_indices(cx)
2823// .get(&collaborator.user_id)
2824// {
2825// if let Some((local_selection_style, _)) = selections.first_mut() {
2826// *local_selection_style =
2827// style.selection_style_for_room_participant(participant_index.0);
2828// }
2829// }
2830// }
2831// }
2832
2833// let mut remote_selections = HashMap::default();
2834// for selection in snapshot.remote_selections_in_range(
2835// &(start_anchor..end_anchor),
2836// collaboration_hub.as_ref(),
2837// cx,
2838// ) {
2839// let selection_style = if let Some(participant_index) = selection.participant_index {
2840// style.selection_style_for_room_participant(participant_index.0)
2841// } else {
2842// style.absent_selection
2843// };
2844
2845// // Don't re-render the leader's selections, since the local selections
2846// // match theirs.
2847// if Some(selection.peer_id) == editor.leader_peer_id {
2848// continue;
2849// }
2850
2851// remote_selections
2852// .entry(selection.replica_id)
2853// .or_insert((selection_style, Vec::new()))
2854// .1
2855// .push(SelectionLayout::new(
2856// selection.selection,
2857// selection.line_mode,
2858// selection.cursor_shape,
2859// &snapshot.display_snapshot,
2860// false,
2861// false,
2862// ));
2863// }
2864
2865// selections.extend(remote_selections.into_values());
2866// }
2867
2868// let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2869// let show_scrollbars = match scrollbar_settings.show {
2870// ShowScrollbar::Auto => {
2871// // Git
2872// (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2873// ||
2874// // Selections
2875// (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty)
2876// // Scrollmanager
2877// || editor.scroll_manager.scrollbars_visible()
2878// }
2879// ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2880// ShowScrollbar::Always => true,
2881// ShowScrollbar::Never => false,
2882// };
2883
2884// let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2885// .into_iter()
2886// .map(|(id, fold)| {
2887// let color = self
2888// .style
2889// .folds
2890// .ellipses
2891// .background
2892// .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2893// .color;
2894
2895// (id, fold, color)
2896// })
2897// .collect();
2898
2899// let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2900// let newest = editor.selections.newest::<Point>(cx);
2901// SelectionLayout::new(
2902// newest,
2903// editor.selections.line_mode,
2904// editor.cursor_shape,
2905// &snapshot.display_snapshot,
2906// true,
2907// true,
2908// )
2909// .head
2910// });
2911
2912// let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2913// start_row..end_row,
2914// &active_rows,
2915// head_for_relative,
2916// is_singleton,
2917// &snapshot,
2918// cx,
2919// );
2920
2921// let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2922
2923// let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2924
2925// let mut max_visible_line_width = 0.0;
2926// let line_layouts =
2927// self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2928// for line_with_invisibles in &line_layouts {
2929// if line_with_invisibles.line.width() > max_visible_line_width {
2930// max_visible_line_width = line_with_invisibles.line.width();
2931// }
2932// }
2933
2934// let style = self.style.clone();
2935// let longest_line_width = layout_line(
2936// snapshot.longest_row(),
2937// &snapshot,
2938// &style,
2939// cx.text_layout_cache(),
2940// )
2941// .width();
2942// let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x;
2943// let em_width = style.text.em_width(cx.font_cache());
2944// let (scroll_width, blocks) = self.layout_blocks(
2945// start_row..end_row,
2946// &snapshot,
2947// size.x,
2948// scroll_width,
2949// gutter_padding,
2950// gutter_width,
2951// em_width,
2952// gutter_width + gutter_margin,
2953// line_height,
2954// &style,
2955// &line_layouts,
2956// editor,
2957// cx,
2958// );
2959
2960// let scroll_max = point(
2961// ((scroll_width - text_size.x) / em_width).max(0.0),
2962// max_row as f32,
2963// );
2964
2965// let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
2966
2967// let autoscrolled = if autoscroll_horizontally {
2968// editor.autoscroll_horizontally(
2969// start_row,
2970// text_size.x,
2971// scroll_width,
2972// em_width,
2973// &line_layouts,
2974// cx,
2975// )
2976// } else {
2977// false
2978// };
2979
2980// if clamped || autoscrolled {
2981// snapshot = editor.snapshot(cx);
2982// }
2983
2984// let style = editor.style(cx);
2985
2986// let mut context_menu = None;
2987// let mut code_actions_indicator = None;
2988// if let Some(newest_selection_head) = newest_selection_head {
2989// if (start_row..end_row).contains(&newest_selection_head.row()) {
2990// if editor.context_menu_visible() {
2991// context_menu =
2992// editor.render_context_menu(newest_selection_head, style.clone(), cx);
2993// }
2994
2995// let active = matches!(
2996// editor.context_menu.read().as_ref(),
2997// Some(crate::ContextMenu::CodeActions(_))
2998// );
2999
3000// code_actions_indicator = editor
3001// .render_code_actions_indicator(&style, active, cx)
3002// .map(|indicator| (newest_selection_head.row(), indicator));
3003// }
3004// }
3005
3006// let visible_rows = start_row..start_row + line_layouts.len() as u32;
3007// let mut hover = editor.hover_state.render(
3008// &snapshot,
3009// &style,
3010// visible_rows,
3011// editor.workspace.as_ref().map(|(w, _)| w.clone()),
3012// cx,
3013// );
3014// let mode = editor.mode;
3015
3016// let mut fold_indicators = editor.render_fold_indicators(
3017// fold_statuses,
3018// &style,
3019// editor.gutter_hovered,
3020// line_height,
3021// gutter_margin,
3022// cx,
3023// );
3024
3025// if let Some((_, context_menu)) = context_menu.as_mut() {
3026// context_menu.layout(
3027// SizeConstraint {
3028// min: gpui::Point::<Pixels>::zero(),
3029// max: point(
3030// cx.window_size().x * 0.7,
3031// (12. * line_height).min((size.y - line_height) / 2.),
3032// ),
3033// },
3034// editor,
3035// cx,
3036// );
3037// }
3038
3039// if let Some((_, indicator)) = code_actions_indicator.as_mut() {
3040// indicator.layout(
3041// SizeConstraint::strict_along(
3042// Axis::Vertical,
3043// line_height * style.code_actions.vertical_scale,
3044// ),
3045// editor,
3046// cx,
3047// );
3048// }
3049
3050// for fold_indicator in fold_indicators.iter_mut() {
3051// if let Some(indicator) = fold_indicator.as_mut() {
3052// indicator.layout(
3053// SizeConstraint::strict_along(
3054// Axis::Vertical,
3055// line_height * style.code_actions.vertical_scale,
3056// ),
3057// editor,
3058// cx,
3059// );
3060// }
3061// }
3062
3063// if let Some((_, hover_popovers)) = hover.as_mut() {
3064// for hover_popover in hover_popovers.iter_mut() {
3065// hover_popover.layout(
3066// SizeConstraint {
3067// min: gpui::Point::<Pixels>::zero(),
3068// max: point(
3069// (120. * em_width) // Default size
3070// .min(size.x / 2.) // Shrink to half of the editor width
3071// .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3072// (16. * line_height) // Default size
3073// .min(size.y / 2.) // Shrink to half of the editor height
3074// .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3075// ),
3076// },
3077// editor,
3078// cx,
3079// );
3080// }
3081// }
3082
3083// let invisible_symbol_font_size = self.style.text.font_size / 2.0;
3084// let invisible_symbol_style = RunStyle {
3085// color: self.style.whitespace,
3086// font_id: self.style.text.font_id,
3087// underline: Default::default(),
3088// };
3089
3090// (
3091// size,
3092// LayoutState {
3093// mode,
3094// position_map: Arc::new(PositionMap {
3095// size,
3096// scroll_max,
3097// line_layouts,
3098// line_height,
3099// em_width,
3100// em_advance,
3101// snapshot,
3102// }),
3103// visible_display_row_range: start_row..end_row,
3104// wrap_guides,
3105// gutter_size,
3106// gutter_padding,
3107// text_size,
3108// scrollbar_row_range,
3109// show_scrollbars,
3110// is_singleton,
3111// max_row,
3112// gutter_margin,
3113// active_rows,
3114// highlighted_rows,
3115// highlighted_ranges,
3116// fold_ranges,
3117// line_number_layouts,
3118// display_hunks,
3119// blocks,
3120// selections,
3121// context_menu,
3122// code_actions_indicator,
3123// fold_indicators,
3124// tab_invisible: cx.text_layout_cache().layout_str(
3125// "→",
3126// invisible_symbol_font_size,
3127// &[("→".len(), invisible_symbol_style)],
3128// ),
3129// space_invisible: cx.text_layout_cache().layout_str(
3130// "•",
3131// invisible_symbol_font_size,
3132// &[("•".len(), invisible_symbol_style)],
3133// ),
3134// hover_popovers: hover,
3135// },
3136// )
3137// }
3138
3139// fn paint(
3140// &mut self,
3141// bounds: Bounds<Pixels>,
3142// visible_bounds: Bounds<Pixels>,
3143// layout: &mut Self::LayoutState,
3144// editor: &mut Editor,
3145// cx: &mut ViewContext<Editor>,
3146// ) -> Self::PaintState {
3147// let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
3148// cx.scene().push_layer(Some(visible_bounds));
3149
3150// let gutter_bounds = Bounds::<Pixels>::new(bounds.origin, layout.gutter_size);
3151// let text_bounds = Bounds::<Pixels>::new(
3152// bounds.origin + point(layout.gutter_size.x, 0.0),
3153// layout.text_size,
3154// );
3155
3156// Self::attach_mouse_handlers(
3157// &layout.position_map,
3158// layout.hover_popovers.is_some(),
3159// visible_bounds,
3160// text_bounds,
3161// gutter_bounds,
3162// bounds,
3163// cx,
3164// );
3165
3166// self.paint_background(gutter_bounds, text_bounds, layout, cx);
3167// if layout.gutter_size.x > 0. {
3168// self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
3169// }
3170// self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
3171
3172// cx.scene().push_layer(Some(bounds));
3173// if !layout.blocks.is_empty {
3174// self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
3175// }
3176// self.paint_scrollbar(bounds, layout, &editor, cx);
3177// cx.scene().pop_layer();
3178// cx.scene().pop_layer();
3179// }
3180
3181// fn rect_for_text_range(
3182// &self,
3183// range_utf16: Range<usize>,
3184// bounds: Bounds<Pixels>,
3185// _: Bounds<Pixels>,
3186// layout: &Self::LayoutState,
3187// _: &Self::PaintState,
3188// _: &Editor,
3189// _: &ViewContext<Editor>,
3190// ) -> Option<Bounds<Pixels>> {
3191// let text_bounds = Bounds::<Pixels>::new(
3192// bounds.origin + point(layout.gutter_size.x, 0.0),
3193// layout.text_size,
3194// );
3195// let content_origin = text_bounds.origin + point(layout.gutter_margin, 0.);
3196// let scroll_position = layout.position_map.snapshot.scroll_position();
3197// let start_row = scroll_position.y as u32;
3198// let scroll_top = scroll_position.y * layout.position_map.line_height;
3199// let scroll_left = scroll_position.x * layout.position_map.em_width;
3200
3201// let range_start = OffsetUtf16(range_utf16.start)
3202// .to_display_point(&layout.position_map.snapshot.display_snapshot);
3203// if range_start.row() < start_row {
3204// return None;
3205// }
3206
3207// let line = &layout
3208// .position_map
3209// .line_layouts
3210// .get((range_start.row() - start_row) as usize)?
3211// .line;
3212// let range_start_x = line.x_for_index(range_start.column() as usize);
3213// let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
3214// Some(Bounds::<Pixels>::new(
3215// content_origin
3216// + point(
3217// range_start_x,
3218// range_start_y + layout.position_map.line_height,
3219// )
3220// - point(scroll_left, scroll_top),
3221// point(
3222// layout.position_map.em_width,
3223// layout.position_map.line_height,
3224// ),
3225// ))
3226// }
3227
3228// fn debug(
3229// &self,
3230// bounds: Bounds<Pixels>,
3231// _: &Self::LayoutState,
3232// _: &Self::PaintState,
3233// _: &Editor,
3234// _: &ViewContext<Editor>,
3235// ) -> json::Value {
3236// json!({
3237// "type": "BufferElement",
3238// "bounds": bounds.to_json()
3239// })
3240// }
3241// }
3242
3243type BufferRow = u32;
3244
3245pub struct LayoutState {
3246 position_map: Arc<PositionMap>,
3247 gutter_size: Size<Pixels>,
3248 gutter_padding: Pixels,
3249 gutter_margin: Pixels,
3250 text_size: gpui::Size<Pixels>,
3251 mode: EditorMode,
3252 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3253 visible_display_row_range: Range<u32>,
3254 active_rows: BTreeMap<u32, bool>,
3255 highlighted_rows: Option<Range<u32>>,
3256 line_number_layouts: Vec<Option<gpui::Line>>,
3257 display_hunks: Vec<DisplayDiffHunk>,
3258 // blocks: Vec<BlockLayout>,
3259 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3260 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)>,
3261 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3262 scrollbar_row_range: Range<f32>,
3263 show_scrollbars: bool,
3264 is_singleton: bool,
3265 max_row: u32,
3266 // context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
3267 // code_actions_indicator: Option<(u32, AnyElement<Editor>)>,
3268 // hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
3269 // fold_indicators: Vec<Option<AnyElement<Editor>>>,
3270 tab_invisible: Line,
3271 space_invisible: Line,
3272}
3273
3274struct PositionMap {
3275 size: Size<Pixels>,
3276 line_height: Pixels,
3277 scroll_max: gpui::Point<f32>,
3278 em_width: Pixels,
3279 em_advance: Pixels,
3280 line_layouts: Vec<LineWithInvisibles>,
3281 snapshot: EditorSnapshot,
3282}
3283
3284#[derive(Debug, Copy, Clone)]
3285pub struct PointForPosition {
3286 pub previous_valid: DisplayPoint,
3287 pub next_valid: DisplayPoint,
3288 pub exact_unclipped: DisplayPoint,
3289 pub column_overshoot_after_line_end: u32,
3290}
3291
3292impl PointForPosition {
3293 #[cfg(test)]
3294 pub fn valid(valid: DisplayPoint) -> Self {
3295 Self {
3296 previous_valid: valid,
3297 next_valid: valid,
3298 exact_unclipped: valid,
3299 column_overshoot_after_line_end: 0,
3300 }
3301 }
3302
3303 pub fn as_valid(&self) -> Option<DisplayPoint> {
3304 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3305 Some(self.previous_valid)
3306 } else {
3307 None
3308 }
3309 }
3310}
3311
3312impl PositionMap {
3313 fn point_for_position(
3314 &self,
3315 text_bounds: Bounds<Pixels>,
3316 position: gpui::Point<Pixels>,
3317 ) -> PointForPosition {
3318 let scroll_position = self.snapshot.scroll_position();
3319 let position = position - text_bounds.origin;
3320 let y = position.y.max(px(0.)).min(self.size.width);
3321 let x = position.x + (scroll_position.x * self.em_width);
3322 let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3323
3324 let (column, x_overshoot_after_line_end) = if let Some(line) = self
3325 .line_layouts
3326 .get(row as usize - scroll_position.y as usize)
3327 .map(|&LineWithInvisibles { ref line, .. }| line)
3328 {
3329 if let Some(ix) = line.index_for_x(x) {
3330 (ix as u32, px(0.))
3331 } else {
3332 (line.len as u32, px(0.).max(x - line.width))
3333 }
3334 } else {
3335 (0, x)
3336 };
3337
3338 let mut exact_unclipped = DisplayPoint::new(row, column);
3339 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3340 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3341
3342 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3343 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3344 PointForPosition {
3345 previous_valid,
3346 next_valid,
3347 exact_unclipped,
3348 column_overshoot_after_line_end,
3349 }
3350 }
3351}
3352
3353struct BlockLayout {
3354 row: u32,
3355 element: AnyElement<Editor>,
3356 style: BlockStyle,
3357}
3358
3359fn layout_line(
3360 row: u32,
3361 snapshot: &EditorSnapshot,
3362 style: &EditorStyle,
3363 cx: &WindowContext,
3364) -> Result<Line> {
3365 let mut line = snapshot.line(row);
3366
3367 if line.len() > MAX_LINE_LEN {
3368 let mut len = MAX_LINE_LEN;
3369 while !line.is_char_boundary(len) {
3370 len -= 1;
3371 }
3372
3373 line.truncate(len);
3374 }
3375
3376 Ok(cx
3377 .text_system()
3378 .layout_text(
3379 &line,
3380 style.text.font_size.to_pixels(cx.rem_size()),
3381 &[TextRun {
3382 len: snapshot.line_len(row) as usize,
3383 font: style.text.font(),
3384 color: Hsla::default(),
3385 underline: None,
3386 }],
3387 None,
3388 )?
3389 .pop()
3390 .unwrap())
3391}
3392
3393#[derive(Debug)]
3394pub struct Cursor {
3395 origin: gpui::Point<Pixels>,
3396 block_width: Pixels,
3397 line_height: Pixels,
3398 color: Hsla,
3399 shape: CursorShape,
3400 block_text: Option<Line>,
3401}
3402
3403impl Cursor {
3404 pub fn new(
3405 origin: gpui::Point<Pixels>,
3406 block_width: Pixels,
3407 line_height: Pixels,
3408 color: Hsla,
3409 shape: CursorShape,
3410 block_text: Option<Line>,
3411 ) -> Cursor {
3412 Cursor {
3413 origin,
3414 block_width,
3415 line_height,
3416 color,
3417 shape,
3418 block_text,
3419 }
3420 }
3421
3422 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3423 Bounds {
3424 origin: self.origin + origin,
3425 size: size(self.block_width, self.line_height),
3426 }
3427 }
3428
3429 pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3430 let bounds = match self.shape {
3431 CursorShape::Bar => Bounds {
3432 origin: self.origin + origin,
3433 size: size(px(2.0), self.line_height),
3434 },
3435 CursorShape::Block | CursorShape::Hollow => Bounds {
3436 origin: self.origin + origin,
3437 size: size(self.block_width, self.line_height),
3438 },
3439 CursorShape::Underscore => Bounds {
3440 origin: self.origin
3441 + origin
3442 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3443 size: size(self.block_width, px(2.0)),
3444 },
3445 };
3446
3447 //Draw background or border quad
3448 if matches!(self.shape, CursorShape::Hollow) {
3449 cx.paint_quad(
3450 bounds,
3451 Corners::default(),
3452 transparent_black(),
3453 Edges::all(px(1.)),
3454 self.color,
3455 );
3456 } else {
3457 cx.paint_quad(
3458 bounds,
3459 Corners::default(),
3460 self.color,
3461 Edges::default(),
3462 transparent_black(),
3463 );
3464 }
3465
3466 if let Some(block_text) = &self.block_text {
3467 block_text.paint(self.origin + origin, self.line_height, cx);
3468 }
3469 }
3470
3471 pub fn shape(&self) -> CursorShape {
3472 self.shape
3473 }
3474}
3475
3476#[derive(Debug)]
3477pub struct HighlightedRange {
3478 pub start_y: Pixels,
3479 pub line_height: Pixels,
3480 pub lines: Vec<HighlightedRangeLine>,
3481 pub color: Hsla,
3482 pub corner_radius: Pixels,
3483}
3484
3485#[derive(Debug)]
3486pub struct HighlightedRangeLine {
3487 pub start_x: Pixels,
3488 pub end_x: Pixels,
3489}
3490
3491impl HighlightedRange {
3492 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
3493 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3494 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3495 self.paint_lines(
3496 self.start_y + self.line_height,
3497 &self.lines[1..],
3498 bounds,
3499 cx,
3500 );
3501 } else {
3502 self.paint_lines(self.start_y, &self.lines, bounds, cx);
3503 }
3504 }
3505
3506 fn paint_lines(
3507 &self,
3508 start_y: Pixels,
3509 lines: &[HighlightedRangeLine],
3510 bounds: Bounds<Pixels>,
3511 cx: &mut WindowContext,
3512 ) {
3513 if lines.is_empty() {
3514 return;
3515 }
3516
3517 let first_line = lines.first().unwrap();
3518 let last_line = lines.last().unwrap();
3519
3520 let first_top_left = point(first_line.start_x, start_y);
3521 let first_top_right = point(first_line.end_x, start_y);
3522
3523 let curve_height = point(Pixels::ZERO, self.corner_radius);
3524 let curve_width = |start_x: Pixels, end_x: Pixels| {
3525 let max = (end_x - start_x) / 2.;
3526 let width = if max < self.corner_radius {
3527 max
3528 } else {
3529 self.corner_radius
3530 };
3531
3532 point(width, Pixels::ZERO)
3533 };
3534
3535 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3536 let mut path = gpui::Path::new(first_top_right - top_curve_width);
3537 path.curve_to(first_top_right + curve_height, first_top_right);
3538
3539 let mut iter = lines.iter().enumerate().peekable();
3540 while let Some((ix, line)) = iter.next() {
3541 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3542
3543 if let Some((_, next_line)) = iter.peek() {
3544 let next_top_right = point(next_line.end_x, bottom_right.y);
3545
3546 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3547 Ordering::Equal => {
3548 path.line_to(bottom_right);
3549 }
3550 Ordering::Less => {
3551 let curve_width = curve_width(next_top_right.x, bottom_right.x);
3552 path.line_to(bottom_right - curve_height);
3553 if self.corner_radius > Pixels::ZERO {
3554 path.curve_to(bottom_right - curve_width, bottom_right);
3555 }
3556 path.line_to(next_top_right + curve_width);
3557 if self.corner_radius > Pixels::ZERO {
3558 path.curve_to(next_top_right + curve_height, next_top_right);
3559 }
3560 }
3561 Ordering::Greater => {
3562 let curve_width = curve_width(bottom_right.x, next_top_right.x);
3563 path.line_to(bottom_right - curve_height);
3564 if self.corner_radius > Pixels::ZERO {
3565 path.curve_to(bottom_right + curve_width, bottom_right);
3566 }
3567 path.line_to(next_top_right - curve_width);
3568 if self.corner_radius > Pixels::ZERO {
3569 path.curve_to(next_top_right + curve_height, next_top_right);
3570 }
3571 }
3572 }
3573 } else {
3574 let curve_width = curve_width(line.start_x, line.end_x);
3575 path.line_to(bottom_right - curve_height);
3576 if self.corner_radius > Pixels::ZERO {
3577 path.curve_to(bottom_right - curve_width, bottom_right);
3578 }
3579
3580 let bottom_left = point(line.start_x, bottom_right.y);
3581 path.line_to(bottom_left + curve_width);
3582 if self.corner_radius > Pixels::ZERO {
3583 path.curve_to(bottom_left - curve_height, bottom_left);
3584 }
3585 }
3586 }
3587
3588 if first_line.start_x > last_line.start_x {
3589 let curve_width = curve_width(last_line.start_x, first_line.start_x);
3590 let second_top_left = point(last_line.start_x, start_y + self.line_height);
3591 path.line_to(second_top_left + curve_height);
3592 if self.corner_radius > Pixels::ZERO {
3593 path.curve_to(second_top_left + curve_width, second_top_left);
3594 }
3595 let first_bottom_left = point(first_line.start_x, second_top_left.y);
3596 path.line_to(first_bottom_left - curve_width);
3597 if self.corner_radius > Pixels::ZERO {
3598 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3599 }
3600 }
3601
3602 path.line_to(first_top_left + curve_height);
3603 if self.corner_radius > Pixels::ZERO {
3604 path.curve_to(first_top_left + top_curve_width, first_top_left);
3605 }
3606 path.line_to(first_top_right - top_curve_width);
3607
3608 cx.paint_path(path, self.color);
3609 }
3610}
3611
3612// fn range_to_bounds(
3613// range: &Range<DisplayPoint>,
3614// content_origin: gpui::Point<Pixels>,
3615// scroll_left: f32,
3616// scroll_top: f32,
3617// visible_row_range: &Range<u32>,
3618// line_end_overshoot: f32,
3619// position_map: &PositionMap,
3620// ) -> impl Iterator<Item = Bounds<Pixels>> {
3621// let mut bounds: SmallVec<[Bounds<Pixels>; 1]> = SmallVec::new();
3622
3623// if range.start == range.end {
3624// return bounds.into_iter();
3625// }
3626
3627// let start_row = visible_row_range.start;
3628// let end_row = visible_row_range.end;
3629
3630// let row_range = if range.end.column() == 0 {
3631// cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3632// } else {
3633// cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3634// };
3635
3636// let first_y =
3637// content_origin.y + row_range.start as f32 * position_map.line_height - scroll_top;
3638
3639// for (idx, row) in row_range.enumerate() {
3640// let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
3641
3642// let start_x = if row == range.start.row() {
3643// content_origin.x + line_layout.x_for_index(range.start.column() as usize)
3644// - scroll_left
3645// } else {
3646// content_origin.x - scroll_left
3647// };
3648
3649// let end_x = if row == range.end.row() {
3650// content_origin.x + line_layout.x_for_index(range.end.column() as usize) - scroll_left
3651// } else {
3652// content_origin.x + line_layout.width() + line_end_overshoot - scroll_left
3653// };
3654
3655// bounds.push(Bounds::<Pixels>::from_points(
3656// point(start_x, first_y + position_map.line_height * idx as f32),
3657// point(end_x, first_y + position_map.line_height * (idx + 1) as f32),
3658// ))
3659// }
3660
3661// bounds.into_iter()
3662// }
3663
3664pub fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
3665 delta.powf(1.5) / 100.0
3666}
3667
3668fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
3669 delta.powf(1.2) / 300.0
3670}
3671
3672// #[cfg(test)]
3673// mod tests {
3674// use super::*;
3675// use crate::{
3676// display_map::{BlockDisposition, BlockProperties},
3677// editor_tests::{init_test, update_test_language_settings},
3678// Editor, MultiBuffer,
3679// };
3680// use gpui::TestAppContext;
3681// use language::language_settings;
3682// use log::info;
3683// use std::{num::NonZeroU32, sync::Arc};
3684// use util::test::sample_text;
3685
3686// #[gpui::test]
3687// fn test_layout_line_numbers(cx: &mut TestAppContext) {
3688// init_test(cx, |_| {});
3689// let editor = cx
3690// .add_window(|cx| {
3691// let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3692// Editor::new(EditorMode::Full, buffer, None, None, cx)
3693// })
3694// .root(cx);
3695// let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3696
3697// let layouts = editor.update(cx, |editor, cx| {
3698// let snapshot = editor.snapshot(cx);
3699// element
3700// .layout_line_numbers(
3701// 0..6,
3702// &Default::default(),
3703// DisplayPoint::new(0, 0),
3704// false,
3705// &snapshot,
3706// cx,
3707// )
3708// .0
3709// });
3710// assert_eq!(layouts.len(), 6);
3711
3712// let relative_rows = editor.update(cx, |editor, cx| {
3713// let snapshot = editor.snapshot(cx);
3714// element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3715// });
3716// assert_eq!(relative_rows[&0], 3);
3717// assert_eq!(relative_rows[&1], 2);
3718// assert_eq!(relative_rows[&2], 1);
3719// // current line has no relative number
3720// assert_eq!(relative_rows[&4], 1);
3721// assert_eq!(relative_rows[&5], 2);
3722
3723// // works if cursor is before screen
3724// let relative_rows = editor.update(cx, |editor, cx| {
3725// let snapshot = editor.snapshot(cx);
3726
3727// element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3728// });
3729// assert_eq!(relative_rows.len(), 3);
3730// assert_eq!(relative_rows[&3], 2);
3731// assert_eq!(relative_rows[&4], 3);
3732// assert_eq!(relative_rows[&5], 4);
3733
3734// // works if cursor is after screen
3735// let relative_rows = editor.update(cx, |editor, cx| {
3736// let snapshot = editor.snapshot(cx);
3737
3738// element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3739// });
3740// assert_eq!(relative_rows.len(), 3);
3741// assert_eq!(relative_rows[&0], 5);
3742// assert_eq!(relative_rows[&1], 4);
3743// assert_eq!(relative_rows[&2], 3);
3744// }
3745
3746// #[gpui::test]
3747// async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3748// init_test(cx, |_| {});
3749
3750// let editor = cx
3751// .add_window(|cx| {
3752// let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3753// Editor::new(EditorMode::Full, buffer, None, None, cx)
3754// })
3755// .root(cx);
3756// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3757// let (_, state) = editor.update(cx, |editor, cx| {
3758// editor.cursor_shape = CursorShape::Block;
3759// editor.change_selections(None, cx, |s| {
3760// s.select_ranges([
3761// Point::new(0, 0)..Point::new(1, 0),
3762// Point::new(3, 2)..Point::new(3, 3),
3763// Point::new(5, 6)..Point::new(6, 0),
3764// ]);
3765// });
3766// element.layout(
3767// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3768// editor,
3769// cx,
3770// )
3771// });
3772// assert_eq!(state.selections.len(), 1);
3773// let local_selections = &state.selections[0].1;
3774// assert_eq!(local_selections.len(), 3);
3775// // moves cursor back one line
3776// assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3777// assert_eq!(
3778// local_selections[0].range,
3779// DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3780// );
3781
3782// // moves cursor back one column
3783// assert_eq!(
3784// local_selections[1].range,
3785// DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3786// );
3787// assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3788
3789// // leaves cursor on the max point
3790// assert_eq!(
3791// local_selections[2].range,
3792// DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3793// );
3794// assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3795
3796// // active lines does not include 1 (even though the range of the selection does)
3797// assert_eq!(
3798// state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3799// vec![0, 3, 5, 6]
3800// );
3801
3802// // multi-buffer support
3803// // in DisplayPoint co-ordinates, this is what we're dealing with:
3804// // 0: [[file
3805// // 1: header]]
3806// // 2: aaaaaa
3807// // 3: bbbbbb
3808// // 4: cccccc
3809// // 5:
3810// // 6: ...
3811// // 7: ffffff
3812// // 8: gggggg
3813// // 9: hhhhhh
3814// // 10:
3815// // 11: [[file
3816// // 12: header]]
3817// // 13: bbbbbb
3818// // 14: cccccc
3819// // 15: dddddd
3820// let editor = cx
3821// .add_window(|cx| {
3822// let buffer = MultiBuffer::build_multi(
3823// [
3824// (
3825// &(sample_text(8, 6, 'a') + "\n"),
3826// vec![
3827// Point::new(0, 0)..Point::new(3, 0),
3828// Point::new(4, 0)..Point::new(7, 0),
3829// ],
3830// ),
3831// (
3832// &(sample_text(8, 6, 'a') + "\n"),
3833// vec![Point::new(1, 0)..Point::new(3, 0)],
3834// ),
3835// ],
3836// cx,
3837// );
3838// Editor::new(EditorMode::Full, buffer, None, None, cx)
3839// })
3840// .root(cx);
3841// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3842// let (_, state) = editor.update(cx, |editor, cx| {
3843// editor.cursor_shape = CursorShape::Block;
3844// editor.change_selections(None, cx, |s| {
3845// s.select_display_ranges([
3846// DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3847// DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3848// ]);
3849// });
3850// element.layout(
3851// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3852// editor,
3853// cx,
3854// )
3855// });
3856
3857// assert_eq!(state.selections.len(), 1);
3858// let local_selections = &state.selections[0].1;
3859// assert_eq!(local_selections.len(), 2);
3860
3861// // moves cursor on excerpt boundary back a line
3862// // and doesn't allow selection to bleed through
3863// assert_eq!(
3864// local_selections[0].range,
3865// DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3866// );
3867// assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3868
3869// // moves cursor on buffer boundary back two lines
3870// // and doesn't allow selection to bleed through
3871// assert_eq!(
3872// local_selections[1].range,
3873// DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3874// );
3875// assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3876// }
3877
3878// #[gpui::test]
3879// fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3880// init_test(cx, |_| {});
3881
3882// let editor = cx
3883// .add_window(|cx| {
3884// let buffer = MultiBuffer::build_simple("", cx);
3885// Editor::new(EditorMode::Full, buffer, None, None, cx)
3886// })
3887// .root(cx);
3888
3889// editor.update(cx, |editor, cx| {
3890// editor.set_placeholder_text("hello", cx);
3891// editor.insert_blocks(
3892// [BlockProperties {
3893// style: BlockStyle::Fixed,
3894// disposition: BlockDisposition::Above,
3895// height: 3,
3896// position: Anchor::min(),
3897// render: Arc::new(|_| Empty::new().into_any),
3898// }],
3899// None,
3900// cx,
3901// );
3902
3903// // Blur the editor so that it displays placeholder text.
3904// cx.blur();
3905// });
3906
3907// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3908// let (size, mut state) = editor.update(cx, |editor, cx| {
3909// element.layout(
3910// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3911// editor,
3912// cx,
3913// )
3914// });
3915
3916// assert_eq!(state.position_map.line_layouts.len(), 4);
3917// assert_eq!(
3918// state
3919// .line_number_layouts
3920// .iter()
3921// .map(Option::is_some)
3922// .collect::<Vec<_>>(),
3923// &[false, false, false, true]
3924// );
3925
3926// // Don't panic.
3927// let bounds = Bounds::<Pixels>::new(Default::default(), size);
3928// editor.update(cx, |editor, cx| {
3929// element.paint(bounds, bounds, &mut state, editor, cx);
3930// });
3931// }
3932
3933// #[gpui::test]
3934// fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3935// const TAB_SIZE: u32 = 4;
3936
3937// let input_text = "\t \t|\t| a b";
3938// let expected_invisibles = vec![
3939// Invisible::Tab {
3940// line_start_offset: 0,
3941// },
3942// Invisible::Whitespace {
3943// line_offset: TAB_SIZE as usize,
3944// },
3945// Invisible::Tab {
3946// line_start_offset: TAB_SIZE as usize + 1,
3947// },
3948// Invisible::Tab {
3949// line_start_offset: TAB_SIZE as usize * 2 + 1,
3950// },
3951// Invisible::Whitespace {
3952// line_offset: TAB_SIZE as usize * 3 + 1,
3953// },
3954// Invisible::Whitespace {
3955// line_offset: TAB_SIZE as usize * 3 + 3,
3956// },
3957// ];
3958// assert_eq!(
3959// expected_invisibles.len(),
3960// input_text
3961// .chars()
3962// .filter(|initial_char| initial_char.is_whitespace())
3963// .count(),
3964// "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
3965// );
3966
3967// init_test(cx, |s| {
3968// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3969// s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
3970// });
3971
3972// let actual_invisibles =
3973// collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
3974
3975// assert_eq!(expected_invisibles, actual_invisibles);
3976// }
3977
3978// #[gpui::test]
3979// fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
3980// init_test(cx, |s| {
3981// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
3982// s.defaults.tab_size = NonZeroU32::new(4);
3983// });
3984
3985// for editor_mode_without_invisibles in [
3986// EditorMode::SingleLine,
3987// EditorMode::AutoHeight { max_lines: 100 },
3988// ] {
3989// let invisibles = collect_invisibles_from_new_editor(
3990// cx,
3991// editor_mode_without_invisibles,
3992// "\t\t\t| | a b",
3993// 500.0,
3994// );
3995// assert!(invisibles.is_empty,
3996// "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
3997// }
3998// }
3999
4000// #[gpui::test]
4001// fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4002// let tab_size = 4;
4003// let input_text = "a\tbcd ".repeat(9);
4004// let repeated_invisibles = [
4005// Invisible::Tab {
4006// line_start_offset: 1,
4007// },
4008// Invisible::Whitespace {
4009// line_offset: tab_size as usize + 3,
4010// },
4011// Invisible::Whitespace {
4012// line_offset: tab_size as usize + 4,
4013// },
4014// Invisible::Whitespace {
4015// line_offset: tab_size as usize + 5,
4016// },
4017// ];
4018// let expected_invisibles = std::iter::once(repeated_invisibles)
4019// .cycle()
4020// .take(9)
4021// .flatten()
4022// .collect::<Vec<_>>();
4023// assert_eq!(
4024// expected_invisibles.len(),
4025// input_text
4026// .chars()
4027// .filter(|initial_char| initial_char.is_whitespace())
4028// .count(),
4029// "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4030// );
4031// info!("Expected invisibles: {expected_invisibles:?}");
4032
4033// init_test(cx, |_| {});
4034
4035// // Put the same string with repeating whitespace pattern into editors of various size,
4036// // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4037// let resize_step = 10.0;
4038// let mut editor_width = 200.0;
4039// while editor_width <= 1000.0 {
4040// update_test_language_settings(cx, |s| {
4041// s.defaults.tab_size = NonZeroU32::new(tab_size);
4042// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4043// s.defaults.preferred_line_length = Some(editor_width as u32);
4044// s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4045// });
4046
4047// let actual_invisibles =
4048// collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
4049
4050// // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4051// // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4052// let mut i = 0;
4053// for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4054// i = actual_index;
4055// match expected_invisibles.get(i) {
4056// Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4057// (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4058// | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4059// _ => {
4060// panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4061// }
4062// },
4063// None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4064// }
4065// }
4066// let missing_expected_invisibles = &expected_invisibles[i + 1..];
4067// assert!(
4068// missing_expected_invisibles.is_empty,
4069// "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4070// );
4071
4072// editor_width += resize_step;
4073// }
4074// }
4075
4076// fn collect_invisibles_from_new_editor(
4077// cx: &mut TestAppContext,
4078// editor_mode: EditorMode,
4079// input_text: &str,
4080// editor_width: f32,
4081// ) -> Vec<Invisible> {
4082// info!(
4083// "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
4084// );
4085// let editor = cx
4086// .add_window(|cx| {
4087// let buffer = MultiBuffer::build_simple(&input_text, cx);
4088// Editor::new(editor_mode, buffer, None, None, cx)
4089// })
4090// .root(cx);
4091
4092// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
4093// let (_, layout_state) = editor.update(cx, |editor, cx| {
4094// editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4095// editor.set_wrap_width(Some(editor_width), cx);
4096
4097// element.layout(
4098// SizeConstraint::new(point(editor_width, 500.), point(editor_width, 500.)),
4099// editor,
4100// cx,
4101// )
4102// });
4103
4104// layout_state
4105// .position_map
4106// .line_layouts
4107// .iter()
4108// .map(|line_with_invisibles| &line_with_invisibles.invisibles)
4109// .flatten()
4110// .cloned()
4111// .collect()
4112// }
4113// }
4114
4115fn build_key_listener<T: 'static>(
4116 listener: impl Fn(
4117 &mut Editor,
4118 &T,
4119 &[&DispatchContext],
4120 DispatchPhase,
4121 &mut ViewContext<Editor>,
4122 ) -> Option<Box<dyn Action>>
4123 + 'static,
4124) -> (TypeId, KeyListener<Editor>) {
4125 (
4126 TypeId::of::<T>(),
4127 Box::new(move |editor, event, dispatch_context, phase, cx| {
4128 let key_event = event.downcast_ref::<T>()?;
4129 listener(editor, key_event, dispatch_context, phase, cx)
4130 }),
4131 )
4132}
4133
4134fn build_action_listener<T: Action>(
4135 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4136) -> (TypeId, KeyListener<Editor>) {
4137 build_key_listener(move |editor, action: &T, dispatch_context, phase, cx| {
4138 if phase == DispatchPhase::Bubble {
4139 listener(editor, action, cx);
4140 }
4141 None
4142 })
4143}