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)> = Vec::new();
1687 // todo!()
1688
1689 // fold_ranges
1690 // .into_iter()
1691 // .map(|(id, fold)| {
1692 // // todo!("folds!")
1693 // // let color = self
1694 // // .style
1695 // // .folds
1696 // // .ellipses
1697 // // .background
1698 // // .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
1699 // // .color;
1700
1701 // // (id, fold, color)
1702 // })
1703 // .collect();
1704
1705 let head_for_relative = newest_selection_head.unwrap_or_else(|| {
1706 let newest = editor.selections.newest::<Point>(cx);
1707 SelectionLayout::new(
1708 newest,
1709 editor.selections.line_mode,
1710 editor.cursor_shape,
1711 &snapshot.display_snapshot,
1712 true,
1713 true,
1714 )
1715 .head
1716 });
1717
1718 let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
1719 start_row..end_row,
1720 &active_rows,
1721 head_for_relative,
1722 is_singleton,
1723 &snapshot,
1724 cx,
1725 );
1726
1727 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
1728
1729 let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
1730
1731 let mut max_visible_line_width = Pixels::ZERO;
1732 let line_layouts =
1733 self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
1734 for line_with_invisibles in &line_layouts {
1735 if line_with_invisibles.line.width > max_visible_line_width {
1736 max_visible_line_width = line_with_invisibles.line.width;
1737 }
1738 }
1739
1740 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
1741 .unwrap()
1742 .width;
1743 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
1744 // todo!("blocks")
1745 // let (scroll_width, blocks) = self.layout_blocks(
1746 // start_row..end_row,
1747 // &snapshot,
1748 // size.x,
1749 // scroll_width,
1750 // gutter_padding,
1751 // gutter_width,
1752 // em_width,
1753 // gutter_width + gutter_margin,
1754 // line_height,
1755 // &style,
1756 // &line_layouts,
1757 // editor,
1758 // cx,
1759 // );
1760
1761 let scroll_max = point(
1762 f32::from((scroll_width - text_size.width) / em_width).max(0.0),
1763 max_row as f32,
1764 );
1765
1766 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
1767
1768 let autoscrolled = if autoscroll_horizontally {
1769 editor.autoscroll_horizontally(
1770 start_row,
1771 text_size.width,
1772 scroll_width,
1773 em_width,
1774 &line_layouts,
1775 cx,
1776 )
1777 } else {
1778 false
1779 };
1780
1781 if clamped || autoscrolled {
1782 snapshot = editor.snapshot(cx);
1783 }
1784
1785 let mut context_menu = None;
1786 let mut code_actions_indicator = None;
1787 if let Some(newest_selection_head) = newest_selection_head {
1788 if (start_row..end_row).contains(&newest_selection_head.row()) {
1789 if editor.context_menu_visible() {
1790 context_menu =
1791 editor.render_context_menu(newest_selection_head, &self.style, cx);
1792 }
1793
1794 let active = matches!(
1795 editor.context_menu.read().as_ref(),
1796 Some(crate::ContextMenu::CodeActions(_))
1797 );
1798
1799 code_actions_indicator = editor
1800 .render_code_actions_indicator(&style, active, cx)
1801 .map(|element| CodeActionsIndicator {
1802 row: newest_selection_head.row(),
1803 element,
1804 });
1805 }
1806 }
1807
1808 let visible_rows = start_row..start_row + line_layouts.len() as u32;
1809 // todo!("hover")
1810 // let mut hover = editor.hover_state.render(
1811 // &snapshot,
1812 // &style,
1813 // visible_rows,
1814 // editor.workspace.as_ref().map(|(w, _)| w.clone()),
1815 // cx,
1816 // );
1817 // let mode = editor.mode;
1818
1819 // todo!("fold_indicators")
1820 // let mut fold_indicators = editor.render_fold_indicators(
1821 // fold_statuses,
1822 // &style,
1823 // editor.gutter_hovered,
1824 // line_height,
1825 // gutter_margin,
1826 // cx,
1827 // );
1828
1829 // todo!("context_menu")
1830 // if let Some((_, context_menu)) = context_menu.as_mut() {
1831 // context_menu.layout(
1832 // SizeConstraint {
1833 // min: gpui::Point::<Pixels>::zero(),
1834 // max: point(
1835 // cx.window_size().x * 0.7,
1836 // (12. * line_height).min((size.y - line_height) / 2.),
1837 // ),
1838 // },
1839 // editor,
1840 // cx,
1841 // );
1842 // }
1843
1844 // todo!("fold indicators")
1845 // for fold_indicator in fold_indicators.iter_mut() {
1846 // if let Some(indicator) = fold_indicator.as_mut() {
1847 // indicator.layout(
1848 // SizeConstraint::strict_along(
1849 // Axis::Vertical,
1850 // line_height * style.code_actions.vertical_scale,
1851 // ),
1852 // editor,
1853 // cx,
1854 // );
1855 // }
1856 // }
1857
1858 // todo!("hover popovers")
1859 // if let Some((_, hover_popovers)) = hover.as_mut() {
1860 // for hover_popover in hover_popovers.iter_mut() {
1861 // hover_popover.layout(
1862 // SizeConstraint {
1863 // min: gpui::Point::<Pixels>::zero(),
1864 // max: point(
1865 // (120. * em_width) // Default size
1866 // .min(size.x / 2.) // Shrink to half of the editor width
1867 // .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1868 // (16. * line_height) // Default size
1869 // .min(size.y / 2.) // Shrink to half of the editor height
1870 // .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1871 // ),
1872 // },
1873 // editor,
1874 // cx,
1875 // );
1876 // }
1877 // }
1878
1879 let invisible_symbol_font_size = font_size / 2.;
1880 let tab_invisible = cx
1881 .text_system()
1882 .layout_text(
1883 "→",
1884 invisible_symbol_font_size,
1885 &[TextRun {
1886 len: "→".len(),
1887 font: self.style.text.font(),
1888 color: cx.theme().colors().editor_invisible,
1889 underline: None,
1890 }],
1891 None,
1892 )
1893 .unwrap()
1894 .pop()
1895 .unwrap();
1896 let space_invisible = cx
1897 .text_system()
1898 .layout_text(
1899 "•",
1900 invisible_symbol_font_size,
1901 &[TextRun {
1902 len: "•".len(),
1903 font: self.style.text.font(),
1904 color: cx.theme().colors().editor_invisible,
1905 underline: None,
1906 }],
1907 None,
1908 )
1909 .unwrap()
1910 .pop()
1911 .unwrap();
1912
1913 LayoutState {
1914 mode: editor_mode,
1915 position_map: Arc::new(PositionMap {
1916 size: bounds.size,
1917 scroll_max,
1918 line_layouts,
1919 line_height,
1920 em_width,
1921 em_advance,
1922 snapshot,
1923 }),
1924 visible_display_row_range: start_row..end_row,
1925 wrap_guides,
1926 gutter_size,
1927 gutter_padding,
1928 text_size,
1929 scrollbar_row_range,
1930 show_scrollbars,
1931 is_singleton,
1932 max_row,
1933 gutter_margin,
1934 active_rows,
1935 highlighted_rows,
1936 highlighted_ranges,
1937 fold_ranges,
1938 line_number_layouts,
1939 display_hunks,
1940 // blocks,
1941 selections,
1942 context_menu,
1943 code_actions_indicator,
1944 // fold_indicators,
1945 tab_invisible,
1946 space_invisible,
1947 // hover_popovers: hover,
1948 }
1949 }
1950
1951 // #[allow(clippy::too_many_arguments)]
1952 // fn layout_blocks(
1953 // &mut self,
1954 // rows: Range<u32>,
1955 // snapshot: &EditorSnapshot,
1956 // editor_width: f32,
1957 // scroll_width: f32,
1958 // gutter_padding: f32,
1959 // gutter_width: f32,
1960 // em_width: f32,
1961 // text_x: f32,
1962 // line_height: f32,
1963 // style: &EditorStyle,
1964 // line_layouts: &[LineWithInvisibles],
1965 // editor: &mut Editor,
1966 // cx: &mut ViewContext<Editor>,
1967 // ) -> (f32, Vec<BlockLayout>) {
1968 // let mut block_id = 0;
1969 // let scroll_x = snapshot.scroll_anchor.offset.x;
1970 // let (fixed_blocks, non_fixed_blocks) = snapshot
1971 // .blocks_in_range(rows.clone())
1972 // .partition::<Vec<_>, _>(|(_, block)| match block {
1973 // TransformBlock::ExcerptHeader { .. } => false,
1974 // TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1975 // });
1976 // let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
1977 // let mut element = match block {
1978 // TransformBlock::Custom(block) => {
1979 // let align_to = block
1980 // .position()
1981 // .to_point(&snapshot.buffer_snapshot)
1982 // .to_display_point(snapshot);
1983 // let anchor_x = text_x
1984 // + if rows.contains(&align_to.row()) {
1985 // line_layouts[(align_to.row() - rows.start) as usize]
1986 // .line
1987 // .x_for_index(align_to.column() as usize)
1988 // } else {
1989 // layout_line(align_to.row(), snapshot, style, cx.text_layout_cache())
1990 // .x_for_index(align_to.column() as usize)
1991 // };
1992
1993 // block.render(&mut BlockContext {
1994 // view_context: cx,
1995 // anchor_x,
1996 // gutter_padding,
1997 // line_height,
1998 // scroll_x,
1999 // gutter_width,
2000 // em_width,
2001 // block_id,
2002 // })
2003 // }
2004 // TransformBlock::ExcerptHeader {
2005 // id,
2006 // buffer,
2007 // range,
2008 // starts_new_buffer,
2009 // ..
2010 // } => {
2011 // let tooltip_style = theme::current(cx).tooltip.clone();
2012 // let include_root = editor
2013 // .project
2014 // .as_ref()
2015 // .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2016 // .unwrap_or_default();
2017 // let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
2018 // let jump_path = ProjectPath {
2019 // worktree_id: file.worktree_id(cx),
2020 // path: file.path.clone(),
2021 // };
2022 // let jump_anchor = range
2023 // .primary
2024 // .as_ref()
2025 // .map_or(range.context.start, |primary| primary.start);
2026 // let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2027
2028 // enum JumpIcon {}
2029 // MouseEventHandler::new::<JumpIcon, _>((*id).into(), cx, |state, _| {
2030 // let style = style.jump_icon.style_for(state);
2031 // Svg::new("icons/arrow_up_right.svg")
2032 // .with_color(style.color)
2033 // .constrained()
2034 // .with_width(style.icon_width)
2035 // .aligned()
2036 // .contained()
2037 // .with_style(style.container)
2038 // .constrained()
2039 // .with_width(style.button_width)
2040 // .with_height(style.button_width)
2041 // })
2042 // .with_cursor_style(CursorStyle::PointingHand)
2043 // .on_click(MouseButton::Left, move |_, editor, cx| {
2044 // if let Some(workspace) = editor
2045 // .workspace
2046 // .as_ref()
2047 // .and_then(|(workspace, _)| workspace.upgrade(cx))
2048 // {
2049 // workspace.update(cx, |workspace, cx| {
2050 // Editor::jump(
2051 // workspace,
2052 // jump_path.clone(),
2053 // jump_position,
2054 // jump_anchor,
2055 // cx,
2056 // );
2057 // });
2058 // }
2059 // })
2060 // .with_tooltip::<JumpIcon>(
2061 // (*id).into(),
2062 // "Jump to Buffer".to_string(),
2063 // Some(Box::new(crate::OpenExcerpts)),
2064 // tooltip_style.clone(),
2065 // cx,
2066 // )
2067 // .aligned()
2068 // .flex_float()
2069 // });
2070
2071 // if *starts_new_buffer {
2072 // let editor_font_size = style.text.font_size;
2073 // let style = &style.diagnostic_path_header;
2074 // let font_size = (style.text_scale_factor * editor_font_size).round();
2075
2076 // let path = buffer.resolve_file_path(cx, include_root);
2077 // let mut filename = None;
2078 // let mut parent_path = None;
2079 // // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2080 // if let Some(path) = path {
2081 // filename = path.file_name().map(|f| f.to_string_lossy.to_string());
2082 // parent_path =
2083 // path.parent().map(|p| p.to_string_lossy.to_string() + "/");
2084 // }
2085
2086 // Flex::row()
2087 // .with_child(
2088 // Label::new(
2089 // filename.unwrap_or_else(|| "untitled".to_string()),
2090 // style.filename.text.clone().with_font_size(font_size),
2091 // )
2092 // .contained()
2093 // .with_style(style.filename.container)
2094 // .aligned(),
2095 // )
2096 // .with_children(parent_path.map(|path| {
2097 // Label::new(path, style.path.text.clone().with_font_size(font_size))
2098 // .contained()
2099 // .with_style(style.path.container)
2100 // .aligned()
2101 // }))
2102 // .with_children(jump_icon)
2103 // .contained()
2104 // .with_style(style.container)
2105 // .with_padding_left(gutter_padding)
2106 // .with_padding_right(gutter_padding)
2107 // .expanded()
2108 // .into_any_named("path header block")
2109 // } else {
2110 // let text_style = style.text.clone();
2111 // Flex::row()
2112 // .with_child(Label::new("⋯", text_style))
2113 // .with_children(jump_icon)
2114 // .contained()
2115 // .with_padding_left(gutter_padding)
2116 // .with_padding_right(gutter_padding)
2117 // .expanded()
2118 // .into_any_named("collapsed context")
2119 // }
2120 // }
2121 // };
2122
2123 // element.layout(
2124 // SizeConstraint {
2125 // min: gpui::Point::<Pixels>::zero(),
2126 // max: point(width, block.height() as f32 * line_height),
2127 // },
2128 // editor,
2129 // cx,
2130 // );
2131 // element
2132 // };
2133
2134 // let mut fixed_block_max_width = 0f32;
2135 // let mut blocks = Vec::new();
2136 // for (row, block) in fixed_blocks {
2137 // let element = render_block(block, f32::INFINITY, block_id);
2138 // block_id += 1;
2139 // fixed_block_max_width = fixed_block_max_width.max(element.size().x + em_width);
2140 // blocks.push(BlockLayout {
2141 // row,
2142 // element,
2143 // style: BlockStyle::Fixed,
2144 // });
2145 // }
2146 // for (row, block) in non_fixed_blocks {
2147 // let style = match block {
2148 // TransformBlock::Custom(block) => block.style(),
2149 // TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2150 // };
2151 // let width = match style {
2152 // BlockStyle::Sticky => editor_width,
2153 // BlockStyle::Flex => editor_width
2154 // .max(fixed_block_max_width)
2155 // .max(gutter_width + scroll_width),
2156 // BlockStyle::Fixed => unreachable!(),
2157 // };
2158 // let element = render_block(block, width, block_id);
2159 // block_id += 1;
2160 // blocks.push(BlockLayout {
2161 // row,
2162 // element,
2163 // style,
2164 // });
2165 // }
2166 // (
2167 // scroll_width.max(fixed_block_max_width - gutter_width),
2168 // blocks,
2169 // )
2170 // }
2171
2172 fn paint_mouse_listeners(
2173 &mut self,
2174 bounds: Bounds<Pixels>,
2175 gutter_bounds: Bounds<Pixels>,
2176 text_bounds: Bounds<Pixels>,
2177 position_map: &Arc<PositionMap>,
2178 cx: &mut ViewContext<Editor>,
2179 ) {
2180 cx.on_mouse_event({
2181 let position_map = position_map.clone();
2182 move |editor, event: &ScrollWheelEvent, phase, cx| {
2183 if phase != DispatchPhase::Bubble {
2184 return;
2185 }
2186
2187 if Self::scroll(editor, event, &position_map, bounds, cx) {
2188 cx.stop_propagation();
2189 }
2190 }
2191 });
2192 cx.on_mouse_event({
2193 let position_map = position_map.clone();
2194 move |editor, event: &MouseDownEvent, phase, cx| {
2195 if phase != DispatchPhase::Bubble {
2196 return;
2197 }
2198
2199 if Self::mouse_down(editor, event, &position_map, text_bounds, gutter_bounds, cx) {
2200 cx.stop_propagation()
2201 }
2202 }
2203 });
2204 cx.on_mouse_event({
2205 let position_map = position_map.clone();
2206 move |editor, event: &MouseUpEvent, phase, cx| {
2207 if phase != DispatchPhase::Bubble {
2208 return;
2209 }
2210
2211 if Self::mouse_up(editor, event, &position_map, text_bounds, cx) {
2212 cx.stop_propagation()
2213 }
2214 }
2215 });
2216 // todo!()
2217 // on_down(MouseButton::Right, {
2218 // let position_map = position_map.clone();
2219 // move |event, editor, cx| {
2220 // if !Self::mouse_right_down(
2221 // editor,
2222 // event.position,
2223 // position_map.as_ref(),
2224 // text_bounds,
2225 // cx,
2226 // ) {
2227 // cx.propagate_event();
2228 // }
2229 // }
2230 // });
2231 cx.on_mouse_event({
2232 let position_map = position_map.clone();
2233 move |editor, event: &MouseMoveEvent, phase, cx| {
2234 if phase != DispatchPhase::Bubble {
2235 return;
2236 }
2237
2238 if Self::mouse_moved(editor, event, &position_map, text_bounds, gutter_bounds, cx) {
2239 cx.stop_propagation()
2240 }
2241 }
2242 });
2243 }
2244}
2245
2246#[derive(Debug)]
2247pub struct LineWithInvisibles {
2248 pub line: Line,
2249 invisibles: Vec<Invisible>,
2250}
2251
2252impl LineWithInvisibles {
2253 fn from_chunks<'a>(
2254 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2255 text_style: &TextStyle,
2256 max_line_len: usize,
2257 max_line_count: usize,
2258 line_number_layouts: &[Option<Line>],
2259 editor_mode: EditorMode,
2260 cx: &WindowContext,
2261 ) -> Vec<Self> {
2262 let mut layouts = Vec::with_capacity(max_line_count);
2263 let mut line = String::new();
2264 let mut invisibles = Vec::new();
2265 let mut styles = Vec::new();
2266 let mut non_whitespace_added = false;
2267 let mut row = 0;
2268 let mut line_exceeded_max_len = false;
2269 let font_size = text_style.font_size.to_pixels(cx.rem_size());
2270
2271 for highlighted_chunk in chunks.chain([HighlightedChunk {
2272 chunk: "\n",
2273 style: None,
2274 is_tab: false,
2275 }]) {
2276 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2277 if ix > 0 {
2278 let layout = cx
2279 .text_system()
2280 .layout_text(&line, font_size, &styles, None);
2281 layouts.push(Self {
2282 line: layout.unwrap().pop().unwrap(),
2283 invisibles: invisibles.drain(..).collect(),
2284 });
2285
2286 line.clear();
2287 styles.clear();
2288 row += 1;
2289 line_exceeded_max_len = false;
2290 non_whitespace_added = false;
2291 if row == max_line_count {
2292 return layouts;
2293 }
2294 }
2295
2296 if !line_chunk.is_empty() && !line_exceeded_max_len {
2297 let text_style = if let Some(style) = highlighted_chunk.style {
2298 text_style
2299 .clone()
2300 .highlight(style)
2301 .map(Cow::Owned)
2302 .unwrap_or_else(|_| Cow::Borrowed(text_style))
2303 } else {
2304 Cow::Borrowed(text_style)
2305 };
2306
2307 if line.len() + line_chunk.len() > max_line_len {
2308 let mut chunk_len = max_line_len - line.len();
2309 while !line_chunk.is_char_boundary(chunk_len) {
2310 chunk_len -= 1;
2311 }
2312 line_chunk = &line_chunk[..chunk_len];
2313 line_exceeded_max_len = true;
2314 }
2315
2316 styles.push(TextRun {
2317 len: line_chunk.len(),
2318 font: text_style.font(),
2319 color: text_style.color,
2320 underline: text_style.underline,
2321 });
2322
2323 if editor_mode == EditorMode::Full {
2324 // Line wrap pads its contents with fake whitespaces,
2325 // avoid printing them
2326 let inside_wrapped_string = line_number_layouts
2327 .get(row)
2328 .and_then(|layout| layout.as_ref())
2329 .is_none();
2330 if highlighted_chunk.is_tab {
2331 if non_whitespace_added || !inside_wrapped_string {
2332 invisibles.push(Invisible::Tab {
2333 line_start_offset: line.len(),
2334 });
2335 }
2336 } else {
2337 invisibles.extend(
2338 line_chunk
2339 .chars()
2340 .enumerate()
2341 .filter(|(_, line_char)| {
2342 let is_whitespace = line_char.is_whitespace();
2343 non_whitespace_added |= !is_whitespace;
2344 is_whitespace
2345 && (non_whitespace_added || !inside_wrapped_string)
2346 })
2347 .map(|(whitespace_index, _)| Invisible::Whitespace {
2348 line_offset: line.len() + whitespace_index,
2349 }),
2350 )
2351 }
2352 }
2353
2354 line.push_str(line_chunk);
2355 }
2356 }
2357 }
2358
2359 layouts
2360 }
2361
2362 fn draw(
2363 &self,
2364 layout: &LayoutState,
2365 row: u32,
2366 scroll_top: Pixels,
2367 content_origin: gpui::Point<Pixels>,
2368 scroll_left: Pixels,
2369 whitespace_setting: ShowWhitespaceSetting,
2370 selection_ranges: &[Range<DisplayPoint>],
2371 cx: &mut ViewContext<Editor>,
2372 ) {
2373 let line_height = layout.position_map.line_height;
2374 let line_y = line_height * row as f32 - scroll_top;
2375
2376 self.line.paint(
2377 content_origin + gpui::point(-scroll_left, line_y),
2378 line_height,
2379 cx,
2380 );
2381
2382 self.draw_invisibles(
2383 &selection_ranges,
2384 layout,
2385 content_origin,
2386 scroll_left,
2387 line_y,
2388 row,
2389 line_height,
2390 whitespace_setting,
2391 cx,
2392 );
2393 }
2394
2395 fn draw_invisibles(
2396 &self,
2397 selection_ranges: &[Range<DisplayPoint>],
2398 layout: &LayoutState,
2399 content_origin: gpui::Point<Pixels>,
2400 scroll_left: Pixels,
2401 line_y: Pixels,
2402 row: u32,
2403 line_height: Pixels,
2404 whitespace_setting: ShowWhitespaceSetting,
2405 cx: &mut ViewContext<Editor>,
2406 ) {
2407 let allowed_invisibles_regions = match whitespace_setting {
2408 ShowWhitespaceSetting::None => return,
2409 ShowWhitespaceSetting::Selection => Some(selection_ranges),
2410 ShowWhitespaceSetting::All => None,
2411 };
2412
2413 for invisible in &self.invisibles {
2414 let (&token_offset, invisible_symbol) = match invisible {
2415 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2416 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2417 };
2418
2419 let x_offset = self.line.x_for_index(token_offset);
2420 let invisible_offset =
2421 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2422 let origin =
2423 content_origin + gpui::point(-scroll_left + x_offset + invisible_offset, line_y);
2424
2425 if let Some(allowed_regions) = allowed_invisibles_regions {
2426 let invisible_point = DisplayPoint::new(row, token_offset as u32);
2427 if !allowed_regions
2428 .iter()
2429 .any(|region| region.start <= invisible_point && invisible_point < region.end)
2430 {
2431 continue;
2432 }
2433 }
2434 invisible_symbol.paint(origin, line_height, cx);
2435 }
2436 }
2437}
2438
2439#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2440enum Invisible {
2441 Tab { line_start_offset: usize },
2442 Whitespace { line_offset: usize },
2443}
2444
2445impl Element<Editor> for EditorElement {
2446 type ElementState = ();
2447
2448 fn id(&self) -> Option<gpui::ElementId> {
2449 None
2450 }
2451
2452 fn initialize(
2453 &mut self,
2454 editor: &mut Editor,
2455 element_state: Option<Self::ElementState>,
2456 cx: &mut gpui::ViewContext<Editor>,
2457 ) -> Self::ElementState {
2458 editor.style = Some(self.style.clone()); // Long-term, we'd like to eliminate this.
2459
2460 let dispatch_context = editor.dispatch_context(cx);
2461 cx.with_element_id(cx.view().entity_id(), |global_id, cx| {
2462 cx.with_key_dispatch(
2463 dispatch_context,
2464 Some(editor.focus_handle.clone()),
2465 |_, cx| {
2466 register_action(cx, Editor::move_left);
2467 register_action(cx, Editor::move_right);
2468 register_action(cx, Editor::move_down);
2469 register_action(cx, Editor::move_up);
2470 // on_action(cx, Editor::new_file); todo!()
2471 // on_action(cx, Editor::new_file_in_direction); todo!()
2472 register_action(cx, Editor::cancel);
2473 register_action(cx, Editor::newline);
2474 register_action(cx, Editor::newline_above);
2475 register_action(cx, Editor::newline_below);
2476 register_action(cx, Editor::backspace);
2477 register_action(cx, Editor::delete);
2478 register_action(cx, Editor::tab);
2479 register_action(cx, Editor::tab_prev);
2480 register_action(cx, Editor::indent);
2481 register_action(cx, Editor::outdent);
2482 register_action(cx, Editor::delete_line);
2483 register_action(cx, Editor::join_lines);
2484 register_action(cx, Editor::sort_lines_case_sensitive);
2485 register_action(cx, Editor::sort_lines_case_insensitive);
2486 register_action(cx, Editor::reverse_lines);
2487 register_action(cx, Editor::shuffle_lines);
2488 register_action(cx, Editor::convert_to_upper_case);
2489 register_action(cx, Editor::convert_to_lower_case);
2490 register_action(cx, Editor::convert_to_title_case);
2491 register_action(cx, Editor::convert_to_snake_case);
2492 register_action(cx, Editor::convert_to_kebab_case);
2493 register_action(cx, Editor::convert_to_upper_camel_case);
2494 register_action(cx, Editor::convert_to_lower_camel_case);
2495 register_action(cx, Editor::delete_to_previous_word_start);
2496 register_action(cx, Editor::delete_to_previous_subword_start);
2497 register_action(cx, Editor::delete_to_next_word_end);
2498 register_action(cx, Editor::delete_to_next_subword_end);
2499 register_action(cx, Editor::delete_to_beginning_of_line);
2500 register_action(cx, Editor::delete_to_end_of_line);
2501 register_action(cx, Editor::cut_to_end_of_line);
2502 register_action(cx, Editor::duplicate_line);
2503 register_action(cx, Editor::move_line_up);
2504 register_action(cx, Editor::move_line_down);
2505 register_action(cx, Editor::transpose);
2506 register_action(cx, Editor::cut);
2507 register_action(cx, Editor::copy);
2508 register_action(cx, Editor::paste);
2509 register_action(cx, Editor::undo);
2510 register_action(cx, Editor::redo);
2511 register_action(cx, Editor::move_page_up);
2512 register_action(cx, Editor::move_page_down);
2513 register_action(cx, Editor::next_screen);
2514 register_action(cx, Editor::scroll_cursor_top);
2515 register_action(cx, Editor::scroll_cursor_center);
2516 register_action(cx, Editor::scroll_cursor_bottom);
2517 register_action(cx, |editor, _: &LineDown, cx| {
2518 editor.scroll_screen(&ScrollAmount::Line(1.), cx)
2519 });
2520 register_action(cx, |editor, _: &LineUp, cx| {
2521 editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
2522 });
2523 register_action(cx, |editor, _: &HalfPageDown, cx| {
2524 editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
2525 });
2526 register_action(cx, |editor, _: &HalfPageUp, cx| {
2527 editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
2528 });
2529 register_action(cx, |editor, _: &PageDown, cx| {
2530 editor.scroll_screen(&ScrollAmount::Page(1.), cx)
2531 });
2532 register_action(cx, |editor, _: &PageUp, cx| {
2533 editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
2534 });
2535 register_action(cx, Editor::move_to_previous_word_start);
2536 register_action(cx, Editor::move_to_previous_subword_start);
2537 register_action(cx, Editor::move_to_next_word_end);
2538 register_action(cx, Editor::move_to_next_subword_end);
2539 register_action(cx, Editor::move_to_beginning_of_line);
2540 register_action(cx, Editor::move_to_end_of_line);
2541 register_action(cx, Editor::move_to_start_of_paragraph);
2542 register_action(cx, Editor::move_to_end_of_paragraph);
2543 register_action(cx, Editor::move_to_beginning);
2544 register_action(cx, Editor::move_to_end);
2545 register_action(cx, Editor::select_up);
2546 register_action(cx, Editor::select_down);
2547 register_action(cx, Editor::select_left);
2548 register_action(cx, Editor::select_right);
2549 register_action(cx, Editor::select_to_previous_word_start);
2550 register_action(cx, Editor::select_to_previous_subword_start);
2551 register_action(cx, Editor::select_to_next_word_end);
2552 register_action(cx, Editor::select_to_next_subword_end);
2553 register_action(cx, Editor::select_to_beginning_of_line);
2554 register_action(cx, Editor::select_to_end_of_line);
2555 register_action(cx, Editor::select_to_start_of_paragraph);
2556 register_action(cx, Editor::select_to_end_of_paragraph);
2557 register_action(cx, Editor::select_to_beginning);
2558 register_action(cx, Editor::select_to_end);
2559 register_action(cx, Editor::select_all);
2560 register_action(cx, |editor, action, cx| {
2561 editor.select_all_matches(action, cx).log_err();
2562 });
2563 register_action(cx, Editor::select_line);
2564 register_action(cx, Editor::split_selection_into_lines);
2565 register_action(cx, Editor::add_selection_above);
2566 register_action(cx, Editor::add_selection_below);
2567 register_action(cx, |editor, action, cx| {
2568 editor.select_next(action, cx).log_err();
2569 });
2570 register_action(cx, |editor, action, cx| {
2571 editor.select_previous(action, cx).log_err();
2572 });
2573 register_action(cx, Editor::toggle_comments);
2574 register_action(cx, Editor::select_larger_syntax_node);
2575 register_action(cx, Editor::select_smaller_syntax_node);
2576 register_action(cx, Editor::move_to_enclosing_bracket);
2577 register_action(cx, Editor::undo_selection);
2578 register_action(cx, Editor::redo_selection);
2579 register_action(cx, Editor::go_to_diagnostic);
2580 register_action(cx, Editor::go_to_prev_diagnostic);
2581 register_action(cx, Editor::go_to_hunk);
2582 register_action(cx, Editor::go_to_prev_hunk);
2583 register_action(cx, Editor::go_to_definition);
2584 register_action(cx, Editor::go_to_definition_split);
2585 register_action(cx, Editor::go_to_type_definition);
2586 register_action(cx, Editor::go_to_type_definition_split);
2587 register_action(cx, Editor::fold);
2588 register_action(cx, Editor::fold_at);
2589 register_action(cx, Editor::unfold_lines);
2590 register_action(cx, Editor::unfold_at);
2591 register_action(cx, Editor::fold_selected_ranges);
2592 register_action(cx, Editor::show_completions);
2593 register_action(cx, Editor::toggle_code_actions);
2594 // on_action(cx, Editor::open_excerpts); todo!()
2595 register_action(cx, Editor::toggle_soft_wrap);
2596 register_action(cx, Editor::toggle_inlay_hints);
2597 register_action(cx, Editor::reveal_in_finder);
2598 register_action(cx, Editor::copy_path);
2599 register_action(cx, Editor::copy_relative_path);
2600 register_action(cx, Editor::copy_highlight_json);
2601 register_action(cx, |editor, action, cx| {
2602 editor
2603 .format(action, cx)
2604 .map(|task| task.detach_and_log_err(cx));
2605 });
2606 register_action(cx, Editor::restart_language_server);
2607 register_action(cx, Editor::show_character_palette);
2608 // on_action(cx, Editor::confirm_completion); todo!()
2609 register_action(cx, |editor, action, cx| {
2610 editor
2611 .confirm_code_action(action, cx)
2612 .map(|task| task.detach_and_log_err(cx));
2613 });
2614 // on_action(cx, Editor::rename); todo!()
2615 // on_action(cx, Editor::confirm_rename); todo!()
2616 // on_action(cx, Editor::find_all_references); todo!()
2617 register_action(cx, Editor::next_copilot_suggestion);
2618 register_action(cx, Editor::previous_copilot_suggestion);
2619 register_action(cx, Editor::copilot_suggest);
2620 register_action(cx, Editor::context_menu_first);
2621 register_action(cx, Editor::context_menu_prev);
2622 register_action(cx, Editor::context_menu_next);
2623 register_action(cx, Editor::context_menu_last);
2624 },
2625 )
2626 });
2627 }
2628
2629 fn layout(
2630 &mut self,
2631 editor: &mut Editor,
2632 element_state: &mut Self::ElementState,
2633 cx: &mut gpui::ViewContext<Editor>,
2634 ) -> gpui::LayoutId {
2635 let rem_size = cx.rem_size();
2636 let mut style = Style::default();
2637 style.size.width = relative(1.).into();
2638 style.size.height = match editor.mode {
2639 EditorMode::SingleLine => self.style.text.line_height_in_pixels(cx.rem_size()).into(),
2640 EditorMode::AutoHeight { .. } => todo!(),
2641 EditorMode::Full => relative(1.).into(),
2642 };
2643 cx.request_layout(&style, None)
2644 }
2645
2646 fn paint(
2647 &mut self,
2648 bounds: Bounds<gpui::Pixels>,
2649 editor: &mut Editor,
2650 element_state: &mut Self::ElementState,
2651 cx: &mut gpui::ViewContext<Editor>,
2652 ) {
2653 let mut layout = self.compute_layout(editor, cx, bounds);
2654 let gutter_bounds = Bounds {
2655 origin: bounds.origin,
2656 size: layout.gutter_size,
2657 };
2658 let text_bounds = Bounds {
2659 origin: gutter_bounds.upper_right(),
2660 size: layout.text_size,
2661 };
2662
2663 // We call with_z_index to establish a new stacking context.
2664 cx.with_z_index(0, |cx| {
2665 cx.with_content_mask(ContentMask { bounds }, |cx| {
2666 self.paint_mouse_listeners(
2667 bounds,
2668 gutter_bounds,
2669 text_bounds,
2670 &layout.position_map,
2671 cx,
2672 );
2673 self.paint_background(gutter_bounds, text_bounds, &layout, cx);
2674 if layout.gutter_size.width > Pixels::ZERO {
2675 self.paint_gutter(gutter_bounds, &mut layout, editor, cx);
2676 }
2677 self.paint_text(text_bounds, &mut layout, editor, cx);
2678 let input_handler = ElementInputHandler::new(bounds, cx);
2679 cx.handle_input(&editor.focus_handle, input_handler);
2680 });
2681 });
2682 }
2683}
2684
2685// impl EditorElement {
2686// type LayoutState = LayoutState;
2687// type PaintState = ();
2688
2689// fn layout(
2690// &mut self,
2691// constraint: SizeConstraint,
2692// editor: &mut Editor,
2693// cx: &mut ViewContext<Editor>,
2694// ) -> (gpui::Point<Pixels>, Self::LayoutState) {
2695// let mut size = constraint.max;
2696// if size.x.is_infinite() {
2697// unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
2698// }
2699
2700// let snapshot = editor.snapshot(cx);
2701// let style = self.style.clone();
2702
2703// let line_height = (style.text.font_size * style.line_height_scalar).round();
2704
2705// let gutter_padding;
2706// let gutter_width;
2707// let gutter_margin;
2708// if snapshot.show_gutter {
2709// let em_width = style.text.em_width(cx.font_cache());
2710// gutter_padding = (em_width * style.gutter_padding_factor).round();
2711// gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
2712// gutter_margin = -style.text.descent(cx.font_cache());
2713// } else {
2714// gutter_padding = 0.0;
2715// gutter_width = 0.0;
2716// gutter_margin = 0.0;
2717// };
2718
2719// let text_width = size.x - gutter_width;
2720// let em_width = style.text.em_width(cx.font_cache());
2721// let em_advance = style.text.em_advance(cx.font_cache());
2722// let overscroll = point(em_width, 0.);
2723// let snapshot = {
2724// editor.set_visible_line_count(size.y / line_height, cx);
2725
2726// let editor_width = text_width - gutter_margin - overscroll.x - em_width;
2727// let wrap_width = match editor.soft_wrap_mode(cx) {
2728// SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2729// SoftWrap::EditorWidth => editor_width,
2730// SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2731// };
2732
2733// if editor.set_wrap_width(Some(wrap_width), cx) {
2734// editor.snapshot(cx)
2735// } else {
2736// snapshot
2737// }
2738// };
2739
2740// let wrap_guides = editor
2741// .wrap_guides(cx)
2742// .iter()
2743// .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2744// .collect();
2745
2746// let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
2747// if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
2748// size.set_y(
2749// scroll_height
2750// .min(constraint.max_along(Axis::Vertical))
2751// .max(constraint.min_along(Axis::Vertical))
2752// .max(line_height)
2753// .min(line_height * max_lines as f32),
2754// )
2755// } else if let EditorMode::SingleLine = snapshot.mode {
2756// size.set_y(line_height.max(constraint.min_along(Axis::Vertical)))
2757// } else if size.y.is_infinite() {
2758// size.set_y(scroll_height);
2759// }
2760// let gutter_size = point(gutter_width, size.y);
2761// let text_size = point(text_width, size.y);
2762
2763// let autoscroll_horizontally = editor.autoscroll_vertically(size.y, line_height, cx);
2764// let mut snapshot = editor.snapshot(cx);
2765
2766// let scroll_position = snapshot.scroll_position();
2767// // The scroll position is a fractional point, the whole number of which represents
2768// // the top of the window in terms of display rows.
2769// let start_row = scroll_position.y as u32;
2770// let height_in_lines = size.y / line_height;
2771// let max_row = snapshot.max_point().row();
2772
2773// // Add 1 to ensure selections bleed off screen
2774// let end_row = 1 + cmp::min(
2775// (scroll_position.y + height_in_lines).ceil() as u32,
2776// max_row,
2777// );
2778
2779// let start_anchor = if start_row == 0 {
2780// Anchor::min()
2781// } else {
2782// snapshot
2783// .buffer_snapshot
2784// .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
2785// };
2786// let end_anchor = if end_row > max_row {
2787// Anchor::max
2788// } else {
2789// snapshot
2790// .buffer_snapshot
2791// .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
2792// };
2793
2794// let mut selections: Vec<(SelectionStyle, Vec<SelectionLayout>)> = Vec::new();
2795// let mut active_rows = BTreeMap::new();
2796// let mut fold_ranges = Vec::new();
2797// let is_singleton = editor.is_singleton(cx);
2798
2799// let highlighted_rows = editor.highlighted_rows();
2800// let theme = theme::current(cx);
2801// let highlighted_ranges = editor.background_highlights_in_range(
2802// start_anchor..end_anchor,
2803// &snapshot.display_snapshot,
2804// theme.as_ref(),
2805// );
2806
2807// fold_ranges.extend(
2808// snapshot
2809// .folds_in_range(start_anchor..end_anchor)
2810// .map(|anchor| {
2811// let start = anchor.start.to_point(&snapshot.buffer_snapshot);
2812// (
2813// start.row,
2814// start.to_display_point(&snapshot.display_snapshot)
2815// ..anchor.end.to_display_point(&snapshot),
2816// )
2817// }),
2818// );
2819
2820// let mut newest_selection_head = None;
2821
2822// if editor.show_local_selections {
2823// let mut local_selections: Vec<Selection<Point>> = editor
2824// .selections
2825// .disjoint_in_range(start_anchor..end_anchor, cx);
2826// local_selections.extend(editor.selections.pending(cx));
2827// let mut layouts = Vec::new();
2828// let newest = editor.selections.newest(cx);
2829// for selection in local_selections.drain(..) {
2830// let is_empty = selection.start == selection.end;
2831// let is_newest = selection == newest;
2832
2833// let layout = SelectionLayout::new(
2834// selection,
2835// editor.selections.line_mode,
2836// editor.cursor_shape,
2837// &snapshot.display_snapshot,
2838// is_newest,
2839// true,
2840// );
2841// if is_newest {
2842// newest_selection_head = Some(layout.head);
2843// }
2844
2845// for row in cmp::max(layout.active_rows.start, start_row)
2846// ..=cmp::min(layout.active_rows.end, end_row)
2847// {
2848// let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
2849// *contains_non_empty_selection |= !is_empty;
2850// }
2851// layouts.push(layout);
2852// }
2853
2854// selections.push((style.selection, layouts));
2855// }
2856
2857// if let Some(collaboration_hub) = &editor.collaboration_hub {
2858// // When following someone, render the local selections in their color.
2859// if let Some(leader_id) = editor.leader_peer_id {
2860// if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
2861// if let Some(participant_index) = collaboration_hub
2862// .user_participant_indices(cx)
2863// .get(&collaborator.user_id)
2864// {
2865// if let Some((local_selection_style, _)) = selections.first_mut() {
2866// *local_selection_style =
2867// style.selection_style_for_room_participant(participant_index.0);
2868// }
2869// }
2870// }
2871// }
2872
2873// let mut remote_selections = HashMap::default();
2874// for selection in snapshot.remote_selections_in_range(
2875// &(start_anchor..end_anchor),
2876// collaboration_hub.as_ref(),
2877// cx,
2878// ) {
2879// let selection_style = if let Some(participant_index) = selection.participant_index {
2880// style.selection_style_for_room_participant(participant_index.0)
2881// } else {
2882// style.absent_selection
2883// };
2884
2885// // Don't re-render the leader's selections, since the local selections
2886// // match theirs.
2887// if Some(selection.peer_id) == editor.leader_peer_id {
2888// continue;
2889// }
2890
2891// remote_selections
2892// .entry(selection.replica_id)
2893// .or_insert((selection_style, Vec::new()))
2894// .1
2895// .push(SelectionLayout::new(
2896// selection.selection,
2897// selection.line_mode,
2898// selection.cursor_shape,
2899// &snapshot.display_snapshot,
2900// false,
2901// false,
2902// ));
2903// }
2904
2905// selections.extend(remote_selections.into_values());
2906// }
2907
2908// let scrollbar_settings = &settings::get::<EditorSettings>(cx).scrollbar;
2909// let show_scrollbars = match scrollbar_settings.show {
2910// ShowScrollbar::Auto => {
2911// // Git
2912// (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
2913// ||
2914// // Selections
2915// (is_singleton && scrollbar_settings.selections && !highlighted_ranges.is_empty)
2916// // Scrollmanager
2917// || editor.scroll_manager.scrollbars_visible()
2918// }
2919// ShowScrollbar::System => editor.scroll_manager.scrollbars_visible(),
2920// ShowScrollbar::Always => true,
2921// ShowScrollbar::Never => false,
2922// };
2923
2924// let fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Color)> = fold_ranges
2925// .into_iter()
2926// .map(|(id, fold)| {
2927// let color = self
2928// .style
2929// .folds
2930// .ellipses
2931// .background
2932// .style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
2933// .color;
2934
2935// (id, fold, color)
2936// })
2937// .collect();
2938
2939// let head_for_relative = newest_selection_head.unwrap_or_else(|| {
2940// let newest = editor.selections.newest::<Point>(cx);
2941// SelectionLayout::new(
2942// newest,
2943// editor.selections.line_mode,
2944// editor.cursor_shape,
2945// &snapshot.display_snapshot,
2946// true,
2947// true,
2948// )
2949// .head
2950// });
2951
2952// let (line_number_layouts, fold_statuses) = self.layout_line_numbers(
2953// start_row..end_row,
2954// &active_rows,
2955// head_for_relative,
2956// is_singleton,
2957// &snapshot,
2958// cx,
2959// );
2960
2961// let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
2962
2963// let scrollbar_row_range = scroll_position.y..(scroll_position.y + height_in_lines);
2964
2965// let mut max_visible_line_width = 0.0;
2966// let line_layouts =
2967// self.layout_lines(start_row..end_row, &line_number_layouts, &snapshot, cx);
2968// for line_with_invisibles in &line_layouts {
2969// if line_with_invisibles.line.width() > max_visible_line_width {
2970// max_visible_line_width = line_with_invisibles.line.width();
2971// }
2972// }
2973
2974// let style = self.style.clone();
2975// let longest_line_width = layout_line(
2976// snapshot.longest_row(),
2977// &snapshot,
2978// &style,
2979// cx.text_layout_cache(),
2980// )
2981// .width();
2982// let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x;
2983// let em_width = style.text.em_width(cx.font_cache());
2984// let (scroll_width, blocks) = self.layout_blocks(
2985// start_row..end_row,
2986// &snapshot,
2987// size.x,
2988// scroll_width,
2989// gutter_padding,
2990// gutter_width,
2991// em_width,
2992// gutter_width + gutter_margin,
2993// line_height,
2994// &style,
2995// &line_layouts,
2996// editor,
2997// cx,
2998// );
2999
3000// let scroll_max = point(
3001// ((scroll_width - text_size.x) / em_width).max(0.0),
3002// max_row as f32,
3003// );
3004
3005// let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3006
3007// let autoscrolled = if autoscroll_horizontally {
3008// editor.autoscroll_horizontally(
3009// start_row,
3010// text_size.x,
3011// scroll_width,
3012// em_width,
3013// &line_layouts,
3014// cx,
3015// )
3016// } else {
3017// false
3018// };
3019
3020// if clamped || autoscrolled {
3021// snapshot = editor.snapshot(cx);
3022// }
3023
3024// let style = editor.style(cx);
3025
3026// let mut context_menu = None;
3027// let mut code_actions_indicator = None;
3028// if let Some(newest_selection_head) = newest_selection_head {
3029// if (start_row..end_row).contains(&newest_selection_head.row()) {
3030// if editor.context_menu_visible() {
3031// context_menu =
3032// editor.render_context_menu(newest_selection_head, style.clone(), cx);
3033// }
3034
3035// let active = matches!(
3036// editor.context_menu.read().as_ref(),
3037// Some(crate::ContextMenu::CodeActions(_))
3038// );
3039
3040// code_actions_indicator = editor
3041// .render_code_actions_indicator(&style, active, cx)
3042// .map(|indicator| (newest_selection_head.row(), indicator));
3043// }
3044// }
3045
3046// let visible_rows = start_row..start_row + line_layouts.len() as u32;
3047// let mut hover = editor.hover_state.render(
3048// &snapshot,
3049// &style,
3050// visible_rows,
3051// editor.workspace.as_ref().map(|(w, _)| w.clone()),
3052// cx,
3053// );
3054// let mode = editor.mode;
3055
3056// let mut fold_indicators = editor.render_fold_indicators(
3057// fold_statuses,
3058// &style,
3059// editor.gutter_hovered,
3060// line_height,
3061// gutter_margin,
3062// cx,
3063// );
3064
3065// if let Some((_, context_menu)) = context_menu.as_mut() {
3066// context_menu.layout(
3067// SizeConstraint {
3068// min: gpui::Point::<Pixels>::zero(),
3069// max: point(
3070// cx.window_size().x * 0.7,
3071// (12. * line_height).min((size.y - line_height) / 2.),
3072// ),
3073// },
3074// editor,
3075// cx,
3076// );
3077// }
3078
3079// if let Some((_, indicator)) = code_actions_indicator.as_mut() {
3080// indicator.layout(
3081// SizeConstraint::strict_along(
3082// Axis::Vertical,
3083// line_height * style.code_actions.vertical_scale,
3084// ),
3085// editor,
3086// cx,
3087// );
3088// }
3089
3090// for fold_indicator in fold_indicators.iter_mut() {
3091// if let Some(indicator) = fold_indicator.as_mut() {
3092// indicator.layout(
3093// SizeConstraint::strict_along(
3094// Axis::Vertical,
3095// line_height * style.code_actions.vertical_scale,
3096// ),
3097// editor,
3098// cx,
3099// );
3100// }
3101// }
3102
3103// if let Some((_, hover_popovers)) = hover.as_mut() {
3104// for hover_popover in hover_popovers.iter_mut() {
3105// hover_popover.layout(
3106// SizeConstraint {
3107// min: gpui::Point::<Pixels>::zero(),
3108// max: point(
3109// (120. * em_width) // Default size
3110// .min(size.x / 2.) // Shrink to half of the editor width
3111// .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3112// (16. * line_height) // Default size
3113// .min(size.y / 2.) // Shrink to half of the editor height
3114// .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3115// ),
3116// },
3117// editor,
3118// cx,
3119// );
3120// }
3121// }
3122
3123// let invisible_symbol_font_size = self.style.text.font_size / 2.0;
3124// let invisible_symbol_style = RunStyle {
3125// color: self.style.whitespace,
3126// font_id: self.style.text.font_id,
3127// underline: Default::default(),
3128// };
3129
3130// (
3131// size,
3132// LayoutState {
3133// mode,
3134// position_map: Arc::new(PositionMap {
3135// size,
3136// scroll_max,
3137// line_layouts,
3138// line_height,
3139// em_width,
3140// em_advance,
3141// snapshot,
3142// }),
3143// visible_display_row_range: start_row..end_row,
3144// wrap_guides,
3145// gutter_size,
3146// gutter_padding,
3147// text_size,
3148// scrollbar_row_range,
3149// show_scrollbars,
3150// is_singleton,
3151// max_row,
3152// gutter_margin,
3153// active_rows,
3154// highlighted_rows,
3155// highlighted_ranges,
3156// fold_ranges,
3157// line_number_layouts,
3158// display_hunks,
3159// blocks,
3160// selections,
3161// context_menu,
3162// code_actions_indicator,
3163// fold_indicators,
3164// tab_invisible: cx.text_layout_cache().layout_str(
3165// "→",
3166// invisible_symbol_font_size,
3167// &[("→".len(), invisible_symbol_style)],
3168// ),
3169// space_invisible: cx.text_layout_cache().layout_str(
3170// "•",
3171// invisible_symbol_font_size,
3172// &[("•".len(), invisible_symbol_style)],
3173// ),
3174// hover_popovers: hover,
3175// },
3176// )
3177// }
3178
3179// fn paint(
3180// &mut self,
3181// bounds: Bounds<Pixels>,
3182// visible_bounds: Bounds<Pixels>,
3183// layout: &mut Self::LayoutState,
3184// editor: &mut Editor,
3185// cx: &mut ViewContext<Editor>,
3186// ) -> Self::PaintState {
3187// let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
3188// cx.scene().push_layer(Some(visible_bounds));
3189
3190// let gutter_bounds = Bounds::<Pixels>::new(bounds.origin, layout.gutter_size);
3191// let text_bounds = Bounds::<Pixels>::new(
3192// bounds.origin + point(layout.gutter_size.x, 0.0),
3193// layout.text_size,
3194// );
3195
3196// Self::attach_mouse_handlers(
3197// &layout.position_map,
3198// layout.hover_popovers.is_some(),
3199// visible_bounds,
3200// text_bounds,
3201// gutter_bounds,
3202// bounds,
3203// cx,
3204// );
3205
3206// self.paint_background(gutter_bounds, text_bounds, layout, cx);
3207// if layout.gutter_size.x > 0. {
3208// self.paint_gutter(gutter_bounds, visible_bounds, layout, editor, cx);
3209// }
3210// self.paint_text(text_bounds, visible_bounds, layout, editor, cx);
3211
3212// cx.scene().push_layer(Some(bounds));
3213// if !layout.blocks.is_empty {
3214// self.paint_blocks(bounds, visible_bounds, layout, editor, cx);
3215// }
3216// self.paint_scrollbar(bounds, layout, &editor, cx);
3217// cx.scene().pop_layer();
3218// cx.scene().pop_layer();
3219// }
3220
3221// fn rect_for_text_range(
3222// &self,
3223// range_utf16: Range<usize>,
3224// bounds: Bounds<Pixels>,
3225// _: Bounds<Pixels>,
3226// layout: &Self::LayoutState,
3227// _: &Self::PaintState,
3228// _: &Editor,
3229// _: &ViewContext<Editor>,
3230// ) -> Option<Bounds<Pixels>> {
3231// let text_bounds = Bounds::<Pixels>::new(
3232// bounds.origin + point(layout.gutter_size.x, 0.0),
3233// layout.text_size,
3234// );
3235// let content_origin = text_bounds.origin + point(layout.gutter_margin, 0.);
3236// let scroll_position = layout.position_map.snapshot.scroll_position();
3237// let start_row = scroll_position.y as u32;
3238// let scroll_top = scroll_position.y * layout.position_map.line_height;
3239// let scroll_left = scroll_position.x * layout.position_map.em_width;
3240
3241// let range_start = OffsetUtf16(range_utf16.start)
3242// .to_display_point(&layout.position_map.snapshot.display_snapshot);
3243// if range_start.row() < start_row {
3244// return None;
3245// }
3246
3247// let line = &layout
3248// .position_map
3249// .line_layouts
3250// .get((range_start.row() - start_row) as usize)?
3251// .line;
3252// let range_start_x = line.x_for_index(range_start.column() as usize);
3253// let range_start_y = range_start.row() as f32 * layout.position_map.line_height;
3254// Some(Bounds::<Pixels>::new(
3255// content_origin
3256// + point(
3257// range_start_x,
3258// range_start_y + layout.position_map.line_height,
3259// )
3260// - point(scroll_left, scroll_top),
3261// point(
3262// layout.position_map.em_width,
3263// layout.position_map.line_height,
3264// ),
3265// ))
3266// }
3267
3268// fn debug(
3269// &self,
3270// bounds: Bounds<Pixels>,
3271// _: &Self::LayoutState,
3272// _: &Self::PaintState,
3273// _: &Editor,
3274// _: &ViewContext<Editor>,
3275// ) -> json::Value {
3276// json!({
3277// "type": "BufferElement",
3278// "bounds": bounds.to_json()
3279// })
3280// }
3281// }
3282
3283type BufferRow = u32;
3284
3285pub struct LayoutState {
3286 position_map: Arc<PositionMap>,
3287 gutter_size: Size<Pixels>,
3288 gutter_padding: Pixels,
3289 gutter_margin: Pixels,
3290 text_size: gpui::Size<Pixels>,
3291 mode: EditorMode,
3292 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3293 visible_display_row_range: Range<u32>,
3294 active_rows: BTreeMap<u32, bool>,
3295 highlighted_rows: Option<Range<u32>>,
3296 line_number_layouts: Vec<Option<gpui::Line>>,
3297 display_hunks: Vec<DisplayDiffHunk>,
3298 // blocks: Vec<BlockLayout>,
3299 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3300 fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)>,
3301 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3302 scrollbar_row_range: Range<f32>,
3303 show_scrollbars: bool,
3304 is_singleton: bool,
3305 max_row: u32,
3306 context_menu: Option<(DisplayPoint, AnyElement<Editor>)>,
3307 code_actions_indicator: Option<CodeActionsIndicator>,
3308 // hover_popovers: Option<(DisplayPoint, Vec<AnyElement<Editor>>)>,
3309 // fold_indicators: Vec<Option<AnyElement<Editor>>>,
3310 tab_invisible: Line,
3311 space_invisible: Line,
3312}
3313
3314struct CodeActionsIndicator {
3315 row: u32,
3316 element: AnyElement<Editor>,
3317}
3318
3319struct PositionMap {
3320 size: Size<Pixels>,
3321 line_height: Pixels,
3322 scroll_max: gpui::Point<f32>,
3323 em_width: Pixels,
3324 em_advance: Pixels,
3325 line_layouts: Vec<LineWithInvisibles>,
3326 snapshot: EditorSnapshot,
3327}
3328
3329#[derive(Debug, Copy, Clone)]
3330pub struct PointForPosition {
3331 pub previous_valid: DisplayPoint,
3332 pub next_valid: DisplayPoint,
3333 pub exact_unclipped: DisplayPoint,
3334 pub column_overshoot_after_line_end: u32,
3335}
3336
3337impl PointForPosition {
3338 #[cfg(test)]
3339 pub fn valid(valid: DisplayPoint) -> Self {
3340 Self {
3341 previous_valid: valid,
3342 next_valid: valid,
3343 exact_unclipped: valid,
3344 column_overshoot_after_line_end: 0,
3345 }
3346 }
3347
3348 pub fn as_valid(&self) -> Option<DisplayPoint> {
3349 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3350 Some(self.previous_valid)
3351 } else {
3352 None
3353 }
3354 }
3355}
3356
3357impl PositionMap {
3358 fn point_for_position(
3359 &self,
3360 text_bounds: Bounds<Pixels>,
3361 position: gpui::Point<Pixels>,
3362 ) -> PointForPosition {
3363 let scroll_position = self.snapshot.scroll_position();
3364 let position = position - text_bounds.origin;
3365 let y = position.y.max(px(0.)).min(self.size.width);
3366 let x = position.x + (scroll_position.x * self.em_width);
3367 let row = (f32::from(y / self.line_height) + scroll_position.y) as u32;
3368
3369 let (column, x_overshoot_after_line_end) = if let Some(line) = self
3370 .line_layouts
3371 .get(row as usize - scroll_position.y as usize)
3372 .map(|&LineWithInvisibles { ref line, .. }| line)
3373 {
3374 if let Some(ix) = line.index_for_x(x) {
3375 (ix as u32, px(0.))
3376 } else {
3377 (line.len as u32, px(0.).max(x - line.width))
3378 }
3379 } else {
3380 (0, x)
3381 };
3382
3383 let mut exact_unclipped = DisplayPoint::new(row, column);
3384 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3385 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3386
3387 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3388 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3389 PointForPosition {
3390 previous_valid,
3391 next_valid,
3392 exact_unclipped,
3393 column_overshoot_after_line_end,
3394 }
3395 }
3396}
3397
3398struct BlockLayout {
3399 row: u32,
3400 element: AnyElement<Editor>,
3401 style: BlockStyle,
3402}
3403
3404fn layout_line(
3405 row: u32,
3406 snapshot: &EditorSnapshot,
3407 style: &EditorStyle,
3408 cx: &WindowContext,
3409) -> Result<Line> {
3410 let mut line = snapshot.line(row);
3411
3412 if line.len() > MAX_LINE_LEN {
3413 let mut len = MAX_LINE_LEN;
3414 while !line.is_char_boundary(len) {
3415 len -= 1;
3416 }
3417
3418 line.truncate(len);
3419 }
3420
3421 Ok(cx
3422 .text_system()
3423 .layout_text(
3424 &line,
3425 style.text.font_size.to_pixels(cx.rem_size()),
3426 &[TextRun {
3427 len: snapshot.line_len(row) as usize,
3428 font: style.text.font(),
3429 color: Hsla::default(),
3430 underline: None,
3431 }],
3432 None,
3433 )?
3434 .pop()
3435 .unwrap())
3436}
3437
3438#[derive(Debug)]
3439pub struct Cursor {
3440 origin: gpui::Point<Pixels>,
3441 block_width: Pixels,
3442 line_height: Pixels,
3443 color: Hsla,
3444 shape: CursorShape,
3445 block_text: Option<Line>,
3446}
3447
3448impl Cursor {
3449 pub fn new(
3450 origin: gpui::Point<Pixels>,
3451 block_width: Pixels,
3452 line_height: Pixels,
3453 color: Hsla,
3454 shape: CursorShape,
3455 block_text: Option<Line>,
3456 ) -> Cursor {
3457 Cursor {
3458 origin,
3459 block_width,
3460 line_height,
3461 color,
3462 shape,
3463 block_text,
3464 }
3465 }
3466
3467 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3468 Bounds {
3469 origin: self.origin + origin,
3470 size: size(self.block_width, self.line_height),
3471 }
3472 }
3473
3474 pub fn paint(&self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3475 let bounds = match self.shape {
3476 CursorShape::Bar => Bounds {
3477 origin: self.origin + origin,
3478 size: size(px(2.0), self.line_height),
3479 },
3480 CursorShape::Block | CursorShape::Hollow => Bounds {
3481 origin: self.origin + origin,
3482 size: size(self.block_width, self.line_height),
3483 },
3484 CursorShape::Underscore => Bounds {
3485 origin: self.origin
3486 + origin
3487 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3488 size: size(self.block_width, px(2.0)),
3489 },
3490 };
3491
3492 //Draw background or border quad
3493 if matches!(self.shape, CursorShape::Hollow) {
3494 cx.paint_quad(
3495 bounds,
3496 Corners::default(),
3497 transparent_black(),
3498 Edges::all(px(1.)),
3499 self.color,
3500 );
3501 } else {
3502 cx.paint_quad(
3503 bounds,
3504 Corners::default(),
3505 self.color,
3506 Edges::default(),
3507 transparent_black(),
3508 );
3509 }
3510
3511 if let Some(block_text) = &self.block_text {
3512 block_text.paint(self.origin + origin, self.line_height, cx);
3513 }
3514 }
3515
3516 pub fn shape(&self) -> CursorShape {
3517 self.shape
3518 }
3519}
3520
3521#[derive(Debug)]
3522pub struct HighlightedRange {
3523 pub start_y: Pixels,
3524 pub line_height: Pixels,
3525 pub lines: Vec<HighlightedRangeLine>,
3526 pub color: Hsla,
3527 pub corner_radius: Pixels,
3528}
3529
3530#[derive(Debug)]
3531pub struct HighlightedRangeLine {
3532 pub start_x: Pixels,
3533 pub end_x: Pixels,
3534}
3535
3536impl HighlightedRange {
3537 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
3538 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3539 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3540 self.paint_lines(
3541 self.start_y + self.line_height,
3542 &self.lines[1..],
3543 bounds,
3544 cx,
3545 );
3546 } else {
3547 self.paint_lines(self.start_y, &self.lines, bounds, cx);
3548 }
3549 }
3550
3551 fn paint_lines(
3552 &self,
3553 start_y: Pixels,
3554 lines: &[HighlightedRangeLine],
3555 bounds: Bounds<Pixels>,
3556 cx: &mut WindowContext,
3557 ) {
3558 if lines.is_empty() {
3559 return;
3560 }
3561
3562 let first_line = lines.first().unwrap();
3563 let last_line = lines.last().unwrap();
3564
3565 let first_top_left = point(first_line.start_x, start_y);
3566 let first_top_right = point(first_line.end_x, start_y);
3567
3568 let curve_height = point(Pixels::ZERO, self.corner_radius);
3569 let curve_width = |start_x: Pixels, end_x: Pixels| {
3570 let max = (end_x - start_x) / 2.;
3571 let width = if max < self.corner_radius {
3572 max
3573 } else {
3574 self.corner_radius
3575 };
3576
3577 point(width, Pixels::ZERO)
3578 };
3579
3580 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3581 let mut path = gpui::Path::new(first_top_right - top_curve_width);
3582 path.curve_to(first_top_right + curve_height, first_top_right);
3583
3584 let mut iter = lines.iter().enumerate().peekable();
3585 while let Some((ix, line)) = iter.next() {
3586 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3587
3588 if let Some((_, next_line)) = iter.peek() {
3589 let next_top_right = point(next_line.end_x, bottom_right.y);
3590
3591 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3592 Ordering::Equal => {
3593 path.line_to(bottom_right);
3594 }
3595 Ordering::Less => {
3596 let curve_width = curve_width(next_top_right.x, bottom_right.x);
3597 path.line_to(bottom_right - curve_height);
3598 if self.corner_radius > Pixels::ZERO {
3599 path.curve_to(bottom_right - curve_width, bottom_right);
3600 }
3601 path.line_to(next_top_right + curve_width);
3602 if self.corner_radius > Pixels::ZERO {
3603 path.curve_to(next_top_right + curve_height, next_top_right);
3604 }
3605 }
3606 Ordering::Greater => {
3607 let curve_width = curve_width(bottom_right.x, next_top_right.x);
3608 path.line_to(bottom_right - curve_height);
3609 if self.corner_radius > Pixels::ZERO {
3610 path.curve_to(bottom_right + curve_width, bottom_right);
3611 }
3612 path.line_to(next_top_right - curve_width);
3613 if self.corner_radius > Pixels::ZERO {
3614 path.curve_to(next_top_right + curve_height, next_top_right);
3615 }
3616 }
3617 }
3618 } else {
3619 let curve_width = curve_width(line.start_x, line.end_x);
3620 path.line_to(bottom_right - curve_height);
3621 if self.corner_radius > Pixels::ZERO {
3622 path.curve_to(bottom_right - curve_width, bottom_right);
3623 }
3624
3625 let bottom_left = point(line.start_x, bottom_right.y);
3626 path.line_to(bottom_left + curve_width);
3627 if self.corner_radius > Pixels::ZERO {
3628 path.curve_to(bottom_left - curve_height, bottom_left);
3629 }
3630 }
3631 }
3632
3633 if first_line.start_x > last_line.start_x {
3634 let curve_width = curve_width(last_line.start_x, first_line.start_x);
3635 let second_top_left = point(last_line.start_x, start_y + self.line_height);
3636 path.line_to(second_top_left + curve_height);
3637 if self.corner_radius > Pixels::ZERO {
3638 path.curve_to(second_top_left + curve_width, second_top_left);
3639 }
3640 let first_bottom_left = point(first_line.start_x, second_top_left.y);
3641 path.line_to(first_bottom_left - curve_width);
3642 if self.corner_radius > Pixels::ZERO {
3643 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3644 }
3645 }
3646
3647 path.line_to(first_top_left + curve_height);
3648 if self.corner_radius > Pixels::ZERO {
3649 path.curve_to(first_top_left + top_curve_width, first_top_left);
3650 }
3651 path.line_to(first_top_right - top_curve_width);
3652
3653 cx.paint_path(path, self.color);
3654 }
3655}
3656
3657// fn range_to_bounds(
3658// range: &Range<DisplayPoint>,
3659// content_origin: gpui::Point<Pixels>,
3660// scroll_left: f32,
3661// scroll_top: f32,
3662// visible_row_range: &Range<u32>,
3663// line_end_overshoot: f32,
3664// position_map: &PositionMap,
3665// ) -> impl Iterator<Item = Bounds<Pixels>> {
3666// let mut bounds: SmallVec<[Bounds<Pixels>; 1]> = SmallVec::new();
3667
3668// if range.start == range.end {
3669// return bounds.into_iter();
3670// }
3671
3672// let start_row = visible_row_range.start;
3673// let end_row = visible_row_range.end;
3674
3675// let row_range = if range.end.column() == 0 {
3676// cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3677// } else {
3678// cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3679// };
3680
3681// let first_y =
3682// content_origin.y + row_range.start as f32 * position_map.line_height - scroll_top;
3683
3684// for (idx, row) in row_range.enumerate() {
3685// let line_layout = &position_map.line_layouts[(row - start_row) as usize].line;
3686
3687// let start_x = if row == range.start.row() {
3688// content_origin.x + line_layout.x_for_index(range.start.column() as usize)
3689// - scroll_left
3690// } else {
3691// content_origin.x - scroll_left
3692// };
3693
3694// let end_x = if row == range.end.row() {
3695// content_origin.x + line_layout.x_for_index(range.end.column() as usize) - scroll_left
3696// } else {
3697// content_origin.x + line_layout.width() + line_end_overshoot - scroll_left
3698// };
3699
3700// bounds.push(Bounds::<Pixels>::from_points(
3701// point(start_x, first_y + position_map.line_height * idx as f32),
3702// point(end_x, first_y + position_map.line_height * (idx + 1) as f32),
3703// ))
3704// }
3705
3706// bounds.into_iter()
3707// }
3708
3709pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3710 (delta.pow(1.5) / 100.0).into()
3711}
3712
3713fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3714 (delta.pow(1.2) / 300.0).into()
3715}
3716
3717// #[cfg(test)]
3718// mod tests {
3719// use super::*;
3720// use crate::{
3721// display_map::{BlockDisposition, BlockProperties},
3722// editor_tests::{init_test, update_test_language_settings},
3723// Editor, MultiBuffer,
3724// };
3725// use gpui::TestAppContext;
3726// use language::language_settings;
3727// use log::info;
3728// use std::{num::NonZeroU32, sync::Arc};
3729// use util::test::sample_text;
3730
3731// #[gpui::test]
3732// fn test_layout_line_numbers(cx: &mut TestAppContext) {
3733// init_test(cx, |_| {});
3734// let editor = cx
3735// .add_window(|cx| {
3736// let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3737// Editor::new(EditorMode::Full, buffer, None, None, cx)
3738// })
3739// .root(cx);
3740// let element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3741
3742// let layouts = editor.update(cx, |editor, cx| {
3743// let snapshot = editor.snapshot(cx);
3744// element
3745// .layout_line_numbers(
3746// 0..6,
3747// &Default::default(),
3748// DisplayPoint::new(0, 0),
3749// false,
3750// &snapshot,
3751// cx,
3752// )
3753// .0
3754// });
3755// assert_eq!(layouts.len(), 6);
3756
3757// let relative_rows = editor.update(cx, |editor, cx| {
3758// let snapshot = editor.snapshot(cx);
3759// element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3760// });
3761// assert_eq!(relative_rows[&0], 3);
3762// assert_eq!(relative_rows[&1], 2);
3763// assert_eq!(relative_rows[&2], 1);
3764// // current line has no relative number
3765// assert_eq!(relative_rows[&4], 1);
3766// assert_eq!(relative_rows[&5], 2);
3767
3768// // works if cursor is before screen
3769// let relative_rows = editor.update(cx, |editor, cx| {
3770// let snapshot = editor.snapshot(cx);
3771
3772// element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3773// });
3774// assert_eq!(relative_rows.len(), 3);
3775// assert_eq!(relative_rows[&3], 2);
3776// assert_eq!(relative_rows[&4], 3);
3777// assert_eq!(relative_rows[&5], 4);
3778
3779// // works if cursor is after screen
3780// let relative_rows = editor.update(cx, |editor, cx| {
3781// let snapshot = editor.snapshot(cx);
3782
3783// element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3784// });
3785// assert_eq!(relative_rows.len(), 3);
3786// assert_eq!(relative_rows[&0], 5);
3787// assert_eq!(relative_rows[&1], 4);
3788// assert_eq!(relative_rows[&2], 3);
3789// }
3790
3791// #[gpui::test]
3792// async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3793// init_test(cx, |_| {});
3794
3795// let editor = cx
3796// .add_window(|cx| {
3797// let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3798// Editor::new(EditorMode::Full, buffer, None, None, cx)
3799// })
3800// .root(cx);
3801// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3802// let (_, state) = editor.update(cx, |editor, cx| {
3803// editor.cursor_shape = CursorShape::Block;
3804// editor.change_selections(None, cx, |s| {
3805// s.select_ranges([
3806// Point::new(0, 0)..Point::new(1, 0),
3807// Point::new(3, 2)..Point::new(3, 3),
3808// Point::new(5, 6)..Point::new(6, 0),
3809// ]);
3810// });
3811// element.layout(
3812// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3813// editor,
3814// cx,
3815// )
3816// });
3817// assert_eq!(state.selections.len(), 1);
3818// let local_selections = &state.selections[0].1;
3819// assert_eq!(local_selections.len(), 3);
3820// // moves cursor back one line
3821// assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3822// assert_eq!(
3823// local_selections[0].range,
3824// DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3825// );
3826
3827// // moves cursor back one column
3828// assert_eq!(
3829// local_selections[1].range,
3830// DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3831// );
3832// assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3833
3834// // leaves cursor on the max point
3835// assert_eq!(
3836// local_selections[2].range,
3837// DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3838// );
3839// assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3840
3841// // active lines does not include 1 (even though the range of the selection does)
3842// assert_eq!(
3843// state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3844// vec![0, 3, 5, 6]
3845// );
3846
3847// // multi-buffer support
3848// // in DisplayPoint co-ordinates, this is what we're dealing with:
3849// // 0: [[file
3850// // 1: header]]
3851// // 2: aaaaaa
3852// // 3: bbbbbb
3853// // 4: cccccc
3854// // 5:
3855// // 6: ...
3856// // 7: ffffff
3857// // 8: gggggg
3858// // 9: hhhhhh
3859// // 10:
3860// // 11: [[file
3861// // 12: header]]
3862// // 13: bbbbbb
3863// // 14: cccccc
3864// // 15: dddddd
3865// let editor = cx
3866// .add_window(|cx| {
3867// let buffer = MultiBuffer::build_multi(
3868// [
3869// (
3870// &(sample_text(8, 6, 'a') + "\n"),
3871// vec![
3872// Point::new(0, 0)..Point::new(3, 0),
3873// Point::new(4, 0)..Point::new(7, 0),
3874// ],
3875// ),
3876// (
3877// &(sample_text(8, 6, 'a') + "\n"),
3878// vec![Point::new(1, 0)..Point::new(3, 0)],
3879// ),
3880// ],
3881// cx,
3882// );
3883// Editor::new(EditorMode::Full, buffer, None, None, cx)
3884// })
3885// .root(cx);
3886// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3887// let (_, state) = editor.update(cx, |editor, cx| {
3888// editor.cursor_shape = CursorShape::Block;
3889// editor.change_selections(None, cx, |s| {
3890// s.select_display_ranges([
3891// DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
3892// DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
3893// ]);
3894// });
3895// element.layout(
3896// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3897// editor,
3898// cx,
3899// )
3900// });
3901
3902// assert_eq!(state.selections.len(), 1);
3903// let local_selections = &state.selections[0].1;
3904// assert_eq!(local_selections.len(), 2);
3905
3906// // moves cursor on excerpt boundary back a line
3907// // and doesn't allow selection to bleed through
3908// assert_eq!(
3909// local_selections[0].range,
3910// DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
3911// );
3912// assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
3913
3914// // moves cursor on buffer boundary back two lines
3915// // and doesn't allow selection to bleed through
3916// assert_eq!(
3917// local_selections[1].range,
3918// DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
3919// );
3920// assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
3921// }
3922
3923// #[gpui::test]
3924// fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
3925// init_test(cx, |_| {});
3926
3927// let editor = cx
3928// .add_window(|cx| {
3929// let buffer = MultiBuffer::build_simple("", cx);
3930// Editor::new(EditorMode::Full, buffer, None, None, cx)
3931// })
3932// .root(cx);
3933
3934// editor.update(cx, |editor, cx| {
3935// editor.set_placeholder_text("hello", cx);
3936// editor.insert_blocks(
3937// [BlockProperties {
3938// style: BlockStyle::Fixed,
3939// disposition: BlockDisposition::Above,
3940// height: 3,
3941// position: Anchor::min(),
3942// render: Arc::new(|_| Empty::new().into_any),
3943// }],
3944// None,
3945// cx,
3946// );
3947
3948// // Blur the editor so that it displays placeholder text.
3949// cx.blur();
3950// });
3951
3952// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
3953// let (size, mut state) = editor.update(cx, |editor, cx| {
3954// element.layout(
3955// SizeConstraint::new(point(500., 500.), point(500., 500.)),
3956// editor,
3957// cx,
3958// )
3959// });
3960
3961// assert_eq!(state.position_map.line_layouts.len(), 4);
3962// assert_eq!(
3963// state
3964// .line_number_layouts
3965// .iter()
3966// .map(Option::is_some)
3967// .collect::<Vec<_>>(),
3968// &[false, false, false, true]
3969// );
3970
3971// // Don't panic.
3972// let bounds = Bounds::<Pixels>::new(Default::default(), size);
3973// editor.update(cx, |editor, cx| {
3974// element.paint(bounds, bounds, &mut state, editor, cx);
3975// });
3976// }
3977
3978// #[gpui::test]
3979// fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
3980// const TAB_SIZE: u32 = 4;
3981
3982// let input_text = "\t \t|\t| a b";
3983// let expected_invisibles = vec![
3984// Invisible::Tab {
3985// line_start_offset: 0,
3986// },
3987// Invisible::Whitespace {
3988// line_offset: TAB_SIZE as usize,
3989// },
3990// Invisible::Tab {
3991// line_start_offset: TAB_SIZE as usize + 1,
3992// },
3993// Invisible::Tab {
3994// line_start_offset: TAB_SIZE as usize * 2 + 1,
3995// },
3996// Invisible::Whitespace {
3997// line_offset: TAB_SIZE as usize * 3 + 1,
3998// },
3999// Invisible::Whitespace {
4000// line_offset: TAB_SIZE as usize * 3 + 3,
4001// },
4002// ];
4003// assert_eq!(
4004// expected_invisibles.len(),
4005// input_text
4006// .chars()
4007// .filter(|initial_char| initial_char.is_whitespace())
4008// .count(),
4009// "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4010// );
4011
4012// init_test(cx, |s| {
4013// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4014// s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4015// });
4016
4017// let actual_invisibles =
4018// collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, 500.0);
4019
4020// assert_eq!(expected_invisibles, actual_invisibles);
4021// }
4022
4023// #[gpui::test]
4024// fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4025// init_test(cx, |s| {
4026// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4027// s.defaults.tab_size = NonZeroU32::new(4);
4028// });
4029
4030// for editor_mode_without_invisibles in [
4031// EditorMode::SingleLine,
4032// EditorMode::AutoHeight { max_lines: 100 },
4033// ] {
4034// let invisibles = collect_invisibles_from_new_editor(
4035// cx,
4036// editor_mode_without_invisibles,
4037// "\t\t\t| | a b",
4038// 500.0,
4039// );
4040// assert!(invisibles.is_empty,
4041// "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4042// }
4043// }
4044
4045// #[gpui::test]
4046// fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4047// let tab_size = 4;
4048// let input_text = "a\tbcd ".repeat(9);
4049// let repeated_invisibles = [
4050// Invisible::Tab {
4051// line_start_offset: 1,
4052// },
4053// Invisible::Whitespace {
4054// line_offset: tab_size as usize + 3,
4055// },
4056// Invisible::Whitespace {
4057// line_offset: tab_size as usize + 4,
4058// },
4059// Invisible::Whitespace {
4060// line_offset: tab_size as usize + 5,
4061// },
4062// ];
4063// let expected_invisibles = std::iter::once(repeated_invisibles)
4064// .cycle()
4065// .take(9)
4066// .flatten()
4067// .collect::<Vec<_>>();
4068// assert_eq!(
4069// expected_invisibles.len(),
4070// input_text
4071// .chars()
4072// .filter(|initial_char| initial_char.is_whitespace())
4073// .count(),
4074// "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4075// );
4076// info!("Expected invisibles: {expected_invisibles:?}");
4077
4078// init_test(cx, |_| {});
4079
4080// // Put the same string with repeating whitespace pattern into editors of various size,
4081// // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4082// let resize_step = 10.0;
4083// let mut editor_width = 200.0;
4084// while editor_width <= 1000.0 {
4085// update_test_language_settings(cx, |s| {
4086// s.defaults.tab_size = NonZeroU32::new(tab_size);
4087// s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4088// s.defaults.preferred_line_length = Some(editor_width as u32);
4089// s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4090// });
4091
4092// let actual_invisibles =
4093// collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, editor_width);
4094
4095// // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4096// // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4097// let mut i = 0;
4098// for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4099// i = actual_index;
4100// match expected_invisibles.get(i) {
4101// Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4102// (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4103// | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4104// _ => {
4105// panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4106// }
4107// },
4108// None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4109// }
4110// }
4111// let missing_expected_invisibles = &expected_invisibles[i + 1..];
4112// assert!(
4113// missing_expected_invisibles.is_empty,
4114// "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4115// );
4116
4117// editor_width += resize_step;
4118// }
4119// }
4120
4121// fn collect_invisibles_from_new_editor(
4122// cx: &mut TestAppContext,
4123// editor_mode: EditorMode,
4124// input_text: &str,
4125// editor_width: f32,
4126// ) -> Vec<Invisible> {
4127// info!(
4128// "Creating editor with mode {editor_mode:?}, width {editor_width} and text '{input_text}'"
4129// );
4130// let editor = cx
4131// .add_window(|cx| {
4132// let buffer = MultiBuffer::build_simple(&input_text, cx);
4133// Editor::new(editor_mode, buffer, None, None, cx)
4134// })
4135// .root(cx);
4136
4137// let mut element = EditorElement::new(editor.read_with(cx, |editor, cx| editor.style(cx)));
4138// let (_, layout_state) = editor.update(cx, |editor, cx| {
4139// editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4140// editor.set_wrap_width(Some(editor_width), cx);
4141
4142// element.layout(
4143// SizeConstraint::new(point(editor_width, 500.), point(editor_width, 500.)),
4144// editor,
4145// cx,
4146// )
4147// });
4148
4149// layout_state
4150// .position_map
4151// .line_layouts
4152// .iter()
4153// .map(|line_with_invisibles| &line_with_invisibles.invisibles)
4154// .flatten()
4155// .cloned()
4156// .collect()
4157// }
4158// }
4159
4160fn register_action<T: Action>(
4161 cx: &mut ViewContext<Editor>,
4162 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4163) {
4164 cx.on_action(TypeId::of::<T>(), move |editor, action, phase, cx| {
4165 let action = action.downcast_ref().unwrap();
4166 if phase == DispatchPhase::Bubble {
4167 listener(editor, action, cx);
4168 }
4169 })
4170}