bacon/tui/
wrap.rs

1use {
2    crate::*,
3    unicode_width::UnicodeWidthChar,
4};
5
6/// Wrap lines into sublines containing positions in the original lines
7pub fn wrap(
8    lines: &[Line],
9    width: u16,
10) -> Vec<Line> {
11    let cols = width as usize - 1; // -1 for the probable scrollbar
12    let mut sub_lines = Vec::new();
13    for line in lines {
14        let summary = line.line_type.is_summary();
15        sub_lines.push(Line {
16            item_idx: line.item_idx,
17            content: TLine::default(),
18            line_type: line.line_type,
19        });
20        let mut sub_cols = line.line_type.cols();
21        let mut wrap_idx = 0; // 1 for first continuation, etc.
22        for string in &line.content.strings {
23            sub_lines
24                .last_mut()
25                .unwrap()
26                .content
27                .strings
28                .push(string.clone()); // might be truncated later
29            let mut byte_offset = 0;
30            for (byte_idx, c) in string.raw.char_indices() {
31                let char_cols = c.width().unwrap_or(0);
32                if sub_cols + char_cols > cols && sub_cols > 0 {
33                    let last_string = sub_lines
34                        .last_mut()
35                        .unwrap()
36                        .content
37                        .strings
38                        .last_mut()
39                        .unwrap();
40                    let after_cut = TString::new(
41                        last_string.csi.clone(),
42                        last_string.raw[byte_idx - byte_offset..].to_string(),
43                    );
44                    last_string.raw.truncate(byte_idx - byte_offset);
45                    byte_offset = byte_idx;
46                    sub_lines.push(Line {
47                        item_idx: line.item_idx,
48                        content: TLine {
49                            strings: vec![after_cut],
50                        },
51                        line_type: LineType::Continuation {
52                            offset: wrap_idx,
53                            summary,
54                        },
55                    });
56                    wrap_idx += 1;
57                    sub_cols = char_cols;
58                } else {
59                    sub_cols += char_cols;
60                }
61            }
62        }
63    }
64    sub_lines
65}