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