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 paint(
2644 &mut self,
2645 bounds: Bounds<gpui::Pixels>,
2646 editor: &mut Editor,
2647 element_state: &mut Self::ElementState,
2648 cx: &mut gpui::ViewContext<Editor>,
2649 ) {
2650 let mut layout = self.compute_layout(editor, cx, bounds);
2651 let gutter_bounds = Bounds {
2652 origin: bounds.origin,
2653 size: layout.gutter_size,
2654 };
2655 let text_bounds = Bounds {
2656 origin: gutter_bounds.upper_right(),
2657 size: layout.text_size,
2658 };
2659
2660 // We call with_z_index to establish a new stacking context.
2661 cx.with_z_index(0, |cx| {
2662 cx.with_content_mask(ContentMask { bounds }, |cx| {
2663 self.paint_mouse_listeners(
2664 bounds,
2665 gutter_bounds,
2666 text_bounds,
2667 &layout.position_map,
2668 cx,
2669 );
2670 self.paint_background(gutter_bounds, text_bounds, &layout, cx);
2671 if layout.gutter_size.width > Pixels::ZERO {
2672 self.paint_gutter(gutter_bounds, &mut layout, editor, cx);
2673 }
2674 self.paint_text(text_bounds, &mut layout, editor, cx);
2675 let input_handler = ElementInputHandler::new(bounds, cx);
2676 cx.handle_input(&editor.focus_handle, input_handler);
2677 });
2678 });
2679 }
2680}
2681
2682// impl EditorElement {
2683// type LayoutState = LayoutState;
2684// type PaintState = ();
2685
2686// fn layout(
2687// &mut self,
2688// constraint: SizeConstraint,
2689// editor: &mut Editor,
2690// cx: &mut ViewContext<Editor>,
2691// ) -> (gpui::Point<Pixels>, Self::LayoutState) {
2692// let mut size = constraint.max;
2693// if size.x.is_infinite() {
2694// unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2695// }
2696
2697// let snapshot = editor.snapshot(cx);
2698// let style = self.style.clone();
2699
2700// let line_height = (style.text.font_size * style.line_height_scalar).round();
2701
2702// let gutter_padding;
2703// let gutter_width;
2704// let gutter_margin;
2705// if snapshot.show_gutter {
2706// let em_width = style.text.em_width(cx.font_cache());
2707// gutter_padding = (em_width * style.gutter_padding_factor).round();
2708// gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2709// gutter_margin = -style.text.descent(cx.font_cache());
2710// } else {
2711// gutter_padding = 0.0;
2712// gutter_width = 0.0;
2713// gutter_margin = 0.0;
2714// };
2715
2716// let text_width = size.x - gutter_width;
2717// let em_width = style.text.em_width(cx.font_cache());
2718// let em_advance = style.text.em_advance(cx.font_cache());
2719// let overscroll = point(em_width, 0.);
2720// let snapshot = {
2721// editor.set_visible_line_count(size.y / line_height, cx);
2722
2723// let editor_width = text_width - gutter_margin - overscroll.x - em_width;
2724// let wrap_width = match editor.soft_wrap_mode(cx) {
2725// SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2726// SoftWrap::EditorWidth => editor_width,
2727// SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2728// };
2729
2730// if editor.set_wrap_width(Some(wrap_width), cx) {
2731// editor.snapshot(cx)
2732// } else {
2733// snapshot
2734// }
2735// };
2736
2737// let wrap_guides = editor
2738// .wrap_guides(cx)
2739// .iter()
2740// .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2741// .collect();
2742
2743// let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2744// if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2745// size.set_y(
2746// scroll_height
2747// .min(constraint.max_along(Axis::Vertical))
2748// .max(constraint.min_along(Axis::Vertical))
2749// .max(line_height)
2750// .min(line_height * max_lines as f32),
2751// )
2752// } else if let EditorMode::SingleLine = snapshot.mode {
2753// size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
2754// } else if size.y.is_infinite() {
2755// size.set_y(scroll_height);
2756// }
2757// let gutter_size = point(gutter_width, size.y);
2758// let text_size = point(text_width, size.y);
2759
2760// let autoscroll_horizontally = editor.autoscroll_vertically(size.y, line_height, cx);
2761// let mut snapshot = editor.snapshot(cx);
2762
2763// let scroll_position = snapshot.scroll_position();
2764// // The scroll position is a fractional point, the whole number of which represents
2765// // the top of the window in terms of display rows.
2766// let start_row = scroll_position.y as u32;
2767// let height_in_lines = size.y / line_height;
2768// let max_row = snapshot.max_point().row();
2769
2770// // Add 1 to ensure selections bleed off screen
2771// let end_row = 1 + cmp::min(
2772// (scroll_position.y + height_in_lines).ceil() as u32,
2773// max_row,
2774// );
2775
2776// let start_anchor = if start_row == 0 {
2777// Anchor::min()
2778// } else {
2779// snapshot
2780// .buffer_snapshot
2781// .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2782// };
2783// let end_anchor = if end_row > max_row {
2784// Anchor::max
2785// } else {
2786// snapshot
2787// .buffer_snapshot
2788// .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2789// };
2790
2791// let mut selections: Vec<(SelectionStyle, Vec<SelectionLayout>)> = Vec::new();
2792// let mut active_rows = BTreeMap::new();
2793// let mut fold_ranges = Vec::new();
2794// let is_singleton = editor.is_singleton(cx);
2795
2796// let highlighted_rows = editor.highlighted_rows();
2797// let theme = theme::current(cx);
2798// let highlighted_ranges = editor.background_highlights_in_range(
2799// start_anchor..end_anchor,
2800// &snapshot.display_snapshot,
2801// theme.as_ref(),
2802// );
2803
2804// fold_ranges.extend(
2805// snapshot
2806// .folds_in_range(start_anchor..end_anchor)
2807// .map(|anchor| {
2808// let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2809// (
2810// start.row,
2811// start.to_display_point(&snapshot.display_snapshot)
2812// ..anchor.end.to_display_point(&snapshot),
2813// )
2814// }),
2815// );
2816
2817// let mut newest_selection_head = None;
2818
2819// if editor.show_local_selections {
2820// let mut local_selections: Vec<Selection<Point>> = editor
2821// .selections
2822// .disjoint_in_range(start_anchor..end_anchor, cx);
2823// local_selections.extend(editor.selections.pending(cx));
2824// let mut layouts = Vec::new();
2825// let newest = editor.selections.newest(cx);
2826// for selection in local_selections.drain(..) {
2827// let is_empty = selection.start == selection.end;
2828// let is_newest = selection == newest;
2829
2830// let layout = SelectionLayout::new(
2831// selection,
2832// editor.selections.line_mode,
2833// editor.cursor_shape,
2834// &snapshot.display_snapshot,
2835// is_newest,
2836// true,
2837// );
2838// if is_newest {
2839// newest_selection_head = Some(layout.head);
2840// }
2841
2842// for row in cmp::max(layout.active_rows.start, start_row)
2843// ..=cmp::min(layout.active_rows.end, end_row)
2844// {
2845// let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2846// *contains_non_empty_selection |= !is_empty;
2847// }
2848// layouts.push(layout);
2849// }
2850
2851// selections.push((style.selection, layouts));
2852// }
2853
2854// if let Some(collaboration_hub) = &editor.collaboration_hub {
2855// // When following someone, render the local selections in their color.
2856// if let Some(leader_id) = editor.leader_peer_id {
2857// if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
2858// if let Some(participant_index) = collaboration_hub
2859// .user_participant_indices(cx)
2860// .get(&collaborator.user_id)
2861// {
2862// if let Some((local_selection_style, _)) = selections.first_mut() {
2863// *local_selection_style =
2864// style.selection_style_for_room_participant(participant_index.0);
2865// }
2866// }
2867// }
2868// }
2869
2870// let mut remote_selections = HashMap::default();
2871// for selection in snapshot.remote_selections_in_range(
2872// &(start_anchor..end_anchor),
2873// collaboration_hub.as_ref(),
2874// cx,
2875// ) {
2876// let selection_style = if let Some(participant_index) = selection.participant_index {
2877// style.selection_style_for_room_participant(participant_index.0)
2878// } else {
2879// style.absent_selection
2880// };
2881
2882// // Don't re-render the leader's selections, since the local selections
2883// // match theirs.
2884// if Some(selection.peer_id) == editor.leader_peer_id {
2885// continue;
2886// }
2887
2888// remote_selections
2889// .entry(selection.replica_id)
2890// .or_insert((selection_style, Vec::new()))
2891// .1
2892// .push(SelectionLayout::new(
2893// selection.selection,
2894// selection.line_mode,
2895// selection.cursor_shape,
2896// &snapshot.display_snapshot,
2897// false,
2898// false,
2899// ));
2900// }
2901
2902// selections.extend(remote_selections.into_values());
2903// }
2904
2905// let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2906// let show_scrollbars = match scrollbar_settings.show {
2907// ShowScrollbar::Auto => {
2908// // Git
2909// (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2910// ||
2911// // Selections
2912// (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty)
2913// // Scrollmanager
2914// || editor.scroll_manager.scrollbars_visible()
2915// }
2916// ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2917// ShowScrollbar::Always => true,
2918// ShowScrollbar::Never => false,
2919// };
2920
2921// let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2922// .into_iter()
2923// .map(|(id, fold)| {
2924// let color = self
2925// .style
2926// .folds
2927// .ellipses
2928// .background
2929// .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2930// .color;
2931
2932// (id, fold, color)
2933// })
2934// .collect();
2935
2936// let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2937// let newest = editor.selections.newest::<Point>(cx);
2938// SelectionLayout::new(
2939// newest,
2940// editor.selections.line_mode,
2941// editor.cursor_shape,
2942// &snapshot.display_snapshot,
2943// true,
2944// true,
2945// )
2946// .head
2947// });
2948
2949// let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2950// start_row..end_row,
2951// &active_rows,
2952// head_for_relative,
2953// is_singleton,
2954// &snapshot,
2955// cx,
2956// );
2957
2958// let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2959
2960// let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2961
2962// let mut max_visible_line_width = 0.0;
2963// let line_layouts =
2964// self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2965// for line_with_invisibles in &line_layouts {
2966// if line_with_invisibles.line.width() > max_visible_line_width {
2967// max_visible_line_width = line_with_invisibles.line.width();
2968// }
2969// }
2970
2971// let style = self.style.clone();
2972// let longest_line_width = layout_line(
2973// snapshot.longest_row(),
2974// &snapshot,
2975// &style,
2976// cx.text_layout_cache(),
2977// )
2978// .width();
2979// let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x;
2980// let em_width = style.text.em_width(cx.font_cache());
2981// let (scroll_width, blocks) = self.layout_blocks(
2982// start_row..end_row,
2983// &snapshot,
2984// size.x,
2985// scroll_width,
2986// gutter_padding,
2987// gutter_width,
2988// em_width,
2989// gutter_width + gutter_margin,
2990// line_height,
2991// &style,
2992// &line_layouts,
2993// editor,
2994// cx,
2995// );
2996
2997// let scroll_max = point(
2998// ((scroll_width - text_size.x) / em_width).max(0.0),
2999// max_row as f32,
3000// );
3001
3002// let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3003
3004// let autoscrolled = if autoscroll_horizontally {
3005// editor.autoscroll_horizontally(
3006// start_row,
3007// text_size.x,
3008// scroll_width,
3009// em_width,
3010// &line_layouts,
3011// cx,
3012// )
3013// } else {
3014// false
3015// };
3016
3017// if clamped || autoscrolled {
3018// snapshot = editor.snapshot(cx);
3019// }
3020
3021// let style = editor.style(cx);
3022
3023// let mut context_menu = None;
3024// let mut code_actions_indicator = None;
3025// if let Some(newest_selection_head) = newest_selection_head {
3026// if (start_row..end_row).contains(&newest_selection_head.row()) {
3027// if editor.context_menu_visible() {
3028// context_menu =
3029// editor.render_context_menu(newest_selection_head, style.clone(), cx);
3030// }
3031
3032// let active = matches!(
3033// editor.context_menu.read().as_ref(),
3034// Some(crate::ContextMenu::CodeActions(_))
3035// );
3036
3037// code_actions_indicator = editor
3038// .render_code_actions_indicator(&style, active, cx)
3039// .map(|indicator| (newest_selection_head.row(), indicator));
3040// }
3041// }
3042
3043// let visible_rows = start_row..start_row + line_layouts.len() as u32;
3044// let mut hover = editor.hover_state.render(
3045// &snapshot,
3046// &style,
3047// visible_rows,
3048// editor.workspace.as_ref().map(|(w, _)| w.clone()),
3049// cx,
3050// );
3051// let mode = editor.mode;
3052
3053// let mut fold_indicators = editor.render_fold_indicators(
3054// fold_statuses,
3055// &style,
3056// editor.gutter_hovered,
3057// line_height,
3058// gutter_margin,
3059// cx,
3060// );
3061
3062// if let Some((_, context_menu)) = context_menu.as_mut() {
3063// context_menu.layout(
3064// SizeConstraint {
3065// min: gpui::Point::<Pixels>::zero(),
3066// max: point(
3067// cx.window_size().x * 0.7,
3068// (12. * line_height).min((size.y - line_height) / 2.),
3069// ),
3070// },
3071// editor,
3072// cx,
3073// );
3074// }
3075
3076// if let Some((_, indicator)) = code_actions_indicator.as_mut() {
3077// indicator.layout(
3078// SizeConstraint::strict_along(
3079// Axis::Vertical,
3080// line_height * style.code_actions.vertical_scale,
3081// ),
3082// editor,
3083// cx,
3084// );
3085// }
3086
3087// for fold_indicator in fold_indicators.iter_mut() {
3088// if let Some(indicator) = fold_indicator.as_mut() {
3089// indicator.layout(
3090// SizeConstraint::strict_along(
3091// Axis::Vertical,
3092// line_height * style.code_actions.vertical_scale,
3093// ),
3094// editor,
3095// cx,
3096// );
3097// }
3098// }
3099
3100// if let Some((_, hover_popovers)) = hover.as_mut() {
3101// for hover_popover in hover_popovers.iter_mut() {
3102// hover_popover.layout(
3103// SizeConstraint {
3104// min: gpui::Point::<Pixels>::zero(),
3105// max: point(
3106// (120. * em_width) // Default size
3107// .min(size.x / 2.) // Shrink to half of the editor width
3108// .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3109// (16. * line_height) // Default size
3110// .min(size.y / 2.) // Shrink to half of the editor height
3111// .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3112// ),
3113// },
3114// editor,
3115// cx,
3116// );
3117// }
3118// }
3119
3120// let invisible_symbol_font_size = self.style.text.font_size / 2.0;
3121// let invisible_symbol_style = RunStyle {
3122// color: self.style.whitespace,
3123// font_id: self.style.text.font_id,
3124// underline: Default::default(),
3125// };
3126
3127// (
3128// size,
3129// LayoutState {
3130// mode,
3131// position_map: Arc::new(PositionMap {
3132// size,
3133// scroll_max,
3134// line_layouts,
3135// line_height,
3136// em_width,
3137// em_advance,
3138// snapshot,
3139// }),
3140// visible_display_row_range: start_row..end_row,
3141// wrap_guides,
3142// gutter_size,
3143// gutter_padding,
3144// text_size,
3145// scrollbar_row_range,
3146// show_scrollbars,
3147// is_singleton,
3148// max_row,
3149// gutter_margin,
3150// active_rows,
3151// highlighted_rows,
3152// highlighted_ranges,
3153// fold_ranges,
3154// line_number_layouts,
3155// display_hunks,
3156// blocks,
3157// selections,
3158// context_menu,
3159// code_actions_indicator,
3160// fold_indicators,
3161// tab_invisible: cx.text_layout_cache().layout_str(
3162// "→",
3163// invisible_symbol_font_size,
3164// &[("→".len(), invisible_symbol_style)],
3165// ),
3166// space_invisible: cx.text_layout_cache().layout_str(
3167// "•",
3168// invisible_symbol_font_size,
3169// &[("•".len(), invisible_symbol_style)],
3170// ),
3171// hover_popovers: hover,
3172// },
3173// )
3174// }
3175
3176// fn paint(
3177// &mut self,
3178// bounds: Bounds<Pixels>,
3179// visible_bounds: Bounds<Pixels>,
3180// layout: &mut Self::LayoutState,
3181// editor: &mut Editor,
3182// cx: &mut ViewContext<Editor>,
3183// ) -> Self::PaintState {
3184// let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
3185// cx.scene().push_layer(Some(visible_bounds));
3186
3187// let gutter_bounds = Bounds::<Pixels>::new(bounds.origin, layout.gutter_size);
3188// let text_bounds = Bounds::<Pixels>::new(
3189// bounds.origin + point(layout.gutter_size.x, 0.0),
3190// layout.text_size,
3191// );
3192
3193// Self::attach_mouse_handlers(
3194// &layout.position_map,
3195// layout.hover_popovers.is_some(),
3196// visible_bounds,
3197// text_bounds,
3198// gutter_bounds,
3199// bounds,
3200// cx,
3201// );
3202
3203// self.paint_background(gutter_bounds, text_bounds, layout, cx);
3204// if layout.gutter_size.x > 0. {
3205// self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
3206// }
3207// self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
3208
3209// cx.scene().push_layer(Some(bounds));
3210// if !layout.blocks.is_empty {
3211// self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
3212// }
3213// self.paint_scrollbar(bounds, layout, &editor, cx);
3214// cx.scene().pop_layer();
3215// cx.scene().pop_layer();
3216// }
3217
3218// fn rect_for_text_range(
3219// &self,
3220// range_utf16: Range<usize>,
3221// bounds: Bounds<Pixels>,
3222// _: Bounds<Pixels>,
3223// layout: &Self::LayoutState,
3224// _: &Self::PaintState,
3225// _: &Editor,
3226// _: &ViewContext<Editor>,
3227// ) -> Option<Bounds<Pixels>> {
3228// let text_bounds = Bounds::<Pixels>::new(
3229// bounds.origin + point(layout.gutter_size.x, 0.0),
3230// layout.text_size,
3231// );
3232// let content_origin = text_bounds.origin + point(layout.gutter_margin, 0.);
3233// let scroll_position = layout.position_map.snapshot.scroll_position();
3234// let start_row = scroll_position.y as u32;
3235// let scroll_top = scroll_position.y * layout.position_map.line_height;
3236// let scroll_left = scroll_position.x * layout.position_map.em_width;
3237
3238// let range_start = OffsetUtf16(range_utf16.start)
3239// .to_display_point(&layout.position_map.snapshot.display_snapshot);
3240// if range_start.row() < start_row {
3241// return None;
3242// }
3243
3244// let line = &layout
3245// .position_map
3246// .line_layouts
3247// .get((range_start.row() - start_row) as usize)?
3248// .line;
3249// let range_start_x = line.x_for_index(range_start.column() as usize);
3250// let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
3251// Some(Bounds::<Pixels>::new(
3252// content_origin
3253// + point(
3254// range_start_x,
3255// range_start_y + layout.position_map.line_height,
3256// )
3257// - point(scroll_left, scroll_top),
3258// point(
3259// layout.position_map.em_width,
3260// layout.position_map.line_height,
3261// ),
3262// ))
3263// }
3264
3265// fn debug(
3266// &self,
3267// bounds: Bounds<Pixels>,
3268// _: &Self::LayoutState,
3269// _: &Self::PaintState,
3270// _: &Editor,
3271// _: &ViewContext<Editor>,
3272// ) -> json::Value {
3273// json!({
3274// "type": "BufferElement",
3275// "bounds": bounds.to_json()
3276// })
3277// }
3278// }
3279
3280type BufferRow = u32;
3281
3282pub struct LayoutState {
3283 position_map: Arc<PositionMap>,
3284 gutter_size: Size<Pixels>,
3285 gutter_padding: Pixels,
3286 gutter_margin: Pixels,
3287 text_size: gpui::Size<Pixels>,
3288 mode: EditorMode,
3289 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3290 visible_display_row_range: Range<u32>,
3291 active_rows: BTreeMap<u32, bool>,
3292 highlighted_rows: Option<Range<u32>>,
3293 line_number_layouts: Vec<Option<gpui::Line>>,
3294 display_hunks: Vec<DisplayDiffHunk>,
3295 // blocks: Vec<BlockLayout>,
3296 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3297 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)>,
3298 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3299 scrollbar_row_range: Range<f32>,
3300 show_scrollbars: bool,
3301 is_singleton: bool,
3302 max_row: u32,
3303 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
3304 code_actions_indicator: Option<CodeActionsIndicator>,
3305 // hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
3306 // fold_indicators: Vec<Option<AnyElement<Editor>>>,
3307 tab_invisible: Line,
3308 space_invisible: Line,
3309}
3310
3311struct CodeActionsIndicator {
3312 row: u32,
3313 element: AnyElement<Editor>,
3314}
3315
3316struct PositionMap {
3317 size: Size<Pixels>,
3318 line_height: Pixels,
3319 scroll_max: gpui::Point<f32>,
3320 em_width: Pixels,
3321 em_advance: Pixels,
3322 line_layouts: Vec<LineWithInvisibles>,
3323 snapshot: EditorSnapshot,
3324}
3325
3326#[derive(Debug, Copy, Clone)]
3327pub struct PointForPosition {
3328 pub previous_valid: DisplayPoint,
3329 pub next_valid: DisplayPoint,
3330 pub exact_unclipped: DisplayPoint,
3331 pub column_overshoot_after_line_end: u32,
3332}
3333
3334impl PointForPosition {
3335 #[cfg(test)]
3336 pub fn valid(valid: DisplayPoint) -> Self {
3337 Self {
3338 previous_valid: valid,
3339 next_valid: valid,
3340 exact_unclipped: valid,
3341 column_overshoot_after_line_end: 0,
3342 }
3343 }
3344
3345 pub fn as_valid(&self) -> Option<DisplayPoint> {
3346 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3347 Some(self.previous_valid)
3348 } else {
3349 None
3350 }
3351 }
3352}
3353
3354impl PositionMap {
3355 fn point_for_position(
3356 &self,
3357 text_bounds: Bounds<Pixels>,
3358 position: gpui::Point<Pixels>,
3359 ) -> PointForPosition {
3360 let scroll_position = self.snapshot.scroll_position();
3361 let position = position - text_bounds.origin;
3362 let y = position.y.max(px(0.)).min(self.size.width);
3363 let x = position.x + (scroll_position.x * self.em_width);
3364 let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3365
3366 let (column, x_overshoot_after_line_end) = if let Some(line) = self
3367 .line_layouts
3368 .get(row as usize - scroll_position.y as usize)
3369 .map(|&LineWithInvisibles { ref line, .. }| line)
3370 {
3371 if let Some(ix) = line.index_for_x(x) {
3372 (ix as u32, px(0.))
3373 } else {
3374 (line.len as u32, px(0.).max(x - line.width))
3375 }
3376 } else {
3377 (0, x)
3378 };
3379
3380 let mut exact_unclipped = DisplayPoint::new(row, column);
3381 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3382 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3383
3384 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3385 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3386 PointForPosition {
3387 previous_valid,
3388 next_valid,
3389 exact_unclipped,
3390 column_overshoot_after_line_end,
3391 }
3392 }
3393}
3394
3395struct BlockLayout {
3396 row: u32,
3397 element: AnyElement<Editor>,
3398 style: BlockStyle,
3399}
3400
3401fn layout_line(
3402 row: u32,
3403 snapshot: &EditorSnapshot,
3404 style: &EditorStyle,
3405 cx: &WindowContext,
3406) -> Result<Line> {
3407 let mut line = snapshot.line(row);
3408
3409 if line.len() > MAX_LINE_LEN {
3410 let mut len = MAX_LINE_LEN;
3411 while !line.is_char_boundary(len) {
3412 len -= 1;
3413 }
3414
3415 line.truncate(len);
3416 }
3417
3418 Ok(cx
3419 .text_system()
3420 .layout_text(
3421 &line,
3422 style.text.font_size.to_pixels(cx.rem_size()),
3423 &[TextRun {
3424 len: snapshot.line_len(row) as usize,
3425 font: style.text.font(),
3426 color: Hsla::default(),
3427 underline: None,
3428 }],
3429 None,
3430 )?
3431 .pop()
3432 .unwrap())
3433}
3434
3435#[derive(Debug)]
3436pub struct Cursor {
3437 origin: gpui::Point<Pixels>,
3438 block_width: Pixels,
3439 line_height: Pixels,
3440 color: Hsla,
3441 shape: CursorShape,
3442 block_text: Option<Line>,
3443}
3444
3445impl Cursor {
3446 pub fn new(
3447 origin: gpui::Point<Pixels>,
3448 block_width: Pixels,
3449 line_height: Pixels,
3450 color: Hsla,
3451 shape: CursorShape,
3452 block_text: Option<Line>,
3453 ) -> Cursor {
3454 Cursor {
3455 origin,
3456 block_width,
3457 line_height,
3458 color,
3459 shape,
3460 block_text,
3461 }
3462 }
3463
3464 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3465 Bounds {
3466 origin: self.origin + origin,
3467 size: size(self.block_width, self.line_height),
3468 }
3469 }
3470
3471 pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3472 let bounds = match self.shape {
3473 CursorShape::Bar => Bounds {
3474 origin: self.origin + origin,
3475 size: size(px(2.0), self.line_height),
3476 },
3477 CursorShape::Block | CursorShape::Hollow => Bounds {
3478 origin: self.origin + origin,
3479 size: size(self.block_width, self.line_height),
3480 },
3481 CursorShape::Underscore => Bounds {
3482 origin: self.origin
3483 + origin
3484 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3485 size: size(self.block_width, px(2.0)),
3486 },
3487 };
3488
3489 //Draw background or border quad
3490 if matches!(self.shape, CursorShape::Hollow) {
3491 cx.paint_quad(
3492 bounds,
3493 Corners::default(),
3494 transparent_black(),
3495 Edges::all(px(1.)),
3496 self.color,
3497 );
3498 } else {
3499 cx.paint_quad(
3500 bounds,
3501 Corners::default(),
3502 self.color,
3503 Edges::default(),
3504 transparent_black(),
3505 );
3506 }
3507
3508 if let Some(block_text) = &self.block_text {
3509 block_text.paint(self.origin + origin, self.line_height, cx);
3510 }
3511 }
3512
3513 pub fn shape(&self) -> CursorShape {
3514 self.shape
3515 }
3516}
3517
3518#[derive(Debug)]
3519pub struct HighlightedRange {
3520 pub start_y: Pixels,
3521 pub line_height: Pixels,
3522 pub lines: Vec<HighlightedRangeLine>,
3523 pub color: Hsla,
3524 pub corner_radius: Pixels,
3525}
3526
3527#[derive(Debug)]
3528pub struct HighlightedRangeLine {
3529 pub start_x: Pixels,
3530 pub end_x: Pixels,
3531}
3532
3533impl HighlightedRange {
3534 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
3535 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3536 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3537 self.paint_lines(
3538 self.start_y + self.line_height,
3539 &self.lines[1..],
3540 bounds,
3541 cx,
3542 );
3543 } else {
3544 self.paint_lines(self.start_y, &self.lines, bounds, cx);
3545 }
3546 }
3547
3548 fn paint_lines(
3549 &self,
3550 start_y: Pixels,
3551 lines: &[HighlightedRangeLine],
3552 bounds: Bounds<Pixels>,
3553 cx: &mut WindowContext,
3554 ) {
3555 if lines.is_empty() {
3556 return;
3557 }
3558
3559 let first_line = lines.first().unwrap();
3560 let last_line = lines.last().unwrap();
3561
3562 let first_top_left = point(first_line.start_x, start_y);
3563 let first_top_right = point(first_line.end_x, start_y);
3564
3565 let curve_height = point(Pixels::ZERO, self.corner_radius);
3566 let curve_width = |start_x: Pixels, end_x: Pixels| {
3567 let max = (end_x - start_x) / 2.;
3568 let width = if max < self.corner_radius {
3569 max
3570 } else {
3571 self.corner_radius
3572 };
3573
3574 point(width, Pixels::ZERO)
3575 };
3576
3577 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3578 let mut path = gpui::Path::new(first_top_right - top_curve_width);
3579 path.curve_to(first_top_right + curve_height, first_top_right);
3580
3581 let mut iter = lines.iter().enumerate().peekable();
3582 while let Some((ix, line)) = iter.next() {
3583 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3584
3585 if let Some((_, next_line)) = iter.peek() {
3586 let next_top_right = point(next_line.end_x, bottom_right.y);
3587
3588 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3589 Ordering::Equal => {
3590 path.line_to(bottom_right);
3591 }
3592 Ordering::Less => {
3593 let curve_width = curve_width(next_top_right.x, bottom_right.x);
3594 path.line_to(bottom_right - curve_height);
3595 if self.corner_radius > Pixels::ZERO {
3596 path.curve_to(bottom_right - curve_width, bottom_right);
3597 }
3598 path.line_to(next_top_right + curve_width);
3599 if self.corner_radius > Pixels::ZERO {
3600 path.curve_to(next_top_right + curve_height, next_top_right);
3601 }
3602 }
3603 Ordering::Greater => {
3604 let curve_width = curve_width(bottom_right.x, next_top_right.x);
3605 path.line_to(bottom_right - curve_height);
3606 if self.corner_radius > Pixels::ZERO {
3607 path.curve_to(bottom_right + curve_width, bottom_right);
3608 }
3609 path.line_to(next_top_right - curve_width);
3610 if self.corner_radius > Pixels::ZERO {
3611 path.curve_to(next_top_right + curve_height, next_top_right);
3612 }
3613 }
3614 }
3615 } else {
3616 let curve_width = curve_width(line.start_x, line.end_x);
3617 path.line_to(bottom_right - curve_height);
3618 if self.corner_radius > Pixels::ZERO {
3619 path.curve_to(bottom_right - curve_width, bottom_right);
3620 }
3621
3622 let bottom_left = point(line.start_x, bottom_right.y);
3623 path.line_to(bottom_left + curve_width);
3624 if self.corner_radius > Pixels::ZERO {
3625 path.curve_to(bottom_left - curve_height, bottom_left);
3626 }
3627 }
3628 }
3629
3630 if first_line.start_x > last_line.start_x {
3631 let curve_width = curve_width(last_line.start_x, first_line.start_x);
3632 let second_top_left = point(last_line.start_x, start_y + self.line_height);
3633 path.line_to(second_top_left + curve_height);
3634 if self.corner_radius > Pixels::ZERO {
3635 path.curve_to(second_top_left + curve_width, second_top_left);
3636 }
3637 let first_bottom_left = point(first_line.start_x, second_top_left.y);
3638 path.line_to(first_bottom_left - curve_width);
3639 if self.corner_radius > Pixels::ZERO {
3640 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3641 }
3642 }
3643
3644 path.line_to(first_top_left + curve_height);
3645 if self.corner_radius > Pixels::ZERO {
3646 path.curve_to(first_top_left + top_curve_width, first_top_left);
3647 }
3648 path.line_to(first_top_right - top_curve_width);
3649
3650 cx.paint_path(path, self.color);
3651 }
3652}
3653
3654// fn range_to_bounds(
3655// range: &Range<DisplayPoint>,
3656// content_origin: gpui::Point<Pixels>,
3657// scroll_left: f32,
3658// scroll_top: f32,
3659// visible_row_range: &Range<u32>,
3660// line_end_overshoot: f32,
3661// position_map: &PositionMap,
3662// ) -> impl Iterator<Item = Bounds<Pixels>> {
3663// let mut bounds: SmallVec<[Bounds<Pixels>; 1]> = SmallVec::new();
3664
3665// if range.start == range.end {
3666// return bounds.into_iter();
3667// }
3668
3669// let start_row = visible_row_range.start;
3670// let end_row = visible_row_range.end;
3671
3672// let row_range = if range.end.column() == 0 {
3673// cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3674// } else {
3675// cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3676// };
3677
3678// let first_y =
3679// content_origin.y + row_range.start as f32 * position_map.line_height - scroll_top;
3680
3681// for (idx, row) in row_range.enumerate() {
3682// let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
3683
3684// let start_x = if row == range.start.row() {
3685// content_origin.x + line_layout.x_for_index(range.start.column() as usize)
3686// - scroll_left
3687// } else {
3688// content_origin.x - scroll_left
3689// };
3690
3691// let end_x = if row == range.end.row() {
3692// content_origin.x + line_layout.x_for_index(range.end.column() as usize) - scroll_left
3693// } else {
3694// content_origin.x + line_layout.width() + line_end_overshoot - scroll_left
3695// };
3696
3697// bounds.push(Bounds::<Pixels>::from_points(
3698// point(start_x, first_y + position_map.line_height * idx as f32),
3699// point(end_x, first_y + position_map.line_height * (idx + 1) as f32),
3700// ))
3701// }
3702
3703// bounds.into_iter()
3704// }
3705
3706pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3707 (delta.pow(1.5) / 100.0).into()
3708}
3709
3710fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3711 (delta.pow(1.2) / 300.0).into()
3712}
3713
3714// #[cfg(test)]
3715// mod tests {
3716// use super::*;
3717// use crate::{
3718// display_map::{BlockDisposition, BlockProperties},
3719// editor_tests::{init_test, update_test_language_settings},
3720// Editor, MultiBuffer,
3721// };
3722// use gpui::TestAppContext;
3723// use language::language_settings;
3724// use log::info;
3725// use std::{num::NonZeroU32, sync::Arc};
3726// use util::test::sample_text;
3727
3728// #[gpui::test]
3729// fn test_layout_line_numbers(cx: &mut TestAppContext) {
3730// init_test(cx, |_| {});
3731// let editor = cx
3732// .add_window(|cx| {
3733// let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3734// Editor::new(EditorMode::Full, buffer, None, None, cx)
3735// })
3736// .root(cx);
3737// let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3738
3739// let layouts = editor.update(cx, |editor, cx| {
3740// let snapshot = editor.snapshot(cx);
3741// element
3742// .layout_line_numbers(
3743// 0..6,
3744// &Default::default(),
3745// DisplayPoint::new(0, 0),
3746// false,
3747// &snapshot,
3748// cx,
3749// )
3750// .0
3751// });
3752// assert_eq!(layouts.len(), 6);
3753
3754// let relative_rows = editor.update(cx, |editor, cx| {
3755// let snapshot = editor.snapshot(cx);
3756// element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3757// });
3758// assert_eq!(relative_rows[&0], 3);
3759// assert_eq!(relative_rows[&1], 2);
3760// assert_eq!(relative_rows[&2], 1);
3761// // current line has no relative number
3762// assert_eq!(relative_rows[&4], 1);
3763// assert_eq!(relative_rows[&5], 2);
3764
3765// // works if cursor is before screen
3766// let relative_rows = editor.update(cx, |editor, cx| {
3767// let snapshot = editor.snapshot(cx);
3768
3769// element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3770// });
3771// assert_eq!(relative_rows.len(), 3);
3772// assert_eq!(relative_rows[&3], 2);
3773// assert_eq!(relative_rows[&4], 3);
3774// assert_eq!(relative_rows[&5], 4);
3775
3776// // works if cursor is after screen
3777// let relative_rows = editor.update(cx, |editor, cx| {
3778// let snapshot = editor.snapshot(cx);
3779
3780// element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3781// });
3782// assert_eq!(relative_rows.len(), 3);
3783// assert_eq!(relative_rows[&0], 5);
3784// assert_eq!(relative_rows[&1], 4);
3785// assert_eq!(relative_rows[&2], 3);
3786// }
3787
3788// #[gpui::test]
3789// async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3790// init_test(cx, |_| {});
3791
3792// let editor = cx
3793// .add_window(|cx| {
3794// let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3795// Editor::new(EditorMode::Full, buffer, None, None, cx)
3796// })
3797// .root(cx);
3798// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3799// let (_, state) = editor.update(cx, |editor, cx| {
3800// editor.cursor_shape = CursorShape::Block;
3801// editor.change_selections(None, cx, |s| {
3802// s.select_ranges([
3803// Point::new(0, 0)..Point::new(1, 0),
3804// Point::new(3, 2)..Point::new(3, 3),
3805// Point::new(5, 6)..Point::new(6, 0),
3806// ]);
3807// });
3808// element.layout(
3809// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3810// editor,
3811// cx,
3812// )
3813// });
3814// assert_eq!(state.selections.len(), 1);
3815// let local_selections = &state.selections[0].1;
3816// assert_eq!(local_selections.len(), 3);
3817// // moves cursor back one line
3818// assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3819// assert_eq!(
3820// local_selections[0].range,
3821// DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3822// );
3823
3824// // moves cursor back one column
3825// assert_eq!(
3826// local_selections[1].range,
3827// DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3828// );
3829// assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3830
3831// // leaves cursor on the max point
3832// assert_eq!(
3833// local_selections[2].range,
3834// DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3835// );
3836// assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3837
3838// // active lines does not include 1 (even though the range of the selection does)
3839// assert_eq!(
3840// state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3841// vec![0, 3, 5, 6]
3842// );
3843
3844// // multi-buffer support
3845// // in DisplayPoint co-ordinates, this is what we're dealing with:
3846// // 0: [[file
3847// // 1: header]]
3848// // 2: aaaaaa
3849// // 3: bbbbbb
3850// // 4: cccccc
3851// // 5:
3852// // 6: ...
3853// // 7: ffffff
3854// // 8: gggggg
3855// // 9: hhhhhh
3856// // 10:
3857// // 11: [[file
3858// // 12: header]]
3859// // 13: bbbbbb
3860// // 14: cccccc
3861// // 15: dddddd
3862// let editor = cx
3863// .add_window(|cx| {
3864// let buffer = MultiBuffer::build_multi(
3865// [
3866// (
3867// &(sample_text(8, 6, 'a') + "\n"),
3868// vec![
3869// Point::new(0, 0)..Point::new(3, 0),
3870// Point::new(4, 0)..Point::new(7, 0),
3871// ],
3872// ),
3873// (
3874// &(sample_text(8, 6, 'a') + "\n"),
3875// vec![Point::new(1, 0)..Point::new(3, 0)],
3876// ),
3877// ],
3878// cx,
3879// );
3880// Editor::new(EditorMode::Full, buffer, None, None, cx)
3881// })
3882// .root(cx);
3883// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3884// let (_, state) = editor.update(cx, |editor, cx| {
3885// editor.cursor_shape = CursorShape::Block;
3886// editor.change_selections(None, cx, |s| {
3887// s.select_display_ranges([
3888// DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3889// DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3890// ]);
3891// });
3892// element.layout(
3893// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3894// editor,
3895// cx,
3896// )
3897// });
3898
3899// assert_eq!(state.selections.len(), 1);
3900// let local_selections = &state.selections[0].1;
3901// assert_eq!(local_selections.len(), 2);
3902
3903// // moves cursor on excerpt boundary back a line
3904// // and doesn't allow selection to bleed through
3905// assert_eq!(
3906// local_selections[0].range,
3907// DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3908// );
3909// assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3910
3911// // moves cursor on buffer boundary back two lines
3912// // and doesn't allow selection to bleed through
3913// assert_eq!(
3914// local_selections[1].range,
3915// DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3916// );
3917// assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3918// }
3919
3920// #[gpui::test]
3921// fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3922// init_test(cx, |_| {});
3923
3924// let editor = cx
3925// .add_window(|cx| {
3926// let buffer = MultiBuffer::build_simple("", cx);
3927// Editor::new(EditorMode::Full, buffer, None, None, cx)
3928// })
3929// .root(cx);
3930
3931// editor.update(cx, |editor, cx| {
3932// editor.set_placeholder_text("hello", cx);
3933// editor.insert_blocks(
3934// [BlockProperties {
3935// style: BlockStyle::Fixed,
3936// disposition: BlockDisposition::Above,
3937// height: 3,
3938// position: Anchor::min(),
3939// render: Arc::new(|_| Empty::new().into_any),
3940// }],
3941// None,
3942// cx,
3943// );
3944
3945// // Blur the editor so that it displays placeholder text.
3946// cx.blur();
3947// });
3948
3949// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3950// let (size, mut state) = editor.update(cx, |editor, cx| {
3951// element.layout(
3952// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3953// editor,
3954// cx,
3955// )
3956// });
3957
3958// assert_eq!(state.position_map.line_layouts.len(), 4);
3959// assert_eq!(
3960// state
3961// .line_number_layouts
3962// .iter()
3963// .map(Option::is_some)
3964// .collect::<Vec<_>>(),
3965// &[false, false, false, true]
3966// );
3967
3968// // Don't panic.
3969// let bounds = Bounds::<Pixels>::new(Default::default(), size);
3970// editor.update(cx, |editor, cx| {
3971// element.paint(bounds, bounds, &mut state, editor, cx);
3972// });
3973// }
3974
3975// #[gpui::test]
3976// fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3977// const TAB_SIZE: u32 = 4;
3978
3979// let input_text = "\t \t|\t| a b";
3980// let expected_invisibles = vec![
3981// Invisible::Tab {
3982// line_start_offset: 0,
3983// },
3984// Invisible::Whitespace {
3985// line_offset: TAB_SIZE as usize,
3986// },
3987// Invisible::Tab {
3988// line_start_offset: TAB_SIZE as usize + 1,
3989// },
3990// Invisible::Tab {
3991// line_start_offset: TAB_SIZE as usize * 2 + 1,
3992// },
3993// Invisible::Whitespace {
3994// line_offset: TAB_SIZE as usize * 3 + 1,
3995// },
3996// Invisible::Whitespace {
3997// line_offset: TAB_SIZE as usize * 3 + 3,
3998// },
3999// ];
4000// assert_eq!(
4001// expected_invisibles.len(),
4002// input_text
4003// .chars()
4004// .filter(|initial_char| initial_char.is_whitespace())
4005// .count(),
4006// "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4007// );
4008
4009// init_test(cx, |s| {
4010// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4011// s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4012// });
4013
4014// let actual_invisibles =
4015// collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
4016
4017// assert_eq!(expected_invisibles, actual_invisibles);
4018// }
4019
4020// #[gpui::test]
4021// fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4022// init_test(cx, |s| {
4023// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4024// s.defaults.tab_size = NonZeroU32::new(4);
4025// });
4026
4027// for editor_mode_without_invisibles in [
4028// EditorMode::SingleLine,
4029// EditorMode::AutoHeight { max_lines: 100 },
4030// ] {
4031// let invisibles = collect_invisibles_from_new_editor(
4032// cx,
4033// editor_mode_without_invisibles,
4034// "\t\t\t| | a b",
4035// 500.0,
4036// );
4037// assert!(invisibles.is_empty,
4038// "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4039// }
4040// }
4041
4042// #[gpui::test]
4043// fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4044// let tab_size = 4;
4045// let input_text = "a\tbcd ".repeat(9);
4046// let repeated_invisibles = [
4047// Invisible::Tab {
4048// line_start_offset: 1,
4049// },
4050// Invisible::Whitespace {
4051// line_offset: tab_size as usize + 3,
4052// },
4053// Invisible::Whitespace {
4054// line_offset: tab_size as usize + 4,
4055// },
4056// Invisible::Whitespace {
4057// line_offset: tab_size as usize + 5,
4058// },
4059// ];
4060// let expected_invisibles = std::iter::once(repeated_invisibles)
4061// .cycle()
4062// .take(9)
4063// .flatten()
4064// .collect::<Vec<_>>();
4065// assert_eq!(
4066// expected_invisibles.len(),
4067// input_text
4068// .chars()
4069// .filter(|initial_char| initial_char.is_whitespace())
4070// .count(),
4071// "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4072// );
4073// info!("Expected invisibles: {expected_invisibles:?}");
4074
4075// init_test(cx, |_| {});
4076
4077// // Put the same string with repeating whitespace pattern into editors of various size,
4078// // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4079// let resize_step = 10.0;
4080// let mut editor_width = 200.0;
4081// while editor_width <= 1000.0 {
4082// update_test_language_settings(cx, |s| {
4083// s.defaults.tab_size = NonZeroU32::new(tab_size);
4084// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4085// s.defaults.preferred_line_length = Some(editor_width as u32);
4086// s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4087// });
4088
4089// let actual_invisibles =
4090// collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
4091
4092// // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4093// // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4094// let mut i = 0;
4095// for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4096// i = actual_index;
4097// match expected_invisibles.get(i) {
4098// Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4099// (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4100// | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4101// _ => {
4102// panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4103// }
4104// },
4105// None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4106// }
4107// }
4108// let missing_expected_invisibles = &expected_invisibles[i + 1..];
4109// assert!(
4110// missing_expected_invisibles.is_empty,
4111// "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4112// );
4113
4114// editor_width += resize_step;
4115// }
4116// }
4117
4118// fn collect_invisibles_from_new_editor(
4119// cx: &mut TestAppContext,
4120// editor_mode: EditorMode,
4121// input_text: &str,
4122// editor_width: f32,
4123// ) -> Vec<Invisible> {
4124// info!(
4125// "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
4126// );
4127// let editor = cx
4128// .add_window(|cx| {
4129// let buffer = MultiBuffer::build_simple(&input_text, cx);
4130// Editor::new(editor_mode, buffer, None, None, cx)
4131// })
4132// .root(cx);
4133
4134// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
4135// let (_, layout_state) = editor.update(cx, |editor, cx| {
4136// editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4137// editor.set_wrap_width(Some(editor_width), cx);
4138
4139// element.layout(
4140// SizeConstraint::new(point(editor_width, 500.), point(editor_width, 500.)),
4141// editor,
4142// cx,
4143// )
4144// });
4145
4146// layout_state
4147// .position_map
4148// .line_layouts
4149// .iter()
4150// .map(|line_with_invisibles| &line_with_invisibles.invisibles)
4151// .flatten()
4152// .cloned()
4153// .collect()
4154// }
4155// }
4156
4157fn register_action<T: Action>(
4158 cx: &mut ViewContext<Editor>,
4159 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4160) {
4161 cx.on_action(TypeId::of::<T>(), move |editor, action, phase, cx| {
4162 let action = action.downcast_ref().unwrap();
4163 if phase == DispatchPhase::Bubble {
4164 listener(editor, action, cx);
4165 }
4166 })
4167}