1use std::hash::{DefaultHasher, Hash, Hasher};
2use std::sync::Arc;
3
4use mln_style::color::Color;
5use mln_style::i18n;
6use mln_style::types::VerticalAlign;
7
8use crate::log_target;
9use crate::text::font_stack::FontStack;
10use crate::text::glyph::GlyphIDType;
11use crate::text::shaper::ShapedText;
12
13pub type SectionIndex = u16;
16
17#[derive(Clone, Debug, Default, PartialEq)]
20pub struct StyledText {
21 pub text: Vec<char>,
22 pub styles: Vec<SectionIndex>,
23}
24
25pub(crate) const SHAPED_GLYPH: char = '\u{FFFC}';
28
29pub(crate) type FontStackHash = u64;
30
31#[must_use]
34pub fn font_stack_hash(font_stack: &FontStack) -> FontStackHash {
35 let mut hasher = DefaultHasher::new();
36 font_stack.hash(&mut hasher);
37 hasher.finish()
38}
39
40#[derive(Clone, Debug)]
43pub struct SectionOptions {
44 pub(crate) scale: f32,
46 pub font_stack: FontStack,
47 pub(crate) font_stack_hash: FontStackHash,
48 pub type_: GlyphIDType,
49 pub(crate) shaped: Option<Arc<ShapedText>>,
52 pub key_section: bool,
55 pub(crate) rtl: bool,
59 pub image_id: Option<String>,
60 pub text_color: Option<Color>,
61 pub vertical_align: VerticalAlign,
63}
64
65impl SectionOptions {
66 #[must_use]
69 pub fn new(scale: f32, font_stack: FontStack, type_: GlyphIDType, text_color: Option<Color>) -> Self {
70 SectionOptions {
71 scale,
72 font_stack_hash: font_stack_hash(&font_stack),
73 font_stack,
74 type_,
75 shaped: None,
76 key_section: true,
77 rtl: false,
78 image_id: None,
79 text_color,
80 vertical_align: VerticalAlign::Bottom,
81 }
82 }
83
84 #[must_use]
86 fn image(image_id: String, vertical_align: VerticalAlign) -> Self {
87 SectionOptions {
88 image_id: Some(image_id),
89 vertical_align,
90 font_stack_hash: 0,
91 ..SectionOptions::new(1.0, FontStack::new(), GlyphIDType::FontPBF, None)
92 }
93 }
94}
95
96const PUA_BEGIN: char = '\u{E000}';
99const PUA_END: char = '\u{F8FF}';
100
101#[derive(Clone, Debug, Default)]
105pub struct TaggedString {
106 styled_text: StyledText,
107 sections: Vec<SectionOptions>,
108 image_section_id: Option<char>,
110 unshaped_text: Option<Vec<char>>,
112}
113
114impl TaggedString {
115 #[must_use]
117 pub fn new(text: Vec<char>, options: SectionOptions) -> Self {
118 let styles = vec![0; text.len()];
119 TaggedString { styled_text: StyledText { text, styles }, sections: vec![options], ..Default::default() }
120 }
121
122 #[must_use]
123 pub fn len(&self) -> usize {
124 self.styled_text.text.len()
125 }
126
127 #[must_use]
128 pub fn is_empty(&self) -> bool {
129 self.styled_text.text.is_empty()
130 }
131
132 #[must_use]
133 pub fn text(&self) -> &[char] {
134 &self.styled_text.text
135 }
136
137 #[must_use]
138 pub fn styled_text(&self) -> &StyledText {
139 &self.styled_text
140 }
141
142 #[must_use]
143 pub fn sections(&self) -> &[SectionOptions] {
144 &self.sections
145 }
146
147 #[must_use]
150 pub fn section_index(&self, index: usize) -> SectionIndex {
151 self.styled_text.styles[index]
152 }
153
154 #[must_use]
156 pub(crate) fn section_of(&self, index: usize) -> &SectionOptions {
157 &self.sections[usize::from(self.section_index(index))]
158 }
159
160 pub fn add_text_section(&mut self, text: &[char], options: SectionOptions) {
162 debug_assert!(options.shaped.is_none() && options.image_id.is_none());
163 self.styled_text.text.extend_from_slice(text);
164 self.push_section(options);
165 }
166
167 pub fn add_shaped_section(&mut self, shaped: &Arc<ShapedText>, rtl: bool, options: SectionOptions) {
170 debug_assert!(options.image_id.is_none());
171 let len = self.styled_text.text.len() + shaped.glyphs.len();
172 self.styled_text.text.resize(len, SHAPED_GLYPH);
173 self.push_section(SectionOptions { shaped: Some(Arc::clone(shaped)), rtl, ..options });
174 }
175
176 pub fn add_image_section(&mut self, image_id: &str, vertical_align: VerticalAlign) {
179 let Some(next) = self.next_image_char() else {
180 log::warn!(target: log_target::STYLE, "Exceeded maximum number of images in a label.");
181 return;
182 };
183 self.styled_text.text.push(next);
184 self.push_section(SectionOptions::image(image_id.to_string(), vertical_align));
185 }
186
187 fn push_section(&mut self, options: SectionOptions) {
189 let index = self.sections.len() as SectionIndex;
190 self.sections.push(options);
191 self.styled_text.styles.resize(self.styled_text.text.len(), index);
192 }
193
194 pub fn verticalize_punctuation(&mut self) {
197 let vertical = i18n::verticalize_punctuation_str(&self.styled_text.text);
198 let StyledText { text, styles } = &mut self.styled_text;
199 for ((c, vertical), &style) in text.iter_mut().zip(vertical).zip(styles.iter()) {
200 if self.sections[usize::from(style)].type_ == GlyphIDType::FontPBF {
201 *c = vertical;
202 }
203 }
204 }
205
206 #[must_use]
209 pub fn allows_vertical_writing_mode(&self) -> bool {
210 self.styled_text.text.iter().zip(&self.styled_text.styles).any(|(&c, &style)| {
211 self.sections[usize::from(style)].type_ == GlyphIDType::FontPBF && i18n::has_upright_vertical_orientation(c)
212 })
213 }
214
215 #[must_use]
217 pub fn is_shaped(&self) -> bool {
218 self.unshaped_text.is_some()
219 }
220
221 pub fn set_unshaped_text(&mut self, text: Vec<char>) {
224 self.unshaped_text = Some(text);
225 }
226
227 #[must_use]
230 pub fn logical_text(&self) -> &[char] {
231 self.unshaped_text.as_deref().unwrap_or(&self.styled_text.text)
232 }
233
234 #[must_use]
237 pub fn has_font_sections(&self) -> bool {
238 self.sections.iter().any(|section| section.type_ != GlyphIDType::FontPBF)
239 }
240
241 fn next_image_char(&mut self) -> Option<char> {
242 let next = match self.image_section_id {
243 None => PUA_BEGIN,
244 Some(last) => char::from_u32(u32::from(last) + 1).filter(|&next| next <= PUA_END)?,
245 };
246 self.image_section_id = Some(next);
247 Some(next)
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 #[test]
257 fn image_sections() {
258 let mut string = TaggedString::default();
259 string.add_image_section("image_name", VerticalAlign::Bottom);
260 assert_eq!(string.text(), ['\u{E000}']);
261 assert_eq!(string.section_of(0).image_id.as_deref(), Some("image_name"));
262
263 let mut max_sections = TaggedString::default();
264 for i in 0..6401 {
265 max_sections.add_image_section(&i.to_string(), VerticalAlign::Bottom);
266 }
267
268 assert_eq!(max_sections.sections().len(), 6400);
269 assert_eq!(max_sections.text()[0], '\u{E000}');
270 assert_eq!(max_sections.text()[6399], '\u{F8FF}');
271 }
272
273 #[test]
274 fn verticalizes_only_glyph_pbf_punctuation() {
275 let face = crate::text::glyph::face_type("tagged-string-test", "font", &[(0, 0xFFFF)]);
276 let mut string = TaggedString::default();
277 string.add_text_section(&['-'], SectionOptions::new(1.0, vec![], GlyphIDType::FontPBF, None));
278 string.add_text_section(&['-'], SectionOptions::new(1.0, vec![], face, None));
279 string.verticalize_punctuation();
280 assert_eq!(string.text(), ['\u{FE32}', '-']);
281 }
282
283 #[test]
284 fn font_stack_hash_tells_stacks_apart() {
285 let stack = |fonts: &[&str]| fonts.iter().map(|f| (*f).to_string()).collect::<FontStack>();
286 assert_eq!(font_stack_hash(&stack(&["Open Sans", "Arial"])), font_stack_hash(&stack(&["Open Sans", "Arial"])));
287 assert_ne!(font_stack_hash(&stack(&["Open Sans", "Arial"])), font_stack_hash(&stack(&["Arial", "Open Sans"])));
288 assert_ne!(font_stack_hash(&stack(&["a", "b"])), font_stack_hash(&stack(&["ab"])));
289 assert_ne!(font_stack_hash(&stack(&["a", "b"])), font_stack_hash(&stack(&["a", "b", ""])));
290 }
291}