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