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