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