Skip to main content

mln_engine/text/
shaping.rs

1//! Label shaping: breaking a label into lines, placing each line's glyphs
2//! and inline images, and aligning the lines on the label's anchor.
3//!
4//! Positions are in pixels at a font size of `ONE_EM`, with y down.
5
6use std::ops::Range;
7
8use glam::Vec2;
9use mln_style::i18n;
10use mln_style::image::TextFit;
11use mln_style::padding::Padding;
12use mln_style::types::{IconTextFitType, SymbolAnchorType, TextJustifyType, TextWritingModeType, VerticalAlign};
13use mln_vec_map::VecSet;
14
15use crate::text::atlas::{ImagePosition, ImagePositions};
16use crate::text::bidi;
17use crate::text::constants::ONE_EM;
18use crate::text::glyph::{
19    Bounds, Glyph, GlyphID, GlyphIDType, GlyphMetrics, GlyphPositions, PositionedGlyph, PositionedLine, Shaping,
20    pbf_code,
21};
22use crate::text::line_breaks::determine_line_breaks;
23use crate::text::shaper::GlyphAdjust;
24use crate::text::tagged_string::{SectionIndex, SectionOptions, StyledText, TaggedString};
25
26/// How [`shape_text`] lays out a label.
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct ShapingOptions {
29    /// The width that lines break at where they can; 0 keeps the text on
30    /// one line.
31    pub max_width: f32,
32    /// The distance between lines of `ONE_EM` glyphs.
33    pub line_height: f32,
34    /// The point of the text that sits on the anchor.
35    pub anchor: SymbolAnchorType,
36    /// Which side lines align on; `Auto` centers them.
37    pub justify: TextJustifyType,
38    /// The space after each glyph that advances the pen.
39    pub spacing: f32,
40    /// How far the text's bounds move from the anchor.
41    pub offset: [f32; 2],
42    pub writing_mode: TextWritingModeType,
43    /// Whether the layer places labels vertically (`text-writing-mode`). In
44    /// vertical text, every glyph but whitespace and complex scripts then
45    /// stands upright; otherwise, as in a line label along a vertical line,
46    /// only the characters that stay upright in vertical writing do, with
47    /// runs of digits and short uppercase codes.
48    pub allow_vertical_placement: bool,
49    /// The text size that line breaking measures inline images at.
50    pub text_size: f32,
51    /// The text size that inline images scale against, at the bucket's zoom.
52    pub text_size_at_bucket_zoom: f32,
53}
54
55/// Where `anchor` sits on a box: the fraction of the box's width left of the
56/// anchor, and of its height above it.
57#[must_use]
58pub fn anchor_alignment(anchor: SymbolAnchorType) -> Vec2 {
59    use SymbolAnchorType as A;
60    let x = match anchor {
61        A::Left | A::TopLeft | A::BottomLeft => 0.0,
62        A::Right | A::TopRight | A::BottomRight => 1.0,
63        A::Center | A::Top | A::Bottom => 0.5,
64    };
65    let y = match anchor {
66        A::Top | A::TopLeft | A::TopRight => 0.0,
67        A::Bottom | A::BottomLeft | A::BottomRight => 1.0,
68        A::Center | A::Left | A::Right => 0.5,
69    };
70    Vec2::new(x, y)
71}
72
73/// The justification that aligns lines on the side of the text that
74/// `anchor` is on.
75#[must_use]
76pub fn anchor_justification(anchor: SymbolAnchorType) -> TextJustifyType {
77    use SymbolAnchorType as A;
78    match anchor {
79        A::Right | A::TopRight | A::BottomRight => TextJustifyType::Right,
80        A::Left | A::TopLeft | A::BottomLeft => TextJustifyType::Left,
81        A::Center | A::Top | A::Bottom => TextJustifyType::Center,
82    }
83}
84
85/// The fraction of a line's width that `justify` moves it left by.
86fn justify_factor(justify: TextJustifyType) -> f32 {
87    match justify {
88        TextJustifyType::Left => 0.0,
89        TextJustifyType::Right => 1.0,
90        TextJustifyType::Center | TextJustifyType::Auto => 0.5,
91    }
92}
93
94/// An icon placed around its anchor.
95#[derive(Clone, Debug, PartialEq)]
96pub struct PositionedIcon {
97    pub image: ImagePosition,
98    pub bounds: Bounds,
99    /// How far in from each edge of the image its content starts, where
100    /// the image has content; collisions count only the content.
101    pub collision_padding: Padding,
102}
103
104impl PositionedIcon {
105    /// `image` offset by `offset`, with `anchor` on the anchor.
106    #[must_use]
107    pub fn new(image: &ImagePosition, offset: [f32; 2], anchor: SymbolAnchorType) -> Self {
108        let size = Vec2::from(image.display_size());
109        let top_left = Vec2::from(offset) - size * anchor_alignment(anchor);
110        let bounds =
111            Bounds { left: top_left.x, top: top_left.y, right: top_left.x + size.x, bottom: top_left.y + size.y };
112
113        let collision_padding = image.content.map_or_else(Padding::default, |content| {
114            let pixel_ratio = image.pixel_ratio;
115            Padding {
116                top: content.top / pixel_ratio,
117                right: size.x - content.right / pixel_ratio,
118                bottom: size.y - content.bottom / pixel_ratio,
119                left: content.left / pixel_ratio,
120            }
121        });
122
123        PositionedIcon { image: image.clone(), bounds, collision_padding }
124    }
125
126    /// Fits the icon to `text` (`icon-text-fit`), drawn at `font_scale`:
127    /// stretched to the text's size plus `padding` (top, right, bottom,
128    /// left) in the dimensions `fit` names, and centered on the text in the
129    /// others, then offset by `offset`. It ignores `icon-anchor`.
130    pub fn fit_to_text(
131        &mut self,
132        text: &Shaping,
133        fit: IconTextFitType,
134        padding: [f32; 4],
135        offset: [f32; 2],
136        font_scale: f32,
137    ) {
138        debug_assert_ne!(fit, IconTextFitType::None);
139        debug_assert!(!text.is_empty());
140        let [width, height] = self.image.display_size();
141        let [top_padding, right_padding, bottom_padding, left_padding] = padding;
142        let text_bounds = text.bounds;
143
144        let (text_left, text_right) = (text_bounds.left * font_scale, text_bounds.right * font_scale);
145        if matches!(fit, IconTextFitType::Width | IconTextFitType::Both) {
146            self.bounds.left = offset[0] + text_left - left_padding;
147            self.bounds.right = offset[0] + text_right + right_padding;
148        } else {
149            self.bounds.left = offset[0] + (text_left + text_right - width) / 2.0;
150            self.bounds.right = self.bounds.left + width;
151        }
152
153        let (text_top, text_bottom) = (text_bounds.top * font_scale, text_bounds.bottom * font_scale);
154        if matches!(fit, IconTextFitType::Height | IconTextFitType::Both) {
155            self.bounds.top = offset[1] + text_top - top_padding;
156            self.bounds.bottom = offset[1] + text_bottom + bottom_padding;
157        } else {
158            self.bounds.top = offset[1] + (text_top + text_bottom - height) / 2.0;
159            self.bounds.bottom = self.bounds.top + height;
160        }
161    }
162
163    /// The bounds of an icon fitted to its text, widened or heightened to
164    /// keep its content's aspect ratio where the image's `textFitWidth` or
165    /// `textFitHeight` asks for it. Other icons keep their bounds.
166    #[must_use]
167    pub fn text_fit_bounds(&self) -> Bounds {
168        let mut bounds = self.bounds;
169        let Some(content) = self.image.content else {
170            return bounds;
171        };
172        if self.image.text_fit_width.is_none() && self.image.text_fit_height.is_none() {
173            return bounds;
174        }
175        // The style spec's default for both.
176        let fit_width = self.image.text_fit_width.unwrap_or(TextFit::StretchOrShrink);
177        let fit_height = self.image.text_fit_height.unwrap_or(TextFit::StretchOrShrink);
178        let (width, height) = (bounds.width(), bounds.height());
179        let content_aspect_ratio = (content.right - content.left) / (content.bottom - content.top);
180
181        if fit_height == TextFit::Proportional {
182            if fit_width == TextFit::Proportional
183                || (fit_width == TextFit::StretchOnly && width / height < content_aspect_ratio)
184            {
185                let new_width = (height * content_aspect_ratio).ceil();
186                bounds.left *= new_width / width;
187                bounds.right = bounds.left + new_width;
188            }
189        } else if fit_width == TextFit::Proportional
190            && fit_height == TextFit::StretchOnly
191            && content_aspect_ratio != 0.0
192            && width / height > content_aspect_ratio
193        {
194            let new_height = (width / content_aspect_ratio).ceil();
195            bounds.top *= new_height / height;
196            bounds.bottom = bounds.top + new_height;
197        }
198        // Where neither is proportional, the icon already fits the content.
199        bounds
200    }
201}
202
203/// A line of a label, or the whole label: its characters and their
204/// sections.
205#[derive(Clone, Copy)]
206struct Line<'a> {
207    text: &'a [char],
208    styles: &'a [SectionIndex],
209    sections: &'a [SectionOptions],
210}
211
212/// A character of a [`Line`].
213struct LineChar<'a> {
214    c: char,
215    section_index: usize,
216    section: &'a SectionOptions,
217    /// The glyph that draws it: its glyph PBF glyph, or its glyph of a
218    /// section that a font face shaped. `None` for a character beyond the
219    /// BMP, or past the glyphs of its shaping.
220    glyph: Option<GlyphID>,
221    /// Where a font face's shaping places the glyph.
222    adjust: Option<GlyphAdjust>,
223}
224
225/// `" \t\n\v\f\r"`, which lines don't start or end with.
226fn is_trim_whitespace(c: char) -> bool {
227    matches!(c, ' ' | '\t' | '\n' | '\u{0B}' | '\u{0C}' | '\r')
228}
229
230impl<'a> Line<'a> {
231    fn new(text: &'a StyledText, sections: &'a [SectionOptions]) -> Self {
232        Line { text: &text.text, styles: &text.styles, sections }
233    }
234
235    fn len(&self) -> usize {
236        self.text.len()
237    }
238
239    fn is_empty(&self) -> bool {
240        self.text.is_empty()
241    }
242
243    fn section(&self, index: usize) -> &'a SectionOptions {
244        &self.sections[usize::from(self.styles[index])]
245    }
246
247    fn slice(self, range: Range<usize>) -> Self {
248        Line { text: &self.text[range.clone()], styles: &self.styles[range], sections: self.sections }
249    }
250
251    /// The line without leading and trailing whitespace, but for that of
252    /// sections drawn from font files.
253    fn trimmed(self) -> Self {
254        let keep = |i: usize| !is_trim_whitespace(self.text[i]) || self.section(i).type_ != GlyphIDType::FontPBF;
255        let Some(start) = (0..self.len()).find(|&i| keep(i)) else {
256            return self.slice(0..0);
257        };
258        let end = (start..self.len()).rfind(|&i| keep(i)).map_or(start, |i| i + 1);
259        self.slice(start..end)
260    }
261
262    /// The largest scale of a section of the line's characters.
263    fn max_scale(&self) -> f32 {
264        self.styles.iter().map(|&style| self.sections[usize::from(style)].scale).fold(0.0, f32::max)
265    }
266
267    fn chars(self) -> impl Iterator<Item = LineChar<'a>> {
268        // A shaped section's glyphs are contiguous, from its first character.
269        let mut section_start = 0;
270        (0..self.len()).map(move |i| {
271            let section_index = usize::from(self.styles[i]);
272            if i > 0 && self.styles[i - 1] != self.styles[i] {
273                section_start = i;
274            }
275            let section = &self.sections[section_index];
276            let c = self.text[i];
277            let (glyph, adjust) = match &section.shaped {
278                Some(shaped) => {
279                    let offset = i - section_start;
280                    (shaped.glyphs.get(offset).copied(), shaped.adjusts.get(offset).copied())
281                }
282                None => (GlyphID::from_char(c), None),
283            };
284            LineChar { c, section_index, section, glyph, adjust }
285        })
286    }
287}
288
289/// How far each character of `text` moves the pen: a shaped glyph by its
290/// shaping, a glyph PBF glyph or an image by its size, with `spacing`.
291pub(crate) fn glyph_advances<'a>(
292    text: &'a TaggedString,
293    spacing: f32,
294    glyphs: &'a GlyphPositions,
295    images: &'a ImagePositions,
296    text_size: f32,
297) -> impl Iterator<Item = f32> + 'a {
298    Line::new(text.styled_text(), text.sections()).chars().map(move |c| {
299        let section = c.section;
300        if section.shaped.is_some() {
301            // A glyph without an advance takes no spacing either.
302            let advance = c.adjust.map_or(0.0, |adjust| adjust.advance);
303            return if advance > 0.01 { advance * section.scale + spacing } else { 0.0 };
304        }
305        match &section.image_id {
306            None => match c.glyph.and_then(|glyph| glyphs.get(&section.font_stack_hash)?.get(&glyph)) {
307                Some(Some(glyph)) => glyph.metrics.advance as f32 * section.scale + spacing,
308                _ => 0.0,
309            },
310            Some(image_id) => images
311                .get(image_id)
312                .map_or(0.0, |image| image.display_size()[0] * section.scale * ONE_EM / text_size + spacing),
313        }
314    })
315}
316
317/// The room a line's content takes across the line: its largest glyph or
318/// image.
319struct LineContentSize {
320    /// The height of a horizontal line.
321    horizontal_height: f32,
322    /// The width of a vertical line.
323    vertical_width: f32,
324}
325
326impl LineContentSize {
327    fn new(line: Line<'_>, images: &ImagePositions, text_size: f32, max_scale: f32) -> Self {
328        let max_glyph_size = max_scale * ONE_EM;
329        let image_scale = ONE_EM / text_size;
330        let (mut max_width, mut max_height) = (0.0_f32, 0.0_f32);
331        for i in 0..line.len() {
332            if let Some(image) = line.section(i).image_id.as_ref().and_then(|id| images.get(id)) {
333                let [width, height] = image.display_size();
334                max_width = max_width.max(width);
335                max_height = max_height.max(height);
336            }
337        }
338        LineContentSize {
339            horizontal_height: max_glyph_size.max(max_height * image_scale),
340            vertical_width: max_glyph_size.max(max_width * image_scale),
341        }
342    }
343
344    /// How far below the line's top a section `size` tall starts. A vertical
345    /// glyph ignores `vertical_align`, as in GL JS.
346    fn baseline_offset(&self, size: f32, vertical: bool, vertical_align: VerticalAlign) -> f32 {
347        if vertical {
348            return self.vertical_width - size;
349        }
350        let factor = match vertical_align {
351            VerticalAlign::Top => 0.0,
352            VerticalAlign::Center => 0.5,
353            VerticalAlign::Bottom => 1.0,
354        };
355        (self.horizontal_height - size) * factor
356    }
357}
358
359const MAX_UPRIGHT_LETTER_RUN: usize = 3;
360
361/// Whether a run of characters that turn with a vertical line stands upright
362/// instead: a number, or a short code such as "JR" or "A1". Longer uppercase
363/// runs are words.
364fn run_is_upright(run: &[char]) -> bool {
365    let is_number = run.iter().any(|&c| i18n::is_digit(c))
366        && run.iter().all(|&c| i18n::is_digit(c) || i18n::is_punctuation_or_symbol(c));
367    let is_short_code =
368        run.len() <= MAX_UPRIGHT_LETTER_RUN && run.iter().all(|&c| i18n::is_digit(c) || i18n::is_uppercase(c));
369    is_number || is_short_code
370}
371
372/// Which characters of `line` stand upright in a vertical line: those that
373/// stay upright in vertical writing, the digits and uppercase letters of
374/// runs that [`run_is_upright`], and punctuation between upright characters,
375/// which takes its vertical form. Keeps words and combining marks together;
376/// images and sections drawn from font files delimit runs.
377fn upright_characters(line: Line<'_>) -> Vec<bool> {
378    let text = line.text;
379    let is_text = |i: usize| {
380        let section = line.section(i);
381        section.type_ == GlyphIDType::FontPBF && section.image_id.is_none()
382    };
383    let mut upright: Vec<bool> =
384        (0..line.len()).map(|i| is_text(i) && i18n::has_upright_vertical_orientation(text[i])).collect();
385
386    let in_run = |upright: &[bool], i: usize| is_text(i) && !upright[i] && !i18n::is_whitespace(text[i]);
387    let mut start = 0;
388    while start < line.len() {
389        if !in_run(&upright, start) {
390            start += 1;
391            continue;
392        }
393        let end = (start + 1..line.len()).find(|&i| !in_run(&upright, i)).unwrap_or(line.len());
394        if run_is_upright(&text[start..end]) {
395            for i in start..end {
396                let c = text[i];
397                upright[i] =
398                    (i18n::is_uppercase(c) || i18n::is_digit(c)) && !i18n::is_char_in_complex_shaping_script(c);
399            }
400        }
401        start = end;
402    }
403
404    for i in 0..line.len() {
405        if !upright[i]
406            && is_text(i)
407            && i18n::verticalize_punctuation(text[i]).is_some()
408            && (i == 0 || upright[i - 1])
409            && upright.get(i + 1).is_none_or(|&next| next)
410        {
411            upright[i] = true;
412        }
413    }
414    upright
415}
416
417/// Moves a line's glyphs left by `justify` of its width.
418fn justify_line(glyphs: &mut [PositionedGlyph], justify: f32) {
419    if justify == 0.0 {
420        return;
421    }
422    let Some(last) = glyphs.last() else { return };
423    let indent = (last.x + last.metrics.advance as f32 * last.scale) * justify;
424    for glyph in glyphs {
425        glyph.x -= indent;
426    }
427}
428
429/// Places the glyphs of a label's lines.
430struct LineShaper<'a> {
431    options: &'a ShapingOptions,
432    glyphs: &'a GlyphPositions,
433    images: &'a ImagePositions,
434}
435
436/// A line's glyphs, placed.
437struct ShapedLine {
438    glyphs: Vec<PositionedGlyph>,
439    /// Where the pen ends up.
440    end_x: f32,
441    /// How far an inline image reaches below a line of the line's largest
442    /// scale.
443    image_overflow: f32,
444}
445
446impl LineShaper<'_> {
447    /// Places the glyphs of `line`, which isn't empty, on a line at `y`.
448    fn shape_line(&self, line: Line<'_>, y: f32, max_scale: f32) -> ShapedLine {
449        let options = self.options;
450        let spacing = options.spacing;
451        let content = LineContentSize::new(line, self.images, options.text_size_at_bucket_zoom, max_scale);
452        let vertical_text = options.writing_mode == TextWritingModeType::Vertical;
453        let upright = (vertical_text && !options.allow_vertical_placement).then(|| upright_characters(line));
454
455        let mut glyphs = Vec::with_capacity(line.len());
456        let mut x = 0.0;
457        let mut image_overflow = 0.0_f32;
458        for (i, c) in line.chars().enumerate() {
459            let Some(mut glyph) = c.glyph else { continue };
460            let section = c.section;
461            let vertical = match &upright {
462                Some(upright) => upright[i],
463                None => {
464                    vertical_text
465                        && glyph.type_ == GlyphIDType::FontPBF
466                        && if options.allow_vertical_placement {
467                            !i18n::is_whitespace(c.c) && !i18n::is_char_in_complex_shaping_script(c.c)
468                        } else {
469                            i18n::has_upright_vertical_orientation(c.c)
470                        }
471                }
472            };
473            // Punctuation that stands upright among upright characters takes
474            // its vertical form.
475            if upright.is_some()
476                && vertical
477                && !i18n::has_upright_vertical_orientation(c.c)
478                && let Some(form) = i18n::verticalize_punctuation(c.c).and_then(pbf_code)
479            {
480                glyph = GlyphID::with_type(form, section.type_);
481            }
482
483            let (rect, metrics, scale, baseline_offset, advance, vertical_advance, offset);
484            match &section.image_id {
485                None => {
486                    let Some(Some(position)) =
487                        self.glyphs.get(&section.font_stack_hash).and_then(|glyphs| glyphs.get(&glyph))
488                    else {
489                        continue;
490                    };
491                    rect = position.rect;
492                    metrics = position.metrics;
493                    scale = section.scale;
494                    let mut glyph_offset = Vec2::ZERO;
495                    advance = match c.adjust {
496                        Some(adjust) => {
497                            glyph_offset = Vec2::new(adjust.x_offset, adjust.y_offset) * scale;
498                            adjust.advance
499                        }
500                        None => metrics.advance as f32,
501                    };
502                    // A glyph without an advance, such as a combining mark,
503                    // aligns to the glyph before it, without its spacing.
504                    if advance < 0.01 {
505                        glyph_offset.x -= spacing;
506                    }
507                    offset = glyph_offset;
508                    baseline_offset = content.baseline_offset(scale * ONE_EM, vertical, section.vertical_align);
509                    vertical_advance = ONE_EM;
510                }
511                Some(image_id) => {
512                    let Some(image) = self.images.get(image_id) else {
513                        continue;
514                    };
515                    let [width, height] = image.display_size();
516                    // An image narrower than its padding has no size.
517                    let (pixel_width, pixel_height) = (width as u32, height as u32);
518                    metrics = GlyphMetrics {
519                        width: pixel_width,
520                        height: pixel_height,
521                        left: f32::from(ImagePosition::PADDING),
522                        top: -f32::from(Glyph::BORDER_SIZE),
523                        advance: if vertical { pixel_height } else { pixel_width },
524                        is_double_resolution: false,
525                    };
526                    rect = image.padded_rect;
527                    scale = section.scale * ONE_EM / options.text_size_at_bucket_zoom;
528                    baseline_offset = content.baseline_offset(height * scale, vertical, section.vertical_align);
529                    advance = metrics.advance as f32;
530                    vertical_advance = advance;
531                    offset = Vec2::ZERO;
532                    // An image taller than an em at the line's largest scale
533                    // pushes the line down.
534                    image_overflow =
535                        image_overflow.max((if vertical { width } else { height }) * scale - ONE_EM * max_scale);
536                }
537            }
538
539            let position = if vertical { Vec2::ZERO } else { offset } + Vec2::new(x, y + baseline_offset);
540            glyphs.push(PositionedGlyph {
541                glyph,
542                x: position.x,
543                y: position.y,
544                vertical,
545                scale,
546                rect,
547                metrics,
548                image_id: section.image_id.clone(),
549                section_index: c.section_index,
550            });
551            if vertical {
552                x += vertical_advance * scale + spacing;
553            } else if advance > 0.01 {
554                x += advance * scale + spacing;
555            }
556        }
557        ShapedLine { glyphs, end_x: x, image_overflow }
558    }
559}
560
561/// Places the glyphs of `lines` and aligns them on the anchor.
562fn shape_lines(
563    lines: &[StyledText],
564    sections: &[SectionOptions],
565    options: &ShapingOptions,
566    glyphs: &GlyphPositions,
567    images: &ImagePositions,
568) -> Shaping {
569    let shaper = LineShaper { options, glyphs, images };
570    let justify = justify_factor(options.justify);
571    let mut positioned_lines = Vec::with_capacity(lines.len());
572    let mut y = Shaping::Y_OFFSET;
573    let mut max_line_length = 0.0_f32;
574    let mut max_line_height = 0.0_f32;
575
576    for line in lines {
577        // Whitespace at a line's ends would throw off its justification.
578        let line = Line::new(line, sections).trimmed();
579        if line.is_empty() {
580            positioned_lines.push(PositionedLine::default());
581            y += options.line_height;
582            continue;
583        }
584
585        let max_scale = line.max_scale();
586        let ShapedLine { glyphs: mut line_glyphs, end_x, image_overflow } = shaper.shape_line(line, y, max_scale);
587        if !line_glyphs.is_empty() {
588            // Not counting the spacing after the last glyph.
589            max_line_length = max_line_length.max(end_x - options.spacing);
590            justify_line(&mut line_glyphs, justify);
591        }
592
593        let line_height = options.line_height * max_scale + image_overflow;
594        y += line_height;
595        max_line_height = max_line_height.max(line_height);
596        let line_offset = image_overflow.max((max_scale - 1.0) * ONE_EM);
597        positioned_lines.push(PositionedLine { glyphs: line_glyphs, line_offset });
598    }
599
600    let alignment = anchor_alignment(options.anchor);
601    let height = y - Shaping::Y_OFFSET;
602    let shift_y = if max_line_height == options.line_height {
603        (0.5 - alignment.y * lines.len() as f32) * options.line_height
604    } else {
605        -height * alignment.y - Shaping::Y_OFFSET
606    };
607    let shift = Vec2::new((justify - alignment.x) * max_line_length, shift_y);
608    let mut verticalizable = false;
609    let mut icons_in_text = false;
610    for glyph in positioned_lines.iter_mut().flat_map(|line| &mut line.glyphs) {
611        glyph.x += shift.x;
612        glyph.y += shift.y;
613        verticalizable |= glyph.vertical;
614        icons_in_text |= glyph.image_id.is_some();
615    }
616
617    let [x, y] = options.offset;
618    let left = x - alignment.x * max_line_length;
619    let top = y - alignment.y * height;
620    Shaping {
621        lines: positioned_lines,
622        bounds: Bounds { left, top, right: left + max_line_length, bottom: top + height },
623        verticalizable,
624        icons_in_text,
625    }
626}
627
628/// The lines of text that holds shaped sections, broken at `line_breaks`
629/// and the ends of paragraphs, in visual order. The bidi analysis covers the
630/// whole text, and sees each shaped section as characters of the section's
631/// direction, which it moves as a block without reversing them again.
632fn reorder_shaped_lines(text: &StyledText, sections: &[SectionOptions], line_breaks: VecSet<usize>) -> Vec<StyledText> {
633    let bidi_text: Vec<char> = text
634        .text
635        .iter()
636        .zip(&text.styles)
637        .map(|(&c, &style)| {
638            let section = &sections[usize::from(style)];
639            match (section.type_, section.rtl) {
640                (GlyphIDType::FontPBF, _) => c,
641                (_, true) => '\u{05D0}',
642                (_, false) => 'a',
643            }
644        })
645        .collect();
646    let block_styles: Vec<bool> = sections.iter().map(|section| section.type_ != GlyphIDType::FontPBF).collect();
647    bidi::reorder_styled_lines_with_blocks(text, line_breaks, &bidi_text, &block_styles)
648}
649
650/// `text` broken into lines, each in visual order.
651fn break_lines(
652    text: &TaggedString,
653    options: &ShapingOptions,
654    glyphs: &GlyphPositions,
655    images: &ImagePositions,
656) -> Vec<StyledText> {
657    let styled = text.styled_text();
658    if styled.text.is_empty() {
659        return Vec::new();
660    }
661    let line_breaks =
662        || determine_line_breaks(text, options.spacing, options.max_width, glyphs, images, options.text_size);
663    match text.sections() {
664        // Text that one font face shaped stays on one line.
665        [section] if section.type_ != GlyphIDType::FontPBF => vec![styled.clone()],
666        [_] => bidi::reorder_lines(&styled.text, line_breaks())
667            .into_iter()
668            .map(|text| StyledText { styles: vec![0; text.len()], text })
669            .collect(),
670        sections if text.has_font_sections() => reorder_shaped_lines(styled, sections, line_breaks()),
671        _ => bidi::reorder_styled_lines(styled, line_breaks()),
672    }
673}
674
675/// Shapes `text` with `options`, from the glyphs and images it draws.
676#[must_use]
677pub fn shape_text(
678    text: &TaggedString,
679    options: &ShapingOptions,
680    glyphs: &GlyphPositions,
681    images: &ImagePositions,
682) -> Shaping {
683    debug_assert!(options.text_size != 0.0);
684    let lines = break_lines(text, options, glyphs, images);
685    shape_lines(&lines, text.sections(), options, glyphs, images)
686}
687
688#[cfg(test)]
689mod tests {
690    use super::*;
691
692    fn trimmed(text: &TaggedString) -> String {
693        Line::new(text.styled_text(), text.sections()).trimmed().text.iter().collect()
694    }
695
696    fn u(s: &str) -> Vec<char> {
697        s.chars().collect()
698    }
699
700    // gtest: TaggedString.Trim
701    #[test]
702    fn trims_lines() {
703        let options = || SectionOptions::new(1.0, vec![], GlyphIDType::FontPBF, None);
704        let basic = TaggedString::new(u(" \t\ntrim that and not this  \n\t"), options());
705        assert_eq!(trimmed(&basic), "trim that and not this");
706
707        let mut two_sections = TaggedString::default();
708        two_sections.add_text_section(&u(" \t\ntrim that"), SectionOptions { scale: 1.5, ..options() });
709        two_sections.add_text_section(&u(" and not this  \n\t"), SectionOptions { scale: 0.5, ..options() });
710        assert_eq!(trimmed(&two_sections), "trim that and not this");
711
712        let empty = TaggedString::new(u("\n\t\u{b} \r  \t\n"), options());
713        assert_eq!(trimmed(&empty), "");
714
715        let no_trim = TaggedString::new(u("no trim!"), options());
716        assert_eq!(trimmed(&no_trim), "no trim!");
717    }
718
719    #[test]
720    fn keeps_whitespace_of_font_sections() {
721        let face = crate::text::glyph::face_type("shaping-trim-test", "font", &[(0, 0xFFFF)]);
722        let mut text = TaggedString::default();
723        text.add_text_section(&u("  a"), SectionOptions::new(1.0, vec![], GlyphIDType::FontPBF, None));
724        text.add_text_section(&u(" b "), SectionOptions::new(1.0, vec![], face, None));
725        text.add_text_section(&u("  "), SectionOptions::new(1.0, vec![], GlyphIDType::FontPBF, None));
726        assert_eq!(trimmed(&text), "a b ");
727    }
728
729    #[test]
730    fn anchor_alignment_and_justification_agree() {
731        use SymbolAnchorType as A;
732        for anchor in
733            [A::Center, A::Left, A::Right, A::Top, A::Bottom, A::TopLeft, A::TopRight, A::BottomLeft, A::BottomRight]
734        {
735            assert_eq!(anchor_alignment(anchor).x, justify_factor(anchor_justification(anchor)));
736        }
737        assert_eq!(anchor_alignment(A::BottomLeft), Vec2::new(0.0, 1.0));
738    }
739}