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