1use super::{
2 display_map::{BlockContext, ToDisplayPoint},
3 Anchor, DisplayPoint, Editor, EditorMode, EditorSnapshot, Input, 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::{CmdChanged, GoToFetchedDefinition, UpdateGoToDefinitionLink},
10 mouse_context_menu::DeployMouseContextMenu,
11 EditorStyle,
12};
13use clock::ReplicaId;
14use collections::{BTreeMap, HashMap};
15use gpui::{
16 color::Color,
17 elements::*,
18 fonts::{HighlightStyle, Underline},
19 geometry::{
20 rect::RectF,
21 vector::{vec2f, Vector2F},
22 PathBuilder,
23 },
24 json::{self, ToJson},
25 platform::CursorStyle,
26 text_layout::{self, Line, RunStyle, TextLayoutCache},
27 AppContext, Axis, Border, CursorRegion, Element, ElementBox, Event, EventContext, KeyDownEvent,
28 LayoutContext, ModifiersChangedEvent, MouseButton, MouseButtonEvent, MouseMovedEvent,
29 MutableAppContext, PaintContext, Quad, Scene, ScrollWheelEvent, SizeConstraint, ViewContext,
30 WeakViewHandle,
31};
32use json::json;
33use language::{Bias, DiagnosticSeverity, Selection};
34use project::ProjectPath;
35use settings::Settings;
36use smallvec::SmallVec;
37use std::{
38 cmp::{self, Ordering},
39 fmt::Write,
40 iter,
41 ops::Range,
42};
43
44const MIN_POPOVER_CHARACTER_WIDTH: f32 = 20.;
45const MIN_POPOVER_LINE_HEIGHT: f32 = 4.;
46const HOVER_POPOVER_GAP: f32 = 10.;
47
48struct SelectionLayout {
49 head: DisplayPoint,
50 range: Range<DisplayPoint>,
51}
52
53impl SelectionLayout {
54 fn new<T: ToPoint + ToDisplayPoint + Clone>(
55 selection: Selection<T>,
56 line_mode: bool,
57 map: &DisplaySnapshot,
58 ) -> Self {
59 if line_mode {
60 let selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
61 let point_range = map.expand_to_line(selection.range());
62 Self {
63 head: selection.head().to_display_point(map),
64 range: point_range.start.to_display_point(map)
65 ..point_range.end.to_display_point(map),
66 }
67 } else {
68 let selection = selection.map(|p| p.to_display_point(map));
69 Self {
70 head: selection.head(),
71 range: selection.range(),
72 }
73 }
74 }
75}
76
77pub struct EditorElement {
78 view: WeakViewHandle<Editor>,
79 style: EditorStyle,
80 cursor_shape: CursorShape,
81}
82
83impl EditorElement {
84 pub fn new(
85 view: WeakViewHandle<Editor>,
86 style: EditorStyle,
87 cursor_shape: CursorShape,
88 ) -> Self {
89 Self {
90 view,
91 style,
92 cursor_shape,
93 }
94 }
95
96 fn view<'a>(&self, cx: &'a AppContext) -> &'a Editor {
97 self.view.upgrade(cx).unwrap().read(cx)
98 }
99
100 fn update_view<F, T>(&self, cx: &mut MutableAppContext, f: F) -> T
101 where
102 F: FnOnce(&mut Editor, &mut ViewContext<Editor>) -> T,
103 {
104 self.view.upgrade(cx).unwrap().update(cx, f)
105 }
106
107 fn snapshot(&self, cx: &mut MutableAppContext) -> EditorSnapshot {
108 self.update_view(cx, |view, cx| view.snapshot(cx))
109 }
110
111 fn mouse_down(
112 &self,
113 position: Vector2F,
114 cmd: bool,
115 alt: bool,
116 shift: bool,
117 mut click_count: usize,
118 layout: &mut LayoutState,
119 paint: &mut PaintState,
120 cx: &mut EventContext,
121 ) -> bool {
122 if cmd && paint.text_bounds.contains_point(position) {
123 let (point, overshoot) = paint.point_for_position(&self.snapshot(cx), layout, position);
124 if overshoot.is_zero() {
125 cx.dispatch_action(GoToFetchedDefinition { point });
126 return true;
127 }
128 }
129
130 if paint.gutter_bounds.contains_point(position) {
131 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
132 } else if !paint.text_bounds.contains_point(position) {
133 return false;
134 }
135
136 let snapshot = self.snapshot(cx.app);
137 let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
138
139 if shift && alt {
140 cx.dispatch_action(Select(SelectPhase::BeginColumnar {
141 position,
142 overshoot: overshoot.column(),
143 }));
144 } else if shift {
145 cx.dispatch_action(Select(SelectPhase::Extend {
146 position,
147 click_count,
148 }));
149 } else {
150 cx.dispatch_action(Select(SelectPhase::Begin {
151 position,
152 add: alt,
153 click_count,
154 }));
155 }
156
157 true
158 }
159
160 fn mouse_right_down(
161 &self,
162 position: Vector2F,
163 layout: &mut LayoutState,
164 paint: &mut PaintState,
165 cx: &mut EventContext,
166 ) -> bool {
167 if !paint.text_bounds.contains_point(position) {
168 return false;
169 }
170
171 let snapshot = self.snapshot(cx.app);
172 let (point, _) = paint.point_for_position(&snapshot, layout, position);
173
174 cx.dispatch_action(DeployMouseContextMenu { position, point });
175 true
176 }
177
178 fn mouse_up(&self, _position: Vector2F, cx: &mut EventContext) -> bool {
179 if self.view(cx.app.as_ref()).is_selecting() {
180 cx.dispatch_action(Select(SelectPhase::End));
181 true
182 } else {
183 false
184 }
185 }
186
187 fn mouse_dragged(
188 &self,
189 position: Vector2F,
190 layout: &mut LayoutState,
191 paint: &mut PaintState,
192 cx: &mut EventContext,
193 ) -> bool {
194 let view = self.view(cx.app.as_ref());
195
196 if view.is_selecting() {
197 let rect = paint.text_bounds;
198 let mut scroll_delta = Vector2F::zero();
199
200 let vertical_margin = layout.line_height.min(rect.height() / 3.0);
201 let top = rect.origin_y() + vertical_margin;
202 let bottom = rect.lower_left().y() - vertical_margin;
203 if position.y() < top {
204 scroll_delta.set_y(-scale_vertical_mouse_autoscroll_delta(top - position.y()))
205 }
206 if position.y() > bottom {
207 scroll_delta.set_y(scale_vertical_mouse_autoscroll_delta(position.y() - bottom))
208 }
209
210 let horizontal_margin = layout.line_height.min(rect.width() / 3.0);
211 let left = rect.origin_x() + horizontal_margin;
212 let right = rect.upper_right().x() - horizontal_margin;
213 if position.x() < left {
214 scroll_delta.set_x(-scale_horizontal_mouse_autoscroll_delta(
215 left - position.x(),
216 ))
217 }
218 if position.x() > right {
219 scroll_delta.set_x(scale_horizontal_mouse_autoscroll_delta(
220 position.x() - right,
221 ))
222 }
223
224 let snapshot = self.snapshot(cx.app);
225 let (position, overshoot) = paint.point_for_position(&snapshot, layout, position);
226
227 cx.dispatch_action(Select(SelectPhase::Update {
228 position,
229 overshoot: overshoot.column(),
230 scroll_position: (snapshot.scroll_position() + scroll_delta)
231 .clamp(Vector2F::zero(), layout.scroll_max),
232 }));
233 true
234 } else {
235 false
236 }
237 }
238
239 fn mouse_moved(
240 &self,
241 position: Vector2F,
242 cmd: bool,
243 layout: &LayoutState,
244 paint: &PaintState,
245 cx: &mut EventContext,
246 ) -> bool {
247 // This will be handled more correctly once https://github.com/zed-industries/zed/issues/1218 is completed
248 // Don't trigger hover popover if mouse is hovering over context menu
249 let point = if paint.text_bounds.contains_point(position) {
250 let (point, overshoot) = paint.point_for_position(&self.snapshot(cx), layout, position);
251 if overshoot.is_zero() {
252 Some(point)
253 } else {
254 None
255 }
256 } else {
257 None
258 };
259
260 cx.dispatch_action(UpdateGoToDefinitionLink {
261 point,
262 cmd_held: cmd,
263 });
264
265 if paint
266 .context_menu_bounds
267 .map_or(false, |context_menu_bounds| {
268 context_menu_bounds.contains_point(position)
269 })
270 {
271 return false;
272 }
273
274 if paint
275 .hover_popover_bounds
276 .iter()
277 .any(|hover_bounds| hover_bounds.contains_point(position))
278 {
279 return false;
280 }
281
282 cx.dispatch_action(HoverAt { point });
283 true
284 }
285
286 fn key_down(&self, input: Option<&str>, cx: &mut EventContext) -> bool {
287 let view = self.view.upgrade(cx.app).unwrap();
288
289 if view.is_focused(cx.app) {
290 if let Some(input) = input {
291 cx.dispatch_action(Input(input.to_string()));
292 true
293 } else {
294 false
295 }
296 } else {
297 false
298 }
299 }
300
301 fn modifiers_changed(&self, cmd: bool, cx: &mut EventContext) -> bool {
302 cx.dispatch_action(CmdChanged { cmd_down: cmd });
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 Event::MouseDown(MouseButtonEvent {
1553 button: MouseButton::Right,
1554 position,
1555 ..
1556 }) => self.mouse_right_down(*position, layout, paint, cx),
1557 Event::MouseUp(MouseButtonEvent {
1558 button: MouseButton::Left,
1559 position,
1560 ..
1561 }) => self.mouse_up(*position, cx),
1562 Event::MouseMoved(MouseMovedEvent {
1563 pressed_button: Some(MouseButton::Left),
1564 position,
1565 ..
1566 }) => self.mouse_dragged(*position, layout, paint, cx),
1567 Event::ScrollWheel(ScrollWheelEvent {
1568 position,
1569 delta,
1570 precise,
1571 }) => self.scroll(*position, *delta, *precise, layout, paint, cx),
1572 Event::KeyDown(KeyDownEvent { input, .. }) => self.key_down(input.as_deref(), cx),
1573 Event::ModifiersChanged(ModifiersChangedEvent { cmd, .. }) => {
1574 self.modifiers_changed(*cmd, cx)
1575 }
1576 Event::MouseMoved(MouseMovedEvent { position, cmd, .. }) => {
1577 self.mouse_moved(*position, *cmd, layout, paint, cx)
1578 }
1579
1580 _ => false,
1581 }
1582 }
1583
1584 fn debug(
1585 &self,
1586 bounds: RectF,
1587 _: &Self::LayoutState,
1588 _: &Self::PaintState,
1589 _: &gpui::DebugContext,
1590 ) -> json::Value {
1591 json!({
1592 "type": "BufferElement",
1593 "bounds": bounds.to_json()
1594 })
1595 }
1596}
1597
1598pub struct LayoutState {
1599 size: Vector2F,
1600 scroll_max: Vector2F,
1601 gutter_size: Vector2F,
1602 gutter_padding: f32,
1603 gutter_margin: f32,
1604 text_size: Vector2F,
1605 snapshot: EditorSnapshot,
1606 active_rows: BTreeMap<u32, bool>,
1607 highlighted_rows: Option<Range<u32>>,
1608 line_layouts: Vec<text_layout::Line>,
1609 line_number_layouts: Vec<Option<text_layout::Line>>,
1610 blocks: Vec<BlockLayout>,
1611 line_height: f32,
1612 em_width: f32,
1613 em_advance: f32,
1614 highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
1615 selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
1616 context_menu: Option<(DisplayPoint, ElementBox)>,
1617 code_actions_indicator: Option<(u32, ElementBox)>,
1618 hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
1619}
1620
1621struct BlockLayout {
1622 row: u32,
1623 element: ElementBox,
1624 style: BlockStyle,
1625}
1626
1627fn layout_line(
1628 row: u32,
1629 snapshot: &EditorSnapshot,
1630 style: &EditorStyle,
1631 layout_cache: &TextLayoutCache,
1632) -> text_layout::Line {
1633 let mut line = snapshot.line(row);
1634
1635 if line.len() > MAX_LINE_LEN {
1636 let mut len = MAX_LINE_LEN;
1637 while !line.is_char_boundary(len) {
1638 len -= 1;
1639 }
1640
1641 line.truncate(len);
1642 }
1643
1644 layout_cache.layout_str(
1645 &line,
1646 style.text.font_size,
1647 &[(
1648 snapshot.line_len(row) as usize,
1649 RunStyle {
1650 font_id: style.text.font_id,
1651 color: Color::black(),
1652 underline: Default::default(),
1653 },
1654 )],
1655 )
1656}
1657
1658pub struct PaintState {
1659 bounds: RectF,
1660 gutter_bounds: RectF,
1661 text_bounds: RectF,
1662 context_menu_bounds: Option<RectF>,
1663 hover_popover_bounds: Vec<RectF>,
1664}
1665
1666impl PaintState {
1667 /// Returns two display points. The first is the nearest valid
1668 /// position in the current buffer and the second is the distance to the
1669 /// nearest valid position if there was overshoot.
1670 fn point_for_position(
1671 &self,
1672 snapshot: &EditorSnapshot,
1673 layout: &LayoutState,
1674 position: Vector2F,
1675 ) -> (DisplayPoint, DisplayPoint) {
1676 let scroll_position = snapshot.scroll_position();
1677 let position = position - self.text_bounds.origin();
1678 let y = position.y().max(0.0).min(layout.size.y());
1679 let row = ((y / layout.line_height) + scroll_position.y()) as u32;
1680 let row_overshoot = row.saturating_sub(snapshot.max_point().row());
1681 let row = cmp::min(row, snapshot.max_point().row());
1682 let line = &layout.line_layouts[(row - scroll_position.y() as u32) as usize];
1683 let x = position.x() + (scroll_position.x() * layout.em_width);
1684
1685 let column = if x >= 0.0 {
1686 line.index_for_x(x)
1687 .map(|ix| ix as u32)
1688 .unwrap_or_else(|| snapshot.line_len(row))
1689 } else {
1690 0
1691 };
1692
1693 let point = snapshot.clip_point(DisplayPoint::new(row, column), Bias::Left);
1694 let mut column_overshoot = (0f32.max(x - line.width()) / layout.em_advance) as u32;
1695 column_overshoot = column_overshoot + column - point.column();
1696
1697 (point, DisplayPoint::new(row_overshoot, column_overshoot))
1698 }
1699}
1700
1701#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1702pub enum CursorShape {
1703 Bar,
1704 Block,
1705 Underscore,
1706}
1707
1708impl Default for CursorShape {
1709 fn default() -> Self {
1710 CursorShape::Bar
1711 }
1712}
1713
1714#[derive(Debug)]
1715pub struct Cursor {
1716 origin: Vector2F,
1717 block_width: f32,
1718 line_height: f32,
1719 color: Color,
1720 shape: CursorShape,
1721 block_text: Option<Line>,
1722}
1723
1724impl Cursor {
1725 pub fn new(
1726 origin: Vector2F,
1727 block_width: f32,
1728 line_height: f32,
1729 color: Color,
1730 shape: CursorShape,
1731 block_text: Option<Line>,
1732 ) -> Cursor {
1733 Cursor {
1734 origin,
1735 block_width,
1736 line_height,
1737 color,
1738 shape,
1739 block_text,
1740 }
1741 }
1742
1743 pub fn paint(&self, origin: Vector2F, cx: &mut PaintContext) {
1744 let bounds = match self.shape {
1745 CursorShape::Bar => RectF::new(self.origin + origin, vec2f(2.0, self.line_height)),
1746 CursorShape::Block => RectF::new(
1747 self.origin + origin,
1748 vec2f(self.block_width, self.line_height),
1749 ),
1750 CursorShape::Underscore => RectF::new(
1751 self.origin + origin + Vector2F::new(0.0, self.line_height - 2.0),
1752 vec2f(self.block_width, 2.0),
1753 ),
1754 };
1755
1756 cx.scene.push_quad(Quad {
1757 bounds,
1758 background: Some(self.color),
1759 border: Border::new(0., Color::black()),
1760 corner_radius: 0.,
1761 });
1762
1763 if let Some(block_text) = &self.block_text {
1764 block_text.paint(self.origin + origin, bounds, self.line_height, cx);
1765 }
1766 }
1767}
1768
1769#[derive(Debug)]
1770pub struct HighlightedRange {
1771 pub start_y: f32,
1772 pub line_height: f32,
1773 pub lines: Vec<HighlightedRangeLine>,
1774 pub color: Color,
1775 pub corner_radius: f32,
1776}
1777
1778#[derive(Debug)]
1779pub struct HighlightedRangeLine {
1780 pub start_x: f32,
1781 pub end_x: f32,
1782}
1783
1784impl HighlightedRange {
1785 pub fn paint(&self, bounds: RectF, scene: &mut Scene) {
1786 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
1787 self.paint_lines(self.start_y, &self.lines[0..1], bounds, scene);
1788 self.paint_lines(
1789 self.start_y + self.line_height,
1790 &self.lines[1..],
1791 bounds,
1792 scene,
1793 );
1794 } else {
1795 self.paint_lines(self.start_y, &self.lines, bounds, scene);
1796 }
1797 }
1798
1799 fn paint_lines(
1800 &self,
1801 start_y: f32,
1802 lines: &[HighlightedRangeLine],
1803 bounds: RectF,
1804 scene: &mut Scene,
1805 ) {
1806 if lines.is_empty() {
1807 return;
1808 }
1809
1810 let mut path = PathBuilder::new();
1811 let first_line = lines.first().unwrap();
1812 let last_line = lines.last().unwrap();
1813
1814 let first_top_left = vec2f(first_line.start_x, start_y);
1815 let first_top_right = vec2f(first_line.end_x, start_y);
1816
1817 let curve_height = vec2f(0., self.corner_radius);
1818 let curve_width = |start_x: f32, end_x: f32| {
1819 let max = (end_x - start_x) / 2.;
1820 let width = if max < self.corner_radius {
1821 max
1822 } else {
1823 self.corner_radius
1824 };
1825
1826 vec2f(width, 0.)
1827 };
1828
1829 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
1830 path.reset(first_top_right - top_curve_width);
1831 path.curve_to(first_top_right + curve_height, first_top_right);
1832
1833 let mut iter = lines.iter().enumerate().peekable();
1834 while let Some((ix, line)) = iter.next() {
1835 let bottom_right = vec2f(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
1836
1837 if let Some((_, next_line)) = iter.peek() {
1838 let next_top_right = vec2f(next_line.end_x, bottom_right.y());
1839
1840 match next_top_right.x().partial_cmp(&bottom_right.x()).unwrap() {
1841 Ordering::Equal => {
1842 path.line_to(bottom_right);
1843 }
1844 Ordering::Less => {
1845 let curve_width = curve_width(next_top_right.x(), bottom_right.x());
1846 path.line_to(bottom_right - curve_height);
1847 if self.corner_radius > 0. {
1848 path.curve_to(bottom_right - curve_width, bottom_right);
1849 }
1850 path.line_to(next_top_right + curve_width);
1851 if self.corner_radius > 0. {
1852 path.curve_to(next_top_right + curve_height, next_top_right);
1853 }
1854 }
1855 Ordering::Greater => {
1856 let curve_width = curve_width(bottom_right.x(), next_top_right.x());
1857 path.line_to(bottom_right - curve_height);
1858 if self.corner_radius > 0. {
1859 path.curve_to(bottom_right + curve_width, bottom_right);
1860 }
1861 path.line_to(next_top_right - curve_width);
1862 if self.corner_radius > 0. {
1863 path.curve_to(next_top_right + curve_height, next_top_right);
1864 }
1865 }
1866 }
1867 } else {
1868 let curve_width = curve_width(line.start_x, line.end_x);
1869 path.line_to(bottom_right - curve_height);
1870 if self.corner_radius > 0. {
1871 path.curve_to(bottom_right - curve_width, bottom_right);
1872 }
1873
1874 let bottom_left = vec2f(line.start_x, bottom_right.y());
1875 path.line_to(bottom_left + curve_width);
1876 if self.corner_radius > 0. {
1877 path.curve_to(bottom_left - curve_height, bottom_left);
1878 }
1879 }
1880 }
1881
1882 if first_line.start_x > last_line.start_x {
1883 let curve_width = curve_width(last_line.start_x, first_line.start_x);
1884 let second_top_left = vec2f(last_line.start_x, start_y + self.line_height);
1885 path.line_to(second_top_left + curve_height);
1886 if self.corner_radius > 0. {
1887 path.curve_to(second_top_left + curve_width, second_top_left);
1888 }
1889 let first_bottom_left = vec2f(first_line.start_x, second_top_left.y());
1890 path.line_to(first_bottom_left - curve_width);
1891 if self.corner_radius > 0. {
1892 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
1893 }
1894 }
1895
1896 path.line_to(first_top_left + curve_height);
1897 if self.corner_radius > 0. {
1898 path.curve_to(first_top_left + top_curve_width, first_top_left);
1899 }
1900 path.line_to(first_top_right - top_curve_width);
1901
1902 scene.push_path(path.build(self.color, Some(bounds)));
1903 }
1904}
1905
1906fn scale_vertical_mouse_autoscroll_delta(delta: f32) -> f32 {
1907 delta.powf(1.5) / 100.0
1908}
1909
1910fn scale_horizontal_mouse_autoscroll_delta(delta: f32) -> f32 {
1911 delta.powf(1.2) / 300.0
1912}
1913
1914#[cfg(test)]
1915mod tests {
1916 use std::sync::Arc;
1917
1918 use super::*;
1919 use crate::{
1920 display_map::{BlockDisposition, BlockProperties},
1921 Editor, MultiBuffer,
1922 };
1923 use settings::Settings;
1924 use util::test::sample_text;
1925
1926 #[gpui::test]
1927 fn test_layout_line_numbers(cx: &mut gpui::MutableAppContext) {
1928 cx.set_global(Settings::test(cx));
1929 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
1930 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1931 Editor::new(EditorMode::Full, buffer, None, None, cx)
1932 });
1933 let element = EditorElement::new(
1934 editor.downgrade(),
1935 editor.read(cx).style(cx),
1936 CursorShape::Bar,
1937 );
1938
1939 let layouts = editor.update(cx, |editor, cx| {
1940 let snapshot = editor.snapshot(cx);
1941 let mut presenter = cx.build_presenter(window_id, 30.);
1942 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1943 element.layout_line_numbers(0..6, &Default::default(), &snapshot, &mut layout_cx)
1944 });
1945 assert_eq!(layouts.len(), 6);
1946 }
1947
1948 #[gpui::test]
1949 fn test_layout_with_placeholder_text_and_blocks(cx: &mut gpui::MutableAppContext) {
1950 cx.set_global(Settings::test(cx));
1951 let buffer = MultiBuffer::build_simple("", cx);
1952 let (window_id, editor) = cx.add_window(Default::default(), |cx| {
1953 Editor::new(EditorMode::Full, buffer, None, None, cx)
1954 });
1955
1956 editor.update(cx, |editor, cx| {
1957 editor.set_placeholder_text("hello", cx);
1958 editor.insert_blocks(
1959 [BlockProperties {
1960 style: BlockStyle::Fixed,
1961 disposition: BlockDisposition::Above,
1962 height: 3,
1963 position: Anchor::min(),
1964 render: Arc::new(|_| Empty::new().boxed()),
1965 }],
1966 cx,
1967 );
1968
1969 // Blur the editor so that it displays placeholder text.
1970 cx.blur();
1971 });
1972
1973 let mut element = EditorElement::new(
1974 editor.downgrade(),
1975 editor.read(cx).style(cx),
1976 CursorShape::Bar,
1977 );
1978
1979 let mut scene = Scene::new(1.0);
1980 let mut presenter = cx.build_presenter(window_id, 30.);
1981 let mut layout_cx = presenter.build_layout_context(Vector2F::zero(), false, cx);
1982 let (size, mut state) = element.layout(
1983 SizeConstraint::new(vec2f(500., 500.), vec2f(500., 500.)),
1984 &mut layout_cx,
1985 );
1986
1987 assert_eq!(state.line_layouts.len(), 4);
1988 assert_eq!(
1989 state
1990 .line_number_layouts
1991 .iter()
1992 .map(Option::is_some)
1993 .collect::<Vec<_>>(),
1994 &[false, false, false, true]
1995 );
1996
1997 // Don't panic.
1998 let bounds = RectF::new(Default::default(), size);
1999 let mut paint_cx = presenter.build_paint_context(&mut scene, bounds.size(), cx);
2000 element.paint(bounds, bounds, &mut state, &mut paint_cx);
2001 }
2002}