use crate::io::PosMetadata; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TextWrapStyle { Normal, Heading1, Heading2, } /// Character columns available for a text style on the target printer. pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize { let base = metadata.chars_per_line().max(1) as usize; match style { TextWrapStyle::Heading1 => (base / 2).max(1), TextWrapStyle::Normal | TextWrapStyle::Heading2 => base, } } /// Word-wrap `text` to at most `max_cols` characters per line. /// Explicit newlines in `text` start a new wrapped paragraph. pub fn wrap_text(text: &str, max_cols: usize) -> Vec { if max_cols == 0 { return vec![text.to_string()]; } let mut lines = Vec::new(); for paragraph in text.split('\n') { lines.extend(wrap_line(paragraph, max_cols)); } if lines.is_empty() { lines.push(String::new()); } lines } fn wrap_line(line: &str, max_cols: usize) -> Vec { if line.is_empty() { return vec![String::new()]; } let mut lines = Vec::new(); let mut current = String::new(); for word in line.split_whitespace() { let word_len = word.chars().count(); if current.is_empty() { if word_len <= max_cols { current.push_str(word); } else { lines.extend(split_long_word(word, max_cols)); } } else { let current_len = current.chars().count(); if current_len + 1 + word_len <= max_cols { current.push(' '); current.push_str(word); } else { lines.push(std::mem::take(&mut current)); if word_len <= max_cols { current.push_str(word); } else { lines.extend(split_long_word(word, max_cols)); } } } } if !current.is_empty() { lines.push(current); } if lines.is_empty() { lines.push(String::new()); } lines } fn split_long_word(word: &str, max_cols: usize) -> Vec { let mut chunks = Vec::new(); let mut chunk = String::new(); for ch in word.chars() { if chunk.chars().count() >= max_cols { chunks.push(std::mem::take(&mut chunk)); } chunk.push(ch); } if !chunk.is_empty() { chunks.push(chunk); } chunks } #[cfg(test)] mod tests { use super::*; fn meta_53mm() -> PosMetadata { PosMetadata { page_width_mm: 53.0, ..Default::default() } } #[test] fn heading1_wraps_at_half_line_width() { let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Heading1); assert_eq!(cols, 16); let lines = wrap_text("Proof of Transfer", cols); assert_eq!(lines, vec!["Proof of", "Transfer"]); } #[test] fn preserves_explicit_newlines() { let lines = wrap_text("Line one\nLine two", 32); assert_eq!(lines, vec!["Line one", "Line two"]); } #[test] fn normal_text_wraps_at_full_width() { let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal); assert_eq!(cols, 32); } }