Skip to main content

fleuron/lines/
shape.rs

1//! Text to glyphs: a span at a time, on the face the cascade named.
2
3use std::ops::Range;
4
5use crate::fonts::{Features, ShapedGlyph};
6
7use super::flatten::{FlatParagraph, StyleSpan};
8use super::line::{ShapedRun, cut_runs};
9use super::paragraph::ParagraphStyle;
10use super::{LineLayout, Uncovered};
11
12impl LineLayout<'_> {
13    /// One string as shaped runs, set the way `style` asks for it.
14    /// The counterpart of `layout` for text that is not broken into
15    /// lines: page furniture, an ornament, an initial letter.
16    pub fn shape(&self, text: &str, style: &ParagraphStyle) -> Option<Vec<ShapedRun>> {
17        let upem = self.registry.metrics(style.font_id)?.units_per_em as f32;
18        let mut flat = FlatParagraph::new();
19        flat.push_styled(text, style, self.small_caps(style));
20        let shaped = self.shape_spans(&flat, style, upem);
21        Some(cut_runs(&flat, &shaped, 0, flat.text.len()))
22    }
23
24    /// Shapes each span. A glyph's cluster is an offset into the
25    /// span, which indexes the paragraph text once offset by the
26    /// span's start. A span set at another size measures in its own
27    /// font units, so `scale` takes it into the paragraph's.
28    ///
29    /// Tracking is added here, to the last glyph of every cluster, so
30    /// every pass downstream measures it without being told about it.
31    pub(super) fn shape_spans(
32        &self,
33        flat: &FlatParagraph,
34        style: &ParagraphStyle,
35        upem: f32,
36    ) -> Vec<ShapedSpan> {
37        flat.spans
38            .iter()
39            .map(|span| {
40                let mut glyphs = self
41                    .registry
42                    .shape_with(span.font_id, &flat.text[span.range.clone()], &span.features)
43                    .unwrap_or_default();
44                self.find_uncovered(flat, span, &glyphs);
45                let track = self.tracking_units(span);
46                if track != 0 {
47                    for at in 0..glyphs.len() {
48                        let last = glyphs
49                            .get(at + 1)
50                            .is_none_or(|next| next.cluster != glyphs[at].cluster);
51                        if last {
52                            glyphs[at].x_advance =
53                                (glyphs[at].x_advance as i64 + track).max(0) as u32;
54                        }
55                    }
56                }
57                let scale = self.scale(span.font_id, span.size, style, upem);
58                ShapedSpan {
59                    range: span.range.clone(),
60                    scale,
61                    track,
62                    tracking: track as f32 * scale,
63                    glyphs,
64                }
65            })
66            .collect()
67    }
68
69    /// Keeps the characters of a span that shaped to the glyph a face
70    /// draws for a character it does not have.
71    ///
72    /// A control character has no glyph in any face and draws
73    /// nothing, so it is not one of them.
74    fn find_uncovered(&self, flat: &FlatParagraph, span: &StyleSpan, glyphs: &[ShapedGlyph]) {
75        for glyph in glyphs.iter().filter(|glyph| glyph.id == 0) {
76            let at = span.range.start + glyph.cluster as usize;
77            let Some(character) = flat.text.get(at..).and_then(|rest| rest.chars().next()) else {
78                continue;
79            };
80            if character.is_control() {
81                continue;
82            }
83            let mut found = self.uncovered.borrow_mut();
84            if found.seen.insert(character) {
85                found.list.push(Uncovered {
86                    character,
87                    font_id: span.font_id,
88                    position: flat.written_at(at),
89                });
90            }
91        }
92    }
93
94    /// A span's tracking in its own font units.
95    fn tracking_units(&self, span: &StyleSpan) -> i64 {
96        if span.tracking == 0.0 || span.size <= 0.0 {
97            return 0;
98        }
99        let upem = self
100            .registry
101            .metrics(span.font_id)
102            .map(|m| m.units_per_em as f32)
103            .unwrap_or(1000.0);
104        (span.tracking / span.size * upem).round() as i64
105    }
106
107    /// What a span's own font units are worth in the paragraph's.
108    /// One em of a 6pt face is not one em of an 11pt one, and the
109    /// measure is written in the paragraph's.
110    fn scale(&self, font_id: u16, size: f32, style: &ParagraphStyle, upem: f32) -> f32 {
111        let span_upem = self
112            .registry
113            .metrics(font_id)
114            .map(|m| m.units_per_em as f32)
115            .unwrap_or(upem);
116        if span_upem <= 0.0 || style.size <= 0.0 {
117            return 1.0;
118        }
119        size / span_upem * upem / style.size
120    }
121
122    /// Draws the hyphen a break inside a word leaves behind.
123    ///
124    /// The break was charged for it when it was chosen, so it is
125    /// drawn in the same face the charge was read from: a hyphen
126    /// taken from one face and paid for out of another is a line
127    /// that measures one width and paints a different one.
128    pub(super) fn hyphenate(&self, runs: &mut Vec<ShapedRun>, style: &ParagraphStyle) {
129        let Some(id) = self.registry.char_glyph(style.font_id, '-') else {
130            return;
131        };
132        let advance = self
133            .registry
134            .advance_width(style.font_id, id)
135            .unwrap_or_default() as u32;
136        let ending = runs
137            .last()
138            .map(|run| run.text_start + run.text.len() as u32)
139            .unwrap_or_default();
140        // The hyphen takes the last run's colour, because colour
141        // costs no width, and the paragraph's face, because that is
142        // where its width was charged.
143        let color = runs.last().map_or(style.color, |run| run.color);
144        // The hyphen belongs to the word it broke, so a rule drawn
145        // across that word is drawn across it too.
146        let decoration = runs.last().map_or(style.decoration, |run| run.decoration);
147        let blend = runs.last().map_or(style.blend, |run| run.blend);
148        // The hyphen belongs to the word it broke, so it sits inside
149        // whatever box that word is in.
150        let inline = runs.last().and_then(|run| run.inline);
151        match runs.last_mut() {
152            Some(run) if run.font_id == style.font_id && run.size == style.size => {
153                run.text.push('-');
154                // A hyphen the breaker drew stands for nothing the
155                // author wrote, so it maps to an empty stretch of the
156                // source and extraction reads straight past it.
157                if let Some(end) = run.source_map.last().copied() {
158                    run.source_map.push(end);
159                }
160                run.glyphs.push(ShapedGlyph {
161                    id,
162                    x_advance: advance,
163                    cluster: ending,
164                });
165                run.advance += advance;
166            }
167            // A break inside an emphasised word: the hyphen is the
168            // paragraph's own, so it goes in a run of its own rather
169            // than into a face it was not measured in.
170            _ => runs.push(ShapedRun {
171                font_id: style.font_id,
172                size: style.size,
173                text: "-".to_string(),
174                source: String::new(),
175                source_map: Vec::new(),
176                text_start: ending,
177                origin: None,
178                pseudo_element: None,
179                inline,
180                lead: 0.0,
181                trail: 0.0,
182                features: Features::NONE,
183                color,
184                decoration,
185                blend,
186                glyphs: vec![ShapedGlyph {
187                    id,
188                    x_advance: advance,
189                    cluster: ending,
190                }],
191                advance,
192            }),
193        }
194    }
195
196    pub(super) fn hyphen_advance(&self, style: &ParagraphStyle) -> u32 {
197        self.registry
198            .char_glyph(style.font_id, '-')
199            .and_then(|g| self.registry.advance_width(style.font_id, g))
200            .unwrap_or(0) as u32
201    }
202}
203
204/// One shaped span, its glyph clusters still relative to the span's
205/// own text.
206pub(super) struct ShapedSpan {
207    /// Byte range of the span in the paragraph text.
208    pub(super) range: Range<usize>,
209    /// What one of this span's font units is worth in the
210    /// paragraph's.
211    pub(super) scale: f32,
212    /// Tracking charged after each of its clusters, in its own font
213    /// units.
214    pub(super) track: i64,
215    /// The same in the paragraph's font units.
216    pub(super) tracking: f32,
217    pub(super) glyphs: Vec<ShapedGlyph>,
218}
219
220impl ShapedSpan {
221    /// The glyphs whose clusters fall in `[start, end)`, clusters
222    /// rebased to the paragraph text.
223    pub(super) fn glyphs_in(&self, start: usize, end: usize) -> Vec<ShapedGlyph> {
224        self.glyphs
225            .iter()
226            .filter(|g| {
227                let cluster = self.range.start + g.cluster as usize;
228                cluster >= start && cluster < end
229            })
230            .map(|g| ShapedGlyph {
231                cluster: g.cluster + self.range.start as u32,
232                ..*g
233            })
234            .collect()
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use crate::content::{Attributes, Inline, NodeId, SourcePos};
241    use crate::lines::Uncovered;
242    use crate::lines::flatten::SMALL_CAPS_RATIO;
243    use crate::lines::testing::{
244        body, hyphenated, layout_body_opts, layout_style, line_text, registry, units_per_em,
245    };
246    use crate::lines::{LineBreakOptions, LineLayout, Measure, Opening, ParagraphStyle};
247    use crate::style::{FontVariantCaps, TextTransform};
248
249    /// The hyphen is painted as well as charged: the run has the
250    /// character and a glyph for it, and the last line has neither.
251    #[test]
252    fn a_hyphenated_line_paints_the_hyphen_it_paid_for() {
253        let text = "extraordinarily";
254        let lines = layout_body_opts(text, 53.0, hyphenated());
255        let first = &lines[0];
256        assert_eq!(line_text(first), "extraordi-");
257
258        let run = first.runs.last().expect("the line has no runs");
259        assert_eq!(
260            run.glyphs.len(),
261            run.text.chars().count(),
262            "the hyphen is in the text and not in the glyphs",
263        );
264        let ranges = run.glyph_ranges();
265        let last = ranges.last().expect("the run has no glyphs");
266        assert_eq!(
267            &run.text[last.start as usize..last.end as usize],
268            "-",
269            "the last glyph does not stand for the hyphen",
270        );
271
272        // Charged and drawn are the same number: the line's width
273        // covers the glyph it ends with.
274        let hyphen = run.glyphs.last().expect("the run has no glyphs").x_advance;
275        assert!(hyphen > 0, "the hyphen has no advance");
276        assert_eq!(
277            first.width,
278            first.runs.iter().map(|r| r.advance).sum::<u32>(),
279            "the line's width and its runs disagree",
280        );
281
282        let last_line = lines.last().expect("no lines");
283        assert!(
284            !line_text(last_line).ends_with('-'),
285            "the last line was hyphenated: {:?}",
286            line_text(last_line),
287        );
288    }
289
290    /// A character the face has no glyph for is found once, at the
291    /// column it was written at, whatever a transform shaped the text
292    /// before it as. Taking what was found starts over.
293    #[test]
294    fn an_uncovered_character_is_found_once_where_it_was_written() {
295        let layout = LineLayout::new(registry());
296        let inlines = vec![Inline::Text {
297            id: NodeId::UNASSIGNED,
298            value: "stra\u{df}e \u{2605} and \u{2605}".into(),
299            attributes: Attributes::default(),
300            position: Some(SourcePos { line: 4, column: 3 }),
301            span: None,
302        }];
303        let mut style = body();
304        style.transform = TextTransform::Uppercase;
305        layout.layout(&inlines, &style, 400.0, Default::default());
306
307        let found = layout.take_uncovered();
308        assert_eq!(
309            found,
310            [Uncovered {
311                character: '\u{2605}',
312                font_id: style.font_id,
313                // Eight bytes of the node come before the star: the
314                // sharp s is two, however many letters it shaped as.
315                position: Some(SourcePos {
316                    line: 4,
317                    column: 11
318                }),
319            }]
320        );
321        assert_eq!(layout.take_uncovered(), []);
322    }
323
324    /// Emphasis is its own span: a paragraph of roman prose around
325    /// italic dialogue breaks into runs at the markup's boundaries,
326    /// each on the face its style resolved to, and a nested `strong`
327    /// takes the bold italic cut.
328    #[test]
329    fn emphasis_shapes_on_its_own_face() {
330        let mut book = crate::content::Book {
331            metadata: Default::default(),
332            sections: vec![crate::content::Section {
333                attributes: Default::default(),
334                blocks: vec![crate::content::Block::Paragraph {
335                    id: NodeId::UNASSIGNED,
336                    inlines: vec![
337                        Inline::Text {
338                            id: NodeId::UNASSIGNED,
339                            value: "He said ".into(),
340                            attributes: Attributes::default(),
341                            position: None,
342                            span: None,
343                        },
344                        Inline::Emphasis {
345                            id: NodeId::UNASSIGNED,
346                            children: vec![
347                                Inline::Text {
348                                    id: NodeId::UNASSIGNED,
349                                    value: "never ".into(),
350                                    attributes: Attributes::default(),
351                                    position: None,
352                                    span: None,
353                                },
354                                Inline::Strong {
355                                    id: NodeId::UNASSIGNED,
356                                    children: vec![Inline::Text {
357                                        id: NodeId::UNASSIGNED,
358                                        value: "again".into(),
359                                        attributes: Attributes::default(),
360                                        position: None,
361                                        span: None,
362                                    }],
363                                    attributes: Attributes::default(),
364                                    position: None,
365                                    span: None,
366                                },
367                            ],
368                            attributes: Attributes::default(),
369                            position: None,
370                            span: None,
371                        },
372                        Inline::Text {
373                            id: NodeId::UNASSIGNED,
374                            value: " to her.".into(),
375                            attributes: Attributes::default(),
376                            position: None,
377                            span: None,
378                        },
379                    ],
380                    attributes: Attributes::default(),
381                    position: None,
382                    span: None,
383                }],
384                ..Default::default()
385            }],
386        };
387        book.assign_node_ids();
388        let styles = crate::style::defaults(&book, registry());
389        let crate::content::Block::Paragraph { id, inlines, .. } = &book.sections[0].blocks[0]
390        else {
391            unreachable!()
392        };
393        let lines = LineLayout::new(registry()).layout_styled(
394            inlines,
395            &styles.paragraph(*id),
396            &styles,
397            &Measure::uniform(400.0),
398            Default::default(),
399            Opening::default(),
400        );
401        assert_eq!(lines.len(), 1);
402        let runs: Vec<(u16, &str)> = lines[0]
403            .runs
404            .iter()
405            .map(|run| (run.font_id, run.text.as_str()))
406            .collect();
407        let face = |italic, weight| {
408            registry()
409                .select(
410                    "eb garamond",
411                    crate::fonts::FaceAttributes { italic, weight },
412                )
413                .unwrap()
414                .id
415        };
416        assert_eq!(
417            runs,
418            vec![
419                (face(false, 400), "He said "),
420                (face(true, 400), "never "),
421                (face(true, 700), "again"),
422                (face(false, 400), " to her."),
423            ],
424        );
425    }
426
427    /// Letter-spacing is advance on the shaper's glyphs: every gap
428    /// between two glyphs opens by the tracking, and the last glyph
429    /// keeps its own advance, so a tracked title measures the tracking
430    /// times one fewer than its glyphs.
431    #[test]
432    fn letter_spacing_opens_the_gaps_between_glyphs() {
433        let plain = layout_style("HANDGLOVES", 400.0, &body());
434        let tracking = 0.08 * body().size;
435        let tracked = layout_style(
436            "HANDGLOVES",
437            400.0,
438            &ParagraphStyle {
439                letter_spacing: tracking,
440                ..body()
441            },
442        );
443        let glyphs = plain[0].runs[0].glyphs.len();
444        assert_eq!(glyphs, 10, "the title shaped to one glyph a letter");
445        let units = tracking / body().size * units_per_em() as f32;
446        assert_eq!(
447            tracked[0].width - plain[0].width,
448            (units * (glyphs - 1) as f32).round() as u32,
449            "tracking did not open exactly the gaps between the glyphs",
450        );
451        for (loose, tight) in tracked[0].runs[0]
452            .glyphs
453            .iter()
454            .zip(&plain[0].runs[0].glyphs)
455            .take(glyphs - 1)
456        {
457            assert_eq!(
458                loose.x_advance - tight.x_advance,
459                units.round() as u32,
460                "a glyph has no tracking of its own",
461            );
462        }
463    }
464
465    /// Small capitals come out of the face where the face has them:
466    /// the run stays at the size around it and draws glyphs the plain
467    /// text does not. A face with no substitutions of its own gets a
468    /// synthesis instead, the letters raised to capitals and set at a
469    /// fraction of the size, and the capitals already there are left
470    /// alone.
471    #[test]
472    fn small_caps_take_the_feature_or_a_synthesis() {
473        let style = ParagraphStyle {
474            caps: FontVariantCaps::SmallCaps,
475            ..body()
476        };
477        let plain = layout_style("hello", 400.0, &body());
478        let feature = layout_style("hello", 400.0, &style);
479        assert_eq!(feature[0].runs.len(), 1, "the feature split the run");
480        assert_eq!(feature[0].runs[0].size, body().size);
481        assert_ne!(
482            feature[0].runs[0]
483                .glyphs
484                .iter()
485                .map(|g| g.id)
486                .collect::<Vec<_>>(),
487            plain[0].runs[0]
488                .glyphs
489                .iter()
490                .map(|g| g.id)
491                .collect::<Vec<_>>(),
492            "the face's small capitals drew the lowercase glyphs",
493        );
494
495        let bare = crate::fonts::registry_without_substitutions();
496        assert!(!bare.has_small_caps(0), "the face still substitutes");
497        let inlines = vec![Inline::Text {
498            id: NodeId::UNASSIGNED,
499            value: "hi Ho".to_string(),
500            attributes: Attributes::default(),
501            position: None,
502            span: None,
503        }];
504        let synthesized =
505            LineLayout::new(&bare).layout(&inlines, &style, 400.0, LineBreakOptions::default());
506        let runs: Vec<(f32, &str, &str)> = synthesized[0]
507            .runs
508            .iter()
509            .map(|run| (run.size, run.text.as_str(), run.source.as_str()))
510            .collect();
511        assert_eq!(
512            runs,
513            vec![
514                (body().size * SMALL_CAPS_RATIO, "HI", "hi"),
515                (body().size, " H", ""),
516                (body().size * SMALL_CAPS_RATIO, "O", "o"),
517            ],
518            "the synthesis did not raise what was lowercase, leave the rest, \
519             and keep what the author wrote",
520        );
521    }
522}