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