Skip to main content

usvg/text/
layout.rs

1// Copyright 2022 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::collections::{HashMap, HashSet};
5use std::num::NonZeroU16;
6use std::sync::Arc;
7
8use fontdb::ID;
9use harfrust::ShapeOptions;
10use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
11use strict_num::NonZeroPositiveF32;
12use tiny_skia_path::{NonZeroRect, Transform};
13use unicode_script::UnicodeScript;
14
15use super::cache::{FontCache, FontInstance, with_optical_sizing};
16use crate::tree::{BBox, IsValidLength};
17use crate::{
18    AlignmentBaseline, ApproxZeroUlps, BaselineShift, DominantBaseline, Fill, FillRule, Font,
19    FontResolver, GlyphId, LengthAdjust, PaintOrder, Path, ShapeRendering, Stroke, Text,
20    TextAnchor, TextChunk, TextDecorationStyle, TextFlow, TextPath, TextSpan, WritingMode,
21};
22
23/// A glyph that has already been positioned correctly.
24///
25/// Note that the transform already takes the font size into consideration, so applying the
26/// transform to the outline of the glyphs is all that is necessary to display it correctly.
27#[derive(Clone, Debug)]
28pub struct PositionedGlyph {
29    /// Returns the transform of the glyph itself within the cluster. For example,
30    /// for zalgo text, it contains the transform to position the glyphs above/below
31    /// the main glyph.
32    glyph_ts: Transform,
33    /// Returns the transform of the whole cluster that the glyph is part of.
34    cluster_ts: Transform,
35    /// Returns the transform of the span that the glyph is a part of.
36    span_ts: Transform,
37    /// The units per em of the font the glyph belongs to.
38    units_per_em: u16,
39    /// The font size the glyph should be scaled to.
40    font_size: f32,
41    /// The ID of the glyph.
42    pub id: GlyphId,
43    /// The text from the original string that corresponds to that glyph.
44    pub text: String,
45    /// The ID of the font the glyph should be taken from. Can be used with the
46    /// [font database of the tree](crate::Tree::fontdb) this glyph is part of.
47    pub font: ID,
48}
49
50impl PositionedGlyph {
51    /// Returns the font size for this glyph.
52    pub fn font_size(&self) -> f32 {
53        self.font_size
54    }
55
56    /// Returns the transform of glyph.
57    pub fn transform(&self) -> Transform {
58        let sx = self.font_size / self.units_per_em as f32;
59
60        self.span_ts
61            .pre_concat(self.cluster_ts)
62            .pre_concat(Transform::from_scale(sx, sx))
63            .pre_concat(self.glyph_ts)
64    }
65
66    /// Returns the transform of glyph, assuming that an outline
67    /// glyph is being used (i.e. from the `glyf` or `CFF/CFF2` table).
68    pub fn outline_transform(&self) -> Transform {
69        // Outlines are mirrored by default.
70        self.transform()
71            .pre_concat(Transform::from_scale(1.0, -1.0))
72    }
73
74    /// Returns the transform for the glyph, assuming that a CBTD-based raster glyph
75    /// is being used.
76    pub fn cbdt_transform(&self, x: f32, y: f32, pixels_per_em: f32) -> Transform {
77        self.transform()
78            .pre_concat(Transform::from_scale(
79                self.units_per_em as f32 / pixels_per_em,
80                self.units_per_em as f32 / pixels_per_em,
81            ))
82            // Right now, the top-left corner of the image would be placed in
83            // on the "text cursor", but we want the bottom-left corner to be there,
84            // so we need to shift it up and also apply the x/y offset.
85            .pre_translate(x, -y)
86    }
87
88    /// Returns the transform for the glyph, assuming that a sbix-based raster glyph
89    /// is being used.
90    pub fn sbix_transform(
91        &self,
92        x: f32,
93        y: f32,
94        bearing_x: f32,
95        bearing_y: f32,
96        pixels_per_em: f32,
97        height: f32,
98    ) -> Transform {
99        self.transform()
100            .pre_translate(bearing_x, -bearing_y)
101            .pre_concat(Transform::from_scale(
102                self.units_per_em as f32 / pixels_per_em,
103                self.units_per_em as f32 / pixels_per_em,
104            ))
105            // Right now, the top-left corner of the image would be placed in
106            // on the "text cursor", but we want the bottom-left corner to be there,
107            // so we need to shift it up and also apply the x/y offset.
108            .pre_translate(x, -height - y)
109    }
110
111    /// Returns the transform for the glyph, assuming that an SVG glyph is
112    /// being used.
113    pub fn svg_transform(&self) -> Transform {
114        self.transform()
115    }
116
117    /// Returns the transform for the glyph, assuming that a COLR glyph is
118    /// being used.
119    pub fn colr_transform(&self) -> Transform {
120        self.outline_transform()
121    }
122}
123
124/// A span contains a number of layouted glyphs that share the same fill, stroke, paint order and
125/// visibility.
126#[derive(Clone, Debug)]
127pub struct Span {
128    /// The fill of the span.
129    pub fill: Option<Fill>,
130    /// The stroke of the span.
131    pub stroke: Option<Stroke>,
132    /// The paint order of the span.
133    pub paint_order: PaintOrder,
134    /// The font size of the span.
135    pub font_size: NonZeroPositiveF32,
136    /// Font variation settings for variable fonts.
137    pub variations: Vec<crate::FontVariation>,
138    /// Font optical sizing mode.
139    pub font_optical_sizing: crate::FontOpticalSizing,
140    /// The visibility of the span.
141    pub visible: bool,
142    /// The glyphs that make up the span.
143    pub positioned_glyphs: Vec<PositionedGlyph>,
144    /// An underline text decoration of the span.
145    /// Needs to be rendered before all glyphs.
146    pub underline: Option<Box<Path>>,
147    /// An overline text decoration of the span.
148    /// Needs to be rendered before all glyphs.
149    pub overline: Option<Box<Path>>,
150    /// A line-through text decoration of the span.
151    /// Needs to be rendered after all glyphs.
152    pub line_through: Option<Box<Path>>,
153}
154
155#[derive(Clone, Debug)]
156struct GlyphCluster {
157    byte_idx: ByteIndex,
158    codepoint: char,
159    width: f32,
160    advance: f32,
161    text_length_spacing: f32,
162    ascent: f32,
163    descent: f32,
164    has_relative_shift: bool,
165    glyphs: Vec<PositionedGlyph>,
166    transform: Transform,
167    path_transform: Transform,
168    visible: bool,
169}
170
171impl GlyphCluster {
172    pub(crate) fn height(&self) -> f32 {
173        self.ascent - self.descent
174    }
175
176    pub(crate) fn transform(&self) -> Transform {
177        self.path_transform.post_concat(self.transform)
178    }
179}
180
181pub(crate) fn layout_text(
182    text_node: &Text,
183    resolver: &FontResolver,
184    fonts: &mut FontCache,
185) -> Option<(Vec<Span>, NonZeroRect)> {
186    for chunk in &text_node.chunks {
187        for span in &chunk.spans {
188            if !fonts.resolved.contains_key(&span.font) {
189                if let Some(font) = (resolver.select_font)(&span.font, &mut fonts.fontdb)
190                    .and_then(|id| resolve_font(id, &span.font.variations, fonts))
191                {
192                    fonts.resolved.insert(span.font.clone(), Arc::new(font));
193                }
194            }
195        }
196    }
197
198    let mut spans = Vec::with_capacity(text_node.chunks.iter().map(|c| c.spans.len()).sum());
199    let mut char_offset = 0;
200    let mut last_x = 0.0;
201    let mut last_y = 0.0;
202    let mut bbox = BBox::default();
203    for chunk in &text_node.chunks {
204        let (x, y) = match chunk.text_flow {
205            TextFlow::Linear => (chunk.x.unwrap_or(last_x), chunk.y.unwrap_or(last_y)),
206            TextFlow::Path(_) => (0.0, 0.0),
207        };
208
209        let mut clusters = process_chunk(chunk, resolver, fonts);
210        if clusters.is_empty() {
211            char_offset += chunk.text.chars().count();
212            continue;
213        }
214
215        apply_writing_mode(text_node.writing_mode, &mut clusters);
216        apply_letter_spacing(chunk, &mut clusters);
217        apply_word_spacing(chunk, &mut clusters);
218
219        apply_length_adjust(chunk, &mut clusters);
220        let mut curr_pos = resolve_clusters_positions(
221            text_node,
222            chunk,
223            char_offset,
224            text_node.writing_mode,
225            &fonts.resolved,
226            &mut clusters,
227        );
228
229        let mut text_ts = Transform::default();
230        if text_node.writing_mode == WritingMode::TopToBottom {
231            if let TextFlow::Linear = chunk.text_flow {
232                text_ts = text_ts.pre_rotate_at(90.0, x, y);
233            }
234        }
235
236        for span in &chunk.spans {
237            let font = match fonts.resolved.get(&span.font) {
238                Some(v) => v,
239                None => continue,
240            };
241
242            let decoration_spans = collect_decoration_spans(span, &clusters);
243
244            let mut span_ts = text_ts;
245            span_ts = span_ts.pre_translate(x, y);
246            if let TextFlow::Linear = chunk.text_flow {
247                let shift = resolve_baseline(span, font, text_node.writing_mode);
248
249                // In case of a horizontal flow, shift transform and not clusters,
250                // because clusters can be rotated and an additional shift will lead
251                // to invalid results.
252                span_ts = span_ts.pre_translate(0.0, shift);
253            }
254
255            let mut underline = None;
256            let mut overline = None;
257            let mut line_through = None;
258
259            if let Some(decoration) = span.decoration.underline.clone() {
260                // TODO: No idea what offset should be used for top-to-bottom layout.
261                // There is
262                // https://www.w3.org/TR/css-text-decor-3/#text-underline-position-property
263                // but it doesn't go into details.
264                let offset = match text_node.writing_mode {
265                    WritingMode::LeftToRight => -font.underline_position(span.font_size.get()),
266                    WritingMode::TopToBottom => font.height(span.font_size.get()) / 2.0,
267                };
268
269                if let Some(path) =
270                    convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)
271                {
272                    bbox = bbox.expand(path.data.bounds());
273                    underline = Some(Box::new(path));
274                }
275            }
276
277            if let Some(decoration) = span.decoration.overline.clone() {
278                let offset = match text_node.writing_mode {
279                    WritingMode::LeftToRight => -font.ascent(span.font_size.get()),
280                    WritingMode::TopToBottom => -font.height(span.font_size.get()) / 2.0,
281                };
282
283                if let Some(path) =
284                    convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)
285                {
286                    bbox = bbox.expand(path.data.bounds());
287                    overline = Some(Box::new(path));
288                }
289            }
290
291            if let Some(decoration) = span.decoration.line_through.clone() {
292                let offset = match text_node.writing_mode {
293                    WritingMode::LeftToRight => -font.line_through_position(span.font_size.get()),
294                    WritingMode::TopToBottom => 0.0,
295                };
296
297                if let Some(path) =
298                    convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)
299                {
300                    bbox = bbox.expand(path.data.bounds());
301                    line_through = Some(Box::new(path));
302                }
303            }
304
305            let mut fill = span.fill.clone();
306            if let Some(ref mut fill) = fill {
307                // The `fill-rule` should be ignored.
308                // https://www.w3.org/TR/SVG2/text.html#TextRenderingOrder
309                //
310                // 'Since the fill-rule property does not apply to SVG text elements,
311                // the specific order of the subpaths within the equivalent path does not matter.'
312                fill.rule = FillRule::NonZero;
313            }
314
315            if let Some((span_fragments, span_bbox)) = convert_span(span, &clusters, span_ts) {
316                bbox = bbox.expand(span_bbox);
317
318                let positioned_glyphs = span_fragments
319                    .into_iter()
320                    .flat_map(|mut gc| {
321                        let cluster_ts = gc.transform();
322                        gc.glyphs.iter_mut().for_each(|pg| {
323                            pg.cluster_ts = cluster_ts;
324                            pg.span_ts = span_ts;
325                        });
326                        gc.glyphs
327                    })
328                    .collect();
329
330                spans.push(Span {
331                    fill,
332                    stroke: span.stroke.clone(),
333                    paint_order: span.paint_order,
334                    font_size: span.font_size,
335                    variations: span.font.variations.clone(),
336                    font_optical_sizing: span.font_optical_sizing,
337                    visible: span.visible,
338                    positioned_glyphs,
339                    underline,
340                    overline,
341                    line_through,
342                });
343            }
344        }
345
346        char_offset += chunk.text.chars().count();
347
348        if text_node.writing_mode == WritingMode::TopToBottom {
349            if let TextFlow::Linear = chunk.text_flow {
350                std::mem::swap(&mut curr_pos.0, &mut curr_pos.1);
351            }
352        }
353
354        last_x = x + curr_pos.0;
355        last_y = y + curr_pos.1;
356    }
357
358    let bbox = bbox.to_non_zero_rect()?;
359
360    Some((spans, bbox))
361}
362
363fn convert_span(
364    span: &TextSpan,
365    clusters: &[GlyphCluster],
366    text_ts: Transform,
367) -> Option<(Vec<GlyphCluster>, NonZeroRect)> {
368    let mut span_clusters = vec![];
369    let mut bboxes_builder = tiny_skia_path::PathBuilder::new();
370
371    for cluster in clusters {
372        if !cluster.visible {
373            continue;
374        }
375
376        if span_contains(span, cluster.byte_idx) {
377            span_clusters.push(cluster.clone());
378        }
379
380        let mut advance = cluster.advance;
381        if advance <= 0.0 {
382            advance = 1.0;
383        }
384
385        // We have to calculate text bbox using font metrics and not glyph shape.
386        if let Some(r) = NonZeroRect::from_xywh(0.0, -cluster.ascent, advance, cluster.height()) {
387            if let Some(r) = r.transform(cluster.transform()) {
388                bboxes_builder.push_rect(r.to_rect());
389            }
390        }
391    }
392
393    let mut bboxes = bboxes_builder.finish()?;
394    bboxes = bboxes.transform(text_ts)?;
395    let bbox = bboxes.compute_tight_bounds()?.to_non_zero_rect()?;
396
397    Some((span_clusters, bbox))
398}
399
400fn collect_decoration_spans(span: &TextSpan, clusters: &[GlyphCluster]) -> Vec<DecorationSpan> {
401    let mut spans = Vec::new();
402
403    let mut started = false;
404    let mut width = 0.0;
405    let mut transform = Transform::default();
406
407    for cluster in clusters {
408        if span_contains(span, cluster.byte_idx) {
409            if started && cluster.has_relative_shift {
410                started = false;
411                spans.push(DecorationSpan { width, transform });
412            }
413
414            if !started {
415                width = cluster.advance;
416                started = true;
417                transform = cluster.transform;
418            } else {
419                width += cluster.advance;
420            }
421        } else if started {
422            spans.push(DecorationSpan { width, transform });
423            started = false;
424        }
425    }
426
427    if started {
428        spans.push(DecorationSpan { width, transform });
429    }
430
431    spans
432}
433
434pub(crate) fn convert_decoration(
435    dy: f32,
436    span: &TextSpan,
437    font: &ResolvedFont,
438    mut decoration: TextDecorationStyle,
439    decoration_spans: &[DecorationSpan],
440    transform: Transform,
441) -> Option<Path> {
442    debug_assert!(!decoration_spans.is_empty());
443
444    let thickness = font.underline_thickness(span.font_size.get());
445
446    let mut builder = tiny_skia_path::PathBuilder::new();
447    for dec_span in decoration_spans {
448        let rect = match NonZeroRect::from_xywh(0.0, -thickness / 2.0, dec_span.width, thickness) {
449            Some(v) => v,
450            None => {
451                log::warn!("a decoration span has a malformed bbox");
452                continue;
453            }
454        };
455
456        let ts = dec_span.transform.pre_translate(0.0, dy);
457
458        let mut path = tiny_skia_path::PathBuilder::from_rect(rect.to_rect());
459        path = match path.transform(ts) {
460            Some(v) => v,
461            None => continue,
462        };
463
464        builder.push_path(&path);
465    }
466
467    let mut path_data = builder.finish()?;
468    path_data = path_data.transform(transform)?;
469
470    Some(Path::new(
471        Box::default(),
472        span.visible,
473        decoration.fill.take(),
474        decoration.stroke.take(),
475        PaintOrder::default(),
476        ShapeRendering::default(),
477        Arc::new(path_data),
478        Transform::default(),
479    ))
480}
481
482/// A text decoration span.
483///
484/// Basically a horizontal line, that will be used for underline, overline and line-through.
485/// It doesn't have a height, since it depends on the Font metrics.
486#[derive(Clone, Copy)]
487pub(crate) struct DecorationSpan {
488    pub(crate) width: f32,
489    pub(crate) transform: Transform,
490}
491
492/// Resolves clusters positions.
493///
494/// Mainly sets the `transform` property.
495///
496/// Returns the last text position. The next text chunk should start from that position.
497fn resolve_clusters_positions(
498    text: &Text,
499    chunk: &TextChunk,
500    char_offset: usize,
501    writing_mode: WritingMode,
502    fonts_cache: &FontsCache,
503    clusters: &mut [GlyphCluster],
504) -> (f32, f32) {
505    match chunk.text_flow {
506        TextFlow::Linear => {
507            resolve_clusters_positions_horizontal(text, chunk, char_offset, writing_mode, clusters)
508        }
509        TextFlow::Path(ref path) => resolve_clusters_positions_path(
510            text,
511            chunk,
512            char_offset,
513            path,
514            writing_mode,
515            fonts_cache,
516            clusters,
517        ),
518    }
519}
520
521fn clusters_length(clusters: &[GlyphCluster]) -> f32 {
522    clusters.iter().fold(0.0, |w, cluster| w + cluster.advance)
523}
524
525fn resolve_relative_shifts(
526    text: &Text,
527    chunk: &TextChunk,
528    offset: usize,
529    clusters: &[GlyphCluster],
530) -> (Vec<(f32, f32)>, Vec<usize>) {
531    // `dx` and `dy` shift a character and all the characters after it in logical order,
532    // while the clusters are in visual order, which differs in right-to-left text.
533    let mut logical_order: Vec<usize> = (0..clusters.len()).collect();
534    logical_order.sort_by_key(|&i| clusters[i].byte_idx.value());
535
536    let mut shifts = vec![(0.0, 0.0); clusters.len()];
537    let (mut shift_x, mut shift_y) = (0.0, 0.0);
538    for &i in &logical_order {
539        let cp = offset + clusters[i].byte_idx.code_point_at(&chunk.text);
540        shift_x += text.dx.get(cp).cloned().unwrap_or(0.0);
541        shift_y += text.dy.get(cp).cloned().unwrap_or(0.0);
542        shifts[i] = (shift_x, shift_y);
543    }
544
545    (shifts, logical_order)
546}
547
548fn resolve_clusters_positions_horizontal(
549    text: &Text,
550    chunk: &TextChunk,
551    offset: usize,
552    writing_mode: WritingMode,
553    clusters: &mut [GlyphCluster],
554) -> (f32, f32) {
555    let (mut shifts, logical_order) = resolve_relative_shifts(text, chunk, offset, clusters);
556    let first = logical_order[0];
557    let last = logical_order[logical_order.len() - 1];
558
559    // Vertical text is laid out horizontally and rotated by 90 degrees afterwards.
560    if writing_mode == WritingMode::TopToBottom {
561        for shift in &mut shifts {
562            *shift = (shift.1, -shift.0);
563        }
564    }
565
566    for i in 1..clusters.len() {
567        if shifts[i] != shifts[i - 1] {
568            clusters[i].has_relative_shift = true;
569        }
570    }
571
572    let mut left = f32::INFINITY;
573    let mut right = f32::NEG_INFINITY;
574    let mut advance = 0.0;
575    for (cluster, (shift_x, _)) in clusters.iter().zip(&shifts) {
576        let start = advance + shift_x;
577        let end = start + cluster.advance - cluster.text_length_spacing;
578        left = left.min(start).min(end);
579        right = right.max(start).max(end);
580        advance += cluster.advance;
581    }
582
583    let mut x = shifts[first].0 - left + process_anchor(chunk.anchor, right - left);
584
585    for (cluster, (shift_x, shift_y)) in clusters.iter_mut().zip(&shifts) {
586        let cp = offset + cluster.byte_idx.code_point_at(&chunk.text);
587
588        cluster.transform = cluster.transform.pre_translate(x + shift_x, *shift_y);
589
590        if let Some(angle) = text.rotate.get(cp).cloned() {
591            if !angle.approx_zero_ulps(4) {
592                cluster.transform = cluster.transform.pre_rotate(angle);
593                cluster.has_relative_shift = true;
594            }
595        }
596
597        x += cluster.advance;
598    }
599
600    (x + shifts[last].0, shifts[last].1)
601}
602
603// Baseline resolving in SVG is a mess.
604// Not only it's poorly documented, but as soon as you start mixing
605// `dominant-baseline` and `alignment-baseline` each application/browser will produce
606// different results.
607//
608// For now, resvg simply tries to match Chrome's output and not the mythical SVG spec output.
609//
610// See `alignment_baseline_shift` method comment for more details.
611pub(crate) fn resolve_baseline(
612    span: &TextSpan,
613    font: &ResolvedFont,
614    writing_mode: WritingMode,
615) -> f32 {
616    let mut shift = -resolve_baseline_shift(&span.baseline_shift, font, span.font_size.get());
617
618    // TODO: support vertical layout as well
619    if writing_mode == WritingMode::LeftToRight {
620        if span.alignment_baseline == AlignmentBaseline::Auto
621            || span.alignment_baseline == AlignmentBaseline::Baseline
622        {
623            shift += font.dominant_baseline_shift(span.dominant_baseline, span.font_size.get());
624        } else {
625            shift += font.alignment_baseline_shift(span.alignment_baseline, span.font_size.get());
626        }
627    }
628
629    shift
630}
631
632fn resolve_baseline_shift(baselines: &[BaselineShift], font: &ResolvedFont, font_size: f32) -> f32 {
633    let mut shift = 0.0;
634    for baseline in baselines.iter().rev() {
635        match baseline {
636            BaselineShift::Baseline => {}
637            BaselineShift::Subscript => shift -= font.subscript_offset(font_size),
638            BaselineShift::Superscript => shift += font.superscript_offset(font_size),
639            BaselineShift::Number(n) => shift += n,
640        }
641    }
642
643    shift
644}
645
646fn resolve_clusters_positions_path(
647    text: &Text,
648    chunk: &TextChunk,
649    char_offset: usize,
650    path: &TextPath,
651    writing_mode: WritingMode,
652    fonts_cache: &FontsCache,
653    clusters: &mut [GlyphCluster],
654) -> (f32, f32) {
655    let mut last_x = 0.0;
656    let mut last_y = 0.0;
657
658    let (shifts, _) = resolve_relative_shifts(text, chunk, char_offset, clusters);
659
660    // In the text path mode, chunk's x/y coordinates provide an additional offset along the path.
661    // The X coordinate is used in a horizontal mode, and Y in vertical.
662    let chunk_offset = match writing_mode {
663        WritingMode::LeftToRight => chunk.x.unwrap_or(0.0),
664        WritingMode::TopToBottom => chunk.y.unwrap_or(0.0),
665    };
666
667    let start_offset =
668        chunk_offset + path.start_offset + process_anchor(chunk.anchor, clusters_length(clusters));
669
670    let normals = collect_normals(text, clusters, &shifts, &path.path, start_offset);
671    for ((cluster, normal), (_, dy)) in clusters.iter_mut().zip(normals).zip(shifts) {
672        let (x, y, angle) = match normal {
673            Some(normal) => (normal.x, normal.y, normal.angle),
674            None => {
675                // Hide clusters that are outside the text path.
676                cluster.visible = false;
677                continue;
678            }
679        };
680
681        // We have to break a decoration line for each cluster during text-on-path.
682        cluster.has_relative_shift = true;
683
684        let orig_ts = cluster.transform;
685
686        // Clusters should be rotated by the x-midpoint x baseline position.
687        let half_width = cluster.width / 2.0;
688        cluster.transform = Transform::default();
689        cluster.transform = cluster.transform.pre_translate(x - half_width, y);
690        cluster.transform = cluster.transform.pre_rotate_at(angle, half_width, 0.0);
691
692        let cp = char_offset + cluster.byte_idx.code_point_at(&chunk.text);
693
694        let baseline_shift = chunk_span_at(chunk, cluster.byte_idx)
695            .map(|span| {
696                let font = match fonts_cache.get(&span.font) {
697                    Some(v) => v,
698                    None => return 0.0,
699                };
700                -resolve_baseline(span, font, writing_mode)
701            })
702            .unwrap_or(0.0);
703
704        // Shift only by `dy` since we already applied `dx`
705        // during offset along the path calculation.
706        if !dy.approx_zero_ulps(4) || !baseline_shift.approx_zero_ulps(4) {
707            let shift = kurbo::Vec2::new(0.0, (dy - baseline_shift) as f64);
708            cluster.transform = cluster
709                .transform
710                .pre_translate(shift.x as f32, shift.y as f32);
711        }
712
713        if let Some(angle) = text.rotate.get(cp).cloned() {
714            if !angle.approx_zero_ulps(4) {
715                cluster.transform = cluster.transform.pre_rotate(angle);
716            }
717        }
718
719        // The possible `lengthAdjust` transform should be applied after text-on-path positioning.
720        cluster.transform = cluster.transform.pre_concat(orig_ts);
721
722        last_x = x + cluster.advance;
723        last_y = y;
724    }
725
726    (last_x, last_y)
727}
728
729pub(crate) fn process_anchor(a: TextAnchor, text_width: f32) -> f32 {
730    match a {
731        TextAnchor::Start => 0.0, // Nothing.
732        TextAnchor::Middle => -text_width / 2.0,
733        TextAnchor::End => -text_width,
734    }
735}
736
737pub(crate) struct PathNormal {
738    pub(crate) x: f32,
739    pub(crate) y: f32,
740    pub(crate) angle: f32,
741}
742
743fn collect_normals(
744    text: &Text,
745    clusters: &[GlyphCluster],
746    shifts: &[(f32, f32)],
747    path: &tiny_skia_path::Path,
748    offset: f32,
749) -> Vec<Option<PathNormal>> {
750    let mut offsets = Vec::with_capacity(clusters.len());
751    let mut normals = Vec::with_capacity(clusters.len());
752    {
753        let mut advance = offset;
754        for (cluster, (shift_x, _)) in clusters.iter().zip(shifts) {
755            // Clusters should be rotated by the x-midpoint x baseline position.
756            let half_width = cluster.width / 2.0;
757
758            let offset = advance + shift_x + half_width;
759
760            // Clusters outside the path have no normals.
761            if offset < 0.0 {
762                normals.push(None);
763            }
764
765            offsets.push(offset as f64);
766            advance += cluster.advance;
767        }
768    }
769
770    let mut prev_mx = path.points()[0].x;
771    let mut prev_my = path.points()[0].y;
772    let mut prev_x = prev_mx;
773    let mut prev_y = prev_my;
774
775    fn create_curve_from_line(px: f32, py: f32, x: f32, y: f32) -> kurbo::CubicBez {
776        let line = kurbo::Line::new(
777            kurbo::Point::new(px as f64, py as f64),
778            kurbo::Point::new(x as f64, y as f64),
779        );
780        let p1 = line.eval(0.33);
781        let p2 = line.eval(0.66);
782        kurbo::CubicBez {
783            p0: line.p0,
784            p1,
785            p2,
786            p3: line.p1,
787        }
788    }
789
790    let mut length: f64 = 0.0;
791    for seg in path.segments() {
792        let curve = match seg {
793            tiny_skia_path::PathSegment::MoveTo(p) => {
794                prev_mx = p.x;
795                prev_my = p.y;
796                prev_x = p.x;
797                prev_y = p.y;
798                continue;
799            }
800            tiny_skia_path::PathSegment::LineTo(p) => {
801                create_curve_from_line(prev_x, prev_y, p.x, p.y)
802            }
803            tiny_skia_path::PathSegment::QuadTo(p1, p) => kurbo::QuadBez {
804                p0: kurbo::Point::new(prev_x as f64, prev_y as f64),
805                p1: kurbo::Point::new(p1.x as f64, p1.y as f64),
806                p2: kurbo::Point::new(p.x as f64, p.y as f64),
807            }
808            .raise(),
809            tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => kurbo::CubicBez {
810                p0: kurbo::Point::new(prev_x as f64, prev_y as f64),
811                p1: kurbo::Point::new(p1.x as f64, p1.y as f64),
812                p2: kurbo::Point::new(p2.x as f64, p2.y as f64),
813                p3: kurbo::Point::new(p.x as f64, p.y as f64),
814            },
815            tiny_skia_path::PathSegment::Close => {
816                create_curve_from_line(prev_x, prev_y, prev_mx, prev_my)
817            }
818        };
819
820        let arclen_accuracy = {
821            let base_arclen_accuracy = 0.5;
822            // Accuracy depends on a current scale.
823            // When we have a tiny path scaled by a large value,
824            // we have to increase out accuracy accordingly.
825            let (sx, sy) = text.abs_transform.get_scale();
826            // 1.0 acts as a threshold to prevent division by 0 and/or low accuracy.
827            base_arclen_accuracy / (sx * sy).sqrt().max(1.0)
828        };
829
830        let curve_len = curve.arclen(arclen_accuracy as f64);
831
832        for offset in &offsets[normals.len()..] {
833            if *offset >= length && *offset <= length + curve_len {
834                let mut offset = curve.inv_arclen(offset - length, arclen_accuracy as f64);
835                // some rounding error may occur, so we give offset a little tolerance
836                debug_assert!((-1.0e-3..=1.0 + 1.0e-3).contains(&offset));
837                offset = offset.clamp(0.0, 1.0);
838
839                let pos = curve.eval(offset);
840                let d = curve.deriv().eval(offset);
841                let d = kurbo::Vec2::new(-d.y, d.x); // tangent
842                let angle = d.atan2().to_degrees() - 90.0;
843
844                normals.push(Some(PathNormal {
845                    x: pos.x as f32,
846                    y: pos.y as f32,
847                    angle: angle as f32,
848                }));
849
850                if normals.len() == offsets.len() {
851                    break;
852                }
853            }
854        }
855
856        length += curve_len;
857        prev_x = curve.p3.x as f32;
858        prev_y = curve.p3.y as f32;
859    }
860
861    // If path ended and we still have unresolved normals - set them to `None`.
862    for _ in 0..(offsets.len() - normals.len()) {
863        normals.push(None);
864    }
865
866    normals
867}
868
869/// Converts a text chunk into a list of outlined clusters.
870///
871/// This function will do the BIDI reordering, text shaping and glyphs outlining,
872/// but not the text layouting. So all clusters are in the 0x0 position.
873fn process_chunk(
874    chunk: &TextChunk,
875    resolver: &FontResolver,
876    fonts: &mut FontCache,
877) -> Vec<GlyphCluster> {
878    // The way this function works is a bit tricky.
879    //
880    // The first problem is BIDI reordering.
881    // We cannot shape text span-by-span, because glyph clusters are not guarantee to be continuous.
882    //
883    // For example:
884    // <text>Hel<tspan fill="url(#lg1)">lo של</tspan>ום.</text>
885    //
886    // Would be shaped as:
887    // H e l l o   ש ל  ו  ם .   (characters)
888    // 0 1 2 3 4 5 12 10 8 6 14  (cluster indices in UTF-8)
889    //       ---         ---     (green span)
890    //
891    // As you can see, our continuous `lo של` span was split into two separated one.
892    // So our 3 spans: black - green - black, become 5 spans: black - green - black - green - black.
893    // If we shape `Hel`, then `lo של` an then `ום` separately - we would get an incorrect output.
894    // To properly handle this we simply shape the whole chunk.
895    //
896    // But this introduces another issue - what to do when we have multiple fonts?
897    // The easy solution would be to simply shape text with each font,
898    // where the first font output is used as a base one and all others overwrite it.
899    // This way in case of:
900    // <text font-family="Arial">Hello <tspan font-family="Helvetica">world</tspan></text>
901    // we would replace Arial glyphs for `world` with Helvetica one. Pretty simple.
902    //
903    // Well, it would work most of the time, but not always.
904    // This is because different fonts can produce different amount of glyphs for the same text.
905    // The most common example are ligatures. Some fonts can shape `fi` as two glyphs `f` and `i`,
906    // but some can use `fi` (U+FB01) instead.
907    // Meaning that during merging we have to overwrite not individual glyphs, but clusters.
908
909    // Glyph splitting assigns distinct glyphs to the same index in the original text, we need to
910    // store previously used indices to make sure we do not re-use the same index while overwriting
911    // span glyphs.
912    let mut positions = HashSet::new();
913
914    let mut glyphs = Vec::new();
915    for span in &chunk.spans {
916        let font = match fonts.resolved.get(&span.font) {
917            Some(v) => v.clone(),
918            None => continue,
919        };
920
921        let tmp_glyphs = shape_text(
922            &chunk.text,
923            font,
924            span.small_caps,
925            span.apply_kerning,
926            &span.font.variations,
927            span.font_size.get(),
928            span.font_optical_sizing,
929            resolver,
930            fonts,
931        );
932
933        // Do nothing with the first run.
934        if glyphs.is_empty() {
935            glyphs = tmp_glyphs;
936            continue;
937        }
938
939        positions.clear();
940
941        // Overwrite span's glyphs.
942        let mut iter = tmp_glyphs.into_iter();
943        while let Some(new_glyph) = iter.next() {
944            if !span_contains(span, new_glyph.byte_idx) {
945                continue;
946            }
947
948            let Some(idx) = glyphs
949                .iter()
950                .position(|g| g.byte_idx == new_glyph.byte_idx)
951                .filter(|pos| !positions.contains(pos))
952            else {
953                continue;
954            };
955
956            positions.insert(idx);
957
958            let prev_cluster_len = glyphs[idx].cluster_len;
959            if prev_cluster_len < new_glyph.cluster_len {
960                // If the new font represents the same cluster with fewer glyphs
961                // then remove remaining glyphs.
962                for _ in 1..new_glyph.cluster_len {
963                    glyphs.remove(idx + 1);
964                }
965            } else if prev_cluster_len > new_glyph.cluster_len {
966                // If the new font represents the same cluster with more glyphs
967                // then insert them after the current one.
968                for j in 1..prev_cluster_len {
969                    if let Some(g) = iter.next() {
970                        glyphs.insert(idx + j, g);
971                    }
972                }
973            }
974
975            glyphs[idx] = new_glyph;
976        }
977    }
978
979    // Convert glyphs to clusters.
980    let mut clusters = Vec::new();
981    for (range, byte_idx) in GlyphClusters::new(&glyphs) {
982        if let Some(span) = chunk_span_at(chunk, byte_idx) {
983            clusters.push(form_glyph_clusters(
984                &glyphs[range],
985                &chunk.text,
986                span.font_size.get(),
987            ));
988        }
989    }
990
991    clusters
992}
993
994fn apply_length_adjust(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {
995    let is_horizontal = matches!(chunk.text_flow, TextFlow::Linear);
996
997    for span in &chunk.spans {
998        let target_width = match span.text_length {
999            Some(v) => v,
1000            None => continue,
1001        };
1002
1003        let mut width = 0.0;
1004        let mut cluster_indexes = Vec::new();
1005        for i in span.start..span.end {
1006            if let Some(index) = clusters.iter().position(|c| c.byte_idx.value() == i) {
1007                cluster_indexes.push(index);
1008            }
1009        }
1010        // Complex scripts can have multi-codepoint clusters therefore we have to remove duplicates.
1011        cluster_indexes.sort();
1012        cluster_indexes.dedup();
1013
1014        for i in &cluster_indexes {
1015            // Use the original cluster `width` and not `advance`.
1016            // This method essentially discards any `word-spacing` and `letter-spacing`.
1017            width += clusters[*i].width;
1018        }
1019
1020        if cluster_indexes.is_empty() {
1021            continue;
1022        }
1023
1024        if span.length_adjust == LengthAdjust::Spacing {
1025            let factor = if cluster_indexes.len() > 1 {
1026                (target_width - width) / (cluster_indexes.len() - 1) as f32
1027            } else {
1028                0.0
1029            };
1030
1031            for i in cluster_indexes {
1032                clusters[i].advance = clusters[i].width + factor;
1033                clusters[i].text_length_spacing = factor;
1034            }
1035        } else {
1036            let factor = target_width / width;
1037            // Prevent multiplying by zero.
1038            if factor < 0.001 {
1039                continue;
1040            }
1041
1042            for i in cluster_indexes {
1043                clusters[i].transform = clusters[i].transform.pre_scale(factor, 1.0);
1044
1045                // Technically just a hack to support the current text-on-path algorithm.
1046                if !is_horizontal {
1047                    clusters[i].advance *= factor;
1048                    clusters[i].width *= factor;
1049                }
1050            }
1051        }
1052    }
1053}
1054
1055/// Rotates clusters according to
1056/// [Unicode Vertical_Orientation Property](https://www.unicode.org/reports/tr50/tr50-19.html).
1057fn apply_writing_mode(writing_mode: WritingMode, clusters: &mut [GlyphCluster]) {
1058    if writing_mode != WritingMode::TopToBottom {
1059        return;
1060    }
1061
1062    for cluster in clusters {
1063        let orientation = unicode_vo::char_orientation(cluster.codepoint);
1064        if orientation == unicode_vo::Orientation::Upright {
1065            let mut ts = Transform::default();
1066            // Position glyph in the center of vertical axis.
1067            ts = ts.pre_translate(0.0, (cluster.ascent + cluster.descent) / 2.0);
1068            // Rotate by 90 degrees in the center.
1069            ts = ts.pre_rotate_at(
1070                -90.0,
1071                cluster.width / 2.0,
1072                -(cluster.ascent + cluster.descent) / 2.0,
1073            );
1074
1075            cluster.path_transform = ts;
1076
1077            // Move "baseline" to the middle and make height equal to width.
1078            cluster.ascent = cluster.width / 2.0;
1079            cluster.descent = -cluster.width / 2.0;
1080        } else {
1081            // Could not find a spec that explains this,
1082            // but this is how other applications are shifting the "rotated" characters
1083            // in the top-to-bottom mode.
1084            cluster.transform = cluster
1085                .transform
1086                .pre_translate(0.0, (cluster.ascent + cluster.descent) / 2.0);
1087        }
1088    }
1089}
1090
1091/// Applies the `letter-spacing` property to a text chunk clusters.
1092///
1093/// [In the CSS spec](https://www.w3.org/TR/css-text-3/#letter-spacing-property).
1094fn apply_letter_spacing(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {
1095    // At least one span should have a non-zero spacing.
1096    if !chunk
1097        .spans
1098        .iter()
1099        .any(|span| !span.letter_spacing.approx_zero_ulps(4))
1100    {
1101        return;
1102    }
1103
1104    let num_clusters = clusters.len();
1105    for (i, cluster) in clusters.iter_mut().enumerate() {
1106        // Spacing must be applied only to characters that belongs to the script
1107        // that supports spacing.
1108        // We are checking only the first code point, since it should be enough.
1109        // https://www.w3.org/TR/css-text-3/#cursive-tracking
1110        let script = cluster.codepoint.script();
1111        if script_supports_letter_spacing(script) {
1112            if let Some(span) = chunk_span_at(chunk, cluster.byte_idx) {
1113                // A space after the last cluster should be ignored,
1114                // since it affects the bbox and text alignment.
1115                if i != num_clusters - 1 {
1116                    cluster.advance += span.letter_spacing;
1117                }
1118
1119                // If the cluster advance became negative - clear it.
1120                // This is an UB so we can do whatever we want, and we mimic Chrome's behavior.
1121                if !cluster.advance.is_valid_length() {
1122                    cluster.width = 0.0;
1123                    cluster.advance = 0.0;
1124                    cluster.glyphs = vec![];
1125                }
1126            }
1127        }
1128    }
1129}
1130
1131/// Applies the `word-spacing` property to a text chunk clusters.
1132///
1133/// [In the CSS spec](https://www.w3.org/TR/css-text-3/#propdef-word-spacing).
1134fn apply_word_spacing(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {
1135    // At least one span should have a non-zero spacing.
1136    if !chunk
1137        .spans
1138        .iter()
1139        .any(|span| !span.word_spacing.approx_zero_ulps(4))
1140    {
1141        return;
1142    }
1143
1144    for cluster in clusters {
1145        if is_word_separator_characters(cluster.codepoint) {
1146            if let Some(span) = chunk_span_at(chunk, cluster.byte_idx) {
1147                // Technically, word spacing 'should be applied half on each
1148                // side of the character', but it doesn't affect us in any way,
1149                // so we are ignoring this.
1150                cluster.advance += span.word_spacing;
1151
1152                // After word spacing, `advance` can be negative.
1153            }
1154        }
1155    }
1156}
1157
1158fn form_glyph_clusters(glyphs: &[Glyph], text: &str, font_size: f32) -> GlyphCluster {
1159    debug_assert!(!glyphs.is_empty());
1160
1161    let mut x = 0.0;
1162    let mut width = 0.0;
1163    let mut advance = 0.0;
1164
1165    let mut positioned_glyphs = vec![];
1166
1167    for glyph in glyphs {
1168        let sx = glyph.font.scale(font_size);
1169
1170        // Apply offset.
1171        //
1172        // The first glyph in the cluster will have an offset from 0x0,
1173        // but the later one will have an offset from the "current position".
1174        // So we have to keep an advance.
1175        // TODO: should be done only inside a single text span
1176        let ts = Transform::from_translate(x + glyph.dx as f32, -glyph.dy as f32);
1177
1178        positioned_glyphs.push(PositionedGlyph {
1179            glyph_ts: ts,
1180            // Will be set later.
1181            cluster_ts: Transform::default(),
1182            // Will be set later.
1183            span_ts: Transform::default(),
1184            units_per_em: glyph.font.units_per_em.get(),
1185            font_size,
1186            font: glyph.font.id,
1187            text: glyph.text.clone(),
1188            id: glyph.id,
1189        });
1190
1191        x += glyph.width as f32;
1192
1193        let glyph_width = glyph.width as f32 * sx;
1194        advance += glyph_width;
1195        if glyph_width > width {
1196            width = glyph_width;
1197        }
1198    }
1199
1200    let byte_idx = glyphs[0].byte_idx;
1201    let font = glyphs[0].font.clone();
1202    GlyphCluster {
1203        byte_idx,
1204        codepoint: byte_idx.char_from(text),
1205        width,
1206        advance,
1207        text_length_spacing: 0.0,
1208        ascent: font.ascent(font_size),
1209        descent: font.descent(font_size),
1210        has_relative_shift: false,
1211        transform: Transform::default(),
1212        path_transform: Transform::default(),
1213        glyphs: positioned_glyphs,
1214        visible: true,
1215    }
1216}
1217
1218#[inline(never)]
1219fn resolve_font(
1220    id: ID,
1221    variations: &[crate::FontVariation],
1222    fonts: &mut FontCache,
1223) -> Option<ResolvedFont> {
1224    let font = &fonts.load(id)?.instance(variations.iter().copied()).font;
1225    let metrics = font.metrics();
1226
1227    // Reject fonts with an out-of-range unitsPerEm, like `ttf-parser` did.
1228    if !(16..=16384).contains(&metrics.raw_units_per_em) {
1229        return None;
1230    }
1231    let units_per_em = NonZeroU16::new(metrics.raw_units_per_em)?;
1232
1233    let line = metrics.h_line().unwrap_or_default();
1234    let ascent = line.ascender.to_f32();
1235    let descent = line.descender.to_f32();
1236
1237    let x_height = metrics
1238        .x_height
1239        .map(|x| x.to_f32())
1240        .filter(|x| *x > 0.0)
1241        .and_then(|x| u16::try_from(x.round() as i32).ok())
1242        .and_then(NonZeroU16::new);
1243    let x_height = match x_height {
1244        Some(height) => height,
1245        None => {
1246            // If not set - fallback to height * 45%.
1247            // 45% is what Firefox uses.
1248            u16::try_from(((ascent - descent) * 0.45).round() as i32)
1249                .ok()
1250                .and_then(NonZeroU16::new)?
1251        }
1252    };
1253
1254    let style_metrics = font.style_metrics();
1255
1256    let line_through_position = match style_metrics.strike_through {
1257        Some(metrics) => metrics.position.to_f32().round() as i16,
1258        None => x_height.get() as i16 / 2,
1259    };
1260
1261    let (underline_position, underline_thickness) = match style_metrics.underline {
1262        Some(metrics) => {
1263            let thickness = u16::try_from(metrics.thickness.to_f32().round() as i32)
1264                .ok()
1265                .and_then(NonZeroU16::new)
1266                .unwrap_or_else(|| NonZeroU16::new(units_per_em.get() / 12).unwrap());
1267
1268            (metrics.position.to_f32().round() as i16, thickness)
1269        }
1270        None => (
1271            -(units_per_em.get() as i16) / 9,
1272            NonZeroU16::new(units_per_em.get() / 12).unwrap(),
1273        ),
1274    };
1275
1276    // 0.2 and 0.4 are generic offsets used by some applications (Inkscape/librsvg).
1277    let subscript_offset = match style_metrics.subscript {
1278        Some(metrics) => metrics.y_offset.to_f32().round() as i16,
1279        None => (units_per_em.get() as f32 / 0.2).round() as i16,
1280    };
1281    let superscript_offset = match style_metrics.superscript {
1282        Some(metrics) => metrics.y_offset.to_f32().round() as i16,
1283        None => (units_per_em.get() as f32 / 0.4).round() as i16,
1284    };
1285
1286    Some(ResolvedFont {
1287        id,
1288        units_per_em,
1289        ascent: ascent.round() as i16,
1290        descent: descent.round() as i16,
1291        x_height,
1292        underline_position,
1293        underline_thickness,
1294        line_through_position,
1295        subscript_offset,
1296        superscript_offset,
1297    })
1298}
1299
1300/// Text shaping with font fallback.
1301pub(crate) fn shape_text(
1302    text: &str,
1303    font: Arc<ResolvedFont>,
1304    small_caps: bool,
1305    apply_kerning: bool,
1306    variations: &[crate::FontVariation],
1307    font_size: f32,
1308    font_optical_sizing: crate::FontOpticalSizing,
1309    resolver: &FontResolver,
1310    fonts: &mut FontCache,
1311) -> Vec<Glyph> {
1312    let shaping_variations = with_optical_sizing(variations, font_optical_sizing, font_size);
1313
1314    let mut glyphs = shape_text_with_font(
1315        text,
1316        font.clone(),
1317        small_caps,
1318        apply_kerning,
1319        shaping_variations.clone(),
1320        fonts,
1321    )
1322    .unwrap_or_default();
1323
1324    // Remember all fonts used for shaping.
1325    let mut used_fonts = vec![font.id];
1326
1327    // Loop until all glyphs become resolved or until no more fonts are left.
1328    'outer: loop {
1329        let mut missing = None;
1330        for glyph in &glyphs {
1331            if glyph.is_missing() {
1332                missing = Some(glyph.byte_idx.char_from(text));
1333                break;
1334            }
1335        }
1336
1337        if let Some(c) = missing {
1338            let fallback_font = match (resolver.select_fallback)(c, &used_fonts, &mut fonts.fontdb)
1339                .and_then(|id| resolve_font(id, variations, fonts))
1340            {
1341                Some(v) => Arc::new(v),
1342                None => break 'outer,
1343            };
1344
1345            // Shape again, using a new font.
1346            let fallback_glyphs = shape_text_with_font(
1347                text,
1348                fallback_font.clone(),
1349                small_caps,
1350                apply_kerning,
1351                shaping_variations.clone(),
1352                fonts,
1353            )
1354            .unwrap_or_default();
1355
1356            let all_matched = fallback_glyphs.iter().all(|g| !g.is_missing());
1357            if all_matched {
1358                // Replace all glyphs when all of them were matched.
1359                glyphs = fallback_glyphs;
1360                break 'outer;
1361            }
1362
1363            // We assume, that shaping with an any font will produce the same amount of glyphs.
1364            // This is incorrect, but good enough for now.
1365            if glyphs.len() != fallback_glyphs.len() {
1366                break 'outer;
1367            }
1368
1369            // TODO: Replace clusters and not glyphs. This should be more accurate.
1370
1371            // Copy new glyphs.
1372            for i in 0..glyphs.len() {
1373                if glyphs[i].is_missing() && !fallback_glyphs[i].is_missing() {
1374                    glyphs[i] = fallback_glyphs[i].clone();
1375                }
1376            }
1377
1378            // Remember this font.
1379            used_fonts.push(fallback_font.id);
1380        } else {
1381            break 'outer;
1382        }
1383    }
1384
1385    // Warn about missing glyphs.
1386    for glyph in &glyphs {
1387        if glyph.is_missing() {
1388            let c = glyph.byte_idx.char_from(text);
1389            // TODO: print a full grapheme
1390            log::warn!(
1391                "No fonts with a {}/U+{:X} character were found.",
1392                c,
1393                c as u32
1394            );
1395        }
1396    }
1397
1398    glyphs
1399}
1400
1401/// Converts a text into a list of glyph IDs.
1402///
1403/// This function will do the BIDI reordering and text shaping.
1404fn shape_text_with_font(
1405    text: &str,
1406    font: Arc<ResolvedFont>,
1407    small_caps: bool,
1408    apply_kerning: bool,
1409    variations: impl IntoIterator<Item = crate::FontVariation>,
1410    fonts: &mut FontCache,
1411) -> Option<Vec<Glyph>> {
1412    use harfrust::{Buffer, Feature, ShapePlan, ShapePlanKey, ShaperFont, Tag};
1413
1414    let FontInstance {
1415        font: hr_font,
1416        plans,
1417        ..
1418    } = fonts.load(font.id)?.instance(variations);
1419
1420    let bidi_info = unicode_bidi::BidiInfo::new(text, Some(unicode_bidi::Level::ltr()));
1421    let paragraph = &bidi_info.paragraphs[0];
1422    let line = paragraph.range.clone();
1423
1424    let mut glyphs = Vec::new();
1425
1426    let shaper = ShaperFont::new(hr_font);
1427
1428    let mut features = Vec::new();
1429    if small_caps {
1430        features.push(Feature::new(Tag::new(b"smcp"), 1, ..));
1431    }
1432    if !apply_kerning {
1433        features.push(Feature::new(Tag::new(b"kern"), 0, ..));
1434    }
1435
1436    let (levels, runs) = bidi_info.visual_runs(paragraph, line);
1437    for run in runs.iter() {
1438        let sub_text = &text[run.clone()];
1439        if sub_text.is_empty() {
1440            continue;
1441        }
1442
1443        let ltr = levels[run.start].is_ltr();
1444        let direction = if ltr {
1445            harfrust::Direction::LeftToRight
1446        } else {
1447            harfrust::Direction::RightToLeft
1448        };
1449
1450        let mut buffer = Buffer::new();
1451        buffer.push_str(sub_text);
1452        buffer.set_direction(direction);
1453
1454        // TODO: explicitly set language?
1455        buffer.guess_segment_properties();
1456
1457        let key = ShapePlanKey::new(hr_font, buffer.script(), direction)
1458            .language(buffer.language())
1459            .features(&features);
1460        let plan = match plans.iter().position(|plan| key.matches(plan)) {
1461            Some(index) => &plans[index],
1462            None => {
1463                plans.push(ShapePlan::new(
1464                    hr_font,
1465                    direction,
1466                    buffer.script(),
1467                    buffer.language(),
1468                    &features,
1469                ));
1470                plans.last()?
1471            }
1472        };
1473
1474        harfrust::shape(
1475            &shaper,
1476            &mut buffer,
1477            ShapeOptions::new().features(&features).plan(Some(plan)),
1478        )
1479        .ok()?;
1480
1481        let positions = buffer.glyph_positions();
1482        let infos = buffer.glyph_infos();
1483
1484        for i in 0..buffer.len() {
1485            let pos = positions[i];
1486            let info = infos[i];
1487            let idx = run.start + info.cluster as usize;
1488
1489            let start = info.cluster as usize;
1490
1491            let end = if ltr {
1492                i.checked_add(1)
1493            } else {
1494                i.checked_sub(1)
1495            }
1496            .and_then(|last| infos.get(last))
1497            .map_or(sub_text.len(), |info| info.cluster as usize);
1498
1499            glyphs.push(Glyph {
1500                byte_idx: ByteIndex::new(idx),
1501                cluster_len: end.checked_sub(start).unwrap_or(0), // TODO: can fail?
1502                text: sub_text[start..end].to_string(),
1503                id: GlyphId(info.glyph_id),
1504                dx: pos.x_offset,
1505                dy: pos.y_offset,
1506                width: pos.x_advance,
1507                font: font.clone(),
1508            });
1509        }
1510    }
1511
1512    Some(glyphs)
1513}
1514
1515/// An iterator over glyph clusters.
1516///
1517/// Input:  0 2 2 2 3 4 4 5 5
1518/// Result: 0 1     4 5   7
1519pub(crate) struct GlyphClusters<'a> {
1520    data: &'a [Glyph],
1521    idx: usize,
1522}
1523
1524impl<'a> GlyphClusters<'a> {
1525    pub(crate) fn new(data: &'a [Glyph]) -> Self {
1526        GlyphClusters { data, idx: 0 }
1527    }
1528}
1529
1530impl Iterator for GlyphClusters<'_> {
1531    type Item = (std::ops::Range<usize>, ByteIndex);
1532
1533    fn next(&mut self) -> Option<Self::Item> {
1534        if self.idx == self.data.len() {
1535            return None;
1536        }
1537
1538        let start = self.idx;
1539        let cluster = self.data[self.idx].byte_idx;
1540        for g in &self.data[self.idx..] {
1541            if g.byte_idx != cluster {
1542                break;
1543            }
1544
1545            self.idx += 1;
1546        }
1547
1548        Some((start..self.idx, cluster))
1549    }
1550}
1551
1552/// Checks that selected script supports letter spacing.
1553///
1554/// [In the CSS spec](https://www.w3.org/TR/css-text-3/#cursive-tracking).
1555///
1556/// The list itself is from: https://github.com/harfbuzz/harfbuzz/issues/64
1557pub(crate) fn script_supports_letter_spacing(script: unicode_script::Script) -> bool {
1558    use unicode_script::Script;
1559
1560    !matches!(
1561        script,
1562        Script::Arabic
1563            | Script::Syriac
1564            | Script::Nko
1565            | Script::Manichaean
1566            | Script::Psalter_Pahlavi
1567            | Script::Mandaic
1568            | Script::Mongolian
1569            | Script::Phags_Pa
1570            | Script::Devanagari
1571            | Script::Bengali
1572            | Script::Gurmukhi
1573            | Script::Modi
1574            | Script::Sharada
1575            | Script::Syloti_Nagri
1576            | Script::Tirhuta
1577            | Script::Ogham
1578    )
1579}
1580
1581/// A glyph.
1582///
1583/// Basically, a glyph ID and it's metrics.
1584#[derive(Clone)]
1585pub(crate) struct Glyph {
1586    /// The glyph ID in the font.
1587    pub(crate) id: GlyphId,
1588
1589    /// Position in bytes in the original string.
1590    ///
1591    /// We use it to match a glyph with a character in the text chunk and therefore with the style.
1592    pub(crate) byte_idx: ByteIndex,
1593
1594    // The length of the cluster in bytes.
1595    pub(crate) cluster_len: usize,
1596
1597    /// The text from the original string that corresponds to that glyph.
1598    pub(crate) text: String,
1599
1600    /// The glyph offset in font units.
1601    pub(crate) dx: i32,
1602
1603    /// The glyph offset in font units.
1604    pub(crate) dy: i32,
1605
1606    /// The glyph width / X-advance in font units.
1607    pub(crate) width: i32,
1608
1609    /// Reference to the source font.
1610    ///
1611    /// Each glyph can have it's own source font.
1612    pub(crate) font: Arc<ResolvedFont>,
1613}
1614
1615impl Glyph {
1616    fn is_missing(&self) -> bool {
1617        self.id.0 == 0
1618    }
1619}
1620
1621#[derive(Clone, Copy, Debug)]
1622pub(crate) struct ResolvedFont {
1623    pub(crate) id: ID,
1624
1625    units_per_em: NonZeroU16,
1626
1627    // All values below are in font units.
1628    ascent: i16,
1629    descent: i16,
1630    x_height: NonZeroU16,
1631
1632    underline_position: i16,
1633    underline_thickness: NonZeroU16,
1634
1635    // line-through thickness should be the the same as underline thickness
1636    // according to the TrueType spec:
1637    // https://docs.microsoft.com/en-us/typography/opentype/spec/os2#ystrikeoutsize
1638    line_through_position: i16,
1639
1640    subscript_offset: i16,
1641    superscript_offset: i16,
1642}
1643
1644pub(crate) fn chunk_span_at(chunk: &TextChunk, byte_offset: ByteIndex) -> Option<&TextSpan> {
1645    chunk
1646        .spans
1647        .iter()
1648        .find(|&span| span_contains(span, byte_offset))
1649}
1650
1651pub(crate) fn span_contains(span: &TextSpan, byte_offset: ByteIndex) -> bool {
1652    byte_offset.value() >= span.start && byte_offset.value() < span.end
1653}
1654
1655/// Checks that the selected character is a word separator.
1656///
1657/// According to: https://www.w3.org/TR/css-text-3/#word-separator
1658pub(crate) fn is_word_separator_characters(c: char) -> bool {
1659    matches!(
1660        c as u32,
1661        0x0020 | 0x00A0 | 0x1361 | 0x010100 | 0x010101 | 0x01039F | 0x01091F
1662    )
1663}
1664
1665impl ResolvedFont {
1666    #[inline]
1667    pub(crate) fn scale(&self, font_size: f32) -> f32 {
1668        font_size / self.units_per_em.get() as f32
1669    }
1670
1671    #[inline]
1672    pub(crate) fn ascent(&self, font_size: f32) -> f32 {
1673        self.ascent as f32 * self.scale(font_size)
1674    }
1675
1676    #[inline]
1677    pub(crate) fn descent(&self, font_size: f32) -> f32 {
1678        self.descent as f32 * self.scale(font_size)
1679    }
1680
1681    #[inline]
1682    pub(crate) fn height(&self, font_size: f32) -> f32 {
1683        self.ascent(font_size) - self.descent(font_size)
1684    }
1685
1686    #[inline]
1687    pub(crate) fn x_height(&self, font_size: f32) -> f32 {
1688        self.x_height.get() as f32 * self.scale(font_size)
1689    }
1690
1691    #[inline]
1692    pub(crate) fn underline_position(&self, font_size: f32) -> f32 {
1693        self.underline_position as f32 * self.scale(font_size)
1694    }
1695
1696    #[inline]
1697    fn underline_thickness(&self, font_size: f32) -> f32 {
1698        self.underline_thickness.get() as f32 * self.scale(font_size)
1699    }
1700
1701    #[inline]
1702    pub(crate) fn line_through_position(&self, font_size: f32) -> f32 {
1703        self.line_through_position as f32 * self.scale(font_size)
1704    }
1705
1706    #[inline]
1707    fn subscript_offset(&self, font_size: f32) -> f32 {
1708        self.subscript_offset as f32 * self.scale(font_size)
1709    }
1710
1711    #[inline]
1712    fn superscript_offset(&self, font_size: f32) -> f32 {
1713        self.superscript_offset as f32 * self.scale(font_size)
1714    }
1715
1716    fn dominant_baseline_shift(&self, baseline: DominantBaseline, font_size: f32) -> f32 {
1717        let alignment = match baseline {
1718            DominantBaseline::Auto => AlignmentBaseline::Auto,
1719            DominantBaseline::UseScript => AlignmentBaseline::Auto, // unsupported
1720            DominantBaseline::NoChange => AlignmentBaseline::Auto,  // already resolved
1721            DominantBaseline::ResetSize => AlignmentBaseline::Auto, // unsupported
1722            DominantBaseline::Ideographic => AlignmentBaseline::Ideographic,
1723            DominantBaseline::Alphabetic => AlignmentBaseline::Alphabetic,
1724            DominantBaseline::Hanging => AlignmentBaseline::Hanging,
1725            DominantBaseline::Mathematical => AlignmentBaseline::Mathematical,
1726            DominantBaseline::Central => AlignmentBaseline::Central,
1727            DominantBaseline::Middle => AlignmentBaseline::Middle,
1728            DominantBaseline::TextAfterEdge => AlignmentBaseline::TextAfterEdge,
1729            DominantBaseline::TextBeforeEdge => AlignmentBaseline::TextBeforeEdge,
1730        };
1731
1732        self.alignment_baseline_shift(alignment, font_size)
1733    }
1734
1735    // The `alignment-baseline` property is a mess.
1736    //
1737    // The SVG 1.1 spec (https://www.w3.org/TR/SVG11/text.html#BaselineAlignmentProperties)
1738    // goes on and on about what this property suppose to do, but doesn't actually explain
1739    // how it should be implemented. It's just a very verbose overview.
1740    //
1741    // As of Nov 2022, only Chrome and Safari support `alignment-baseline`. Firefox isn't.
1742    // Same goes for basically every SVG library in existence.
1743    // Meaning we have no idea how exactly it should be implemented.
1744    //
1745    // And even Chrome and Safari cannot agree on how to handle `baseline`, `after-edge`,
1746    // `text-after-edge` and `ideographic` variants. Producing vastly different output.
1747    //
1748    // As per spec, a proper implementation should get baseline values from the font itself,
1749    // using `BASE` and `bsln` TrueType tables. If those tables are not present,
1750    // we have to synthesize them (https://drafts.csswg.org/css-inline/#baseline-synthesis-fonts).
1751    // And in the worst case scenario simply fallback to hardcoded values.
1752    //
1753    // Also, most fonts do not provide `BASE` and `bsln` tables to begin with.
1754    //
1755    // Again, as of Nov 2022, Chrome does only the latter:
1756    // https://github.com/chromium/chromium/blob/main/third_party/blink/renderer/platform/fonts/font_metrics.cc#L153
1757    //
1758    // Since baseline TrueType tables parsing and baseline synthesis are pretty hard,
1759    // we do what Chrome does - use hardcoded values. And it seems like Safari does the same.
1760    //
1761    //
1762    // But that's not all! SVG 2 and CSS Inline Layout 3 did a baseline handling overhaul,
1763    // and it's far more complex now. Not sure if anyone actually supports it.
1764    fn alignment_baseline_shift(&self, alignment: AlignmentBaseline, font_size: f32) -> f32 {
1765        match alignment {
1766            AlignmentBaseline::Auto => 0.0,
1767            AlignmentBaseline::Baseline => 0.0,
1768            AlignmentBaseline::BeforeEdge | AlignmentBaseline::TextBeforeEdge => {
1769                self.ascent(font_size)
1770            }
1771            AlignmentBaseline::Middle => self.x_height(font_size) * 0.5,
1772            AlignmentBaseline::Central => self.ascent(font_size) - self.height(font_size) * 0.5,
1773            AlignmentBaseline::AfterEdge | AlignmentBaseline::TextAfterEdge => {
1774                self.descent(font_size)
1775            }
1776            AlignmentBaseline::Ideographic => self.descent(font_size),
1777            AlignmentBaseline::Alphabetic => 0.0,
1778            AlignmentBaseline::Hanging => self.ascent(font_size) * 0.8,
1779            AlignmentBaseline::Mathematical => self.ascent(font_size) * 0.5,
1780        }
1781    }
1782}
1783
1784pub(crate) type FontsCache = HashMap<Font, Arc<ResolvedFont>>;
1785
1786/// A read-only text index in bytes.
1787///
1788/// Guarantee to be on a char boundary and in text bounds.
1789#[derive(Clone, Copy, PartialEq, Debug)]
1790pub(crate) struct ByteIndex(usize);
1791
1792impl ByteIndex {
1793    fn new(i: usize) -> Self {
1794        ByteIndex(i)
1795    }
1796
1797    pub(crate) fn value(&self) -> usize {
1798        self.0
1799    }
1800
1801    /// Converts byte position into a code point position.
1802    pub(crate) fn code_point_at(&self, text: &str) -> usize {
1803        text.char_indices()
1804            .take_while(|(i, _)| *i != self.0)
1805            .count()
1806    }
1807
1808    /// Converts byte position into a character.
1809    pub(crate) fn char_from(&self, text: &str) -> char {
1810        text[self.0..].chars().next().unwrap()
1811    }
1812}