//! Source lines laid out on a fixed grid: tabs expanded to stops, wide //! characters given two cells, and long lines wrapped at the column limit. use crate::highlight::Colors; use arborium_theme::theme::Color; use unicode_width::UnicodeWidthChar; /// One glyph at a grid column; a wide glyph also covers the next column. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Glyph { pub column: usize, pub ch: char, pub color: Color, } /// One row of the image: a source line, or the continuation of a wrapped one. #[derive(Debug, Clone, PartialEq)] pub struct Row { pub line: usize, pub continued: bool, pub glyphs: Vec, } /// The 1-based lines of `source` with the byte offset each starts at. /// A final newline ends the last line rather than starting an empty one. pub fn lines(source: &str) -> Vec<(usize, &str)> { let mut offset = 0; let mut lines = Vec::new(); for line in source.split_inclusive('\n') { let text = line .strip_suffix("\r\n") .or_else(|| line.strip_suffix('\n')) .unwrap_or(line); lines.push((offset, text)); offset += line.len(); } lines } pub fn rows( lines: &[(usize, &str)], first: usize, colors: &Colors, columns: usize, tab_width: usize, ) -> Vec { let mut rows = Vec::new(); let mut cursor = colors.cursor(lines.first().map_or(0, |(offset, _)| *offset)); for (index, (offset, text)) in lines.iter().enumerate() { let line = first + index; let mut row = Row { line, continued: false, glyphs: Vec::new(), }; let mut column = 0; for (at, ch) in text.char_indices() { let color = cursor.at(offset + at); let (glyph, mut width) = match ch { '\t' => (' ', tab_width - column % tab_width), ch if ch.is_control() => ('\u{FFFD}', 1), // Combining marks have no cell of their own; they are dropped. ch => match ch.width() { Some(0) => continue, width => (ch, width.unwrap_or(1)), }, }; if column + width > columns && column > 0 { rows.push(std::mem::replace( &mut row, Row { line, continued: true, glyphs: Vec::new(), }, )); column = 0; if ch == '\t' { width = tab_width; } } if glyph != ' ' { row.glyphs.push(Glyph { column, ch: glyph, color, }); } column += width.min(columns); } rows.push(row); } rows } /// Consecutive rows that fit one image, as evenly sized as the fewest pages /// allow, so a range just over one page is not a full page and a sliver. /// A page ends at a line boundary unless one line is taller than a page. pub fn pages(rows: &[Row], max_rows: usize) -> Vec> { // Split oversized lines on fresh pages at balanced row intervals. let count = rows.len().div_ceil(max_rows).max(1); let chunk = rows.len().div_ceil(count).max(1); let mut pages = Vec::new(); let mut breaks = vec![0]; for end in (1..=rows.len()).filter(|&i| i == rows.len() || !rows[i].continued) { let mut start = *breaks.last().unwrap(); if end - start > max_rows { pages.extend(whole_pages(&breaks, max_rows)); while end - start > chunk { pages.push(start..start + chunk); start += chunk; } breaks.clear(); breaks.push(start); } breaks.push(end); } pages.extend(whole_pages(&breaks, max_rows)); pages } fn whole_pages(breaks: &[usize], max_rows: usize) -> Vec> { let last = breaks[breaks.len() - 1]; // Pack backwards to find the earliest start of each page in a // minimum-page layout. Moving a break later leaves its suffix feasible. let mut pages = Vec::new(); let mut end = breaks.len() - 1; while end > 0 { let mut start = end - 1; while start > 0 && breaks[end] - breaks[start - 1] <= max_rows { start -= 1; } pages.push(breaks[start]..breaks[end]); end = start; } pages.reverse(); for i in 0..pages.len().saturating_sub(1) { let start = pages[i].start; let target = start + (last - start).div_ceil(pages.len() - i); if target > pages[i].end { let end = breaks[breaks.partition_point(|&b| b <= target) - 1]; pages[i].end = end; pages[i + 1].start = end; } } pages } #[cfg(test)] mod tests { use super::*; use arborium_theme::theme::builtin; use proptest::prelude::*; fn plain(source: &str, columns: usize) -> Vec { let colors = Colors::new(source, None, &builtin::github_light()); rows(&lines(source), 1, &colors, columns, 4) } fn text(row: &Row) -> String { let mut text = String::new(); for glyph in &row.glyphs { while text.chars().count() < glyph.column { text.push(' '); } text.push(glyph.ch); } text } #[test] fn lines_keep_offsets_and_drop_line_endings() { assert_eq!( lines("a\r\nbc\n\nd"), vec![(0, "a"), (3, "bc"), (6, ""), (7, "d")] ); assert_eq!(lines("a\n"), vec![(0, "a")]); assert!(lines("").is_empty()); } #[test] fn bare_carriage_return_at_eof_is_visible() { let rows = plain("a\r\nb\r", 79); assert_eq!(text(&rows[0]), "a"); assert_eq!(text(&rows[1]), "b\u{FFFD}"); } #[test] fn tabs_stop_at_multiples_of_the_tab_width() { let rows = plain("a\tb\n\tc", 79); assert_eq!(text(&rows[0]), "a b"); assert_eq!(text(&rows[1]), " c"); } #[test] fn wrapped_tab_uses_the_continuation_rows_first_stop() { let rows = plain(&format!("{}\tb", "a".repeat(21)), 21); assert_eq!(text(&rows[1]), " b"); } #[test] fn long_lines_wrap_and_wide_characters_never_split() { let rows = plain("abcdefg\n漢字漢", 3); let wrapped: Vec<_> = rows .iter() .map(|row| (row.line, row.continued, text(row))) .collect(); assert_eq!( wrapped, vec![ (1, false, "abc".into()), (1, true, "def".into()), (1, true, "g".into()), (2, false, "漢".into()), (2, true, "字".into()), (2, true, "漢".into()), ] ); assert_eq!(rows[3].glyphs[0].column, 0); } #[test] fn control_characters_are_visible_and_empty_lines_keep_a_row() { let rows = plain("a\u{1b}b\n\nc\u{301}", 79); assert_eq!(text(&rows[0]), "a\u{FFFD}b"); assert_eq!(rows[1].glyphs, vec![]); assert_eq!(text(&rows[2]), "c"); } #[test] fn pages_break_between_lines_unless_one_line_fills_a_page() { let rows = plain("aa\nbbbbbb\ncc\ndddddddddd", 2); // rows: a(1) b b b(2) c(3) d d d d d(4) assert_eq!(pages(&rows, 3), vec![0..1, 1..4, 4..5, 5..8, 8..10]); } #[test] fn page_sized_line_stays_whole_after_a_short_line() { let rows = plain("aa\nbbbbbb", 2); assert_eq!(pages(&rows, 3), vec![0..1, 1..4]); } #[test] fn a_range_just_over_one_page_splits_evenly() { let rows = plain(&"x\n".repeat(81), 79); assert_eq!(pages(&rows, 80), vec![0..41, 41..81]); assert_eq!(pages(&rows[..80], 80), vec![0..80]); } /// Source text mixing narrow, wide and zero-width characters, tabs, /// spaces, control characters and both line endings. fn source() -> impl Strategy { proptest::collection::vec( prop_oneof![ Just("a"), Just("漢"), Just("😀"), Just("e\u{301}"), Just("\t"), Just(" "), Just("\u{1b}"), Just("\n"), Just("\r\n"), ], 0..60, ) .prop_map(|parts| parts.concat()) } /// What a line shows, in order: every character but spaces, tabs and /// zero-width marks, with control characters made visible. fn shown(line: &str) -> String { line.chars() .filter_map(|ch| match ch { ' ' | '\t' => None, ch if ch.is_control() => Some('\u{FFFD}'), ch if ch.width() == Some(0) => None, ch => Some(ch), }) .collect() } proptest! { #![proptest_config(crate::property::config(256))] // Each line starts one row and continues in the rows after it, no // glyph runs past the columns unless it alone is wider, glyphs keep // their order, and every visible character is drawn once. #[test] fn rows_fit_the_columns_and_draw_every_character( source in source(), columns in 1usize..8, ) { let rows = plain(&source, columns); let lines = lines(&source); let starts: Vec = rows.iter().filter(|row| !row.continued).map(|row| row.line).collect(); prop_assert_eq!(starts, (1..=lines.len()).collect::>()); prop_assert!(rows.windows(2).all(|pair| pair[0].line <= pair[1].line)); for row in &rows { for glyph in &row.glyphs { let width = glyph.ch.width().unwrap_or(1); prop_assert!(glyph.column + width <= columns || glyph.column == 0); } prop_assert!(row .glyphs .windows(2) .all(|pair| pair[0].column < pair[1].column)); } for (index, (_, line)) in lines.iter().enumerate() { let drawn: String = rows .iter() .filter(|row| row.line == index + 1) .flat_map(|row| row.glyphs.iter().map(|glyph| glyph.ch)) .collect(); prop_assert_eq!(drawn, shown(line)); } } // Pages cover the rows once, in order, each within the limit, and a // page starts inside a line only when that line is taller than a page. #[test] fn pages_cover_the_rows_once_and_break_between_lines( source in source(), columns in 1usize..6, max_rows in 1usize..6, ) { let rows = plain(&source, columns); let pages = pages(&rows, max_rows); let mut next = 0; for page in &pages { prop_assert_eq!(page.start, next); prop_assert!(!page.is_empty() && page.len() <= max_rows); if page.start < rows.len() && rows[page.start].continued { let line = rows[page.start].line; let tall = rows.iter().filter(|row| row.line == line).count(); prop_assert!(tall > max_rows); } next = page.end; } prop_assert_eq!(next, rows.len()); } } }