BlueGit

timfa posprint

Files

posprint / src / text_wrap.rs

text_wrap.rs

checkboxes
timfa Tim Falken · pushed by timfa · 4 months ago
00ee9454 History
text_wrap.rs 7.6 KiB Download Raw
1use crate::io::PosMetadata;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum TextWrapStyle {
5 Normal,
6 Heading1,
7 Heading2,
8}
9
10/// Character columns available for a text style on the target printer.
11pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize {
12 let base = metadata.chars_per_line().max(1) as usize;
13 match style {
14 TextWrapStyle::Heading1 => (base / 2).max(1),
15 TextWrapStyle::Normal | TextWrapStyle::Heading2 => base,
16 }
17}
18
19/// ASCII top-level bullet — universally supported on ESC/POS printers.
20pub const BULLET_FIRST_PREFIX: &str = "* ";
21/// Indent for wrapped continuation lines at depth 0 (same width as [`BULLET_FIRST_PREFIX`]).
22pub const BULLET_NEXT_PREFIX: &str = " ";
23
24/// Word-wrap a top-level bullet list item with hanging indentation (`* `).
25pub fn wrap_bullet_item(text: &str, max_cols: usize) -> Vec<String> {
26 wrap_bullet_item_at_depth(text, max_cols, 0)
27}
28
29/// Word-wrap a bullet at nesting `depth` (0 = `* `, nested = indented `- `).
30pub fn wrap_bullet_item_at_depth(text: &str, max_cols: usize, depth: u8) -> Vec<String> {
31 let (first, next) = bullet_prefixes(depth);
32 wrap_hanging(text, max_cols, &first, &next)
33}
34
35fn bullet_prefixes(depth: u8) -> (String, String) {
36 let indent = " ".repeat(usize::from(depth));
37 if depth == 0 {
38 (BULLET_FIRST_PREFIX.to_string(), BULLET_NEXT_PREFIX.to_string())
39 } else {
40 let first = format!("{indent}- ");
41 let next = " ".repeat(first.chars().count());
42 (first, next)
43 }
44}
45
46/// Word-wrap `text` with different budgets for the first and subsequent lines.
47pub fn wrap_hanging(
48 text: &str,
49 max_cols: usize,
50 first_prefix: &str,
51 next_prefix: &str,
52) -> Vec<String> {
53 let first_budget = max_cols.saturating_sub(first_prefix.chars().count());
54 let next_budget = max_cols.saturating_sub(next_prefix.chars().count());
55 let content_lines = wrap_content_var_budget(text, first_budget, next_budget);
56
57 content_lines
58 .into_iter()
59 .enumerate()
60 .map(|(idx, line)| {
61 if idx == 0 {
62 format!("{first_prefix}{line}")
63 } else {
64 format!("{next_prefix}{line}")
65 }
66 })
67 .collect()
68}
69
70fn wrap_content_var_budget(text: &str, first_budget: usize, next_budget: usize) -> Vec<String> {
71 if first_budget == 0 && next_budget == 0 {
72 return vec![text.to_string()];
73 }
74
75 let words: Vec<&str> = text.split_whitespace().collect();
76 if words.is_empty() {
77 return vec![String::new()];
78 }
79
80 let mut lines = Vec::new();
81 let mut current = String::new();
82 let mut budget = first_budget.max(1);
83 let mut word_idx = 0usize;
84
85 while word_idx < words.len() {
86 let word = words[word_idx];
87 let word_len = word.chars().count();
88
89 if current.is_empty() {
90 if word_len <= budget {
91 current.push_str(word);
92 word_idx += 1;
93 } else {
94 let mut remaining = word;
95 while !remaining.is_empty() {
96 let chunk = take_char_prefix(remaining, budget);
97 let consumed = chunk.chars().count();
98 if chunk.is_empty() {
99 break;
100 }
101 lines.push(chunk);
102 remaining = &remaining[remaining
103 .char_indices()
104 .nth(consumed)
105 .map(|(idx, _)| idx)
106 .unwrap_or(remaining.len())..];
107 budget = next_budget.max(1);
108 }
109 }
110 } else {
111 let current_len = current.chars().count();
112 if current_len + 1 + word_len <= budget {
113 current.push(' ');
114 current.push_str(word);
115 word_idx += 1;
116 } else {
117 lines.push(std::mem::take(&mut current));
118 budget = next_budget.max(1);
119 }
120 }
121 }
122
123 if !current.is_empty() {
124 lines.push(current);
125 }
126 if lines.is_empty() {
127 lines.push(String::new());
128 }
129 lines
130}
131
132fn take_char_prefix(text: &str, max_chars: usize) -> String {
133 text.chars().take(max_chars).collect()
134}
135
136/// Word-wrap `text` to at most `max_cols` characters per line.
137/// Explicit newlines in `text` start a new wrapped paragraph.
138pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
139 if max_cols == 0 {
140 return vec![text.to_string()];
141 }
142
143 let mut lines = Vec::new();
144 for paragraph in text.split('\n') {
145 lines.extend(wrap_line(paragraph, max_cols));
146 }
147 if lines.is_empty() {
148 lines.push(String::new());
149 }
150 lines
151}
152
153fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
154 if line.is_empty() {
155 return vec![String::new()];
156 }
157
158 let mut lines = Vec::new();
159 let mut current = String::new();
160
161 for word in line.split_whitespace() {
162 let word_len = word.chars().count();
163 if current.is_empty() {
164 if word_len <= max_cols {
165 current.push_str(word);
166 } else {
167 lines.extend(split_long_word(word, max_cols));
168 }
169 } else {
170 let current_len = current.chars().count();
171 if current_len + 1 + word_len <= max_cols {
172 current.push(' ');
173 current.push_str(word);
174 } else {
175 lines.push(std::mem::take(&mut current));
176 if word_len <= max_cols {
177 current.push_str(word);
178 } else {
179 lines.extend(split_long_word(word, max_cols));
180 }
181 }
182 }
183 }
184
185 if !current.is_empty() {
186 lines.push(current);
187 }
188
189 if lines.is_empty() {
190 lines.push(String::new());
191 }
192 lines
193}
194
195fn split_long_word(word: &str, max_cols: usize) -> Vec<String> {
196 let mut chunks = Vec::new();
197 let mut chunk = String::new();
198 for ch in word.chars() {
199 if chunk.chars().count() >= max_cols {
200 chunks.push(std::mem::take(&mut chunk));
201 }
202 chunk.push(ch);
203 }
204 if !chunk.is_empty() {
205 chunks.push(chunk);
206 }
207 chunks
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 fn meta_53mm() -> PosMetadata {
215 PosMetadata {
216 page_width_mm: 53.0,
217 ..Default::default()
218 }
219 }
220
221 #[test]
222 fn heading1_wraps_at_half_line_width() {
223 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Heading1);
224 assert_eq!(cols, 16);
225 let lines = wrap_text("Proof of Transfer", cols);
226 assert_eq!(lines, vec!["Proof of", "Transfer"]);
227 }
228
229 #[test]
230 fn preserves_explicit_newlines() {
231 let lines = wrap_text("Line one\nLine two", 32);
232 assert_eq!(lines, vec!["Line one", "Line two"]);
233 }
234
235 #[test]
236 fn normal_text_wraps_at_full_width() {
237 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal);
238 assert_eq!(cols, 32);
239 }
240
241 #[test]
242 fn bullet_wrap_uses_hanging_indent() {
243 let lines = wrap_bullet_item("this is a long line", 15);
244 assert_eq!(lines, vec!["* this is a", " long line"]);
245 }
246
247 #[test]
248 fn nested_bullet_uses_dash_and_indent() {
249 let lines = wrap_bullet_item_at_depth("this is a long line", 18, 1);
250 assert_eq!(lines, vec![" - this is a", " long line"]);
251 }
252}