1mod folding;
17mod heights;
18mod wrap;
19
20pub use folding::{FoldMarker, indent_fold_ranges};
21pub use heights::HeightMap;
22pub use wrap::{LineRows, wrap_line, wrap_slice};
23
24use std::ops::Range;
25
26use folding::{Fold, Hidden, shift_foldable, shift_lines};
27use rustaco_core::{Assoc, Rope, Selections, TextModel, char_to_position, line_end, line_len};
28use unicode_width::UnicodeWidthChar;
29
30#[derive(Clone, Copy, Debug, PartialEq)]
32pub struct Metrics {
33 pub char_width: f32,
35 pub line_height: f32,
36}
37
38#[derive(Clone, Copy, Debug, Default, PartialEq)]
39pub struct Rect {
40 pub x: f32,
41 pub y: f32,
42 pub width: f32,
43 pub height: f32,
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub struct StyleSpan {
49 pub start: usize,
50 pub end: usize,
51 pub style: u32,
52}
53
54pub trait Styler {
56 fn spans(&self, line: usize) -> Vec<StyleSpan>;
57}
58
59pub struct Plain;
61
62impl Styler for Plain {
63 fn spans(&self, _line: usize) -> Vec<StyleSpan> {
64 Vec::new()
65 }
66}
67
68#[derive(Clone, Debug, PartialEq)]
70pub struct TextRun {
71 pub x: f32,
72 pub text: String,
73 pub style: u32,
74}
75
76#[derive(Clone, Debug, PartialEq)]
78pub struct FrameLine {
79 pub line: usize,
80 pub row: usize,
82 pub y: f32,
83 pub height: f32,
84 pub runs: Vec<TextRun>,
85}
86
87#[derive(Clone, Debug, Default, PartialEq)]
90#[non_exhaustive]
91pub struct Frame {
92 pub gutter_width: f32,
93 pub lines: Vec<FrameLine>,
94 pub selections: Vec<Rect>,
95 pub carets: Vec<Rect>,
96 pub current_line: Option<Rect>,
98 pub fold_markers: Vec<FoldMarker>,
100 pub fold_ellipses: Vec<Rect>,
102 pub minimap: Option<MinimapFrame>,
104 pub sticky: Vec<FrameLine>,
107 pub zones: Vec<(u32, Rect)>,
109}
110
111#[derive(Clone, Copy, Debug, PartialEq)]
115struct Zone {
116 id: u32,
117 anchor: Option<usize>,
118 line: Option<usize>,
120 height: f32,
121}
122
123#[derive(Clone, Debug, Default, PartialEq)]
126pub struct MinimapFrame {
127 pub x: f32,
129 pub width: f32,
130 pub row_height: f32,
132 pub blocks: Vec<MinimapBlock>,
133 pub slider: Rect,
134}
135
136#[derive(Clone, Copy, Debug, PartialEq)]
138pub struct MinimapBlock {
139 pub x: f32,
140 pub y: f32,
141 pub width: f32,
142 pub style: u32,
143}
144
145const MINIMAP_ROW: f32 = 2.0;
147const MINIMAP_CELL: f32 = 1.0;
148
149type OverviewCache = ((u64, u64, u32), Vec<(f32, f32, u32)>);
152
153pub const INLAY_STYLE: u32 = u32::MAX - 1;
155
156const FOLD_MARKER_CELLS: f32 = 2.0;
158
159const SCROLLBAR_WIDTH: f32 = 14.0;
161
162const MIN_WRAP_CELLS: usize = 10;
164
165#[derive(Clone, Debug)]
166pub struct View {
167 pub metrics: Metrics,
168 pub width: f32,
169 pub height: f32,
170 scroll_top: f64,
171 scroll_left: f32,
172 widest_cells: usize,
174 tab_size: usize,
176 wrap: bool,
178 minimap_width: f32,
180 sticky_max: usize,
182 zones: Vec<Zone>,
183 inlays: Vec<(usize, String)>,
185 top_padding: f64,
187 geometry: u64,
189 overview_cache: std::cell::RefCell<Option<OverviewCache>>,
191 heights: HeightMap,
192 synced: Option<Synced>,
194 folds: Vec<Fold>,
195 hidden: Hidden,
196 foldable: Vec<(usize, usize)>,
198}
199
200#[derive(Clone, Copy, Debug, PartialEq)]
201struct Synced {
202 version: u64,
203 line_height: f32,
204 wrap_cells: Option<usize>,
205 tab_size: usize,
206}
207
208impl View {
209 pub fn new(metrics: Metrics, width: f32, height: f32) -> Self {
210 Self {
211 metrics,
212 width,
213 height,
214 scroll_top: 0.0,
215 scroll_left: 0.0,
216 widest_cells: 0,
217 tab_size: 4,
218 wrap: false,
219 minimap_width: 0.0,
220 sticky_max: 0,
221 zones: Vec::new(),
222 inlays: Vec::new(),
223 top_padding: 0.0,
224 geometry: 0,
225 overview_cache: std::cell::RefCell::new(None),
226 heights: HeightMap::new(1, metrics.line_height),
227 synced: None,
228 folds: Vec::new(),
229 hidden: Hidden::default(),
230 foldable: Vec::new(),
231 }
232 }
233
234 pub fn scroll_top(&self) -> f64 {
235 self.scroll_top
236 }
237
238 pub fn scroll_left(&self) -> f32 {
239 self.scroll_left
240 }
241
242 pub fn resize(&mut self, width: f32, height: f32) {
243 self.width = width;
244 self.height = height;
245 }
246
247 pub fn set_wrap(&mut self, wrap: bool) {
249 self.wrap = wrap;
250 if wrap {
251 self.scroll_left = 0.0;
252 }
253 }
254
255 pub fn wraps(&self) -> bool {
256 self.wrap
257 }
258
259 pub fn set_minimap(&mut self, width: f32) {
262 self.minimap_width = width.max(0.0);
263 }
264
265 pub fn minimap_width(&self) -> f32 {
266 self.minimap_width
267 }
268
269 pub fn set_sticky_scroll(&mut self, max: usize) {
272 self.sticky_max = max;
273 }
274
275 pub fn sticky_lines(&self, rope: &Rope) -> Vec<(usize, f32)> {
279 if self.sticky_max == 0 || self.foldable.is_empty() {
280 return Vec::new();
281 }
282 let lh = self.metrics.line_height;
283 let mut stack: Vec<(usize, usize)> = Vec::new();
284 loop {
285 let probe = self.line_at_y(rope, self.scroll_top + (stack.len() as f32 * lh) as f64);
287 let next = self
288 .foldable
289 .iter()
290 .take_while(|&&(h, _)| h < probe)
291 .filter(|&&(h, e)| e >= probe && !self.is_hidden(h) && stack.last().is_none_or(|&(sh, _)| h > sh))
292 .min_by_key(|&&(h, _)| h)
293 .copied();
294 match next {
295 Some(region) if stack.len() < self.sticky_max => stack.push(region),
296 _ => break,
297 }
298 }
299 let mut out = Vec::with_capacity(stack.len());
300 for (i, &(header, end)) in stack.iter().enumerate() {
301 let natural = i as f32 * lh;
302 let end_bottom = (self.line_top(end) - self.scroll_top) as f32 + self.line_height(end);
304 out.push((header, natural.min(end_bottom - lh)));
305 }
306 out
307 }
308
309 fn text_width(&self, rope: &Rope) -> f32 {
311 self.width - self.gutter_width(rope) - self.minimap_width
312 }
313
314 pub fn gutter_width(&self, rope: &Rope) -> f32 {
315 let digits = rope.len_lines().to_string().len().max(2);
316 (digits as f32 + 3.0 + FOLD_MARKER_CELLS) * self.metrics.char_width
317 }
318
319 fn wrap_cells(&self, rope: &Rope) -> Option<usize> {
321 self.wrap.then(|| {
322 let text = self.text_width(rope) - if self.minimap_width > 0.0 { 0.0 } else { SCROLLBAR_WIDTH };
323 ((text / self.metrics.char_width).floor().max(0.0) as usize).max(MIN_WRAP_CELLS)
324 })
325 }
326
327 pub fn line_rows(&self, rope: &Rope, line: usize) -> LineRows {
329 match self.synced.and_then(|s| s.wrap_cells) {
330 Some(w) => wrap_line(rope, line, self.tab_size, w),
331 None => LineRows::single(),
332 }
333 }
334
335 pub fn sync(&mut self, model: &TextModel) {
340 let rope = model.rope();
341 let target = Synced {
342 version: model.version(),
343 line_height: self.metrics.line_height,
344 wrap_cells: self.wrap_cells(rope),
345 tab_size: model.options.tab_size.max(1),
346 };
347 if self.synced == Some(target) && self.heights.len() == rope.len_lines() {
348 return;
349 }
350 self.tab_size = target.tab_size;
351 let lh = target.line_height;
352 let layout_same = self.synced.is_some_and(|s| Synced { version: target.version, ..s } == target);
353 let mut incremental = false;
354 if let Some(s) = self.synced.filter(|_| layout_same)
355 && let (Ok(events), Ok(changes)) = (model.events_since(s.version), model.changes_since(s.version))
356 {
357 self.remove_zone_heights();
358 let mut touched: Vec<Range<usize>> = Vec::new();
360 for e in events {
361 let a = e.start_point.row;
362 let old = e.old_end_point.row - a;
363 let new = e.new_end_point.row - a;
364 if old != 0 || new != 0 {
365 self.heights.splice(a + 1, old, std::iter::repeat_n(lh, new));
366 shift_foldable(&mut self.foldable, a, old, new);
367 for r in &mut touched {
368 shift_lines(r, a, old, new);
369 }
370 }
371 touched.push(a..a + new + 1);
372 }
373 for c in changes {
374 for f in &mut self.folds {
375 f.start = c.map(f.start, Assoc::After);
376 f.end = c.map(f.end, Assoc::After);
377 }
378 for z in &mut self.zones {
380 z.anchor = z.anchor.map(|a| c.map(a, Assoc::Before));
381 }
382 for (offset, _) in &mut self.inlays {
383 *offset = c.map(*offset, Assoc::Before);
384 }
385 }
386 incremental = self.heights.len() == rope.len_lines();
387 if incremental && target.wrap_cells.is_some() {
388 self.synced = Some(target);
389 for r in touched {
390 for line in r.start..r.end.min(rope.len_lines()) {
391 let rows = self.line_rows(rope, line).count();
392 self.heights.set(line, rows as f32 * lh);
393 }
394 }
395 }
396 }
397 if !incremental {
398 for z in &mut self.zones {
399 z.line = None;
400 }
401 let stale = self.synced.is_some() && layout_same;
402 self.synced = Some(target);
403 self.heights = match target.wrap_cells {
404 None => HeightMap::new(rope.len_lines(), lh),
405 Some(width) => {
406 let mut map = HeightMap::new(0, lh);
407 let tab = self.tab_size;
408 let rows = rope.lines().map(|line| wrap_slice(line, tab, width).count() as f32 * lh);
410 map.splice(0, 0, rows);
411 map
412 }
413 };
414 if stale {
415 self.folds.clear();
417 self.foldable.clear();
418 }
419 }
420 self.synced = Some(target);
421 self.add_zone_heights(rope);
422 self.apply_folds(rope);
423 }
424
425 fn remove_zone_heights(&mut self) {
427 for z in &mut self.zones {
428 if let Some(l) = z.line.take()
429 && l < self.heights.len()
430 {
431 let h = self.heights.height(l);
432 self.heights.set(l, (h - z.height).max(0.0));
433 }
434 }
435 self.top_padding = 0.0;
436 }
437
438 fn add_zone_heights(&mut self, rope: &Rope) {
440 let len = rope.len_chars();
441 self.top_padding = 0.0;
442 for z in &mut self.zones {
443 match z.anchor {
444 None => self.top_padding += z.height as f64,
445 Some(a) => {
446 let l = rope.char_to_line(a.min(len));
447 let h = self.heights.height(l);
448 self.heights.set(l, h + z.height);
449 z.line = Some(l);
450 }
451 }
452 }
453 }
454
455 pub fn add_zone(&mut self, model: &TextModel, id: u32, after: Option<usize>, height: f32) {
458 self.sync(model);
459 self.remove_zone_heights();
460 let rope = model.rope();
461 let anchor = after.map(|l| line_end(rope, l.min(rope.len_lines() - 1)));
462 self.zones.push(Zone { id, anchor, line: None, height: height.max(0.0) });
463 self.add_zone_heights(rope);
464 self.apply_folds(rope);
465 }
466
467 pub fn remove_zone(&mut self, model: &TextModel, id: u32) -> bool {
469 self.sync(model);
470 self.remove_zone_heights();
471 let before = self.zones.len();
472 self.zones.retain(|z| z.id != id);
473 let rope = model.rope();
474 self.add_zone_heights(rope);
475 self.apply_folds(rope);
476 self.zones.len() != before
477 }
478
479 pub fn set_zones(&mut self, model: &TextModel, zones: impl IntoIterator<Item = (u32, Option<usize>, f32)>) {
482 self.sync(model);
483 self.remove_zone_heights();
484 let rope = model.rope();
485 let last = rope.len_lines() - 1;
486 self.zones = zones
487 .into_iter()
488 .map(|(id, after, height)| Zone {
489 id,
490 anchor: after.map(|l| line_end(rope, l.min(last))),
491 line: None,
492 height: height.max(0.0),
493 })
494 .collect();
495 self.add_zone_heights(rope);
496 self.apply_folds(rope);
497 }
498 fn apply_folds(&mut self, rope: &Rope) {
499 let len = rope.len_chars();
500 let mut ranges: Vec<Range<usize>> = Vec::new();
501 self.folds.retain(|f| {
502 let (header, last) = (rope.char_to_line(f.start.min(len)), rope.char_to_line(f.end.min(len)));
503 if last <= header {
504 return false;
505 }
506 ranges.push(header + 1..last + 1);
507 true
508 });
509 self.folds.sort_by_key(|f| f.start);
510 self.folds.dedup_by_key(|f| rope.char_to_line(f.start.min(len)));
511 self.hidden = Hidden::new(ranges, &self.heights);
512 self.geometry += 1;
513 }
514
515 pub fn set_foldable(&mut self, mut ranges: Vec<(usize, usize)>) {
520 ranges.retain(|&(s, e)| e > s);
521 ranges.sort_unstable();
522 ranges.dedup();
523 self.foldable = ranges;
524 }
525
526 pub fn is_hidden(&self, line: usize) -> bool {
527 self.hidden.run_of(line).is_some()
528 }
529
530 fn next_shown(&self, line: usize) -> usize {
532 self.hidden.run_of(line).map_or(line, |i| self.hidden.ranges[i].end)
533 }
534
535 fn prev_shown(&self, line: usize) -> usize {
537 self.hidden.run_of(line).map_or(line, |i| self.hidden.ranges[i].start.saturating_sub(1))
538 }
539
540 fn shown(&self, lines: Range<usize>) -> Vec<usize> {
542 let mut out = Vec::new();
543 let mut line = self.next_shown(lines.start);
544 while line < lines.end {
545 out.push(line);
546 line = self.next_shown(line + 1);
547 }
548 out
549 }
550
551 pub fn shown_segments(&self, lines: Range<usize>) -> Vec<Range<usize>> {
553 let mut out: Vec<Range<usize>> = Vec::new();
554 for l in self.shown(lines) {
555 match out.last_mut() {
556 Some(r) if r.end == l => r.end += 1,
557 _ => out.push(l..l + 1),
558 }
559 }
560 out
561 }
562
563 pub fn is_folded(&self, rope: &Rope, line: usize) -> bool {
565 let len = rope.len_chars();
566 self.folds.iter().any(|f| rope.char_to_line(f.start.min(len)) == line)
567 }
568
569 pub fn fold(&mut self, model: &TextModel, line: usize) -> bool {
571 self.sync(model);
572 let rope = model.rope();
573 let candidate = self
574 .foldable
575 .iter()
576 .filter(|&&(s, e)| s <= line && line <= e && !self.is_folded(rope, s))
577 .min_by_key(|&&(s, e)| e - s)
578 .copied();
579 let Some((s, e)) = candidate else { return false };
580 self.folds.push(Fold { start: line_end(rope, s), end: line_end(rope, e) });
581 self.apply_folds(rope);
582 true
583 }
584
585 pub fn unfold(&mut self, model: &TextModel, line: usize) -> bool {
587 self.sync(model);
588 let rope = model.rope();
589 let len = rope.len_chars();
590 let before = self.folds.len();
591 self.folds.retain(|f| {
592 let (h, l) = (rope.char_to_line(f.start.min(len)), rope.char_to_line(f.end.min(len)));
593 !(h <= line && line <= l)
594 });
595 let changed = self.folds.len() != before;
596 if changed {
597 self.apply_folds(rope);
598 }
599 changed
600 }
601
602 pub fn toggle_fold(&mut self, model: &TextModel, line: usize) -> bool {
604 self.sync(model);
605 if self.is_folded(model.rope(), line) { self.unfold(model, line) } else { self.fold(model, line) }
606 }
607
608 pub fn fold_all(&mut self, model: &TextModel) {
610 self.sync(model);
611 let rope = model.rope();
612 self.folds =
613 self.foldable.iter().map(|&(s, e)| Fold { start: line_end(rope, s), end: line_end(rope, e) }).collect();
614 self.apply_folds(rope);
615 }
616
617 pub fn unfold_all(&mut self, model: &TextModel) {
618 self.sync(model);
619 self.folds.clear();
620 self.apply_folds(model.rope());
621 }
622
623 pub fn reveal_positions(&mut self, model: &TextModel, positions: impl IntoIterator<Item = usize>) -> bool {
626 self.sync(model);
627 let rope = model.rope();
628 let lines: Vec<usize> = positions
629 .into_iter()
630 .map(|p| rope.char_to_line(p.min(rope.len_chars())))
631 .filter(|&l| self.is_hidden(l))
632 .collect();
633 if lines.is_empty() {
634 return false;
635 }
636 let len = rope.len_chars();
637 self.folds.retain(|f| {
638 let (h, l) = (rope.char_to_line(f.start.min(len)), rope.char_to_line(f.end.min(len)));
639 !lines.iter().any(|&x| h < x && x <= l)
640 });
641 self.apply_folds(rope);
642 true
643 }
644
645 pub fn shown_line_for(&self, line: usize) -> usize {
647 self.prev_shown(line)
648 }
649
650 pub fn line_top(&self, line: usize) -> f64 {
654 if line < self.heights.len() {
655 self.top_padding + self.hidden.top(&self.heights, line)
656 } else {
657 self.hidden.total(&self.heights) + (line - self.heights.len()) as f64 * self.metrics.line_height as f64
659 }
660 }
661
662 pub fn line_height(&self, line: usize) -> f32 {
664 if line >= self.heights.len() {
665 self.metrics.line_height
666 } else if self.is_hidden(line) {
667 0.0
668 } else {
669 self.heights.height(line)
670 }
671 }
672
673 pub fn line_at_y(&self, rope: &Rope, y: f64) -> usize {
675 let total = self.hidden.total(&self.heights);
676 let line = if y >= total && self.heights.len() < rope.len_lines() {
677 self.heights.len() + ((y - total) / self.metrics.line_height as f64) as usize
679 } else {
680 self.hidden.line_at(&self.heights, y - self.top_padding)
681 };
682 line.min(rope.len_lines() - 1)
683 }
684
685 fn row_at_y(&self, rope: &Rope, y: f64) -> (usize, usize) {
687 let line = self.line_at_y(rope, y);
688 let row = ((y - self.line_top(line)) / self.metrics.line_height as f64).max(0.0) as usize;
689 let rows = self.line_rows(rope, line).count();
690 (line, row.min(rows - 1))
691 }
692
693 pub fn content_height(&self, rope: &Rope) -> f64 {
695 let last = self.prev_shown(rope.len_lines() - 1);
696 self.line_top(last) + self.height as f64
697 }
698
699 pub fn content_width(&self, rope: &Rope) -> f32 {
700 if self.wrap {
701 return self.width;
702 }
703 self.gutter_width(rope) + (self.widest_cells + 2) as f32 * self.metrics.char_width
704 }
705
706 pub fn visible_lines(&self, rope: &Rope) -> Range<usize> {
709 let first = self.line_at_y(rope, self.scroll_top);
710 let last = self.line_at_y(rope, self.scroll_top + self.height as f64);
711 first..last + 1
712 }
713
714 fn y_of(&self, line: usize) -> f32 {
716 (self.line_top(line) - self.scroll_top) as f32
717 }
718
719 pub fn set_inlays(&mut self, model: &TextModel, mut hints: Vec<(usize, String)>) {
722 self.sync(model);
723 hints.retain(|(_, label)| !label.is_empty());
724 hints.sort_by_key(|h| h.0);
725 self.inlays = hints;
726 }
727
728 fn inlays_on(&self, rope: &Rope, line: usize) -> Vec<(usize, usize, &str)> {
730 if self.inlays.is_empty() {
731 return Vec::new();
732 }
733 let start = rope.line_to_char(line);
734 let end = start + line_len(rope, line);
735 let from = self.inlays.partition_point(|h| h.0 < start);
736 self.inlays[from..]
737 .iter()
738 .take_while(|h| h.0 <= end)
739 .map(|(o, label)| (o - start, label.chars().map(|c| c.width().unwrap_or(1)).sum(), label.as_str()))
740 .collect()
741 }
742
743 fn locate(&self, rope: &Rope, rows: &LineRows, line: usize, column: usize) -> (usize, usize) {
746 let row = rows.row_of(column);
747 let tab = self.tab_size;
748 let start_cells = if row == 0 { 0 } else { visual_column(rope, line, rows.starts[row], tab) };
749 let hints: usize =
750 self.inlays_on(rope, line).iter().filter(|h| h.0 >= rows.starts[row] && h.0 < column).map(|h| h.1).sum();
751 (row, rows.indent_of(row) + visual_column(rope, line, column, tab) - start_cells + hints)
752 }
753
754 fn column_in_row(&self, rope: &Rope, rows: &LineRows, line: usize, row: usize, cells: f32) -> usize {
757 if !self.inlays_on(rope, line).is_empty() {
758 let start = rows.starts[row];
760 let end = rows.starts.get(row + 1).map_or(line_len(rope, line), |&n| n - 1);
761 let mut best = (start, f32::MAX);
762 for col in start..=end {
763 let d = (self.locate(rope, rows, line, col).1 as f32 - cells).abs();
764 if d < best.1 {
765 best = (col, d);
766 }
767 }
768 return best.0;
769 }
770 let tab = self.tab_size;
771 let start = rows.starts[row];
772 let start_cells = if row == 0 { 0 } else { visual_column(rope, line, start, tab) };
773 let target = (cells - rows.indent_of(row) as f32).max(0.0) + start_cells as f32;
774 let column = column_at_cells(rope, line, target, tab).max(start);
775 match rows.starts.get(row + 1) {
776 Some(&next) => column.min(next - 1),
777 None => column,
778 }
779 }
780
781 pub fn vertical_target(
784 &self,
785 rope: &Rope,
786 head: usize,
787 goal: Option<usize>,
788 lines: isize,
789 ) -> (usize, Option<usize>) {
790 let p = char_to_position(rope, head);
791 let mut line = self.prev_shown(p.line);
792 let mut rows = self.line_rows(rope, line);
793 let (mut row, x) = self.locate(rope, &rows, line, p.column.min(line_len(rope, line)));
794 let goal = goal.unwrap_or(x);
795 for _ in 0..lines.unsigned_abs() {
796 if lines < 0 {
797 if row > 0 {
798 row -= 1;
799 continue;
800 }
801 if line == 0 {
802 return (0, None);
803 }
804 line = self.prev_shown(line - 1);
805 rows = self.line_rows(rope, line);
806 row = rows.count() - 1;
807 } else {
808 if row + 1 < rows.count() {
809 row += 1;
810 continue;
811 }
812 let next = self.next_shown(line + 1);
813 if next >= rope.len_lines() {
814 return (rope.len_chars(), None);
815 }
816 line = next;
817 rows = self.line_rows(rope, line);
818 row = 0;
819 }
820 }
821 let column = self.column_in_row(rope, &rows, line, row, goal as f32);
822 (rope.line_to_char(line) + column, Some(goal))
823 }
824
825 pub fn page_rows(&self) -> usize {
827 ((self.height / self.metrics.line_height) as usize).saturating_sub(1).max(1)
828 }
829
830 pub fn scroll_to(&mut self, rope: &Rope, top: f64, left: f32) {
833 let max_top = (self.content_height(rope) - self.height as f64).max(0.0);
834 let max_left = (self.content_width(rope) - self.width + self.minimap_width).max(0.0);
835 self.scroll_top = top.clamp(0.0, max_top);
836 self.scroll_left = if self.wrap { 0.0 } else { left.clamp(0.0, max_left) };
837 }
838
839 pub fn scroll_by(&mut self, rope: &Rope, dx: f32, dy: f64) {
840 self.scroll_to(rope, self.scroll_top + dy, self.scroll_left + dx);
841 }
842
843 pub fn reveal(&mut self, rope: &Rope, pos: usize) {
845 let p = char_to_position(rope, pos);
846 let line = self.prev_shown(p.line);
847 let rows = self.line_rows(rope, line);
848 let (row, x_cells) = if line == p.line { self.locate(rope, &rows, line, p.column) } else { (0, 0) };
849 let lh = self.metrics.line_height as f64;
850 let top = self.line_top(line) + row as f64 * lh;
851 let bottom = top + lh;
852 let mut scroll_top = self.scroll_top;
853 if top < scroll_top {
854 scroll_top = top;
855 } else if bottom > scroll_top + self.height as f64 {
856 scroll_top = bottom - self.height as f64;
857 }
858
859 let cw = self.metrics.char_width;
860 self.widest_cells = self.widest_cells.max(x_cells + 1);
861 let text_width = self.text_width(rope);
862 let margin = 4.0 * cw;
863 let x = x_cells as f32 * cw;
864 let mut scroll_left = self.scroll_left;
865 if x - margin < scroll_left {
866 scroll_left = (x - margin).max(0.0);
867 } else if x + margin > scroll_left + text_width {
868 scroll_left = x + margin - text_width;
869 }
870 self.scroll_to(rope, scroll_top, scroll_left);
871 }
872
873 pub fn hit_test(&self, rope: &Rope, x: f32, y: f32) -> usize {
877 let (line, row) = self.row_at_y(rope, y as f64 + self.scroll_top);
878 let rows = self.line_rows(rope, line);
879 let cells = ((x - self.gutter_width(rope) + self.scroll_left) / self.metrics.char_width).max(0.0);
880 rope.line_to_char(line) + self.column_in_row(rope, &rows, line, row.min(rows.count() - 1), cells)
881 }
882
883 pub fn line_and_cells_at(&self, rope: &Rope, x: f32, y: f32) -> (usize, f32) {
887 let (line, row) = self.row_at_y(rope, y as f64 + self.scroll_top);
888 let cells = ((x - self.gutter_width(rope) + self.scroll_left) / self.metrics.char_width).max(0.0);
889 if row == 0 {
890 return (line, cells);
891 }
892 let rows = self.line_rows(rope, line);
893 let row = row.min(rows.count() - 1);
894 let start_cells = visual_column(rope, line, rows.starts[row], self.tab_size) as f32;
895 (line, (cells - rows.indent_of(row) as f32).max(0.0) + start_cells)
896 }
897
898 pub fn in_fold_gutter(&self, rope: &Rope, x: f32) -> bool {
900 let g = self.gutter_width(rope);
901 x >= g - (FOLD_MARKER_CELLS + 0.5) * self.metrics.char_width && x < g - 0.5 * self.metrics.char_width
902 }
903
904 pub fn offset_at_cells(&self, rope: &Rope, line: usize, cells: f32) -> usize {
906 rope.line_to_char(line) + column_at_cells(rope, line, cells, self.tab_size)
907 }
908
909 pub fn layout(&mut self, model: &TextModel, selections: &Selections, styler: &dyn Styler) -> Frame {
912 self.sync(model);
913 let tab = self.tab_size;
914 let rope = model.rope();
915 let Metrics { char_width: cw, line_height: lh } = self.metrics;
916 let gutter = self.gutter_width(rope);
917 let visible = self.visible_lines(rope);
918 let first_cell = (self.scroll_left / cw).floor() as usize;
919 let last_cell = ((self.scroll_left + self.width - gutter) / cw).ceil() as usize + 1;
920
921 let mut frame = Frame { gutter_width: gutter, ..Frame::default() };
922 let mut widest = self.widest_cells;
923 let len = rope.len_chars();
924 let folded_headers: Vec<usize> = self.folds.iter().map(|f| rope.char_to_line(f.start.min(len))).collect();
925 let mut foldable_at = self.foldable.partition_point(|&(s, _)| s < visible.start);
926 let (top, bottom) = (-lh, self.height + lh);
927
928 for line in self.shown(visible.clone()) {
929 let spans = styler.spans(line);
930 let inlays = self.inlays_on(rope, line);
931 let rows = self.line_rows(rope, line);
932 let y = self.y_of(line);
933 let line_len = line_len(rope, line);
934 for row in 0..rows.count() {
935 let row_y = y + row as f32 * lh;
936 if row_y < top || row_y > bottom {
937 continue;
938 }
939 let cols = rows.starts[row]..rows.starts.get(row + 1).copied().unwrap_or(line_len);
940 let start_cells = if row == 0 { 0 } else { visual_column(rope, line, cols.start, tab) };
941 let shift = rows.indent_of(row) as f32 - start_cells as f32;
942 let x_of = |cells: usize| gutter + (cells as f32 + shift) * cw - self.scroll_left;
943 let window = first_cell + start_cells..last_cell + start_cells;
944 let (runs, cells) = layout_line(rope, line, cols, &spans, window, tab, &x_of, &inlays);
945 widest = widest.max(cells);
946 frame.lines.push(FrameLine { line, row, y: row_y, height: lh, runs });
947 }
948 while foldable_at < self.foldable.len() && self.foldable[foldable_at].0 < line {
949 foldable_at += 1;
950 }
951 let folded = folded_headers.contains(&line);
952 if folded || self.foldable.get(foldable_at).is_some_and(|&(s, _)| s == line) {
953 frame.fold_markers.push(FoldMarker { line, y, height: lh, folded });
954 }
955 if folded {
956 let (row, x) = self.locate(rope, &rows, line, line_len);
957 let end = gutter + x as f32 * cw - self.scroll_left;
958 frame.fold_ellipses.push(Rect { x: end + cw, y: y + row as f32 * lh, width: 3.0 * cw, height: lh });
959 }
960 }
961
962 let primary = selections.primary();
963 let primary_line = rope.char_to_line(primary.head);
964 if visible.contains(&primary_line) && primary.is_empty() && !self.is_hidden(primary_line) {
965 frame.current_line = Some(Rect {
966 x: 0.0,
967 y: self.y_of(primary_line),
968 width: self.width,
969 height: self.line_height(primary_line),
970 });
971 }
972
973 for sel in selections.iter() {
974 if let Some(r) = self.caret_rect(rope, sel.head, gutter) {
975 frame.carets.push(r);
976 }
977 if sel.is_empty() {
978 continue;
979 }
980 frame.selections.extend(self.range_rects(rope, sel.start()..sel.end(), gutter));
981 }
982 self.widest_cells = widest;
983 frame.minimap = self.minimap(rope, styler);
984 frame.zones = self.zone_rects(rope, visible.clone());
985 for (line, y) in self.sticky_lines(rope) {
986 let spans = styler.spans(line);
987 let x_of = |cells: usize| gutter + cells as f32 * cw - self.scroll_left;
988 let len = line_len(rope, line);
989 let (runs, _) = layout_line(rope, line, 0..len, &spans, first_cell..last_cell, tab, &x_of, &[]);
990 frame.sticky.push(FrameLine { line, row: 0, y, height: lh, runs });
991 }
992 frame
993 }
994
995 fn zone_rects(&self, rope: &Rope, visible: Range<usize>) -> Vec<(u32, Rect)> {
997 let gutter = self.gutter_width(rope);
998 let width = self.width - gutter - self.minimap_width;
999 let lh = self.metrics.line_height;
1000 let mut below: Vec<(usize, f32)> = Vec::new(); let mut top = -(self.scroll_top as f32);
1002 let mut out = Vec::new();
1003 for z in &self.zones {
1004 match z.line {
1005 None if z.anchor.is_none() => {
1006 out.push((z.id, Rect { x: gutter, y: top, width, height: z.height }));
1007 top += z.height;
1008 }
1009 Some(l) if visible.contains(&l) && !self.is_hidden(l) => {
1010 let placed = match below.iter_mut().find(|(line, _)| *line == l) {
1011 Some((_, h)) => {
1012 let at = *h;
1013 *h += z.height;
1014 at
1015 }
1016 None => {
1017 below.push((l, z.height));
1018 0.0
1019 }
1020 };
1021 let rows = self.line_rows(rope, l).count() as f32;
1022 let y = self.y_of(l) + rows * lh + placed;
1023 out.push((z.id, Rect { x: gutter, y, width, height: z.height }));
1024 }
1025 _ => {}
1026 }
1027 }
1028 out.sort_by(|a, b| a.1.y.total_cmp(&b.1.y));
1029 out
1030 }
1031
1032 fn minimap_geometry(&self, rope: &Rope) -> (f64, f64, f64) {
1035 let lh = self.metrics.line_height as f64;
1036 let scale = MINIMAP_ROW as f64 / lh;
1037 let max_scroll = (self.content_height(rope) - self.height as f64).max(0.0);
1038 let document = max_scroll + self.height as f64;
1040 let fits = self.height as f64 / scale;
1041 let offset =
1043 if document <= fits || max_scroll == 0.0 { 0.0 } else { self.scroll_top / max_scroll * (document - fits) };
1044 (document, scale, offset)
1045 }
1046
1047 pub fn minimap_lines(&self, rope: &Rope) -> Range<usize> {
1049 if self.minimap_width <= 0.0 {
1050 return 0..0;
1051 }
1052 let (_, scale, offset) = self.minimap_geometry(rope);
1053 let first = self.line_at_y(rope, offset);
1054 let last = self.line_at_y(rope, offset + self.height as f64 / scale);
1055 first..last + 1
1056 }
1057
1058 fn minimap(&self, rope: &Rope, styler: &dyn Styler) -> Option<MinimapFrame> {
1059 if self.minimap_width <= 0.0 {
1060 return None;
1061 }
1062 let (_, scale, offset) = self.minimap_geometry(rope);
1063 let x0 = self.width - self.minimap_width;
1064 let max_cells = (self.minimap_width / MINIMAP_CELL) as usize;
1065 let lh = self.metrics.line_height as f64;
1066 let tab = self.tab_size;
1067 let mut blocks = Vec::new();
1068 for line in self.shown(self.minimap_lines(rope)) {
1069 let spans = styler.spans(line);
1070 let rows = self.line_rows(rope, line);
1071 let top = self.line_top(line);
1072 let mut row = 0;
1073 let mut cells = 0usize; let mut row_shift = 0isize; let mut span_idx = 0;
1076 let mut run: Option<MinimapBlock> = None;
1077 let y_of_row = |row: usize| ((top + row as f64 * lh - offset) * scale) as f32;
1078 for (col, c) in rope.line(line).chars().take(line_len(rope, line)).enumerate() {
1079 if rows.starts.get(row + 1) == Some(&col) {
1080 blocks.extend(run.take());
1081 row += 1;
1082 row_shift = rows.indent as isize - cells as isize;
1083 }
1084 let w = cell_width(c, cells, tab);
1085 let x = (cells as isize + row_shift) as usize;
1086 cells += w;
1087 if x >= max_cells {
1088 continue;
1089 }
1090 if c.is_whitespace() {
1091 blocks.extend(run.take());
1092 continue;
1093 }
1094 while span_idx < spans.len() && spans[span_idx].end <= col {
1095 span_idx += 1;
1096 }
1097 let style = spans.get(span_idx).filter(|s| s.start <= col).map_or(0, |s| s.style);
1098 match &mut run {
1099 Some(r) if r.style == style => r.width += w as f32 * MINIMAP_CELL,
1100 _ => {
1101 blocks.extend(run.take());
1102 run = Some(MinimapBlock {
1103 x: x0 + x as f32 * MINIMAP_CELL,
1104 y: y_of_row(row),
1105 width: w as f32 * MINIMAP_CELL,
1106 style,
1107 });
1108 }
1109 }
1110 }
1111 blocks.extend(run);
1112 }
1113 let slider = self.minimap_slider(rope);
1114 Some(MinimapFrame { x: x0, width: self.minimap_width, row_height: MINIMAP_ROW, blocks, slider })
1115 }
1116
1117 pub fn minimap_slider(&self, rope: &Rope) -> Rect {
1119 let (document, scale, offset) = self.minimap_geometry(rope);
1120 Rect {
1121 x: self.width - self.minimap_width,
1122 y: ((self.scroll_top - offset) * scale) as f32,
1123 width: self.minimap_width,
1124 height: (self.height as f64 * scale).min(document * scale) as f32,
1125 }
1126 }
1127
1128 pub fn in_minimap(&self, x: f32) -> bool {
1130 self.minimap_width > 0.0 && x >= self.width - self.minimap_width
1131 }
1132
1133 pub fn minimap_scroll_target(&self, rope: &Rope, y: f32) -> f64 {
1136 let (_, scale, offset) = self.minimap_geometry(rope);
1137 offset + y as f64 / scale - self.height as f64 / 2.0
1138 }
1139
1140 pub fn minimap_drag_factor(&self, rope: &Rope) -> f64 {
1142 let (document, scale, _) = self.minimap_geometry(rope);
1143 let fits = self.height as f64 / scale;
1144 let max_scroll = (self.content_height(rope) - self.height as f64).max(0.0);
1145 if document > fits {
1146 let slider = self.height as f64 * scale;
1147 max_scroll / (self.height as f64 - slider).max(1.0)
1148 } else {
1149 1.0 / scale
1150 }
1151 }
1152
1153 pub fn position_rect(&self, rope: &Rope, pos: usize) -> Option<Rect> {
1156 self.caret_rect(rope, pos.min(rope.len_chars()), self.gutter_width(rope))
1157 }
1158
1159 fn caret_rect(&self, rope: &Rope, pos: usize, gutter: f32) -> Option<Rect> {
1161 let p = char_to_position(rope, pos);
1162 if !self.visible_lines(rope).contains(&p.line) || self.is_hidden(p.line) {
1163 return None;
1164 }
1165 let rows = self.line_rows(rope, p.line);
1166 let (row, x) = self.locate(rope, &rows, p.line, p.column);
1167 let lh = self.metrics.line_height;
1168 Some(Rect {
1169 x: gutter + x as f32 * self.metrics.char_width - self.scroll_left,
1170 y: self.y_of(p.line) + row as f32 * lh,
1171 width: 2.0,
1172 height: lh,
1173 })
1174 }
1175
1176 fn range_rects(&self, rope: &Rope, range: std::ops::Range<usize>, gutter: f32) -> Vec<Rect> {
1179 self.range_rects_in(rope, range, gutter, &self.visible_lines(rope))
1180 }
1181
1182 fn range_rects_in(
1184 &self,
1185 rope: &Rope,
1186 range: std::ops::Range<usize>,
1187 gutter: f32,
1188 visible: &Range<usize>,
1189 ) -> Vec<Rect> {
1190 let cw = self.metrics.char_width;
1191 let lh = self.metrics.line_height;
1192 let x_at = |cells: usize| gutter + cells as f32 * cw - self.scroll_left;
1193 let (start, end) = (char_to_position(rope, range.start), char_to_position(rope, range.end));
1194 let mut out = Vec::new();
1195 let lines = start.line.max(visible.start)..(end.line + 1).min(visible.end);
1196 for line in self.shown(lines) {
1197 let from = if line == start.line { start.column } else { 0 };
1198 let (to, newline) = if line == end.line { (end.column, false) } else { (line_len(rope, line), true) };
1199 let rows = self.line_rows(rope, line);
1200 let y = self.y_of(line);
1201 let (first_row, x_from) = self.locate(rope, &rows, line, from);
1202 let (last_row, x_to) = self.locate(rope, &rows, line, to);
1203 for row in first_row..=last_row {
1204 let x0 = if row == first_row { x_from } else { rows.indent_of(row) };
1205 let (x1, extra) = if row == last_row {
1206 (x_to, if newline { cw * 0.5 } else { 0.0 })
1207 } else {
1208 let (_, end_cells) = self.locate_row_end(rope, &rows, line, row);
1210 (end_cells, 0.0)
1211 };
1212 let (x0, x1) = (x_at(x0), x_at(x1) + extra);
1213 out.push(Rect { x: x0, y: y + row as f32 * lh, width: x1 - x0, height: lh });
1214 }
1215 }
1216 out
1217 }
1218
1219 fn locate_row_end(&self, rope: &Rope, rows: &LineRows, line: usize, row: usize) -> (usize, usize) {
1221 let tab = self.tab_size;
1222 let start_cells = if row == 0 { 0 } else { visual_column(rope, line, rows.starts[row], tab) };
1223 let end_cells = visual_column(rope, line, rows.starts[row + 1], tab);
1224 let hints: usize = self
1225 .inlays_on(rope, line)
1226 .iter()
1227 .filter(|h| h.0 >= rows.starts[row] && h.0 < rows.starts[row + 1])
1228 .map(|h| h.1)
1229 .sum();
1230 (row, rows.indent_of(row) + end_cells - start_cells + hints)
1231 }
1232
1233 pub fn decoration_rects(&self, model: &TextModel) -> Vec<(Rect, u32)> {
1236 let rope = model.rope();
1237 let visible = self.visible_lines(rope);
1238 let range = rope.line_to_char(visible.start)..rope.line_to_char(visible.end.min(rope.len_lines()));
1239 let gutter = self.gutter_width(rope);
1240 model
1241 .decorations
1242 .in_range(range)
1243 .into_iter()
1244 .flat_map(|d| {
1245 self.range_rects_in(rope, d.range.clone(), gutter, &visible).into_iter().map(move |r| (r, d.kind))
1246 })
1247 .collect()
1248 }
1249
1250 pub fn line_bands(&self, model: &TextModel, whole_line: impl Fn(u32) -> bool) -> Vec<(Rect, u32)> {
1253 let gutter = self.gutter_width(model.rope());
1254 self.decorated_lines(model, whole_line)
1255 .into_iter()
1256 .map(|(line, kind)| {
1257 let r =
1258 Rect { x: gutter, y: self.y_of(line), width: self.width - gutter, height: self.line_height(line) };
1259 (r, kind)
1260 })
1261 .collect()
1262 }
1263
1264 pub fn gutter_marks(&self, model: &TextModel, accept: impl Fn(u32) -> bool) -> Vec<(f32, f32, u32)> {
1267 self.decorated_lines(model, accept)
1268 .into_iter()
1269 .map(|(line, kind)| (self.y_of(line), self.line_height(line), kind))
1270 .collect()
1271 }
1272
1273 fn decorated_lines(&self, model: &TextModel, accept: impl Fn(u32) -> bool) -> Vec<(usize, u32)> {
1275 let rope = model.rope();
1276 let visible = self.visible_lines(rope);
1277 let range = rope.line_to_char(visible.start)..rope.line_to_char(visible.end.min(rope.len_lines()));
1278 let mut out = Vec::new();
1279 for d in model.decorations.in_range(range).into_iter().filter(|d| accept(d.kind)) {
1280 let first = rope.char_to_line(d.range.start).max(visible.start);
1281 let end_pos = if d.range.end > d.range.start { d.range.end - 1 } else { d.range.end };
1283 let last = rope.char_to_line(end_pos.min(rope.len_chars())).min(visible.end - 1);
1284 for line in self.shown(first..last + 1) {
1285 out.push((line, d.kind));
1286 }
1287 }
1288 out.sort_unstable();
1289 out.dedup();
1290 out
1291 }
1292
1293 pub fn overview_marks(&self, model: &TextModel, track: f32, accept: impl Fn(u32) -> bool) -> Vec<(f32, f32, u32)> {
1299 let key = (model.decorations.generation(), self.geometry, track.to_bits());
1300 if let Some((k, marks)) = self.overview_cache.borrow().as_ref()
1301 && *k == key
1302 {
1303 return marks.clone();
1304 }
1305 let marks = self.compute_overview_marks(model, track, accept);
1306 *self.overview_cache.borrow_mut() = Some((key, marks.clone()));
1307 marks
1308 }
1309
1310 fn compute_overview_marks(
1311 &self,
1312 model: &TextModel,
1313 track: f32,
1314 accept: impl Fn(u32) -> bool,
1315 ) -> Vec<(f32, f32, u32)> {
1316 let rope = model.rope();
1317 let total = (self.content_height(rope) - self.height as f64 + self.metrics.line_height as f64).max(1.0);
1318 let scale = track as f64 / total;
1319 let len = rope.len_chars();
1320 let mut out: Vec<(f32, f32, u32)> = model
1321 .decorations
1322 .iter()
1323 .filter(|d| accept(d.kind))
1324 .map(|d| {
1325 let a = self.prev_shown(rope.char_to_line(d.range.start.min(len)));
1326 let b = self.prev_shown(rope.char_to_line(d.range.end.min(len)));
1327 let top = self.line_top(a) * scale;
1328 let bottom = (self.line_top(b) + self.line_height(b) as f64) * scale;
1329 (top as f32, ((bottom - top) as f32).max(2.0), d.kind)
1330 })
1331 .collect();
1332 out.sort_by(|x, y| x.2.cmp(&y.2).then(x.0.total_cmp(&y.0)));
1333 let mut merged: Vec<(f32, f32, u32)> = Vec::with_capacity(out.len().min(4096));
1335 for m in out {
1336 match merged.last_mut() {
1337 Some(last) if last.2 == m.2 && m.0 <= last.0 + last.1 + 0.5 => {
1338 last.1 = last.1.max(m.0 + m.1 - last.0);
1339 }
1340 _ => merged.push(m),
1341 }
1342 }
1343 merged
1344 }
1345
1346 pub fn indent_guides(&self, model: &TextModel, cursor_line: usize) -> Vec<Guide> {
1352 let rope = model.rope();
1353 let tab = self.tab_size.max(1);
1354 let visible = self.visible_lines(rope);
1355 let total = rope.len_lines();
1356 let lines = self.shown(visible.start..visible.end.min(total));
1357 let raw: Vec<Option<usize>> = lines.iter().map(|&l| indent_level(rope, l, tab)).collect();
1360 let first = lines.first().copied().unwrap_or(0);
1361 let last = lines.last().copied().unwrap_or(0);
1362 let above =
1363 (first.saturating_sub(GUIDE_REACH)..first).rev().find_map(|l| indent_level(rope, l, tab)).unwrap_or(0);
1364 let below = (last + 1..(last + GUIDE_REACH).min(total)).find_map(|l| indent_level(rope, l, tab)).unwrap_or(0);
1365 let mut levels = vec![0; raw.len()];
1366 let mut prev = above;
1367 for (i, r) in raw.iter().enumerate() {
1368 if let Some(l) = r {
1369 prev = *l;
1370 }
1371 levels[i] = prev;
1372 }
1373 let mut next = below;
1374 for (i, r) in raw.iter().enumerate().rev() {
1375 match r {
1376 Some(l) => next = *l,
1377 None => levels[i] = levels[i].min(next),
1378 }
1379 }
1380 let active_level = guide_level(rope, cursor_line, tab).max(1);
1381
1382 let cw = self.metrics.char_width;
1383 let gutter = self.gutter_width(rope);
1384 let mut guides = Vec::new();
1385 let max_level = levels.iter().copied().max().unwrap_or(0);
1386 for level in 1..=max_level {
1387 let x = gutter + ((level - 1) * tab) as f32 * cw - self.scroll_left;
1388 let mut start: Option<usize> = None;
1389 for i in 0..=lines.len() {
1390 let inside = i < lines.len() && levels[i] >= level;
1391 match (inside, start) {
1392 (true, None) => start = Some(i),
1393 (false, Some(s)) => {
1394 let (first, last) = (lines[s], lines[i - 1]);
1395 let bottom_line = self.next_shown(last + 1);
1396 let active = level == active_level && (first..bottom_line).contains(&cursor_line);
1397 guides.push(Guide {
1398 x,
1399 top: self.y_of(first),
1400 bottom: self.y_of(last) + self.line_height(last),
1401 level,
1402 active,
1403 });
1404 start = None;
1405 }
1406 _ => {}
1407 }
1408 }
1409 }
1410 guides
1411 }
1412
1413 pub fn char_rects(&self, model: &TextModel, pos: usize) -> Vec<Rect> {
1415 let rope = model.rope();
1416 let end = (pos + 1).min(rope.len_chars());
1417 let mut rects = self.range_rects(rope, pos..end, self.gutter_width(rope));
1418 rects.truncate(1);
1419 rects
1420 }
1421
1422 pub fn char_range_rects(&self, model: &TextModel, range: std::ops::Range<usize>) -> Vec<Rect> {
1424 let rope = model.rope();
1425 self.range_rects(rope, range, self.gutter_width(rope))
1426 }
1427
1428 pub fn ruler_positions(&self, model: &TextModel, columns: &[usize]) -> Vec<f32> {
1430 let gutter = self.gutter_width(model.rope());
1431 columns.iter().map(|&c| gutter + c as f32 * self.metrics.char_width - self.scroll_left).collect()
1432 }
1433
1434 pub fn whitespace_marks(&self, model: &TextModel) -> Vec<(f32, f32, usize, bool)> {
1437 let rope = model.rope();
1438 let tab = self.tab_size.max(1);
1439 let cw = self.metrics.char_width;
1440 let lh = self.metrics.line_height;
1441 let gutter = self.gutter_width(rope);
1442 let mut out = Vec::new();
1443 for line in self.shown(self.visible_lines(rope)) {
1444 let y = self.y_of(line);
1445 let rows = self.line_rows(rope, line);
1446 let inlays = self.inlays_on(rope, line);
1447 let mut cells = 0;
1448 let mut row = 0;
1449 let mut row_shift = 0isize;
1450 for (col, c) in rope.line(line).chars().take(line_len(rope, line).min(MAX_MARKED_COLUMNS)).enumerate() {
1451 if rows.starts.get(row + 1) == Some(&col) {
1452 row += 1;
1453 row_shift = rows.indent as isize - cells as isize;
1454 }
1455 for h in inlays.iter().filter(|h| h.0 == col) {
1456 row_shift += h.1 as isize;
1457 }
1458 let w = cell_width(c, cells, tab);
1459 if c == ' ' || c == '\t' {
1460 let x = (cells as isize + row_shift) as f32;
1461 out.push((gutter + x * cw - self.scroll_left, y + row as f32 * lh, w, c == '\t'));
1462 }
1463 cells += w;
1464 }
1465 }
1466 out
1467 }
1468}
1469
1470const GUIDE_REACH: usize = 200;
1472
1473fn guide_level(rope: &Rope, line: usize, tab: usize) -> usize {
1476 if let Some(l) = indent_level(rope, line, tab) {
1477 return l;
1478 }
1479 let total = rope.len_lines();
1480 let prev = (line.saturating_sub(GUIDE_REACH)..line).rev().find_map(|l| indent_level(rope, l, tab)).unwrap_or(0);
1481 let next = (line + 1..(line + GUIDE_REACH).min(total)).find_map(|l| indent_level(rope, l, tab)).unwrap_or(0);
1482 prev.min(next)
1483}
1484
1485fn indent_level(rope: &Rope, line: usize, tab: usize) -> Option<usize> {
1487 let len = line_len(rope, line);
1488 let mut cells = 0;
1489 for c in rope.line(line).chars().take(len) {
1490 match c {
1491 ' ' => cells += 1,
1492 '\t' => cells += tab - cells % tab,
1493 _ => return Some(cells / tab),
1494 }
1495 }
1496 None
1497}
1498
1499const MAX_MARKED_COLUMNS: usize = 2000;
1501
1502#[derive(Clone, Copy, Debug, PartialEq)]
1504pub struct Guide {
1505 pub x: f32,
1506 pub top: f32,
1507 pub bottom: f32,
1508 pub level: usize,
1509 pub active: bool,
1511}
1512
1513pub(crate) fn cell_width(c: char, at_cell: usize, tab: usize) -> usize {
1514 if c == '\t' { tab - at_cell % tab } else { c.width().unwrap_or(1) }
1515}
1516
1517pub fn visual_column(rope: &Rope, line: usize, column: usize, tab: usize) -> usize {
1519 rope.line(line).chars().take(column).fold(0, |cells, c| cells + cell_width(c, cells, tab))
1520}
1521
1522pub fn column_at_cells(rope: &Rope, line: usize, cells: f32, tab: usize) -> usize {
1524 let len = line_len(rope, line);
1525 let mut acc = 0usize;
1526 for (i, c) in rope.line(line).chars().take(len).enumerate() {
1527 let w = cell_width(c, acc, tab);
1528 if cells < acc as f32 + w as f32 / 2.0 {
1529 return i;
1530 }
1531 acc += w;
1532 }
1533 len
1534}
1535
1536#[allow(clippy::too_many_arguments)]
1540fn layout_line(
1541 rope: &Rope,
1542 line: usize,
1543 cols: Range<usize>,
1544 spans: &[StyleSpan],
1545 window: Range<usize>,
1546 tab: usize,
1547 x_of: &dyn Fn(usize) -> f32,
1548 inlays: &[(usize, usize, &str)],
1549) -> (Vec<TextRun>, usize) {
1550 let mut runs: Vec<TextRun> = Vec::new();
1551 let mut span_idx = 0;
1552 let mut acc = 0usize;
1553 let mut shift = 0usize;
1555 let mut prev_off_grid = false;
1556 let hint = |col: usize, acc: usize, shift: &mut usize, runs: &mut Vec<TextRun>| {
1557 for &(_, cells, label) in inlays.iter().filter(|h| h.0 == col && cols.contains(&col)) {
1558 runs.push(TextRun { x: x_of(acc + *shift), text: label.to_owned(), style: INLAY_STYLE });
1559 *shift += cells;
1560 }
1561 };
1562 let line_end = line_len(rope, line);
1563 for (col, c) in rope.line(line).chars().take(cols.end).enumerate() {
1564 let w = cell_width(c, acc, tab);
1565 if acc >= window.end {
1566 return (runs, acc + shift + (cols.end - col));
1569 }
1570 if col >= cols.start {
1571 hint(col, acc, &mut shift, &mut runs);
1572 }
1573 if col >= cols.start && acc + w > window.start {
1574 while span_idx < spans.len() && spans[span_idx].end <= col {
1575 span_idx += 1;
1576 }
1577 let style = spans.get(span_idx).filter(|s| s.start <= col).map_or(0, |s| s.style);
1578 let off_grid = !c.is_ascii();
1582 let start_new =
1583 off_grid || prev_off_grid || runs.last().is_none_or(|r| r.style != style || r.style == INLAY_STYLE);
1584 prev_off_grid = off_grid;
1585 if start_new {
1586 runs.push(TextRun { x: x_of(acc + shift), text: String::new(), style });
1587 }
1588 let run = runs.last_mut().expect("a run was just ensured");
1589 if c == '\t' {
1590 run.text.extend(std::iter::repeat_n(' ', w));
1591 } else {
1592 run.text.push(c);
1593 }
1594 }
1595 acc += w;
1596 }
1597 if cols.end == line_end {
1599 let mut cols_end = cols.clone();
1600 cols_end.end += 1;
1601 for &(_, cells, label) in inlays.iter().filter(|h| h.0 == line_end && cols_end.contains(&h.0)) {
1602 runs.push(TextRun { x: x_of(acc + shift), text: label.to_owned(), style: INLAY_STYLE });
1603 shift += cells;
1604 }
1605 }
1606 (runs, acc + shift)
1607}
1608
1609#[cfg(test)]
1610mod tests {
1611 use super::*;
1612 use rustaco_core::{Document, Selection, Selections};
1613
1614 fn view() -> View {
1615 View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 400.0, 100.0)
1616 }
1617
1618 #[test]
1619 fn tabs_and_wide_chars_take_cells() {
1620 let rope = Rope::from_str("\tab\u{4E2D}c");
1621 assert_eq!(visual_column(&rope, 0, 1, 4), 4);
1622 assert_eq!(visual_column(&rope, 0, 4, 4), 8);
1623 assert_eq!(visual_column(&rope, 0, 1, 2), 2);
1624 assert_eq!(column_at_cells(&rope, 0, 1.9, 4), 0);
1625 assert_eq!(column_at_cells(&rope, 0, 2.1, 4), 1);
1626 assert_eq!(column_at_cells(&rope, 0, 99.0, 4), 5);
1627 }
1628
1629 #[test]
1630 fn layout_only_visible_lines() {
1631 let text: String = (0..100).map(|i| format!("line {i}\n")).collect();
1632 let doc = Document::new(&text);
1633 let mut v = view();
1634 v.scroll_to(doc.rope(), 400.0, 0.0);
1635 let frame = v.layout(doc.model(), doc.selections(), &Plain);
1636 assert_eq!(frame.lines.first().map(|l| l.line), Some(20));
1637 assert_eq!(frame.lines.len(), 6);
1638 assert_eq!(frame.lines[0].y, 0.0);
1639 assert_eq!(frame.lines[0].runs[0].text, "line 20");
1640 }
1641
1642 #[test]
1643 fn runs_split_by_style_and_expand_tabs() {
1644 struct Kw;
1645 impl Styler for Kw {
1646 fn spans(&self, _: usize) -> Vec<StyleSpan> {
1647 vec![StyleSpan { start: 0, end: 2, style: 7 }]
1648 }
1649 }
1650 let doc = Document::new("fn\tx");
1651 let frame = view().layout(doc.model(), doc.selections(), &Kw);
1652 let runs = &frame.lines[0].runs;
1653 assert_eq!(runs.len(), 2);
1654 assert_eq!((runs[0].text.as_str(), runs[0].style), ("fn", 7));
1655 assert_eq!(runs[1].text, " x");
1656 assert_eq!(runs[1].x, frame.gutter_width + 20.0);
1657 }
1658
1659 #[test]
1660 fn hit_test_and_reveal() {
1661 let text: String = (0..50).map(|_| "abcdef\n").collect();
1662 let doc = Document::new(&text);
1663 let mut v = view();
1664 let g = v.gutter_width(doc.rope());
1665 assert_eq!(v.hit_test(doc.rope(), g + 26.0, 45.0), 2 * 7 + 3);
1666 v.reveal(doc.rope(), 30 * 7);
1667 assert_eq!(v.scroll_top(), 31.0 * 20.0 - 100.0);
1668 }
1669
1670 #[test]
1671 fn decoration_rects_follow_the_text() {
1672 use rustaco_core::Stickiness;
1673 let doc = Document::new("abc\ndef\nghi");
1674 let mut v = view();
1675 v.layout(doc.model(), doc.selections(), &Plain);
1676 let mut model = doc.model().clone();
1677 model.decorations.set(7, 3, Stickiness::NeverGrows, [1..2, 5..9]);
1678 let rects = v.decoration_rects(&model);
1679 assert_eq!(rects.len(), 3, "one rect for 1..2, two for the range across a line break");
1680 assert!(rects.iter().all(|(_, kind)| *kind == 3));
1681 assert_eq!(rects[0].0.width, 10.0);
1682 }
1683
1684 #[test]
1685 fn multi_line_selection_rects() {
1686 let mut doc = Document::new("abc\nde\nf");
1687 doc.set_selections(Selections::single(Selection::new(1, 8)));
1688 let frame = view().layout(doc.model(), doc.selections(), &Plain);
1689 assert_eq!(frame.selections.len(), 3);
1690 assert_eq!(frame.carets.len(), 1);
1691 assert!(frame.current_line.is_none());
1692 }
1693}
1694
1695#[cfg(test)]
1696mod guide_tests {
1697 use super::*;
1698 use rustaco_core::Document;
1699
1700 #[test]
1701 fn guides_follow_blocks_and_mark_the_active_one() {
1702 let text = "fn a() {\n x\n\n y\n z\n}\nq";
1703 let doc = Document::new(text);
1704 let mut v = View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 400.0, 400.0);
1705 v.layout(doc.model(), doc.selections(), &Plain);
1706 let guides = v.indent_guides(doc.model(), 4);
1707 let level1: Vec<&Guide> = guides.iter().filter(|g| g.level == 1).collect();
1708 assert_eq!(level1.len(), 1, "the blank line inside the block keeps the guide whole");
1709 assert_eq!((level1[0].top, level1[0].bottom), (20.0, 100.0));
1710 let level2: Vec<&Guide> = guides.iter().filter(|g| g.level == 2).collect();
1711 assert_eq!(level2.len(), 1);
1712 assert!(level2[0].active, "the cursor on line 4 is in the level-2 block");
1713 assert!(!level1[0].active);
1714 assert_eq!(v.whitespace_marks(doc.model()).len(), 2 + 4 + 4 + 8, "two spaces in the fn line, then the indents");
1715 }
1716}
1717
1718#[cfg(test)]
1719mod fold_tests {
1720 use super::*;
1721 use rustaco_core::{Document, Edit, Selection};
1722
1723 const TEXT: &str = "fn a() {\n one\n two\n}\nfn b() {\n three\n}\nend";
1724
1725 fn setup() -> (Document, View) {
1726 let doc = Document::new(TEXT);
1727 let mut v = View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 400.0, 400.0);
1728 v.sync(doc.model());
1729 v.set_foldable(indent_fold_ranges(doc.rope(), 4));
1730 (doc, v)
1731 }
1732
1733 #[test]
1734 fn folded_lines_take_no_space() {
1735 let (doc, mut v) = setup();
1736 assert!(v.fold(doc.model(), 2), "line 2 lies in the region headed by line 0");
1737 let frame = v.layout(doc.model(), doc.selections(), &Plain);
1738 let lines: Vec<usize> = frame.lines.iter().map(|l| l.line).collect();
1739 assert_eq!(lines, vec![0, 3, 4, 5, 6, 7]);
1740 assert_eq!(frame.lines[1].y, 20.0);
1741 assert_eq!(
1742 frame.fold_markers.iter().map(|m| (m.line, m.folded)).collect::<Vec<_>>(),
1743 vec![(0, true), (4, false)]
1744 );
1745 assert_eq!(frame.fold_ellipses.len(), 1);
1746 assert_eq!(v.line_at_y(doc.rope(), 25.0), 3);
1747 assert_eq!(v.vertical_target(doc.rope(), 0, None, 1).0, doc.rope().line_to_char(3));
1748 assert_eq!(v.vertical_target(doc.rope(), doc.rope().line_to_char(3), None, -1).0, 0);
1749 }
1750
1751 #[test]
1752 fn folds_follow_edits_and_open_for_carets() {
1753 let (mut doc, mut v) = setup();
1754 v.fold(doc.model(), 4);
1755 doc.apply_edits(vec![Edit::insert(0, "// top\n")]);
1756 v.sync(doc.model());
1757 assert!(v.is_folded(doc.rope(), 5), "the fold moved down with its header");
1758 assert!(v.is_hidden(6) && !v.is_hidden(7));
1759 let inside = doc.rope().line_to_char(6) + 2;
1760 doc.set_selections(rustaco_core::Selections::single(Selection::cursor(inside)));
1761 assert!(v.reveal_positions(doc.model(), [inside]));
1762 assert!(!v.is_hidden(6));
1763 }
1764
1765 #[test]
1766 fn heights_match_a_fresh_view_after_random_edits() {
1767 let mut seed = 0x9e37_79b9_u64;
1768 let mut rand = move |n: usize| {
1769 seed ^= seed << 13;
1770 seed ^= seed >> 7;
1771 seed ^= seed << 17;
1772 (seed % n.max(1) as u64) as usize
1773 };
1774 let text: String = (0..300).map(|i| format!("{}line {i}\n", " ".repeat(i % 4))).collect();
1775 let mut doc = Document::new(&text);
1776 let mut v = View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 400.0, 400.0);
1777 v.sync(doc.model());
1778 for step in 0..200 {
1779 if step % 10 == 0 {
1780 v.set_foldable(indent_fold_ranges(doc.rope(), 4));
1781 let line = rand(doc.rope().len_lines());
1782 v.fold(doc.model(), line);
1783 }
1784 let len = doc.rope().len_chars();
1785 let a = rand(len + 1);
1786 let b = (a + rand(40)).min(len);
1787 let insert = ["", "x", "\n", "\n y\n", "{\n\n}"][rand(5)];
1788 doc.apply_edits(vec![Edit::new(a, b, insert)]);
1789 v.sync(doc.model());
1790 let lines = doc.rope().len_lines();
1791 assert_eq!(v.heights.len(), lines);
1792 let mut top = 0.0f64;
1794 for l in 0..lines {
1795 assert_eq!(v.line_top(l), top, "top of line {l} at step {step}");
1796 if !v.is_hidden(l) {
1797 top += 20.0;
1798 }
1799 }
1800 }
1801 }
1802}
1803
1804#[cfg(test)]
1805mod wrap_tests {
1806 use super::*;
1807 use rustaco_core::{Document, Edit, Selection};
1808
1809 fn wrapped_view() -> View {
1811 let mut v = View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 284.0, 200.0);
1812 v.set_wrap(true);
1813 v
1814 }
1815
1816 #[test]
1817 fn long_lines_take_several_rows() {
1818 let doc = Document::new("short\nthe quick brown fox jumps over the lazy dog\nend");
1819 let mut v = wrapped_view();
1820 let frame = v.layout(doc.model(), doc.selections(), &Plain);
1821 let rows: Vec<(usize, usize, f32)> = frame.lines.iter().map(|l| (l.line, l.row, l.y)).collect();
1822 assert_eq!(rows, vec![(0, 0, 0.0), (1, 0, 20.0), (1, 1, 40.0), (1, 2, 60.0), (2, 0, 80.0)]);
1823 assert_eq!(frame.lines[2].runs[0].text, "jumps over the lazy ");
1824 assert_eq!(v.line_top(2), 80.0);
1825 assert_eq!(v.line_at_y(doc.rope(), 70.0), 1);
1826 }
1827
1828 #[test]
1829 fn carets_hit_tests_and_moves_follow_rows() {
1830 let text = "the quick brown fox jumps over the lazy dog";
1831 let mut doc = Document::new(text);
1832 let mut v = wrapped_view();
1833 let jumps = text.find("jumps").unwrap();
1834 doc.set_selections(rustaco_core::Selections::single(Selection::cursor(jumps + 2)));
1835 let frame = v.layout(doc.model(), doc.selections(), &Plain);
1836 let g = frame.gutter_width;
1837 assert_eq!((frame.carets[0].x, frame.carets[0].y), (g + 20.0, 20.0));
1838 assert_eq!(v.hit_test(doc.rope(), g + 21.0, 25.0), jumps + 2);
1839 assert_eq!(
1840 v.hit_test(doc.rope(), g + 500.0, 5.0),
1841 jumps - 1,
1842 "past a wrapping row's end, before its last char"
1843 );
1844 let (up, goal) = v.vertical_target(doc.rope(), jumps + 2, None, -1);
1845 assert_eq!((up, goal), (2, Some(2)));
1846 assert_eq!(v.vertical_target(doc.rope(), up, goal, 2).0, text.find("dog").unwrap() + 2);
1847 let rects = v.char_range_rects(doc.model(), 4..jumps + 2);
1848 assert_eq!(rects.len(), 2, "one rectangle per row");
1849 }
1850
1851 #[test]
1852 fn every_column_round_trips_through_rows() {
1853 let text =
1854 "\tfn wrapped(aaa: u32, bbbbbbbbbbbbbbbbbbbbbbbbbbbbb: \u{4E2D}\u{4E2D}, c: [u8; 4]) -> bool { true }";
1855 let doc = Document::new(text);
1856 let mut v = wrapped_view();
1857 v.sync(doc.model());
1858 let rope = doc.rope();
1859 let rows = v.line_rows(rope, 0);
1860 assert!(rows.count() > 3);
1861 for column in 0..line_len(rope, 0) {
1862 let (row, x) = v.locate(rope, &rows, 0, column);
1863 assert_eq!(v.column_in_row(rope, &rows, 0, row, x as f32), column, "column {column}");
1864 }
1865 }
1866
1867 #[test]
1868 fn heights_follow_edits_while_wrapping() {
1869 let mut seed = 0x51ed_270b_u64;
1870 let mut rand = move |n: usize| {
1871 seed ^= seed << 13;
1872 seed ^= seed >> 7;
1873 seed ^= seed << 17;
1874 (seed % n.max(1) as u64) as usize
1875 };
1876 let text: String = (0..200).map(|i| format!("{} {}\n", "word ".repeat(i % 9), i)).collect();
1877 let mut doc = Document::new(&text);
1878 let mut v = wrapped_view();
1879 v.sync(doc.model());
1880 for step in 0..200 {
1881 let len = doc.rope().len_chars();
1882 let a = rand(len + 1);
1883 let b = (a + rand(30)).min(len);
1884 let insert = ["", "x", "\n", " long words here and there ", "\nnew line\n"][rand(5)];
1885 doc.apply_edits(vec![Edit::new(a, b, insert)]);
1886 v.sync(doc.model());
1887 let mut fresh = wrapped_view();
1888 fresh.sync(doc.model());
1889 for l in 0..doc.rope().len_lines() {
1890 assert_eq!(v.heights.height(l), fresh.heights.height(l), "line {l} at step {step}");
1891 }
1892 }
1893 }
1894}
1895
1896#[cfg(test)]
1897mod minimap_tests {
1898 use super::*;
1899 use rustaco_core::Document;
1900
1901 #[test]
1902 fn minimap_draws_blocks_and_a_slider() {
1903 let text: String = (0..500).map(|i| format!("let x{i} = {i};\n")).collect();
1904 let doc = Document::new(&text);
1905 let mut v = View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 600.0, 200.0);
1906 v.set_minimap(80.0);
1907 let frame = v.layout(doc.model(), doc.selections(), &Plain);
1908 let m = frame.minimap.expect("the minimap is on");
1909 assert_eq!((m.x, m.width), (520.0, 80.0));
1910 let first_row: Vec<&MinimapBlock> = m.blocks.iter().filter(|b| b.y == 0.0).collect();
1912 assert_eq!(first_row.len(), 4);
1913 assert_eq!((first_row[0].x, first_row[0].width), (520.0, 3.0));
1914 assert_eq!(m.slider.y, 0.0);
1915 assert_eq!(m.slider.height, 20.0, "the viewport's 10 rows at 2 px each");
1916 v.scroll_to(doc.rope(), 1e9, 0.0);
1918 let m = v.layout(doc.model(), doc.selections(), &Plain).minimap.unwrap();
1919 assert!((m.slider.y + m.slider.height - 200.0).abs() < 1.0, "slider at {:?}", m.slider);
1920 }
1921}
1922
1923#[cfg(test)]
1924mod sticky_tests {
1925 use super::*;
1926 use rustaco_core::Document;
1927
1928 #[test]
1929 fn headers_of_enclosing_scopes_stay_pinned() {
1930 let mut text = String::from("impl A {\n fn f() {\n");
1932 for i in 0..30 {
1933 text.push_str(&format!(" line{i};\n"));
1934 }
1935 text.push_str(" }\n}\nafter\n");
1936 let doc = Document::new(&text);
1937 let mut v = View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 400.0, 200.0);
1938 v.sync(doc.model());
1939 v.set_foldable(indent_fold_ranges(doc.rope(), 4));
1940 v.set_sticky_scroll(5);
1941 v.scroll_to(doc.rope(), 10.0 * 20.0, 0.0);
1942 let frame = v.layout(doc.model(), doc.selections(), &Plain);
1943 let pinned: Vec<(usize, f32)> = frame.sticky.iter().map(|l| (l.line, l.y)).collect();
1944 assert_eq!(pinned, vec![(0, 0.0), (1, 20.0)]);
1945 assert_eq!(frame.sticky[1].runs[0].text.trim(), "fn f() {");
1946 v.scroll_to(doc.rope(), 31.0 * 20.0 - 15.0, 0.0);
1948 let pinned = v.sticky_lines(doc.rope());
1949 assert_eq!(pinned.len(), 2);
1950 assert!(pinned[1].1 < 20.0, "pushed up: {pinned:?}");
1951 v.scroll_to(doc.rope(), 0.0, 0.0);
1953 assert!(v.sticky_lines(doc.rope()).is_empty());
1954 }
1955}
1956
1957#[cfg(test)]
1958mod zone_tests {
1959 use super::*;
1960 use rustaco_core::{Document, Edit};
1961
1962 fn view() -> View {
1963 View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 400.0, 400.0)
1964 }
1965
1966 #[test]
1967 fn zones_add_space_between_lines_and_follow_edits() {
1968 let mut doc = Document::new("a\nb\nc\nd");
1969 let mut v = view();
1970 v.set_zones(doc.model(), [(7, Some(1), 50.0), (8, None, 10.0)]);
1971 let frame = v.layout(doc.model(), doc.selections(), &Plain);
1972 let tops: Vec<(usize, f32)> = frame.lines.iter().map(|l| (l.line, l.y)).collect();
1973 assert_eq!(tops, vec![(0, 10.0), (1, 30.0), (2, 100.0), (3, 120.0)]);
1974 assert_eq!(
1975 frame.zones,
1976 vec![
1977 (8, Rect { x: frame.gutter_width, y: 0.0, width: 400.0 - frame.gutter_width, height: 10.0 }),
1978 (7, Rect { x: frame.gutter_width, y: 50.0, width: 400.0 - frame.gutter_width, height: 50.0 }),
1979 ]
1980 );
1981 assert_eq!(doc.rope().char_to_line(v.hit_test(doc.rope(), 100.0, 80.0)), 1);
1983 doc.apply_edits(vec![Edit::insert(0, "new\n")]);
1985 let frame = v.layout(doc.model(), doc.selections(), &Plain);
1986 assert_eq!(frame.zones[1].1.y, 70.0);
1987 assert_eq!(v.line_top(3), 120.0);
1988 let end_of_b = doc.rope().line_to_char(2) + 1;
1990 doc.apply_edits(vec![Edit::insert(end_of_b, "\nmore")]);
1991 v.sync(doc.model());
1992 assert_eq!(v.line_top(3), 10.0 + 3.0 * 20.0 + 50.0, "the zone stays after line 2, before the new line");
1993 v.set_zones(doc.model(), []);
1994 assert_eq!(v.line_top(3), 60.0);
1995 }
1996}
1997
1998#[cfg(test)]
1999mod grid_tests {
2000 use super::*;
2001 use rustaco_core::Document;
2002
2003 #[test]
2004 fn chars_outside_ascii_sit_on_the_grid() {
2005 let doc = Document::new("a\u{4E2D}b\u{e9}cd");
2006 let mut v = View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 400.0, 100.0);
2007 let frame = v.layout(doc.model(), doc.selections(), &Plain);
2008 let g = frame.gutter_width;
2009 let runs: Vec<(&str, f32)> = frame.lines[0].runs.iter().map(|r| (r.text.as_str(), r.x - g)).collect();
2010 assert_eq!(runs, vec![("a", 0.0), ("\u{4E2D}", 10.0), ("b", 30.0), ("\u{e9}", 40.0), ("cd", 50.0)]);
2011 }
2012}
2013
2014#[cfg(test)]
2015mod inlay_tests {
2016 use super::*;
2017 use rustaco_core::{Document, Edit, Selection, Selections};
2018
2019 #[test]
2020 fn hints_push_text_right_and_carets_stay_before_them() {
2021 let mut doc = Document::new("let x = 1;");
2022 let mut v = View::new(Metrics { char_width: 10.0, line_height: 20.0 }, 400.0, 100.0);
2023 v.set_inlays(doc.model(), vec![(5, ": i32".into())]);
2024 doc.set_selections(Selections::single(Selection::cursor(5)));
2025 let frame = v.layout(doc.model(), doc.selections(), &Plain);
2026 let g = frame.gutter_width;
2027 let runs: Vec<(&str, f32, bool)> =
2028 frame.lines[0].runs.iter().map(|r| (r.text.as_str(), r.x - g, r.style == INLAY_STYLE)).collect();
2029 assert_eq!(runs, vec![("let x", 0.0, false), (": i32", 50.0, true), (" = 1;", 100.0, false)]);
2030 assert_eq!(frame.carets[0].x - g, 50.0, "the caret at the hint stays before it");
2031 assert_eq!(v.hit_test(doc.rope(), g + 70.0, 5.0), 5);
2033 assert_eq!(v.hit_test(doc.rope(), g + 110.0, 5.0), 6);
2034 doc.apply_edits(vec![Edit::insert(0, " ")]);
2036 let frame = v.layout(doc.model(), doc.selections(), &Plain);
2037 assert!(frame.lines[0].runs.iter().any(|r| r.style == INLAY_STYLE && r.x - g == 70.0));
2038 }
2039}