BlueGit

timfa posprint

Files

posprint / src / text_wrap.rs

text_wrap.rs

text_wrap.rs 8.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 // Hard-break overlong tokens (URLs, etc.). Must advance word_idx
95 // or this loop never terminates.
96 let mut remaining = word;
97 while !remaining.is_empty() {
98 let chunk = take_char_prefix(remaining, budget);
99 let consumed = chunk.chars().count();
100 if chunk.is_empty() {
101 break;
102 }
103 lines.push(chunk);
104 remaining = &remaining[remaining
105 .char_indices()
106 .nth(consumed)
107 .map(|(idx, _)| idx)
108 .unwrap_or(remaining.len())..];
109 budget = next_budget.max(1);
110 }
111 word_idx += 1;
112 }
113 } else {
114 let current_len = current.chars().count();
115 if current_len + 1 + word_len <= budget {
116 current.push(' ');
117 current.push_str(word);
118 word_idx += 1;
119 } else {
120 lines.push(std::mem::take(&mut current));
121 budget = next_budget.max(1);
122 }
123 }
124 }
125
126 if !current.is_empty() {
127 lines.push(current);
128 }
129 if lines.is_empty() {
130 lines.push(String::new());
131 }
132 lines
133}
134
135fn take_char_prefix(text: &str, max_chars: usize) -> String {
136 text.chars().take(max_chars).collect()
137}
138
139/// Word-wrap `text` to at most `max_cols` characters per line.
140/// Explicit newlines in `text` start a new wrapped paragraph.
141pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
142 if max_cols == 0 {
143 return vec![text.to_string()];
144 }
145
146 let mut lines = Vec::new();
147 for paragraph in text.split('\n') {
148 lines.extend(wrap_line(paragraph, max_cols));
149 }
150 if lines.is_empty() {
151 lines.push(String::new());
152 }
153 lines
154}
155
156fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
157 if line.is_empty() {
158 return vec![String::new()];
159 }
160
161 let mut lines = Vec::new();
162 let mut current = String::new();
163
164 for word in line.split_whitespace() {
165 let word_len = word.chars().count();
166 if current.is_empty() {
167 if word_len <= max_cols {
168 current.push_str(word);
169 } else {
170 lines.extend(split_long_word(word, max_cols));
171 }
172 } else {
173 let current_len = current.chars().count();
174 if current_len + 1 + word_len <= max_cols {
175 current.push(' ');
176 current.push_str(word);
177 } else {
178 lines.push(std::mem::take(&mut current));
179 if word_len <= max_cols {
180 current.push_str(word);
181 } else {
182 lines.extend(split_long_word(word, max_cols));
183 }
184 }
185 }
186 }
187
188 if !current.is_empty() {
189 lines.push(current);
190 }
191
192 if lines.is_empty() {
193 lines.push(String::new());
194 }
195 lines
196}
197
198fn split_long_word(word: &str, max_cols: usize) -> Vec<String> {
199 let mut chunks = Vec::new();
200 let mut chunk = String::new();
201 for ch in word.chars() {
202 if chunk.chars().count() >= max_cols {
203 chunks.push(std::mem::take(&mut chunk));
204 }
205 chunk.push(ch);
206 }
207 if !chunk.is_empty() {
208 chunks.push(chunk);
209 }
210 chunks
211}
212
213#[cfg(test)]
214mod tests {
215 use super::*;
216
217 fn meta_53mm() -> PosMetadata {
218 PosMetadata {
219 page_width_mm: 53.0,
220 ..Default::default()
221 }
222 }
223
224 #[test]
225 fn heading1_wraps_at_half_line_width() {
226 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Heading1);
227 assert_eq!(cols, 16);
228 let lines = wrap_text("Proof of Transfer", cols);
229 assert_eq!(lines, vec!["Proof of", "Transfer"]);
230 }
231
232 #[test]
233 fn preserves_explicit_newlines() {
234 let lines = wrap_text("Line one\nLine two", 32);
235 assert_eq!(lines, vec!["Line one", "Line two"]);
236 }
237
238 #[test]
239 fn normal_text_wraps_at_full_width() {
240 let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal);
241 assert_eq!(cols, 32);
242 }
243
244 #[test]
245 fn bullet_wrap_uses_hanging_indent() {
246 let lines = wrap_bullet_item("this is a long line", 15);
247 assert_eq!(lines, vec!["* this is a", " long line"]);
248 }
249
250 #[test]
251 fn nested_bullet_uses_dash_and_indent() {
252 let lines = wrap_bullet_item_at_depth("this is a long line", 16, 1);
253 assert_eq!(lines, vec![" - this is a", " long line"]);
254 }
255
256 #[test]
257 fn hanging_wrap_hard_breaks_url_without_hanging() {
258 let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88";
259 let lines = wrap_bullet_item(url, 32);
260 assert!(lines.len() >= 2, "expected hard-break into multiple lines: {lines:?}");
261 assert!(lines[0].starts_with("* https://"));
262 let joined: String = lines
263 .iter()
264 .map(|l| {
265 l.strip_prefix("* ")
266 .or_else(|| l.strip_prefix(" "))
267 .unwrap_or(l)
268 })
269 .collect();
270 assert_eq!(joined, url);
271 }
272
273 #[test]
274 fn plain_wrap_hard_breaks_url() {
275 let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88";
276 let lines = wrap_text(url, 32);
277 assert!(lines.len() >= 2);
278 assert_eq!(lines.concat(), url);
279 }
280}