-
Notifications
You must be signed in to change notification settings - Fork 591
Expand file tree
/
Copy pathelement.rs
More file actions
2059 lines (1793 loc) · 71.3 KB
/
element.rs
File metadata and controls
2059 lines (1793 loc) · 71.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{ops::Range, rc::Rc};
use gpui::{
App, Bounds, Corners, Element, ElementId, ElementInputHandler, Entity, GlobalElementId, Half,
HighlightStyle, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, LayoutId,
MouseButton, MouseMoveEvent, Path, Pixels, Point, ShapedLine, SharedString, Size, Style,
Styled as _, TextAlign, TextRun, TextStyle, UnderlineStyle, Window, fill, point, px, relative,
size,
};
use ropey::Rope;
use smallvec::SmallVec;
use crate::{
ActiveTheme as _, Colorize, IconName, Root, Selectable, Sizable as _,
button::{Button, ButtonVariants as _},
input::{RopeExt as _, blink_cursor::CURSOR_WIDTH, display_map::LineLayout},
};
use super::{InputState, LastLayout, WhitespaceIndicators, mode::InputMode};
const BOTTOM_MARGIN_ROWS: usize = 3;
pub(super) const RIGHT_MARGIN: Pixels = px(10.);
pub(super) const LINE_NUMBER_RIGHT_MARGIN: Pixels = px(10.);
const FOLD_ICON_WIDTH: Pixels = px(14.);
const FOLD_ICON_HITBOX_WIDTH: Pixels = px(18.);
/// Layout information for fold icons.
struct FoldIconLayout {
/// Hitbox for the line number area (used for hover detection)
line_number_hitbox: Hitbox,
/// List of (display_row, is_folded, icon_element) pairs for each fold candidate
icons: Vec<(usize, bool, gpui::AnyElement)>,
}
pub(super) struct TextElement {
pub(crate) state: Entity<InputState>,
placeholder: SharedString,
}
impl TextElement {
pub(super) fn new(state: Entity<InputState>) -> Self {
Self {
state,
placeholder: SharedString::default(),
}
}
/// Set the placeholder text of the input field.
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
fn paint_mouse_listeners(&mut self, window: &mut Window, _: &mut App) {
window.on_mouse_event({
let state = self.state.clone();
move |event: &MouseMoveEvent, _, window, cx| {
if event.pressed_button == Some(MouseButton::Left) {
state.update(cx, |state, cx| {
state.on_drag_move(event, window, cx);
});
}
}
});
}
/// Returns the:
///
/// - cursor bounds
/// - scroll offset
/// - current row index (No only the visible lines, but all lines)
///
/// This method also will update for track scroll to cursor.
fn layout_cursor(
&self,
last_layout: &LastLayout,
bounds: &mut Bounds<Pixels>,
_: &mut Window,
cx: &mut App,
) -> (Option<Bounds<Pixels>>, Point<Pixels>, Option<usize>) {
let state = self.state.read(cx);
let line_height = last_layout.line_height;
let visible_range = &last_layout.visible_range;
let lines = &last_layout.lines;
let line_number_width = last_layout.line_number_width;
let mut selected_range = state.selected_range;
if let Some(ime_marked_range) = &state.ime_marked_range {
selected_range = (ime_marked_range.end..ime_marked_range.end).into();
}
let is_selected_all = selected_range.len() == state.text.len();
let mut cursor = state.cursor();
if state.masked {
// Because masked use `*`, 1 char with 1 byte.
selected_range.start = state.text.offset_to_char_index(selected_range.start);
selected_range.end = state.text.offset_to_char_index(selected_range.end);
cursor = state.text.offset_to_char_index(cursor);
}
let mut current_row = None;
let mut scroll_offset = state.scroll_handle.offset();
let mut cursor_bounds = None;
// If the input has a fixed height (Otherwise is auto-grow), we need to add a bottom margin to the input.
let top_bottom_margin = if state.mode.is_auto_grow() {
line_height
} else if visible_range.len() < BOTTOM_MARGIN_ROWS * 8 {
line_height
} else {
BOTTOM_MARGIN_ROWS * line_height
};
// The cursor corresponds to the current cursor position in the text no only the line.
let mut cursor_pos = None;
let mut cursor_start = None;
let mut cursor_end = None;
let mut prev_lines_offset = 0;
let mut offset_y = px(0.);
let buffer_lines = state.display_map.lines();
for (ix, wrap_line) in buffer_lines.iter().enumerate() {
let row = ix;
let line_origin = point(px(0.), offset_y);
// break loop if all cursor positions are found
if cursor_pos.is_some() && cursor_start.is_some() && cursor_end.is_some() {
break;
}
let in_visible_range = ix >= visible_range.start;
if let Some(line) = in_visible_range
.then(|| lines.get(ix.saturating_sub(visible_range.start)))
.flatten()
{
// If in visible range lines
if cursor_pos.is_none() {
let offset = cursor.saturating_sub(prev_lines_offset);
if let Some(pos) = line.position_for_index(offset, last_layout) {
current_row = Some(row);
cursor_pos = Some(line_origin + pos);
}
}
if cursor_start.is_none() {
let offset = selected_range.start.saturating_sub(prev_lines_offset);
if let Some(pos) = line.position_for_index(offset, last_layout) {
cursor_start = Some(line_origin + pos);
}
}
if cursor_end.is_none() {
let offset = selected_range.end.saturating_sub(prev_lines_offset);
if let Some(pos) = line.position_for_index(offset, last_layout) {
cursor_end = Some(line_origin + pos);
}
}
offset_y += line.size(line_height).height;
// +1 for the last `\n`
// Use wrap_line.len() (buffer line length) instead of line.len() (LineLayout length)
// because hidden (folded) LineLayouts have len=0 but the buffer line has content
prev_lines_offset += wrap_line.len() + 1;
} else {
// If not in the visible range.
// Just increase the offset_y and prev_lines_offset.
// This will let the scroll_offset to track the cursor position correctly.
if prev_lines_offset >= cursor && cursor_pos.is_none() {
current_row = Some(row);
cursor_pos = Some(line_origin);
}
if prev_lines_offset >= selected_range.start && cursor_start.is_none() {
cursor_start = Some(line_origin);
}
if prev_lines_offset >= selected_range.end && cursor_end.is_none() {
cursor_end = Some(line_origin);
}
// 需要考虑折叠:只累加可见的 wrap rows
let visible_wrap_rows =
state.display_map.visible_wrap_row_count_for_buffer_line(ix);
offset_y += line_height * visible_wrap_rows;
// +1 for the last `\n`
prev_lines_offset += wrap_line.len() + 1;
}
}
if let (Some(cursor_pos), Some(cursor_start), Some(cursor_end)) =
(cursor_pos, cursor_start, cursor_end)
{
let selection_changed = state.last_selected_range != Some(selected_range);
if selection_changed && !is_selected_all {
// Apart from left alignment, just leave enough space for the cursor size on the right side.
let safety_margin = if last_layout.text_align == TextAlign::Left {
RIGHT_MARGIN
} else {
CURSOR_WIDTH
};
scroll_offset.x = if scroll_offset.x + cursor_pos.x
> (bounds.size.width - line_number_width - safety_margin)
{
// cursor is out of right
bounds.size.width - line_number_width - safety_margin - cursor_pos.x
} else if scroll_offset.x + cursor_pos.x < px(0.) {
// cursor is out of left
scroll_offset.x - cursor_pos.x
} else {
scroll_offset.x
};
// If we change the scroll_offset.y, GPUI will render and trigger the next run loop.
// So, here we just adjust offset by `line_height` for move smooth.
scroll_offset.y =
if scroll_offset.y + cursor_pos.y > bounds.size.height - top_bottom_margin {
// cursor is out of bottom
scroll_offset.y - line_height
} else if scroll_offset.y + cursor_pos.y < top_bottom_margin {
// cursor is out of top
(scroll_offset.y + line_height).min(px(0.))
} else {
scroll_offset.y
};
// For selection to move scroll
if state.selection_reversed {
if scroll_offset.x + cursor_start.x < px(0.) {
// selection start is out of left
scroll_offset.x = -cursor_start.x;
}
if scroll_offset.y + cursor_start.y < px(0.) {
// selection start is out of top
scroll_offset.y = -cursor_start.y;
}
} else {
// TODO: Consider to remove this part,
// maybe is not necessary (But selection_reversed is needed).
if scroll_offset.x + cursor_end.x <= px(0.) {
// selection end is out of left
scroll_offset.x = -cursor_end.x;
}
if scroll_offset.y + cursor_end.y <= px(0.) {
// selection end is out of top
scroll_offset.y = -cursor_end.y;
}
}
}
// cursor bounds
let cursor_height = match state.size {
crate::Size::Large => 1.,
crate::Size::Small => 0.75,
_ => 0.85,
} * line_height;
cursor_bounds = Some(Bounds::new(
point(
bounds.left() + cursor_pos.x + line_number_width + scroll_offset.x,
bounds.top() + cursor_pos.y + ((line_height - cursor_height) / 2.),
),
size(CURSOR_WIDTH, cursor_height),
));
}
if let Some(deferred_scroll_offset) = state.deferred_scroll_offset {
scroll_offset = deferred_scroll_offset;
}
bounds.origin = bounds.origin + scroll_offset;
(cursor_bounds, scroll_offset, current_row)
}
/// Layout the match range to a Path.
pub(crate) fn layout_match_range(
range: Range<usize>,
last_layout: &LastLayout,
bounds: &Bounds<Pixels>,
buffer_lines: &[super::display_map::LineItem],
) -> Option<Path<Pixels>> {
if range.is_empty() {
return None;
}
if range.start < last_layout.visible_range_offset.start
|| range.end > last_layout.visible_range_offset.end
{
return None;
}
let line_height = last_layout.line_height;
let visible_top = last_layout.visible_top;
let visible_range = &last_layout.visible_range;
let lines = &last_layout.lines;
let line_number_width = last_layout.line_number_width;
let start_ix = range.start;
let end_ix = range.end;
// Start from visible_top (which already accounts for all lines before visible range)
let mut prev_lines_offset = last_layout.visible_range_offset.start;
let mut offset_y = visible_top;
let mut line_corners = vec![];
// Only iterate over buffer lines in the visible range
for ix in visible_range.start..visible_range.end {
let wrap_line = &buffer_lines[ix];
let line_index = ix - visible_range.start;
let line = &lines[line_index];
let line_size = line.size(line_height);
let line_wrap_width = line_size.width;
let line_origin = point(px(0.), offset_y);
let line_cursor_start =
line.position_for_index(start_ix.saturating_sub(prev_lines_offset), last_layout);
let line_cursor_end =
line.position_for_index(end_ix.saturating_sub(prev_lines_offset), last_layout);
if line_cursor_start.is_some() || line_cursor_end.is_some() {
let start = line_cursor_start
.unwrap_or_else(|| line.position_for_index(0, last_layout).unwrap());
let end = line_cursor_end
.unwrap_or_else(|| line.position_for_index(line.len(), last_layout).unwrap());
// Split the selection into multiple items
let wrapped_lines =
(end.y / line_height).ceil() as usize - (start.y / line_height).ceil() as usize;
let mut end_x = end.x;
if wrapped_lines > 0 {
end_x = line_wrap_width;
}
// Ensure at least 6px width for the selection for empty lines.
end_x = end_x.max(start.x + px(6.));
line_corners.push(Corners {
top_left: line_origin + point(start.x, start.y),
top_right: line_origin + point(end_x, start.y),
bottom_left: line_origin + point(start.x, start.y + line_height),
bottom_right: line_origin + point(end_x, start.y + line_height),
});
// wrapped lines
for i in 1..=wrapped_lines {
let start = point(px(0.), start.y + i as f32 * line_height);
let mut end = point(end.x, end.y + i as f32 * line_height);
if i < wrapped_lines {
end.x = line_size.width;
}
line_corners.push(Corners {
top_left: line_origin + point(start.x, start.y),
top_right: line_origin + point(end.x, start.y),
bottom_left: line_origin + point(start.x, start.y + line_height),
bottom_right: line_origin + point(end.x, start.y + line_height),
});
}
}
if line_cursor_start.is_some() && line_cursor_end.is_some() {
break;
}
offset_y += line_size.height;
// +1 for skip the last `\n`
// Use wrap_line.len() (original buffer line length) instead of line.len() (LineLayout length)
prev_lines_offset += wrap_line.len() + 1;
}
let mut points = vec![];
if line_corners.is_empty() {
return None;
}
// Fix corners to make sure the left to right direction
for corners in &mut line_corners {
if corners.top_left.x > corners.top_right.x {
std::mem::swap(&mut corners.top_left, &mut corners.top_right);
std::mem::swap(&mut corners.bottom_left, &mut corners.bottom_right);
}
}
for corners in &line_corners {
points.push(corners.top_right);
points.push(corners.bottom_right);
points.push(corners.bottom_left);
}
let mut rev_line_corners = line_corners.iter().rev().peekable();
while let Some(corners) = rev_line_corners.next() {
points.push(corners.top_left);
if let Some(next) = rev_line_corners.peek() {
if next.top_left.x > corners.top_left.x {
points.push(point(next.top_left.x, corners.top_left.y));
}
}
}
// print_points_as_svg_path(&line_corners, &points);
let path_origin = bounds.origin + point(line_number_width, px(0.));
let first_p = *points.get(0).unwrap();
let mut builder = gpui::PathBuilder::fill();
builder.move_to(path_origin + first_p);
for p in points.iter().skip(1) {
builder.line_to(path_origin + *p);
}
builder.build().ok()
}
fn layout_search_matches(
&self,
last_layout: &LastLayout,
bounds: &Bounds<Pixels>,
cx: &mut App,
) -> Vec<(Path<Pixels>, bool)> {
let state = self.state.read(cx);
let buffer_lines = state.display_map.lines();
let search_panel = state.search_panel.clone();
let Some((ranges, current_match_ix)) = search_panel.and_then(|panel| {
if let Some(matcher) = panel.read(cx).matcher() {
Some((matcher.matched_ranges.clone(), matcher.current_match_ix))
} else {
None
}
}) else {
return vec![];
};
let mut paths = Vec::new();
for (index, range) in ranges.as_ref().iter().enumerate() {
if let Some(path) =
Self::layout_match_range(range.clone(), last_layout, bounds, buffer_lines)
{
paths.push((path, current_match_ix == index));
}
}
paths
}
fn layout_hover_highlight(
&self,
last_layout: &LastLayout,
bounds: &Bounds<Pixels>,
cx: &mut App,
) -> Option<Path<Pixels>> {
let state = self.state.read(cx);
let buffer_lines = state.display_map.lines();
let hover_popover = state.hover_popover.clone();
let Some(symbol_range) = hover_popover.map(|popover| popover.read(cx).symbol_range.clone())
else {
return None;
};
Self::layout_match_range(symbol_range, last_layout, bounds, buffer_lines)
}
fn layout_document_colors(
&self,
document_colors: &[(Range<usize>, Hsla)],
last_layout: &LastLayout,
bounds: &Bounds<Pixels>,
cx: &mut App,
) -> Vec<(Path<Pixels>, Hsla)> {
let buffer_lines = self.state.read(cx).display_map.lines();
let mut paths = vec![];
for (range, color) in document_colors.iter() {
if let Some(path) =
Self::layout_match_range(range.clone(), last_layout, bounds, buffer_lines)
{
paths.push((path, *color));
}
}
paths
}
fn layout_selections(
&self,
last_layout: &LastLayout,
bounds: &mut Bounds<Pixels>,
window: &mut Window,
cx: &mut App,
) -> Option<Path<Pixels>> {
let state = self.state.read(cx);
if !state.focus_handle.is_focused(window) {
return None;
}
let buffer_lines = state.display_map.lines();
let mut selected_range = state.selected_range;
if let Some(ime_marked_range) = &state.ime_marked_range {
if !ime_marked_range.is_empty() {
selected_range = (ime_marked_range.end..ime_marked_range.end).into();
}
}
if selected_range.is_empty() {
return None;
}
if state.masked {
// Because masked use `*`, 1 char with 1 byte.
selected_range.start = state.text.offset_to_char_index(selected_range.start);
selected_range.end = state.text.offset_to_char_index(selected_range.end);
}
let (start_ix, end_ix) = if selected_range.start < selected_range.end {
(selected_range.start, selected_range.end)
} else {
(selected_range.end, selected_range.start)
};
let range = start_ix.max(last_layout.visible_range_offset.start)
..end_ix.min(last_layout.visible_range_offset.end);
Self::layout_match_range(range, &last_layout, bounds, buffer_lines)
}
/// Calculate the visible range of lines in the viewport.
///
/// Returns
///
/// - visible_range: The visible range is based on unwrapped lines (Zero based).
/// - visible_top: The top position of the first visible line in the scroll viewport.
fn calculate_visible_range(
&self,
state: &InputState,
line_height: Pixels,
input_height: Pixels,
) -> (Range<usize>, Pixels) {
// Add extra rows to avoid showing empty space when scroll to bottom.
let extra_rows = 1;
let mut visible_top = px(0.);
if state.mode.is_single_line() {
return (0..1, visible_top);
}
let total_lines = state.display_map.wrap_row_count();
let scroll_top = if let Some(deferred_scroll_offset) = state.deferred_scroll_offset {
deferred_scroll_offset.y
} else {
state.scroll_handle.offset().y
};
let mut visible_range = 0..total_lines;
let mut line_bottom = px(0.);
for (ix, _line) in state.display_map.lines().iter().enumerate() {
// 获取该 buffer line 中可见的 wrap rows 数量
let visible_wrap_rows = state.display_map.visible_wrap_row_count_for_buffer_line(ix);
// 如果全部被折叠,跳过
if visible_wrap_rows == 0 {
continue;
}
// 只累加可见 wrap rows 的高度
let wrapped_height = line_height * visible_wrap_rows;
line_bottom += wrapped_height;
if line_bottom < -scroll_top {
visible_top = line_bottom - wrapped_height;
visible_range.start = ix;
}
if line_bottom + scroll_top >= input_height {
visible_range.end = (ix + extra_rows).min(total_lines);
break;
}
}
(visible_range, visible_top)
}
/// Return (line_number_width, line_number_len)
fn layout_line_numbers(
state: &InputState,
text: &Rope,
font_size: Pixels,
style: &TextStyle,
window: &mut Window,
) -> (Pixels, usize) {
let total_lines = text.lines_len();
let line_number_len = match total_lines {
0..=9999 => 5,
10000..=99999 => 6,
100000..=999999 => 7,
_ => 8,
};
let mut line_number_width = if state.mode.line_number() {
let empty_line_number = window.text_system().shape_line(
"+".repeat(line_number_len).into(),
font_size,
&[TextRun {
len: line_number_len,
font: style.font(),
color: gpui::black(),
background_color: None,
underline: None,
strikethrough: None,
}],
None,
);
empty_line_number.width + LINE_NUMBER_RIGHT_MARGIN
} else if state.mode.is_code_editor() && state.mode.is_multi_line() {
LINE_NUMBER_RIGHT_MARGIN
} else {
px(0.)
};
if state.mode.is_folding() {
// Add extra space for fold icons
line_number_width += FOLD_ICON_HITBOX_WIDTH
}
(line_number_width, line_number_len)
}
/// Layout shaped lines for whitespace indicators (space and tab).
///
/// Returns `WhitespaceIndicators` with shaped lines for space and tab characters.
fn layout_whitespace_indicators(
state: &InputState,
text_size: Pixels,
style: &TextStyle,
window: &mut Window,
cx: &App,
) -> Option<WhitespaceIndicators> {
if !state.show_whitespaces {
return None;
}
let invisible_color = cx
.theme()
.highlight_theme
.style
.editor_invisible
.unwrap_or(cx.theme().muted_foreground);
let space_font_size = text_size.half();
let tab_font_size = text_size;
let space_text = SharedString::new_static("•");
let space = window.text_system().shape_line(
space_text.clone(),
space_font_size,
&[TextRun {
len: space_text.len(),
font: style.font(),
color: invisible_color,
background_color: None,
underline: None,
strikethrough: None,
}],
None,
);
let tab_text = SharedString::new_static("→");
let tab = window.text_system().shape_line(
tab_text.clone(),
tab_font_size,
&[TextRun {
len: tab_text.len(),
font: style.font(),
color: invisible_color,
background_color: None,
underline: None,
strikethrough: None,
}],
None,
);
Some(WhitespaceIndicators { space, tab })
}
/// Compute inline completion ghost lines for rendering.
///
/// Returns (first_line, ghost_lines) where:
/// - first_line: Shaped text for the first line (goes after cursor on same line)
/// - ghost_lines: Shaped lines for subsequent lines (shift content down)
fn layout_inline_completion(
state: &InputState,
visible_range: &Range<usize>,
font_size: Pixels,
window: &mut Window,
cx: &App,
) -> (Option<ShapedLine>, Vec<ShapedLine>) {
// Must be focused to show inline completion
if !state.focus_handle.is_focused(window) {
return (None, vec![]);
}
let Some(completion_item) = state.inline_completion.item.as_ref() else {
return (None, vec![]);
};
// Get cursor row from cursor position
let cursor_row = state.cursor_position().line as usize;
// Only show if cursor row is visible
if cursor_row < visible_range.start || cursor_row >= visible_range.end {
return (None, vec![]);
}
let completion_text = &completion_item.insert_text;
let completion_color = cx.theme().muted_foreground.opacity(0.5);
let text_style = window.text_style();
let font = text_style.font();
let lines: Vec<&str> = completion_text.split('\n').collect();
if lines.is_empty() {
return (None, vec![]);
}
// Shape first line (goes after cursor)
let first_text: SharedString = lines[0].to_string().into();
let first_line = if !first_text.is_empty() {
let first_run = TextRun {
len: first_text.len(),
font: font.clone(),
color: completion_color,
background_color: None,
underline: None,
strikethrough: None,
};
Some(
window
.text_system()
.shape_line(first_text, font_size, &[first_run], None),
)
} else {
None
};
// Shape ghost lines (lines 2+ that shift content down)
let ghost_lines: Vec<ShapedLine> = lines[1..]
.iter()
.map(|line_text| {
let text: SharedString = line_text.to_string().into();
let len = text.len().max(1); // Ensure at least 1 for empty lines
let run = TextRun {
len,
font: font.clone(),
color: completion_color,
background_color: None,
underline: None,
strikethrough: None,
};
// Use space for empty lines so they take up height
let shaped_text = if text.is_empty() { " ".into() } else { text };
window
.text_system()
.shape_line(shaped_text, font_size, &[run], None)
})
.collect();
(first_line, ghost_lines)
}
/// Return (line_number_width, line_number_len)
/// Layout fold icon hitboxes during prepaint phase.
///
/// This creates hitboxes for the fold icon area, positioned to the right of line numbers.
/// Icons are created and prepainted here to avoid panics.
fn layout_fold_icons(
&self,
bounds: &Bounds<Pixels>,
last_layout: &LastLayout,
window: &mut Window,
cx: &mut App,
) -> FoldIconLayout {
// First pass: collect fold information from state
struct FoldInfo {
buffer_line: usize,
is_folded: bool,
display_row: usize,
offset_y: Pixels,
}
let line_number_hitbox = window.insert_hitbox(
Bounds::new(
bounds.origin + point(px(0.), last_layout.visible_top),
size(last_layout.line_number_width, bounds.size.height),
),
HitboxBehavior::Normal,
);
let mut icon_layout = FoldIconLayout {
line_number_hitbox,
icons: vec![],
};
let fold_infos: Vec<FoldInfo> = {
let state = self.state.read(cx);
if !state.mode.is_folding() {
return icon_layout;
}
let mut infos = Vec::new();
let mut offset_y = last_layout.visible_top;
for (ix, line) in last_layout.lines.iter().enumerate() {
// visible_range contains buffer lines (not display rows)
let buffer_line = last_layout.visible_range.start + ix;
// Skip hidden (folded) lines - they should not show fold icons
if !state.display_map.is_buffer_line_hidden(buffer_line)
&& state.display_map.is_fold_candidate(buffer_line)
{
let is_folded = state.display_map.is_folded_at(buffer_line);
infos.push(FoldInfo {
buffer_line,
is_folded,
display_row: buffer_line,
offset_y,
});
}
offset_y += line.wrapped_lines.len() * last_layout.line_height;
}
infos
}; // state is dropped here
// Second pass: create and prepaint icons
let line_height = last_layout.line_height;
let line_number_width = last_layout.line_number_width
- LINE_NUMBER_RIGHT_MARGIN.half()
- FOLD_ICON_HITBOX_WIDTH;
let icon_relative_pos = point(
(FOLD_ICON_HITBOX_WIDTH - FOLD_ICON_WIDTH).half(),
(line_height - FOLD_ICON_WIDTH).half(),
);
for (ix, info) in fold_infos.iter().enumerate() {
// Position fold icon to the right of line numbers
let fold_icon_bounds = Bounds::new(
bounds.origin + icon_relative_pos + point(line_number_width, info.offset_y),
size(FOLD_ICON_HITBOX_WIDTH, line_height),
);
// Create and prepaint icon
let mut icon = Button::new(("fold", ix))
.ghost()
.icon(if info.is_folded {
IconName::ChevronRight
} else {
IconName::ChevronDown
})
.xsmall()
.rounded_xs()
.size(FOLD_ICON_WIDTH)
.selected(info.is_folded)
.on_mouse_down(MouseButton::Left, {
let state = self.state.clone();
let buffer_line = info.buffer_line;
move |_, _: &mut Window, cx: &mut App| {
cx.stop_propagation();
state.update(cx, |state, cx| {
state.display_map.toggle_fold(buffer_line);
cx.notify();
});
}
})
.into_any_element();
icon.prepaint_as_root(
fold_icon_bounds.origin,
fold_icon_bounds.size.into(),
window,
cx,
);
icon_layout
.icons
.push((info.display_row, info.is_folded, icon));
}
icon_layout
}
/// Paint fold icons using prepaint hitboxes.
///
/// This handles:
/// - Rendering fold icons (chevron-right for folded, chevron-down for expanded)
/// - Mouse click handling to toggle fold state
/// - Cursor style changes on hover
/// - Only show icon on hover or for current line
fn paint_fold_icons(
&mut self,
fold_icon_layout: &mut FoldIconLayout,
current_row: Option<usize>,
window: &mut Window,
cx: &mut App,
) {
let is_hovered = fold_icon_layout.line_number_hitbox.is_hovered(window);
for (display_row, is_folded, icon) in fold_icon_layout.icons.iter_mut() {
let is_current_line = current_row == Some(*display_row);
if !is_hovered && !is_current_line && !*is_folded {
continue;
}
icon.paint(window, cx);
}
}
#[allow(clippy::too_many_arguments)]
fn layout_lines(
state: &InputState,
display_text: &Rope,
last_layout: &LastLayout,
font_size: Pixels,
runs: &[TextRun],
bg_segments: &[(Range<usize>, Hsla)],
whitespace_indicators: Option<WhitespaceIndicators>,
window: &mut Window,
) -> Vec<LineLayout> {
let is_single_line = state.mode.is_single_line();
let buffer_lines = state.display_map.lines();
let visible_range = &last_layout.visible_range;
let visible_range_offset = &last_layout.visible_range_offset;
if is_single_line {
let shaped_line = window.text_system().shape_line(
display_text.to_string().into(),
font_size,
&runs,
None,
);
let line_layout = LineLayout::new()
.lines(smallvec::smallvec![shaped_line])
.with_whitespaces(whitespace_indicators);
return vec![line_layout];
}
// Empty to use placeholder, the placeholder is not in the wrapper map.
if state.text.len() == 0 {
return display_text
.to_string()
.split("\n")
.map(|line| {
let shaped_line = window.text_system().shape_line(
line.to_string().into(),
font_size,
&runs,
None,
);
LineLayout::new()
.lines(smallvec::smallvec![shaped_line])
.with_whitespaces(whitespace_indicators.clone())
})
.collect();
}
let visible_text = display_text
.slice_lines(visible_range.start..visible_range.end)
.to_string();
let mut lines = vec![];
let mut offset = 0;
for (ix, line) in visible_text.split("\n").enumerate() {
let buffer_line = visible_range.start + ix;
let line_item = buffer_lines
.get(buffer_line)
.expect("line should exists in wrapper");
debug_assert_eq!(line_item.len(), line.len());
// Check if this buffer line is completely folded
let is_hidden = state.display_map.is_buffer_line_hidden(buffer_line);
if is_hidden {
// Create an empty LineLayout for folded lines
lines.push(LineLayout::new());
offset += line.len() + 1; // +1 for the `\n`
continue;
}
let mut wrapped_lines = SmallVec::with_capacity(1);
for range in &line_item.wrapped_lines {
let line_runs = runs_for_range(runs, offset, &range);
let line_runs = if bg_segments.is_empty() {
line_runs