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