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