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