1use super::{
2 display_map::{BlockContext, ToDisplayPoint},
3 Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Scroll, Select, SelectPhase,
4 SoftWrap, ToPoint, MAX_LINE_LEN,
5};
6use crate::{
7 display_map::{BlockStyle, DisplaySnapshot, TransformBlock},
8 hover_popover::HoverAt,
9 link_go_to_definition::{
10 CmdShiftChanged, GoToFetchedDefinition, GoToFetchedTypeDefinition, UpdateGoToDefinitionLink,
11 },
12 mouse_context_menu::DeployMouseContextMenu,
13 EditorStyle,
14};
15use clock::ReplicaId;
16use collections::{BTreeMap, HashMap};
17use gpui::{
18 color::Color,
19 elements::*,
20 fonts::{HighlightStyle, Underline},
21 geometry::{
22 rect::RectF,
23 vector::{vec2f, Vector2F},
24 PathBuilder,
25 },
26 json::{self, ToJson},
27 platform::CursorStyle,
28 text_layout::{self, Line, RunStyle, TextLayoutCache},
29 AppContext, Axis, Border, CursorRegion, Element, ElementBox, Event, EventContext,
30 LayoutContext, ModifiersChangedEvent, MouseButton, MouseButtonEvent, MouseMovedEvent,
31 MutableAppContext, PaintContext, Quad, Scene, ScrollWheelEvent, SizeConstraint, ViewContext,
32 WeakViewHandle,
33};
34use json::json;
35use language::{Bias, DiagnosticSeverity, OffsetUtf16, Selection};
36use project::ProjectPath;
37use settings::Settings;
38use smallvec::SmallVec;
39use std::{
40 cmp::{self, Ordering},
41 fmt::Write,
42 iter,
43 ops::Range,
44};
45
46const MIN_POPOVER_CHARACTER_WIDTH: f32 = 20.;
47const MIN_POPOVER_LINE_HEIGHT: f32 = 4.;
48const HOVER_POPOVER_GAP: f32 = 10.;
49
50struct SelectionLayout {
51 head: DisplayPoint,
52 range: Range<DisplayPoint>,
53}
54
55impl SelectionLayout {
56 fn new<T: ToPoint + ToDisplayPoint + Clone>(
57 selection: Selection<T>,
58 line_mode: bool,
59 map: &DisplaySnapshot,
60 ) -> Self {
61 if line_mode {
62 let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
63 let point_range = map.expand_to_line(selection.range());
64 Self {
65 head: selection.head().to_display_point(map),
66 range: point_range.start.to_display_point(map)
67 ..point_range.end.to_display_point(map),
68 }
69 } else {
70 let selection = selection.map(|p| p.to_display_point(map));
71 Self {
72 head: selection.head(),
73 range: selection.range(),
74 }
75 }
76 }
77}
78
79pub struct EditorElement {
80 view: WeakViewHandle<Editor>,
81 style: EditorStyle,
82 cursor_shape: CursorShape,
83}
84
85impl EditorElement {
86 pub fn new(
87 view: WeakViewHandle<Editor>,
88 style: EditorStyle,
89 cursor_shape: CursorShape,
90 ) -> Self {
91 Self {
92 view,
93 style,
94 cursor_shape,
95 }
96 }
97
98 fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
99 self.view.upgrade(cx).unwrap().read(cx)
100 }
101
102 fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
103 where
104 F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
105 {
106 self.view.upgrade(cx).unwrap().update(cx, f)
107 }
108
109 fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
110 self.update_view(cx, |view, cx| view.snapshot(cx))
111 }
112
113 fn mouse_down(
114 &self,
115 position: Vector2F,
116 cmd: bool,
117 alt: bool,
118 shift: bool,
119 mut click_count: usize,
120 layout: &mut LayoutState,
121 paint: &mut PaintState,
122 cx: &mut EventContext,
123 ) -> bool {
124 if cmd && paint.text_bounds.contains_point(position) {
125 let (point, overshoot) = paint.point_for_position(&self.snapshot(cx), layout, position);
126 if overshoot.is_zero() {
127 if shift {
128 cx.dispatch_action(GoToFetchedTypeDefinition { point });
129 } else {
130 cx.dispatch_action(GoToFetchedDefinition { point });
131 }
132
133 return true;
134 }
135 }
136
137 if paint.gutter_bounds.contains_point(position) {
138 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
139 } else if !paint.text_bounds.contains_point(position) {
140 return false;
141 }
142
143 let snapshot = self.snapshot(cx.app);
144 let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
145
146 if shift && alt {
147 cx.dispatch_action(Select(SelectPhase::BeginColumnar {
148 position,
149 overshoot: overshoot.column(),
150 }));
151 } else if shift {
152 cx.dispatch_action(Select(SelectPhase::Extend {
153 position,
154 click_count,
155 }));
156 } else {
157 cx.dispatch_action(Select(SelectPhase::Begin {
158 position,
159 add: alt,
160 click_count,
161 }));
162 }
163
164 true
165 }
166
167 fn mouse_right_down(
168 &self,
169 position: Vector2F,
170 layout: &mut LayoutState,
171 paint: &mut PaintState,
172 cx: &mut EventContext,
173 ) -> bool {
174 if !paint.text_bounds.contains_point(position) {
175 return false;
176 }
177
178 let snapshot = self.snapshot(cx.app);
179 let (point, _) = paint.point_for_position(&snapshot, layout, position);
180
181 cx.dispatch_action(DeployMouseContextMenu { position, point });
182 true
183 }
184
185 fn mouse_up(&self, _position: Vector2F, cx: &mut EventContext) -> bool {
186 if self.view(cx.app.as_ref()).is_selecting() {
187 cx.dispatch_action(Select(SelectPhase::End));
188 true
189 } else {
190 false
191 }
192 }
193
194 fn mouse_dragged(
195 &self,
196 position: Vector2F,
197 layout: &mut LayoutState,
198 paint: &mut PaintState,
199 cx: &mut EventContext,
200 ) -> bool {
201 let view = self.view(cx.app.as_ref());
202
203 if view.is_selecting() {
204 let rect = paint.text_bounds;
205 let mut scroll_delta = Vector2F::zero();
206
207 let vertical_margin = layout.line_height.min(rect.height() / 3.0);
208 let top = rect.origin_y() + vertical_margin;
209 let bottom = rect.lower_left().y() - vertical_margin;
210 if position.y() < top {
211 scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
212 }
213 if position.y() > bottom {
214 scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
215 }
216
217 let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
218 let left = rect.origin_x() + horizontal_margin;
219 let right = rect.upper_right().x() - horizontal_margin;
220 if position.x() < left {
221 scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
222 left - position.x(),
223 ))
224 }
225 if position.x() > right {
226 scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
227 position.x() - right,
228 ))
229 }
230
231 let snapshot = self.snapshot(cx.app);
232 let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
233
234 cx.dispatch_action(Select(SelectPhase::Update {
235 position,
236 overshoot: overshoot.column(),
237 scroll_position: (snapshot.scroll_position() + scroll_delta)
238 .clamp(Vector2F::zero(), layout.scroll_max),
239 }));
240 true
241 } else {
242 false
243 }
244 }
245
246 fn mouse_moved(
247 &self,
248 MouseMovedEvent {
249 cmd,
250 shift,
251 position,
252 ..
253 }: MouseMovedEvent,
254 layout: &LayoutState,
255 paint: &PaintState,
256 cx: &mut EventContext,
257 ) -> bool {
258 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
259 // Don't trigger hover popover if mouse is hovering over context menu
260 let point = if paint.text_bounds.contains_point(position) {
261 let (point, overshoot) = paint.point_for_position(&self.snapshot(cx), layout, position);
262 if overshoot.is_zero() {
263 Some(point)
264 } else {
265 None
266 }
267 } else {
268 None
269 };
270
271 cx.dispatch_action(UpdateGoToDefinitionLink {
272 point,
273 cmd_held: cmd,
274 shift_held: shift,
275 });
276
277 if paint
278 .context_menu_bounds
279 .map_or(false, |context_menu_bounds| {
280 context_menu_bounds.contains_point(position)
281 })
282 {
283 return false;
284 }
285
286 if paint
287 .hover_popover_bounds
288 .iter()
289 .any(|hover_bounds| hover_bounds.contains_point(position))
290 {
291 return false;
292 }
293
294 cx.dispatch_action(HoverAt { point });
295 true
296 }
297
298 fn modifiers_changed(&self, event: ModifiersChangedEvent, cx: &mut EventContext) -> bool {
299 cx.dispatch_action(CmdShiftChanged {
300 cmd_down: event.cmd,
301 shift_down: event.shift,
302 });
303 false
304 }
305
306 fn scroll(
307 &self,
308 position: Vector2F,
309 mut delta: Vector2F,
310 precise: bool,
311 layout: &mut LayoutState,
312 paint: &mut PaintState,
313 cx: &mut EventContext,
314 ) -> bool {
315 if !paint.bounds.contains_point(position) {
316 return false;
317 }
318
319 let snapshot = self.snapshot(cx.app);
320 let max_glyph_width = layout.em_width;
321 if !precise {
322 delta *= vec2f(max_glyph_width, layout.line_height);
323 }
324
325 let scroll_position = snapshot.scroll_position();
326 let x = (scroll_position.x() * max_glyph_width - delta.x()) / max_glyph_width;
327 let y = (scroll_position.y() * layout.line_height - delta.y()) / layout.line_height;
328 let scroll_position = vec2f(x, y).clamp(Vector2F::zero(), layout.scroll_max);
329
330 cx.dispatch_action(Scroll(scroll_position));
331
332 true
333 }
334
335 fn paint_background(
336 &self,
337 gutter_bounds: RectF,
338 text_bounds: RectF,
339 layout: &LayoutState,
340 cx: &mut PaintContext,
341 ) {
342 let bounds = gutter_bounds.union_rect(text_bounds);
343 let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
344 let editor = self.view(cx.app);
345 cx.scene.push_quad(Quad {
346 bounds: gutter_bounds,
347 background: Some(self.style.gutter_background),
348 border: Border::new(0., Color::transparent_black()),
349 corner_radius: 0.,
350 });
351 cx.scene.push_quad(Quad {
352 bounds: text_bounds,
353 background: Some(self.style.background),
354 border: Border::new(0., Color::transparent_black()),
355 corner_radius: 0.,
356 });
357
358 if let EditorMode::Full = editor.mode {
359 let mut active_rows = layout.active_rows.iter().peekable();
360 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
361 let mut end_row = *start_row;
362 while active_rows.peek().map_or(false, |r| {
363 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
364 }) {
365 active_rows.next().unwrap();
366 end_row += 1;
367 }
368
369 if !contains_non_empty_selection {
370 let origin = vec2f(
371 bounds.origin_x(),
372 bounds.origin_y() + (layout.line_height * *start_row as f32) - scroll_top,
373 );
374 let size = vec2f(
375 bounds.width(),
376 layout.line_height * (end_row - start_row + 1) as f32,
377 );
378 cx.scene.push_quad(Quad {
379 bounds: RectF::new(origin, size),
380 background: Some(self.style.active_line_background),
381 border: Border::default(),
382 corner_radius: 0.,
383 });
384 }
385 }
386
387 if let Some(highlighted_rows) = &layout.highlighted_rows {
388 let origin = vec2f(
389 bounds.origin_x(),
390 bounds.origin_y() + (layout.line_height * highlighted_rows.start as f32)
391 - scroll_top,
392 );
393 let size = vec2f(
394 bounds.width(),
395 layout.line_height * highlighted_rows.len() as f32,
396 );
397 cx.scene.push_quad(Quad {
398 bounds: RectF::new(origin, size),
399 background: Some(self.style.highlighted_line_background),
400 border: Border::default(),
401 corner_radius: 0.,
402 });
403 }
404 }
405 }
406
407 fn paint_gutter(
408 &mut self,
409 bounds: RectF,
410 visible_bounds: RectF,
411 layout: &mut LayoutState,
412 cx: &mut PaintContext,
413 ) {
414 let scroll_top = layout.snapshot.scroll_position().y() * layout.line_height;
415 for (ix, line) in layout.line_number_layouts.iter().enumerate() {
416 if let Some(line) = line {
417 let line_origin = bounds.origin()
418 + vec2f(
419 bounds.width() - line.width() - layout.gutter_padding,
420 ix as f32 * layout.line_height - (scroll_top % layout.line_height),
421 );
422 line.paint(line_origin, visible_bounds, layout.line_height, cx);
423 }
424 }
425
426 if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
427 let mut x = bounds.width() - layout.gutter_padding;
428 let mut y = *row as f32 * layout.line_height - scroll_top;
429 x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
430 y += (layout.line_height - indicator.size().y()) / 2.;
431 indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
432 }
433 }
434
435 fn paint_text(
436 &mut self,
437 bounds: RectF,
438 visible_bounds: RectF,
439 layout: &mut LayoutState,
440 paint: &mut PaintState,
441 cx: &mut PaintContext,
442 ) {
443 let view = self.view(cx.app);
444 let style = &self.style;
445 let local_replica_id = view.replica_id(cx);
446 let scroll_position = layout.snapshot.scroll_position();
447 let start_row = scroll_position.y() as u32;
448 let scroll_top = scroll_position.y() * layout.line_height;
449 let end_row = ((scroll_top + bounds.height()) / layout.line_height).ceil() as u32 + 1; // Add 1 to ensure selections bleed off screen
450 let max_glyph_width = layout.em_width;
451 let scroll_left = scroll_position.x() * max_glyph_width;
452 let content_origin = bounds.origin() + vec2f(layout.gutter_margin, 0.);
453
454 cx.scene.push_layer(Some(bounds));
455
456 cx.scene.push_cursor_region(CursorRegion {
457 bounds,
458 style: if !view.link_go_to_definition_state.definitions.is_empty() {
459 CursorStyle::PointingHand
460 } else {
461 CursorStyle::IBeam
462 },
463 });
464
465 for (range, color) in &layout.highlighted_ranges {
466 self.paint_highlighted_range(
467 range.clone(),
468 start_row,
469 end_row,
470 *color,
471 0.,
472 0.15 * layout.line_height,
473 layout,
474 content_origin,
475 scroll_top,
476 scroll_left,
477 bounds,
478 cx,
479 );
480 }
481
482 let mut cursors = SmallVec::<[Cursor; 32]>::new();
483 for (replica_id, selections) in &layout.selections {
484 let selection_style = style.replica_selection_style(*replica_id);
485 let corner_radius = 0.15 * layout.line_height;
486
487 for selection in selections {
488 self.paint_highlighted_range(
489 selection.range.clone(),
490 start_row,
491 end_row,
492 selection_style.selection,
493 corner_radius,
494 corner_radius * 2.,
495 layout,
496 content_origin,
497 scroll_top,
498 scroll_left,
499 bounds,
500 cx,
501 );
502
503 if view.show_local_cursors() || *replica_id != local_replica_id {
504 let cursor_position = selection.head;
505 if (start_row..end_row).contains(&cursor_position.row()) {
506 let cursor_row_layout =
507 &layout.line_layouts[(cursor_position.row() - start_row) as usize];
508 let cursor_column = cursor_position.column() as usize;
509
510 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
511 let mut block_width =
512 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
513 if block_width == 0.0 {
514 block_width = layout.em_width;
515 }
516
517 let block_text =
518 if let CursorShape::Block = self.cursor_shape {
519 layout.snapshot.chars_at(cursor_position).next().and_then(
520 |character| {
521 let font_id =
522 cursor_row_layout.font_for_index(cursor_column)?;
523 let text = character.to_string();
524
525 Some(cx.text_layout_cache.layout_str(
526 &text,
527 cursor_row_layout.font_size(),
528 &[(
529 text.len(),
530 RunStyle {
531 font_id,
532 color: style.background,
533 underline: Default::default(),
534 },
535 )],
536 ))
537 },
538 )
539 } else {
540 None
541 };
542
543 let x = cursor_character_x - scroll_left;
544 let y = cursor_position.row() as f32 * layout.line_height - scroll_top;
545 cursors.push(Cursor {
546 color: selection_style.cursor,
547 block_width,
548 origin: vec2f(x, y),
549 line_height: layout.line_height,
550 shape: self.cursor_shape,
551 block_text,
552 });
553 }
554 }
555 }
556 }
557
558 if let Some(visible_text_bounds) = bounds.intersection(visible_bounds) {
559 // Draw glyphs
560 for (ix, line) in layout.line_layouts.iter().enumerate() {
561 let row = start_row + ix as u32;
562 line.paint(
563 content_origin
564 + vec2f(-scroll_left, row as f32 * layout.line_height - scroll_top),
565 visible_text_bounds,
566 layout.line_height,
567 cx,
568 );
569 }
570 }
571
572 cx.scene.push_layer(Some(bounds));
573 for cursor in cursors {
574 cursor.paint(content_origin, cx);
575 }
576 cx.scene.pop_layer();
577
578 if let Some((position, context_menu)) = layout.context_menu.as_mut() {
579 cx.scene.push_stacking_context(None);
580 let cursor_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
581 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_left;
582 let y = (position.row() + 1) as f32 * layout.line_height - scroll_top;
583 let mut list_origin = content_origin + vec2f(x, y);
584 let list_width = context_menu.size().x();
585 let list_height = context_menu.size().y();
586
587 // Snap the right edge of the list to the right edge of the window if
588 // its horizontal bounds overflow.
589 if list_origin.x() + list_width > cx.window_size.x() {
590 list_origin.set_x((cx.window_size.x() - list_width).max(0.));
591 }
592
593 if list_origin.y() + list_height > bounds.max_y() {
594 list_origin.set_y(list_origin.y() - layout.line_height - list_height);
595 }
596
597 context_menu.paint(
598 list_origin,
599 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
600 cx,
601 );
602
603 paint.context_menu_bounds = Some(RectF::new(list_origin, context_menu.size()));
604
605 cx.scene.pop_stacking_context();
606 }
607
608 if let Some((position, hover_popovers)) = layout.hover_popovers.as_mut() {
609 cx.scene.push_stacking_context(None);
610
611 // This is safe because we check on layout whether the required row is available
612 let hovered_row_layout = &layout.line_layouts[(position.row() - start_row) as usize];
613
614 // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
615 // height. This is the size we will use to decide whether to render popovers above or below
616 // the hovered line.
617 let first_size = hover_popovers[0].size();
618 let height_to_reserve =
619 first_size.y() + 1.5 * MIN_POPOVER_LINE_HEIGHT as f32 * layout.line_height;
620
621 // Compute Hovered Point
622 let x = hovered_row_layout.x_for_index(position.column() as usize) - scroll_left;
623 let y = position.row() as f32 * layout.line_height - scroll_top;
624 let hovered_point = content_origin + vec2f(x, y);
625
626 paint.hover_popover_bounds.clear();
627
628 if hovered_point.y() - height_to_reserve > 0.0 {
629 // There is enough space above. Render popovers above the hovered point
630 let mut current_y = hovered_point.y();
631 for hover_popover in hover_popovers {
632 let size = hover_popover.size();
633 let mut popover_origin = vec2f(hovered_point.x(), current_y - size.y());
634
635 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
636 if x_out_of_bounds < 0.0 {
637 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
638 }
639
640 hover_popover.paint(
641 popover_origin,
642 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
643 cx,
644 );
645
646 paint.hover_popover_bounds.push(
647 RectF::new(popover_origin, hover_popover.size())
648 .dilate(Vector2F::new(0., 5.)),
649 );
650
651 current_y = popover_origin.y() - HOVER_POPOVER_GAP;
652 }
653 } else {
654 // There is not enough space above. Render popovers below the hovered point
655 let mut current_y = hovered_point.y() + layout.line_height;
656 for hover_popover in hover_popovers {
657 let size = hover_popover.size();
658 let mut popover_origin = vec2f(hovered_point.x(), current_y);
659
660 let x_out_of_bounds = bounds.max_x() - (popover_origin.x() + size.x());
661 if x_out_of_bounds < 0.0 {
662 popover_origin.set_x(popover_origin.x() + x_out_of_bounds);
663 }
664
665 hover_popover.paint(
666 popover_origin,
667 RectF::from_points(Vector2F::zero(), vec2f(f32::MAX, f32::MAX)), // Let content bleed outside of editor
668 cx,
669 );
670
671 paint.hover_popover_bounds.push(
672 RectF::new(popover_origin, hover_popover.size())
673 .dilate(Vector2F::new(0., 5.)),
674 );
675
676 current_y = popover_origin.y() + size.y() + HOVER_POPOVER_GAP;
677 }
678 }
679
680 cx.scene.pop_stacking_context();
681 }
682
683 cx.scene.pop_layer();
684 }
685
686 fn paint_highlighted_range(
687 &self,
688 range: Range<DisplayPoint>,
689 start_row: u32,
690 end_row: u32,
691 color: Color,
692 corner_radius: f32,
693 line_end_overshoot: f32,
694 layout: &LayoutState,
695 content_origin: Vector2F,
696 scroll_top: f32,
697 scroll_left: f32,
698 bounds: RectF,
699 cx: &mut PaintContext,
700 ) {
701 if range.start != range.end {
702 let row_range = if range.end.column() == 0 {
703 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
704 } else {
705 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
706 };
707
708 let highlighted_range = HighlightedRange {
709 color,
710 line_height: layout.line_height,
711 corner_radius,
712 start_y: content_origin.y() + row_range.start as f32 * layout.line_height
713 - scroll_top,
714 lines: row_range
715 .into_iter()
716 .map(|row| {
717 let line_layout = &layout.line_layouts[(row - start_row) as usize];
718 HighlightedRangeLine {
719 start_x: if row == range.start.row() {
720 content_origin.x()
721 + line_layout.x_for_index(range.start.column() as usize)
722 - scroll_left
723 } else {
724 content_origin.x() - scroll_left
725 },
726 end_x: if row == range.end.row() {
727 content_origin.x()
728 + line_layout.x_for_index(range.end.column() as usize)
729 - scroll_left
730 } else {
731 content_origin.x() + line_layout.width() + line_end_overshoot
732 - scroll_left
733 },
734 }
735 })
736 .collect(),
737 };
738
739 highlighted_range.paint(bounds, cx.scene);
740 }
741 }
742
743 fn paint_blocks(
744 &mut self,
745 bounds: RectF,
746 visible_bounds: RectF,
747 layout: &mut LayoutState,
748 cx: &mut PaintContext,
749 ) {
750 let scroll_position = layout.snapshot.scroll_position();
751 let scroll_left = scroll_position.x() * layout.em_width;
752 let scroll_top = scroll_position.y() * layout.line_height;
753
754 for block in &mut layout.blocks {
755 let mut origin =
756 bounds.origin() + vec2f(0., block.row as f32 * layout.line_height - scroll_top);
757 if !matches!(block.style, BlockStyle::Sticky) {
758 origin += vec2f(-scroll_left, 0.);
759 }
760 block.element.paint(origin, visible_bounds, cx);
761 }
762 }
763
764 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &LayoutContext) -> f32 {
765 let digit_count = (snapshot.max_buffer_row() as f32).log10().floor() as usize + 1;
766 let style = &self.style;
767
768 cx.text_layout_cache
769 .layout_str(
770 "1".repeat(digit_count).as_str(),
771 style.text.font_size,
772 &[(
773 digit_count,
774 RunStyle {
775 font_id: style.text.font_id,
776 color: Color::black(),
777 underline: Default::default(),
778 },
779 )],
780 )
781 .width()
782 }
783
784 fn layout_line_numbers(
785 &self,
786 rows: Range<u32>,
787 active_rows: &BTreeMap<u32, bool>,
788 snapshot: &EditorSnapshot,
789 cx: &LayoutContext,
790 ) -> Vec<Option<text_layout::Line>> {
791 let style = &self.style;
792 let include_line_numbers = snapshot.mode == EditorMode::Full;
793 let mut line_number_layouts = Vec::with_capacity(rows.len());
794 let mut line_number = String::new();
795 for (ix, row) in snapshot
796 .buffer_rows(rows.start)
797 .take((rows.end - rows.start) as usize)
798 .enumerate()
799 {
800 let display_row = rows.start + ix as u32;
801 let color = if active_rows.contains_key(&display_row) {
802 style.line_number_active
803 } else {
804 style.line_number
805 };
806 if let Some(buffer_row) = row {
807 if include_line_numbers {
808 line_number.clear();
809 write!(&mut line_number, "{}", buffer_row + 1).unwrap();
810 line_number_layouts.push(Some(cx.text_layout_cache.layout_str(
811 &line_number,
812 style.text.font_size,
813 &[(
814 line_number.len(),
815 RunStyle {
816 font_id: style.text.font_id,
817 color,
818 underline: Default::default(),
819 },
820 )],
821 )));
822 }
823 } else {
824 line_number_layouts.push(None);
825 }
826 }
827
828 line_number_layouts
829 }
830
831 fn layout_lines(
832 &mut self,
833 rows: Range<u32>,
834 snapshot: &EditorSnapshot,
835 cx: &LayoutContext,
836 ) -> Vec<text_layout::Line> {
837 if rows.start >= rows.end {
838 return Vec::new();
839 }
840
841 // When the editor is empty and unfocused, then show the placeholder.
842 if snapshot.is_empty() && !snapshot.is_focused() {
843 let placeholder_style = self
844 .style
845 .placeholder_text
846 .as_ref()
847 .unwrap_or_else(|| &self.style.text);
848 let placeholder_text = snapshot.placeholder_text();
849 let placeholder_lines = placeholder_text
850 .as_ref()
851 .map_or("", AsRef::as_ref)
852 .split('\n')
853 .skip(rows.start as usize)
854 .chain(iter::repeat(""))
855 .take(rows.len());
856 return placeholder_lines
857 .map(|line| {
858 cx.text_layout_cache.layout_str(
859 line,
860 placeholder_style.font_size,
861 &[(
862 line.len(),
863 RunStyle {
864 font_id: placeholder_style.font_id,
865 color: placeholder_style.color,
866 underline: Default::default(),
867 },
868 )],
869 )
870 })
871 .collect();
872 } else {
873 let style = &self.style;
874 let chunks = snapshot.chunks(rows.clone(), true).map(|chunk| {
875 let mut highlight_style = chunk
876 .syntax_highlight_id
877 .and_then(|id| id.style(&style.syntax));
878
879 if let Some(chunk_highlight) = chunk.highlight_style {
880 if let Some(highlight_style) = highlight_style.as_mut() {
881 highlight_style.highlight(chunk_highlight);
882 } else {
883 highlight_style = Some(chunk_highlight);
884 }
885 }
886
887 let mut diagnostic_highlight = HighlightStyle::default();
888
889 if chunk.is_unnecessary {
890 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
891 }
892
893 if let Some(severity) = chunk.diagnostic_severity {
894 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
895 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
896 let diagnostic_style = super::diagnostic_style(severity, true, style);
897 diagnostic_highlight.underline = Some(Underline {
898 color: Some(diagnostic_style.message.text.color),
899 thickness: 1.0.into(),
900 squiggly: true,
901 });
902 }
903 }
904
905 if let Some(highlight_style) = highlight_style.as_mut() {
906 highlight_style.highlight(diagnostic_highlight);
907 } else {
908 highlight_style = Some(diagnostic_highlight);
909 }
910
911 (chunk.text, highlight_style)
912 });
913 layout_highlighted_chunks(
914 chunks,
915 &style.text,
916 &cx.text_layout_cache,
917 &cx.font_cache,
918 MAX_LINE_LEN,
919 rows.len() as usize,
920 )
921 }
922 }
923
924 fn layout_blocks(
925 &mut self,
926 rows: Range<u32>,
927 snapshot: &EditorSnapshot,
928 editor_width: f32,
929 scroll_width: f32,
930 gutter_padding: f32,
931 gutter_width: f32,
932 em_width: f32,
933 text_x: f32,
934 line_height: f32,
935 style: &EditorStyle,
936 line_layouts: &[text_layout::Line],
937 cx: &mut LayoutContext,
938 ) -> (f32, Vec<BlockLayout>) {
939 let editor = if let Some(editor) = self.view.upgrade(cx) {
940 editor
941 } else {
942 return Default::default();
943 };
944
945 let tooltip_style = cx.global::<Settings>().theme.tooltip.clone();
946 let scroll_x = snapshot.scroll_position.x();
947 let (fixed_blocks, non_fixed_blocks) = snapshot
948 .blocks_in_range(rows.clone())
949 .partition::<Vec<_>, _>(|(_, block)| match block {
950 TransformBlock::ExcerptHeader { .. } => false,
951 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
952 });
953 let mut render_block = |block: &TransformBlock, width: f32| {
954 let mut element = match block {
955 TransformBlock::Custom(block) => {
956 let align_to = block
957 .position()
958 .to_point(&snapshot.buffer_snapshot)
959 .to_display_point(snapshot);
960 let anchor_x = text_x
961 + if rows.contains(&align_to.row()) {
962 line_layouts[(align_to.row() - rows.start) as usize]
963 .x_for_index(align_to.column() as usize)
964 } else {
965 layout_line(align_to.row(), snapshot, style, cx.text_layout_cache)
966 .x_for_index(align_to.column() as usize)
967 };
968
969 cx.render(&editor, |_, cx| {
970 block.render(&mut BlockContext {
971 cx,
972 anchor_x,
973 gutter_padding,
974 line_height,
975 scroll_x,
976 gutter_width,
977 em_width,
978 })
979 })
980 }
981 TransformBlock::ExcerptHeader {
982 key,
983 buffer,
984 range,
985 starts_new_buffer,
986 ..
987 } => {
988 let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
989 let jump_position = range
990 .primary
991 .as_ref()
992 .map_or(range.context.start, |primary| primary.start);
993 let jump_action = crate::Jump {
994 path: ProjectPath {
995 worktree_id: file.worktree_id(cx),
996 path: file.path.clone(),
997 },
998 position: language::ToPoint::to_point(&jump_position, buffer),
999 anchor: jump_position,
1000 };
1001
1002 enum JumpIcon {}
1003 cx.render(&editor, |_, cx| {
1004 MouseEventHandler::new::<JumpIcon, _, _>(*key, cx, |state, _| {
1005 let style = style.jump_icon.style_for(state, false);
1006 Svg::new("icons/arrow_up_right_8.svg")
1007 .with_color(style.color)
1008 .constrained()
1009 .with_width(style.icon_width)
1010 .aligned()
1011 .contained()
1012 .with_style(style.container)
1013 .constrained()
1014 .with_width(style.button_width)
1015 .with_height(style.button_width)
1016 .boxed()
1017 })
1018 .with_cursor_style(CursorStyle::PointingHand)
1019 .on_click(MouseButton::Left, move |_, cx| {
1020 cx.dispatch_action(jump_action.clone())
1021 })
1022 .with_tooltip::<JumpIcon, _>(
1023 *key,
1024 "Jump to Buffer".to_string(),
1025 Some(Box::new(crate::OpenExcerpts)),
1026 tooltip_style.clone(),
1027 cx,
1028 )
1029 .aligned()
1030 .flex_float()
1031 .boxed()
1032 })
1033 });
1034
1035 if *starts_new_buffer {
1036 let style = &self.style.diagnostic_path_header;
1037 let font_size =
1038 (style.text_scale_factor * self.style.text.font_size).round();
1039
1040 let mut filename = None;
1041 let mut parent_path = None;
1042 if let Some(file) = buffer.file() {
1043 let path = file.path();
1044 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1045 parent_path =
1046 path.parent().map(|p| p.to_string_lossy().to_string() + "/");
1047 }
1048
1049 Flex::row()
1050 .with_child(
1051 Label::new(
1052 filename.unwrap_or_else(|| "untitled".to_string()),
1053 style.filename.text.clone().with_font_size(font_size),
1054 )
1055 .contained()
1056 .with_style(style.filename.container)
1057 .aligned()
1058 .boxed(),
1059 )
1060 .with_children(parent_path.map(|path| {
1061 Label::new(path, style.path.text.clone().with_font_size(font_size))
1062 .contained()
1063 .with_style(style.path.container)
1064 .aligned()
1065 .boxed()
1066 }))
1067 .with_children(jump_icon)
1068 .contained()
1069 .with_style(style.container)
1070 .with_padding_left(gutter_padding)
1071 .with_padding_right(gutter_padding)
1072 .expanded()
1073 .named("path header block")
1074 } else {
1075 let text_style = self.style.text.clone();
1076 Flex::row()
1077 .with_child(Label::new("…".to_string(), text_style).boxed())
1078 .with_children(jump_icon)
1079 .contained()
1080 .with_padding_left(gutter_padding)
1081 .with_padding_right(gutter_padding)
1082 .expanded()
1083 .named("collapsed context")
1084 }
1085 }
1086 };
1087
1088 element.layout(
1089 SizeConstraint {
1090 min: Vector2F::zero(),
1091 max: vec2f(width, block.height() as f32 * line_height),
1092 },
1093 cx,
1094 );
1095 element
1096 };
1097
1098 let mut fixed_block_max_width = 0f32;
1099 let mut blocks = Vec::new();
1100 for (row, block) in fixed_blocks {
1101 let element = render_block(block, f32::INFINITY);
1102 fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
1103 blocks.push(BlockLayout {
1104 row,
1105 element,
1106 style: BlockStyle::Fixed,
1107 });
1108 }
1109 for (row, block) in non_fixed_blocks {
1110 let style = match block {
1111 TransformBlock::Custom(block) => block.style(),
1112 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1113 };
1114 let width = match style {
1115 BlockStyle::Sticky => editor_width,
1116 BlockStyle::Flex => editor_width
1117 .max(fixed_block_max_width)
1118 .max(gutter_width + scroll_width),
1119 BlockStyle::Fixed => unreachable!(),
1120 };
1121 let element = render_block(block, width);
1122 blocks.push(BlockLayout {
1123 row,
1124 element,
1125 style,
1126 });
1127 }
1128 (
1129 scroll_width.max(fixed_block_max_width - gutter_width),
1130 blocks,
1131 )
1132 }
1133}
1134
1135impl Element for EditorElement {
1136 type LayoutState = LayoutState;
1137 type PaintState = PaintState;
1138
1139 fn layout(
1140 &mut self,
1141 constraint: SizeConstraint,
1142 cx: &mut LayoutContext,
1143 ) -> (Vector2F, Self::LayoutState) {
1144 let mut size = constraint.max;
1145 if size.x().is_infinite() {
1146 unimplemented!("we don't yet handle an infinite width constraint on buffer elements");
1147 }
1148
1149 let snapshot = self.snapshot(cx.app);
1150 let style = self.style.clone();
1151 let line_height = style.text.line_height(cx.font_cache);
1152
1153 let gutter_padding;
1154 let gutter_width;
1155 let gutter_margin;
1156 if snapshot.mode == EditorMode::Full {
1157 gutter_padding = style.text.em_width(cx.font_cache) * style.gutter_padding_factor;
1158 gutter_width = self.max_line_number_width(&snapshot, cx) + gutter_padding * 2.0;
1159 gutter_margin = -style.text.descent(cx.font_cache);
1160 } else {
1161 gutter_padding = 0.0;
1162 gutter_width = 0.0;
1163 gutter_margin = 0.0;
1164 };
1165
1166 let text_width = size.x() - gutter_width;
1167 let em_width = style.text.em_width(cx.font_cache);
1168 let em_advance = style.text.em_advance(cx.font_cache);
1169 let overscroll = vec2f(em_width, 0.);
1170 let snapshot = self.update_view(cx.app, |view, cx| {
1171 let wrap_width = match view.soft_wrap_mode(cx) {
1172 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
1173 SoftWrap::EditorWidth => {
1174 Some(text_width - gutter_margin - overscroll.x() - em_width)
1175 }
1176 SoftWrap::Column(column) => Some(column as f32 * em_advance),
1177 };
1178
1179 if view.set_wrap_width(wrap_width, cx) {
1180 view.snapshot(cx)
1181 } else {
1182 snapshot
1183 }
1184 });
1185
1186 let scroll_height = (snapshot.max_point().row() + 1) as f32 * line_height;
1187 if let EditorMode::AutoHeight { max_lines } = snapshot.mode {
1188 size.set_y(
1189 scroll_height
1190 .min(constraint.max_along(Axis::Vertical))
1191 .max(constraint.min_along(Axis::Vertical))
1192 .min(line_height * max_lines as f32),
1193 )
1194 } else if let EditorMode::SingleLine = snapshot.mode {
1195 size.set_y(
1196 line_height
1197 .min(constraint.max_along(Axis::Vertical))
1198 .max(constraint.min_along(Axis::Vertical)),
1199 )
1200 } else if size.y().is_infinite() {
1201 size.set_y(scroll_height);
1202 }
1203 let gutter_size = vec2f(gutter_width, size.y());
1204 let text_size = vec2f(text_width, size.y());
1205
1206 let (autoscroll_horizontally, mut snapshot) = self.update_view(cx.app, |view, cx| {
1207 let autoscroll_horizontally = view.autoscroll_vertically(size.y(), line_height, cx);
1208 let snapshot = view.snapshot(cx);
1209 (autoscroll_horizontally, snapshot)
1210 });
1211
1212 let scroll_position = snapshot.scroll_position();
1213 // The scroll position is a fractional point, the whole number of which represents
1214 // the top of the window in terms of display rows.
1215 let start_row = scroll_position.y() as u32;
1216 let scroll_top = scroll_position.y() * line_height;
1217
1218 // Add 1 to ensure selections bleed off screen
1219 let end_row = 1 + cmp::min(
1220 ((scroll_top + size.y()) / line_height).ceil() as u32,
1221 snapshot.max_point().row(),
1222 );
1223
1224 let start_anchor = if start_row == 0 {
1225 Anchor::min()
1226 } else {
1227 snapshot
1228 .buffer_snapshot
1229 .anchor_before(DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left))
1230 };
1231 let end_anchor = if end_row > snapshot.max_point().row() {
1232 Anchor::max()
1233 } else {
1234 snapshot
1235 .buffer_snapshot
1236 .anchor_before(DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right))
1237 };
1238
1239 let mut selections: Vec<(ReplicaId, Vec<SelectionLayout>)> = Vec::new();
1240 let mut active_rows = BTreeMap::new();
1241 let mut highlighted_rows = None;
1242 let mut highlighted_ranges = Vec::new();
1243 self.update_view(cx.app, |view, cx| {
1244 let display_map = view.display_map.update(cx, |map, cx| map.snapshot(cx));
1245
1246 highlighted_rows = view.highlighted_rows();
1247 let theme = cx.global::<Settings>().theme.as_ref();
1248 highlighted_ranges = view.background_highlights_in_range(
1249 start_anchor.clone()..end_anchor.clone(),
1250 &display_map,
1251 theme,
1252 );
1253
1254 let mut remote_selections = HashMap::default();
1255 for (replica_id, line_mode, selection) in display_map
1256 .buffer_snapshot
1257 .remote_selections_in_range(&(start_anchor.clone()..end_anchor.clone()))
1258 {
1259 // The local selections match the leader's selections.
1260 if Some(replica_id) == view.leader_replica_id {
1261 continue;
1262 }
1263 remote_selections
1264 .entry(replica_id)
1265 .or_insert(Vec::new())
1266 .push(SelectionLayout::new(selection, line_mode, &display_map));
1267 }
1268 selections.extend(remote_selections);
1269
1270 if view.show_local_selections {
1271 let mut local_selections = view
1272 .selections
1273 .disjoint_in_range(start_anchor..end_anchor, cx);
1274 local_selections.extend(view.selections.pending(cx));
1275 for selection in &local_selections {
1276 let is_empty = selection.start == selection.end;
1277 let selection_start = snapshot.prev_line_boundary(selection.start).1;
1278 let selection_end = snapshot.next_line_boundary(selection.end).1;
1279 for row in cmp::max(selection_start.row(), start_row)
1280 ..=cmp::min(selection_end.row(), end_row)
1281 {
1282 let contains_non_empty_selection =
1283 active_rows.entry(row).or_insert(!is_empty);
1284 *contains_non_empty_selection |= !is_empty;
1285 }
1286 }
1287
1288 // Render the local selections in the leader's color when following.
1289 let local_replica_id = view.leader_replica_id.unwrap_or(view.replica_id(cx));
1290
1291 selections.push((
1292 local_replica_id,
1293 local_selections
1294 .into_iter()
1295 .map(|selection| {
1296 SelectionLayout::new(selection, view.selections.line_mode, &display_map)
1297 })
1298 .collect(),
1299 ));
1300 }
1301 });
1302
1303 let line_number_layouts =
1304 self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
1305
1306 let mut max_visible_line_width = 0.0;
1307 let line_layouts = self.layout_lines(start_row..end_row, &snapshot, cx);
1308 for line in &line_layouts {
1309 if line.width() > max_visible_line_width {
1310 max_visible_line_width = line.width();
1311 }
1312 }
1313
1314 let style = self.style.clone();
1315 let longest_line_width = layout_line(
1316 snapshot.longest_row(),
1317 &snapshot,
1318 &style,
1319 cx.text_layout_cache,
1320 )
1321 .width();
1322 let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.x();
1323 let em_width = style.text.em_width(cx.font_cache);
1324 let (scroll_width, blocks) = self.layout_blocks(
1325 start_row..end_row,
1326 &snapshot,
1327 size.x(),
1328 scroll_width,
1329 gutter_padding,
1330 gutter_width,
1331 em_width,
1332 gutter_width + gutter_margin,
1333 line_height,
1334 &style,
1335 &line_layouts,
1336 cx,
1337 );
1338
1339 let max_row = snapshot.max_point().row();
1340 let scroll_max = vec2f(
1341 ((scroll_width - text_size.x()) / em_width).max(0.0),
1342 max_row.saturating_sub(1) as f32,
1343 );
1344
1345 self.update_view(cx.app, |view, cx| {
1346 let clamped = view.clamp_scroll_left(scroll_max.x());
1347 let autoscrolled;
1348 if autoscroll_horizontally {
1349 autoscrolled = view.autoscroll_horizontally(
1350 start_row,
1351 text_size.x(),
1352 scroll_width,
1353 em_width,
1354 &line_layouts,
1355 cx,
1356 );
1357 } else {
1358 autoscrolled = false;
1359 }
1360
1361 if clamped || autoscrolled {
1362 snapshot = view.snapshot(cx);
1363 }
1364 });
1365
1366 let mut context_menu = None;
1367 let mut code_actions_indicator = None;
1368 let mut hover = None;
1369 cx.render(&self.view.upgrade(cx).unwrap(), |view, cx| {
1370 let newest_selection_head = view
1371 .selections
1372 .newest::<usize>(cx)
1373 .head()
1374 .to_display_point(&snapshot);
1375
1376 let style = view.style(cx);
1377 if (start_row..end_row).contains(&newest_selection_head.row()) {
1378 if view.context_menu_visible() {
1379 context_menu =
1380 view.render_context_menu(newest_selection_head, style.clone(), cx);
1381 }
1382
1383 code_actions_indicator = view
1384 .render_code_actions_indicator(&style, cx)
1385 .map(|indicator| (newest_selection_head.row(), indicator));
1386 }
1387
1388 let visible_rows = start_row..start_row + line_layouts.len() as u32;
1389 hover = view.hover_state.render(&snapshot, &style, visible_rows, cx);
1390 });
1391
1392 if let Some((_, context_menu)) = context_menu.as_mut() {
1393 context_menu.layout(
1394 SizeConstraint {
1395 min: Vector2F::zero(),
1396 max: vec2f(
1397 cx.window_size.x() * 0.7,
1398 (12. * line_height).min((size.y() - line_height) / 2.),
1399 ),
1400 },
1401 cx,
1402 );
1403 }
1404
1405 if let Some((_, indicator)) = code_actions_indicator.as_mut() {
1406 indicator.layout(
1407 SizeConstraint::strict_along(Axis::Vertical, line_height * 0.618),
1408 cx,
1409 );
1410 }
1411
1412 if let Some((_, hover_popovers)) = hover.as_mut() {
1413 for hover_popover in hover_popovers.iter_mut() {
1414 hover_popover.layout(
1415 SizeConstraint {
1416 min: Vector2F::zero(),
1417 max: vec2f(
1418 (120. * em_width) // Default size
1419 .min(size.x() / 2.) // Shrink to half of the editor width
1420 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1421 (16. * line_height) // Default size
1422 .min(size.y() / 2.) // Shrink to half of the editor height
1423 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1424 ),
1425 },
1426 cx,
1427 );
1428 }
1429 }
1430
1431 (
1432 size,
1433 LayoutState {
1434 size,
1435 scroll_max,
1436 gutter_size,
1437 gutter_padding,
1438 text_size,
1439 gutter_margin,
1440 snapshot,
1441 active_rows,
1442 highlighted_rows,
1443 highlighted_ranges,
1444 line_layouts,
1445 line_number_layouts,
1446 blocks,
1447 line_height,
1448 em_width,
1449 em_advance,
1450 selections,
1451 context_menu,
1452 code_actions_indicator,
1453 hover_popovers: hover,
1454 },
1455 )
1456 }
1457
1458 fn paint(
1459 &mut self,
1460 bounds: RectF,
1461 visible_bounds: RectF,
1462 layout: &mut Self::LayoutState,
1463 cx: &mut PaintContext,
1464 ) -> Self::PaintState {
1465 cx.scene.push_layer(Some(bounds));
1466
1467 let gutter_bounds = RectF::new(bounds.origin(), layout.gutter_size);
1468 let text_bounds = RectF::new(
1469 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1470 layout.text_size,
1471 );
1472
1473 let mut paint_state = PaintState {
1474 bounds,
1475 gutter_bounds,
1476 text_bounds,
1477 context_menu_bounds: None,
1478 hover_popover_bounds: Default::default(),
1479 };
1480
1481 self.paint_background(gutter_bounds, text_bounds, layout, cx);
1482 if layout.gutter_size.x() > 0. {
1483 self.paint_gutter(gutter_bounds, visible_bounds, layout, cx);
1484 }
1485 self.paint_text(text_bounds, visible_bounds, layout, &mut paint_state, cx);
1486
1487 if !layout.blocks.is_empty() {
1488 cx.scene.push_layer(Some(bounds));
1489 self.paint_blocks(bounds, visible_bounds, layout, cx);
1490 cx.scene.pop_layer();
1491 }
1492
1493 cx.scene.pop_layer();
1494
1495 paint_state
1496 }
1497
1498 fn dispatch_event(
1499 &mut self,
1500 event: &Event,
1501 _: RectF,
1502 _: RectF,
1503 layout: &mut LayoutState,
1504 paint: &mut PaintState,
1505 cx: &mut EventContext,
1506 ) -> bool {
1507 if let Some((_, context_menu)) = &mut layout.context_menu {
1508 if context_menu.dispatch_event(event, cx) {
1509 return true;
1510 }
1511 }
1512
1513 if let Some((_, indicator)) = &mut layout.code_actions_indicator {
1514 if indicator.dispatch_event(event, cx) {
1515 return true;
1516 }
1517 }
1518
1519 if let Some((_, popover_elements)) = &mut layout.hover_popovers {
1520 for popover_element in popover_elements.iter_mut() {
1521 if popover_element.dispatch_event(event, cx) {
1522 return true;
1523 }
1524 }
1525 }
1526
1527 for block in &mut layout.blocks {
1528 if block.element.dispatch_event(event, cx) {
1529 return true;
1530 }
1531 }
1532
1533 match event {
1534 Event::MouseDown(MouseButtonEvent {
1535 button: MouseButton::Left,
1536 position,
1537 cmd,
1538 alt,
1539 shift,
1540 click_count,
1541 ..
1542 }) => self.mouse_down(
1543 *position,
1544 *cmd,
1545 *alt,
1546 *shift,
1547 *click_count,
1548 layout,
1549 paint,
1550 cx,
1551 ),
1552
1553 Event::MouseDown(MouseButtonEvent {
1554 button: MouseButton::Right,
1555 position,
1556 ..
1557 }) => self.mouse_right_down(*position, layout, paint, cx),
1558
1559 Event::MouseUp(MouseButtonEvent {
1560 button: MouseButton::Left,
1561 position,
1562 ..
1563 }) => self.mouse_up(*position, cx),
1564
1565 Event::MouseMoved(MouseMovedEvent {
1566 pressed_button: Some(MouseButton::Left),
1567 position,
1568 ..
1569 }) => self.mouse_dragged(*position, layout, paint, cx),
1570
1571 Event::ScrollWheel(ScrollWheelEvent {
1572 position,
1573 delta,
1574 precise,
1575 }) => self.scroll(*position, *delta, *precise, layout, paint, cx),
1576
1577 &Event::ModifiersChanged(event) => self.modifiers_changed(event, cx),
1578
1579 &Event::MouseMoved(event) => self.mouse_moved(event, layout, paint, cx),
1580
1581 _ => false,
1582 }
1583 }
1584
1585 fn rect_for_text_range(
1586 &self,
1587 range_utf16: Range<usize>,
1588 bounds: RectF,
1589 _: RectF,
1590 layout: &Self::LayoutState,
1591 _: &Self::PaintState,
1592 _: &gpui::MeasurementContext,
1593 ) -> Option<RectF> {
1594 let text_bounds = RectF::new(
1595 bounds.origin() + vec2f(layout.gutter_size.x(), 0.0),
1596 layout.text_size,
1597 );
1598 let content_origin = text_bounds.origin() + vec2f(layout.gutter_margin, 0.);
1599 let scroll_position = layout.snapshot.scroll_position();
1600 let start_row = scroll_position.y() as u32;
1601 let scroll_top = scroll_position.y() * layout.line_height;
1602 let scroll_left = scroll_position.x() * layout.em_width;
1603
1604 let range_start =
1605 OffsetUtf16(range_utf16.start).to_display_point(&layout.snapshot.display_snapshot);
1606 if range_start.row() < start_row {
1607 return None;
1608 }
1609
1610 let line = layout
1611 .line_layouts
1612 .get((range_start.row() - start_row) as usize)?;
1613 let range_start_x = line.x_for_index(range_start.column() as usize);
1614 let range_start_y = range_start.row() as f32 * layout.line_height;
1615 Some(RectF::new(
1616 content_origin + vec2f(range_start_x, range_start_y + layout.line_height)
1617 - vec2f(scroll_left, scroll_top),
1618 vec2f(layout.em_width, layout.line_height),
1619 ))
1620 }
1621
1622 fn debug(
1623 &self,
1624 bounds: RectF,
1625 _: &Self::LayoutState,
1626 _: &Self::PaintState,
1627 _: &gpui::DebugContext,
1628 ) -> json::Value {
1629 json!({
1630 "type": "BufferElement",
1631 "bounds": bounds.to_json()
1632 })
1633 }
1634}
1635
1636pub struct LayoutState {
1637 size: Vector2F,
1638 scroll_max: Vector2F,
1639 gutter_size: Vector2F,
1640 gutter_padding: f32,
1641 gutter_margin: f32,
1642 text_size: Vector2F,
1643 snapshot: EditorSnapshot,
1644 active_rows: BTreeMap<u32, bool>,
1645 highlighted_rows: Option<Range<u32>>,
1646 line_layouts: Vec<text_layout::Line>,
1647 line_number_layouts: Vec<Option<text_layout::Line>>,
1648 blocks: Vec<BlockLayout>,
1649 line_height: f32,
1650 em_width: f32,
1651 em_advance: f32,
1652 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1653 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1654 context_menu: Option<(DisplayPoint, ElementBox)>,
1655 code_actions_indicator: Option<(u32, ElementBox)>,
1656 hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
1657}
1658
1659struct BlockLayout {
1660 row: u32,
1661 element: ElementBox,
1662 style: BlockStyle,
1663}
1664
1665fn layout_line(
1666 row: u32,
1667 snapshot: &EditorSnapshot,
1668 style: &EditorStyle,
1669 layout_cache: &TextLayoutCache,
1670) -> text_layout::Line {
1671 let mut line = snapshot.line(row);
1672
1673 if line.len() > MAX_LINE_LEN {
1674 let mut len = MAX_LINE_LEN;
1675 while !line.is_char_boundary(len) {
1676 len -= 1;
1677 }
1678
1679 line.truncate(len);
1680 }
1681
1682 layout_cache.layout_str(
1683 &line,
1684 style.text.font_size,
1685 &[(
1686 snapshot.line_len(row) as usize,
1687 RunStyle {
1688 font_id: style.text.font_id,
1689 color: Color::black(),
1690 underline: Default::default(),
1691 },
1692 )],
1693 )
1694}
1695
1696pub struct PaintState {
1697 bounds: RectF,
1698 gutter_bounds: RectF,
1699 text_bounds: RectF,
1700 context_menu_bounds: Option<RectF>,
1701 hover_popover_bounds: Vec<RectF>,
1702}
1703
1704impl PaintState {
1705 /// Returns two display points. The first is the nearest valid
1706 /// position in the current buffer and the second is the distance to the
1707 /// nearest valid position if there was overshoot.
1708 fn point_for_position(
1709 &self,
1710 snapshot: &EditorSnapshot,
1711 layout: &LayoutState,
1712 position: Vector2F,
1713 ) -> (DisplayPoint, DisplayPoint) {
1714 let scroll_position = snapshot.scroll_position();
1715 let position = position - self.text_bounds.origin();
1716 let y = position.y().max(0.0).min(layout.size.y());
1717 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1718 let row_overshoot = row.saturating_sub(snapshot.max_point().row());
1719 let row = cmp::min(row, snapshot.max_point().row());
1720 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1721 let x = position.x() + (scroll_position.x() * layout.em_width);
1722
1723 let column = if x >= 0.0 {
1724 line.index_for_x(x)
1725 .map(|ix| ix as u32)
1726 .unwrap_or_else(|| snapshot.line_len(row))
1727 } else {
1728 0
1729 };
1730
1731 let point = snapshot.clip_point(DisplayPoint::new(row, column), Bias::Left);
1732 let mut column_overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1733 column_overshoot = column_overshoot + column - point.column();
1734
1735 (point, DisplayPoint::new(row_overshoot, column_overshoot))
1736 }
1737}
1738
1739#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1740pub enum CursorShape {
1741 Bar,
1742 Block,
1743 Underscore,
1744}
1745
1746impl Default for CursorShape {
1747 fn default() -> Self {
1748 CursorShape::Bar
1749 }
1750}
1751
1752#[derive(Debug)]
1753pub struct Cursor {
1754 origin: Vector2F,
1755 block_width: f32,
1756 line_height: f32,
1757 color: Color,
1758 shape: CursorShape,
1759 block_text: Option<Line>,
1760}
1761
1762impl Cursor {
1763 pub fn new(
1764 origin: Vector2F,
1765 block_width: f32,
1766 line_height: f32,
1767 color: Color,
1768 shape: CursorShape,
1769 block_text: Option<Line>,
1770 ) -> Cursor {
1771 Cursor {
1772 origin,
1773 block_width,
1774 line_height,
1775 color,
1776 shape,
1777 block_text,
1778 }
1779 }
1780
1781 pub fn bounding_rect(&self, origin: Vector2F) -> RectF {
1782 RectF::new(
1783 self.origin + origin,
1784 vec2f(self.block_width, self.line_height),
1785 )
1786 }
1787
1788 pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
1789 let bounds = match self.shape {
1790 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
1791 CursorShape::Block => RectF::new(
1792 self.origin + origin,
1793 vec2f(self.block_width, self.line_height),
1794 ),
1795 CursorShape::Underscore => RectF::new(
1796 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
1797 vec2f(self.block_width, 2.0),
1798 ),
1799 };
1800
1801 cx.scene.push_quad(Quad {
1802 bounds,
1803 background: Some(self.color),
1804 border: Border::new(0., Color::black()),
1805 corner_radius: 0.,
1806 });
1807
1808 if let Some(block_text) = &self.block_text {
1809 block_text.paint(self.origin + origin, bounds, self.line_height, cx);
1810 }
1811 }
1812}
1813
1814#[derive(Debug)]
1815pub struct HighlightedRange {
1816 pub start_y: f32,
1817 pub line_height: f32,
1818 pub lines: Vec<HighlightedRangeLine>,
1819 pub color: Color,
1820 pub corner_radius: f32,
1821}
1822
1823#[derive(Debug)]
1824pub struct HighlightedRangeLine {
1825 pub start_x: f32,
1826 pub end_x: f32,
1827}
1828
1829impl HighlightedRange {
1830 pub fn paint(&self, bounds: RectF, scene: &mut Scene) {
1831 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1832 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1833 self.paint_lines(
1834 self.start_y + self.line_height,
1835 &self.lines[1..],
1836 bounds,
1837 scene,
1838 );
1839 } else {
1840 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1841 }
1842 }
1843
1844 fn paint_lines(
1845 &self,
1846 start_y: f32,
1847 lines: &[HighlightedRangeLine],
1848 bounds: RectF,
1849 scene: &mut Scene,
1850 ) {
1851 if lines.is_empty() {
1852 return;
1853 }
1854
1855 let mut path = PathBuilder::new();
1856 let first_line = lines.first().unwrap();
1857 let last_line = lines.last().unwrap();
1858
1859 let first_top_left = vec2f(first_line.start_x, start_y);
1860 let first_top_right = vec2f(first_line.end_x, start_y);
1861
1862 let curve_height = vec2f(0., self.corner_radius);
1863 let curve_width = |start_x: f32, end_x: f32| {
1864 let max = (end_x - start_x) / 2.;
1865 let width = if max < self.corner_radius {
1866 max
1867 } else {
1868 self.corner_radius
1869 };
1870
1871 vec2f(width, 0.)
1872 };
1873
1874 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1875 path.reset(first_top_right - top_curve_width);
1876 path.curve_to(first_top_right + curve_height, first_top_right);
1877
1878 let mut iter = lines.iter().enumerate().peekable();
1879 while let Some((ix, line)) = iter.next() {
1880 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1881
1882 if let Some((_, next_line)) = iter.peek() {
1883 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1884
1885 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1886 Ordering::Equal => {
1887 path.line_to(bottom_right);
1888 }
1889 Ordering::Less => {
1890 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1891 path.line_to(bottom_right - curve_height);
1892 if self.corner_radius > 0. {
1893 path.curve_to(bottom_right - curve_width, bottom_right);
1894 }
1895 path.line_to(next_top_right + curve_width);
1896 if self.corner_radius > 0. {
1897 path.curve_to(next_top_right + curve_height, next_top_right);
1898 }
1899 }
1900 Ordering::Greater => {
1901 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1902 path.line_to(bottom_right - curve_height);
1903 if self.corner_radius > 0. {
1904 path.curve_to(bottom_right + curve_width, bottom_right);
1905 }
1906 path.line_to(next_top_right - curve_width);
1907 if self.corner_radius > 0. {
1908 path.curve_to(next_top_right + curve_height, next_top_right);
1909 }
1910 }
1911 }
1912 } else {
1913 let curve_width = curve_width(line.start_x, line.end_x);
1914 path.line_to(bottom_right - curve_height);
1915 if self.corner_radius > 0. {
1916 path.curve_to(bottom_right - curve_width, bottom_right);
1917 }
1918
1919 let bottom_left = vec2f(line.start_x, bottom_right.y());
1920 path.line_to(bottom_left + curve_width);
1921 if self.corner_radius > 0. {
1922 path.curve_to(bottom_left - curve_height, bottom_left);
1923 }
1924 }
1925 }
1926
1927 if first_line.start_x > last_line.start_x {
1928 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1929 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1930 path.line_to(second_top_left + curve_height);
1931 if self.corner_radius > 0. {
1932 path.curve_to(second_top_left + curve_width, second_top_left);
1933 }
1934 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1935 path.line_to(first_bottom_left - curve_width);
1936 if self.corner_radius > 0. {
1937 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1938 }
1939 }
1940
1941 path.line_to(first_top_left + curve_height);
1942 if self.corner_radius > 0. {
1943 path.curve_to(first_top_left + top_curve_width, first_top_left);
1944 }
1945 path.line_to(first_top_right - top_curve_width);
1946
1947 scene.push_path(path.build(self.color, Some(bounds)));
1948 }
1949}
1950
1951fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1952 delta.powf(1.5) / 100.0
1953}
1954
1955fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1956 delta.powf(1.2) / 300.0
1957}
1958
1959#[cfg(test)]
1960mod tests {
1961 use std::sync::Arc;
1962
1963 use super::*;
1964 use crate::{
1965 display_map::{BlockDisposition, BlockProperties},
1966 Editor, MultiBuffer,
1967 };
1968 use settings::Settings;
1969 use util::test::sample_text;
1970
1971 #[gpui::test]
1972 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1973 cx.set_global(Settings::test(cx));
1974 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1975 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1976 Editor::new(EditorMode::Full, buffer, None, None, cx)
1977 });
1978 let element = EditorElement::new(
1979 editor.downgrade(),
1980 editor.read(cx).style(cx),
1981 CursorShape::Bar,
1982 );
1983
1984 let layouts = editor.update(cx, |editor, cx| {
1985 let snapshot = editor.snapshot(cx);
1986 let mut presenter = cx.build_presenter(window_id, 30.);
1987 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1988 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1989 });
1990 assert_eq!(layouts.len(), 6);
1991 }
1992
1993 #[gpui::test]
1994 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1995 cx.set_global(Settings::test(cx));
1996 let buffer = MultiBuffer::build_simple("", cx);
1997 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1998 Editor::new(EditorMode::Full, buffer, None, None, cx)
1999 });
2000
2001 editor.update(cx, |editor, cx| {
2002 editor.set_placeholder_text("hello", cx);
2003 editor.insert_blocks(
2004 [BlockProperties {
2005 style: BlockStyle::Fixed,
2006 disposition: BlockDisposition::Above,
2007 height: 3,
2008 position: Anchor::min(),
2009 render: Arc::new(|_| Empty::new().boxed()),
2010 }],
2011 cx,
2012 );
2013
2014 // Blur the editor so that it displays placeholder text.
2015 cx.blur();
2016 });
2017
2018 let mut element = EditorElement::new(
2019 editor.downgrade(),
2020 editor.read(cx).style(cx),
2021 CursorShape::Bar,
2022 );
2023
2024 let mut scene = Scene::new(1.0);
2025 let mut presenter = cx.build_presenter(window_id, 30.);
2026 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
2027 let (size, mut state) = element.layout(
2028 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
2029 &mut layout_cx,
2030 );
2031
2032 assert_eq!(state.line_layouts.len(), 4);
2033 assert_eq!(
2034 state
2035 .line_number_layouts
2036 .iter()
2037 .map(Option::is_some)
2038 .collect::<Vec<_>>(),
2039 &[false, false, false, true]
2040 );
2041
2042 // Don't panic.
2043 let bounds = RectF::new(Default::default(), size);
2044 let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2045 element.paint(bounds, bounds, &mut state, &mut paint_cx);
2046 }
2047}