From cf5157c3cf46103849ededaaeffb1646dd39a6eb Mon Sep 17 00:00:00 2001 From: Simon Bruder Date: Fri, 19 Jul 2024 18:02:03 +0200 Subject: [PATCH] label: Add text wrapping --- src/label/mod.rs | 38 +++++++++++++++++++++++++++++++------- src/label/preset.rs | 9 +++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/label/mod.rs b/src/label/mod.rs index 5cdeef3..941451c 100644 --- a/src/label/mod.rs +++ b/src/label/mod.rs @@ -124,6 +124,7 @@ impl Code128Config { pub struct TextConfig { font_size: f32, position: (Mm, Mm), + wrap: Option, } impl TextConfig { @@ -133,15 +134,38 @@ impl TextConfig { font: &IndirectFontRef, text: Option, ) -> Result<()> { - layer.use_text( - text.ok_or(Error::DataIncomplete("ID text".to_string()))?, - self.font_size, - self.position.0, - self.position.1, - font, - ); + layer.begin_text_section(); + layer.set_font(font, self.font_size); + layer.set_line_height(self.font_size); + layer.set_text_cursor(self.position.0, self.position.1); + if let Some(text) = self.wrap(text) { + for line in text.split('\n') { + layer.write_text(line, font); + layer.add_line_break(); + } + } else { + return Err(Error::DataIncomplete("ID text".to_string())); + } + layer.end_text_section(); Ok(()) } + + fn wrap>(&self, text: Option) -> Option { + if let Some(wrap) = self.wrap { + let mut inserted = 0; + text.map(|s| { + let s = s.into(); + let mut chars: Vec = s.chars().collect(); + for i in (wrap..s.len()).step_by(wrap) { + chars.insert(i + inserted, '\n'); + inserted += 1; + } + chars.iter().collect() + }) + } else { + text.map(|s| s.into()) + } + } } #[derive(Debug)] diff --git a/src/label/preset.rs b/src/label/preset.rs index 033d8f8..3093686 100644 --- a/src/label/preset.rs +++ b/src/label/preset.rs @@ -53,14 +53,17 @@ impl Into for LabelPreset { id_text: Some(TextConfig { font_size: 7.0, position: (Mm(0.0), Mm(22.0)), + wrap: None, }), short_id_text: Some(TextConfig { font_size: 7.0, position: (Mm(21.0), Mm(0.6)), + wrap: None, }), branding: Some(TextConfig { font_size: 7.0, position: (Mm(39.5), Mm(0.6)), + wrap: None, }), }, Self::SeikoSlpMrlCode128 => LabelConfig { @@ -74,14 +77,17 @@ impl Into for LabelPreset { id_text: Some(TextConfig { font_size: 7.0, position: (Mm(0.0), Mm(22.0)), + wrap: None, }), short_id_text: Some(TextConfig { font_size: 7.0, position: (Mm(0.0), Mm(0.0)), + wrap: None, }), branding: Some(TextConfig { font_size: 7.0, position: (Mm(39.5), Mm(0.6)), + wrap: None, }), }, Self::SeikoSlpMrl => LabelConfig { @@ -98,14 +104,17 @@ impl Into for LabelPreset { id_text: Some(TextConfig { font_size: 7.0, position: (Mm(0.0), Mm(22.0)), + wrap: None, }), short_id_text: Some(TextConfig { font_size: 7.0, position: (Mm(17.0), Mm(0.0)), + wrap: None, }), branding: Some(TextConfig { font_size: 7.0, position: (Mm(39.5), Mm(0.6)), + wrap: None, }), }, }