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