BlueGit

timfa posprint

Files

posprint / src / text_wrap.rs

text_wrap.rs

text_wrap.rs 11.8 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_tokens_var_budget(&tokenize(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
70/// Word-wrap `text` to at most `max_cols` characters per line.
71/// Explicit newlines in `text` start a new wrapped paragraph.
72/// Consecutive spaces are preserved (not collapsed).
73pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
74 if max_cols == 0 {
75 return vec![text.to_string()];
76 }
77
78 let mut lines = Vec::new();
79 for paragraph in text.split('\n') {
80 lines.extend(wrap_line(paragraph, max_cols));
81 }
82 if lines.is_empty() {
83 lines.push(String::new());
84 }
85 lines
86}
87
88fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
89 if line.is_empty() {
90 return vec![String::new()];
91 }
92 wrap_tokens_var_budget(&tokenize(line), max_cols, max_cols)
93}
94
95/// Split into alternating word / whitespace runs so multi-space gaps stay intact.
96fn tokenize(text: &str) -> Vec<Token<'_>> {
97 let mut tokens = Vec::new();
98 let mut rest = text;
99 while !rest.is_empty() {
100 let first = rest.chars().next().unwrap();
101 if is_wrap_space(first) {
102 let end = rest
103 .char_indices()
104 .find(|(_, c)| !is_wrap_space(*c))
105 .map(|(i, _)| i)
106 .unwrap_or(rest.len());
107 tokens.push(Token::Spaces(&rest[..end]));
108 rest = &rest[end..];
109 } else {
110 let end = rest
111 .char_indices()
112 .find(|(_, c)| is_wrap_space(*c))
113 .map(|(i, _)| i)
114 .unwrap_or(rest.len());
115 tokens.push(Token::Word(&rest[..end]));
116 rest = &rest[end..];
117 }
118 }
119 tokens
120}
121
122fn is_wrap_space(c: char) -> bool {
123 c == ' ' || c == '\t'
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127enum Token<'a> {
128 Word(&'a str),
129 Spaces(&'a str),
130}
131
132impl<'a> Token<'a> {
133 fn as_str(self) -> &'a str {
134 match self {
135 Token::Word(s) | Token::Spaces(s) => s,
136 }
137 }
138
139 fn len_chars(self) -> usize {
140 self.as_str().chars().count()
141 }
142
143 fn is_spaces(self) -> bool {
144 matches!(self, Token::Spaces(_))
145 }
146}
147
148fn wrap_tokens_var_budget(
149 tokens: &[Token<'_>],
150 first_budget: usize,
151 next_budget: usize,
152) -> Vec<String> {
153 if tokens.is_empty() {
154 return vec![String::new()];
155 }
156 if first_budget == 0 && next_budget == 0 {
157 return vec![tokens.iter().map(|t| t.as_str()).collect()];
158 }
159
160 let mut lines = Vec::new();
161 let mut current = String::new();
162 let mut budget = first_budget.max(1);
163 let mut idx = 0usize;
164 // After wrapping mid-line, skip the whitespace that sat between words.
165 let mut skip_leading_spaces = false;
166
167 while idx < tokens.len() {
168 let tok = tokens[idx];
169
170 if tok.is_spaces() {
171 if current.is_empty() {
172 if skip_leading_spaces {
173 idx += 1;
174 continue;
175 }
176 // Leading spaces of the original line (or a space-only line).
177 let spaces = tok.as_str();
178 let space_len = tok.len_chars();
179 if space_len <= budget {
180 current.push_str(spaces);
181 idx += 1;
182 } else {
183 let mut remaining = spaces;
184 while !remaining.is_empty() {
185 let chunk = take_char_prefix(remaining, budget);
186 let consumed = chunk.chars().count();
187 if chunk.is_empty() {
188 break;
189 }
190 lines.push(chunk);
191 remaining = char_slice_from(remaining, consumed);
192 budget = next_budget.max(1);
193 }
194 idx += 1;
195 skip_leading_spaces = false;
196 }
197 continue;
198 }
199
200 let cur_len = current.chars().count();
201 let space_len = tok.len_chars();
202 if cur_len + space_len <= budget {
203 current.push_str(tok.as_str());
204 idx += 1;
205 } else {
206 // Spaces don't fit: end the line (trim trailing pad) and skip
207 // this space run on the continuation.
208 flush_line(&mut lines, &mut current);
209 budget = next_budget.max(1);
210 skip_leading_spaces = true;
211 }
212 continue;
213 }
214
215 // Word token
216 let word = tok.as_str();
217 let word_len = tok.len_chars();
218
219 if current.is_empty() {
220 if word_len <= budget {
221 current.push_str(word);
222 idx += 1;
223 skip_leading_spaces = false;
224 } else {
225 let mut remaining = word;
226 while !remaining.is_empty() {
227 let chunk = take_char_prefix(remaining, budget);
228 let consumed = chunk.chars().count();
229 if chunk.is_empty() {
230 break;
231 }
232 lines.push(chunk);
233 remaining = char_slice_from(remaining, consumed);
234 budget = next_budget.max(1);
235 }
236 idx += 1;
237 skip_leading_spaces = true;
238 }
239 continue;
240 }
241
242 let cur_len = current.chars().count();
243 if cur_len + word_len <= budget {
244 current.push_str(word);
245 idx += 1;
246 skip_leading_spaces = false;
247 } else {
248 flush_line(&mut lines, &mut current);
249 budget = next_budget.max(1);
250 skip_leading_spaces = true;
251 // Retry the same word on the new line.
252 }
253 }
254
255 if !current.is_empty() {
256 lines.push(current);
257 }
258 if lines.is_empty() {
259 lines.push(String::new());
260 }
261 lines
262}
263
264fn flush_line(lines: &mut Vec<String>, current: &mut String) {
265 // Drop trailing spaces that only existed as padding before a wrapped word.
266 let trimmed = current.trim_end_matches(is_wrap_space).to_string();
267 if !trimmed.is_empty() {
268 lines.push(trimmed);
269 }
270 current.clear();
271}
272
273fn take_char_prefix(text: &str, max_chars: usize) -> String {
274 text.chars().take(max_chars).collect()
275}
276
277fn char_slice_from(text: &str, skip_chars: usize) -> &str {
278 match text.char_indices().nth(skip_chars) {
279 Some((idx, _)) => &text[idx..],
280 None => "",
281 }
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287
288 fn meta_53mm() -> PosMetadata {
289 PosMetadata {
290 page_width_mm: 53.0,
291 ..Default::default()
292 }
293 }
294
295 #[test]
296 fn heading1_wraps_at_half_line_width() {
297 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Heading1);
298 assert_eq!(cols, 16);
299 let lines = wrap_text("Proof of Transfer", cols);
300 assert_eq!(lines, vec!["Proof of", "Transfer"]);
301 }
302
303 #[test]
304 fn preserves_explicit_newlines() {
305 let lines = wrap_text("Line one\nLine two", 32);
306 assert_eq!(lines, vec!["Line one", "Line two"]);
307 }
308
309 #[test]
310 fn normal_text_wraps_at_full_width() {
311 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal);
312 assert_eq!(cols, 32);
313 }
314
315 #[test]
316 fn bullet_wrap_uses_hanging_indent() {
317 let lines = wrap_bullet_item("this is a long line", 15);
318 assert_eq!(lines, vec!["* this is a", " long line"]);
319 }
320
321 #[test]
322 fn nested_bullet_uses_dash_and_indent() {
323 let lines = wrap_bullet_item_at_depth("this is a long line", 16, 1);
324 assert_eq!(lines, vec![" - this is a", " long line"]);
325 }
326
327 #[test]
328 fn hanging_wrap_hard_breaks_url_without_hanging() {
329 let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88";
330 let lines = wrap_bullet_item(url, 32);
331 assert!(
332 lines.len() >= 2,
333 "expected hard-break into multiple lines: {lines:?}"
334 );
335 assert!(lines[0].starts_with("* https://"));
336 let joined: String = lines
337 .iter()
338 .map(|l| {
339 l.strip_prefix("* ")
340 .or_else(|| l.strip_prefix(" "))
341 .unwrap_or(l)
342 })
343 .collect();
344 assert_eq!(joined, url);
345 }
346
347 #[test]
348 fn plain_wrap_hard_breaks_url() {
349 let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88";
350 let lines = wrap_text(url, 32);
351 assert!(lines.len() >= 2);
352 assert_eq!(lines.concat(), url);
353 }
354
355 #[test]
356 fn preserves_multiple_spaces_within_line() {
357 let lines = wrap_text("Item 12.00", 32);
358 assert_eq!(lines, vec!["Item 12.00"]);
359 }
360
361 #[test]
362 fn preserves_multiple_spaces_when_wrapping() {
363 // "aa" + 4 spaces + "bb" = 8; budget 6 wraps before bb, spaces not leading next line.
364 let lines = wrap_text("aa bb", 6);
365 assert_eq!(lines, vec!["aa", "bb"]);
366 }
367
368 #[test]
369 fn preserves_leading_spaces() {
370 let lines = wrap_text(" hello", 32);
371 assert_eq!(lines, vec![" hello"]);
372 }
373
374 #[test]
375 fn space_only_line_is_preserved() {
376 let lines = wrap_text(" ", 32);
377 assert_eq!(lines, vec![" "]);
378 }
379
380 #[test]
381 fn bullet_preserves_multiple_spaces() {
382 let lines = wrap_bullet_item("A B", 32);
383 assert_eq!(lines, vec!["* A B"]);
384 }
385}