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