Skip to main content

mln_engine/text/
tagged_string.rs

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
13/// The index of a section of a [`TaggedString`]. A label in the device's
14/// fonts takes a section for each word and each space.
15pub type SectionIndex = u16;
16
17/// Text as characters, with the index of each character's section. `text`
18/// and `styles` are equally long.
19#[derive(Clone, Debug, Default, PartialEq)]
20pub struct StyledText {
21    pub text: Vec<char>,
22    pub styles: Vec<SectionIndex>,
23}
24
25/// What the text of a shaped section holds for each of its glyphs: U+FFFC
26/// OBJECT REPLACEMENT CHARACTER.
27pub(crate) const SHAPED_GLYPH: char = '\u{FFFC}';
28
29pub(crate) type FontStackHash = u64;
30
31/// A key for a font stack in the glyph maps: [`std::hash`] of its font
32/// names. Every thread and worker of one build computes the same key.
33#[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/// The options of a section of a [`TaggedString`]: a run of text in one
41/// font stack and style, or an inline image.
42#[derive(Clone, Debug)]
43pub struct SectionOptions {
44    /// The section's font size, relative to the label's `text-size`.
45    pub scale: f32,
46    pub font_stack: FontStack,
47    pub(crate) font_stack_hash: FontStackHash,
48    pub type_: GlyphIDType,
49    /// The glyphs of a section that a font face shaped. The section's text
50    /// holds a [`SHAPED_GLYPH`] for each.
51    pub(crate) shaped: Option<Arc<ShapedText>>,
52    /// Whether the section is the last of a section of the style's
53    /// `format` expression, rather than one of the runs it splits into.
54    pub key_section: bool,
55    /// Whether a section of text that a font shaped runs right to left.
56    /// Its glyphs are in visual order, so bidi reorders the section as one
57    /// block.
58    pub(crate) rtl: bool,
59    pub image_id: Option<String>,
60    pub text_color: Option<Color>,
61    /// Where the section sits in a horizontal line that's taller than it.
62    pub vertical_align: VerticalAlign,
63}
64
65impl SectionOptions {
66    /// The options of a key section of text, aligned to the bottom of its
67    /// line.
68    #[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    /// The options of an image section, which has no font stack.
85    #[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
96/// The characters that stand for inline images: the Private Use Area of the
97/// Basic Multilingual Plane, which leaves room for 6400 images in a label.
98const PUA_BEGIN: char = '\u{E000}';
99const PUA_END: char = '\u{F8FF}';
100
101/// A label's text, a character at a time, with each character's section, so
102/// that operations that rearrange characters, such as bidi, keep their
103/// formatting.
104#[derive(Clone, Debug, Default)]
105pub struct TaggedString {
106    styled_text: StyledText,
107    sections: Vec<SectionOptions>,
108    /// The character of the last image section, if any.
109    image_section_id: Option<char>,
110    /// The text that font faces shaped this text from, once they have.
111    unshaped_text: Option<Vec<char>>,
112}
113
114impl TaggedString {
115    /// `text` in one section.
116    #[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    /// The index of the section of the character at `index`. Panics when
148    /// out of range.
149    #[must_use]
150    pub fn section_index(&self, index: usize) -> SectionIndex {
151        self.styled_text.styles[index]
152    }
153
154    /// The section of the character at `index`. Panics when out of range.
155    #[must_use]
156    pub fn section_of(&self, index: usize) -> &SectionOptions {
157        &self.sections[usize::from(self.section_index(index))]
158    }
159
160    /// Appends `text` as a section with `options`.
161    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    /// Appends a section of glyphs that a font face shaped, in visual order,
168    /// from text that runs right to left if `rtl`.
169    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    /// Appends an inline image. A label holds at most 6400; it logs a
177    /// warning and drops any more.
178    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    /// Adds `options` as the section of the characters that have none yet.
188    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    /// Replaces punctuation drawn from glyph PBFs with its vertical forms,
195    /// where its neighbors allow.
196    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    /// Whether a character drawn from glyph PBFs stays upright in vertical
207    /// writing mode.
208    #[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    /// Whether font faces shaped the text: [`Self::set_unshaped_text`].
216    #[must_use]
217    pub fn is_shaped(&self) -> bool {
218        self.unshaped_text.is_some()
219    }
220
221    /// Marks the text as shaped by font faces from `text`, which the shaped
222    /// sections no longer hold.
223    pub fn set_unshaped_text(&mut self, text: Vec<char>) {
224        self.unshaped_text = Some(text);
225    }
226
227    /// What the text says, as characters: the text before font faces
228    /// shaped it, if they did. Labels with equal text compare equal.
229    #[must_use]
230    pub fn logical_text(&self) -> &[char] {
231        self.unshaped_text.as_deref().unwrap_or(&self.styled_text.text)
232    }
233
234    /// Whether a section draws from a font file, which shapes it, rather
235    /// than glyph PBFs.
236    #[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    // gtest: TaggedString.ImageSections
256    #[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}