Skip to main content

usvg/parser/
text.rs

1// Copyright 2019 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::sync::Arc;
5
6use kurbo::{ParamCurve, ParamCurveArclen};
7use svgtypes::{FontFamily, Length, LengthUnit, parse_font_families};
8
9use super::svgtree::{AId, EId, FromValue, SvgNode};
10use super::{OptionLog, converter, style};
11use crate::*;
12
13impl<'a, 'input: 'a> FromValue<'a, 'input> for TextAnchor {
14    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
15        match value {
16            "start" => Some(TextAnchor::Start),
17            "middle" => Some(TextAnchor::Middle),
18            "end" => Some(TextAnchor::End),
19            _ => None,
20        }
21    }
22}
23
24impl<'a, 'input: 'a> FromValue<'a, 'input> for AlignmentBaseline {
25    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
26        match value {
27            "auto" => Some(AlignmentBaseline::Auto),
28            "baseline" => Some(AlignmentBaseline::Baseline),
29            "before-edge" => Some(AlignmentBaseline::BeforeEdge),
30            "text-before-edge" => Some(AlignmentBaseline::TextBeforeEdge),
31            "middle" => Some(AlignmentBaseline::Middle),
32            "central" => Some(AlignmentBaseline::Central),
33            "after-edge" => Some(AlignmentBaseline::AfterEdge),
34            "text-after-edge" => Some(AlignmentBaseline::TextAfterEdge),
35            "ideographic" => Some(AlignmentBaseline::Ideographic),
36            "alphabetic" => Some(AlignmentBaseline::Alphabetic),
37            "hanging" => Some(AlignmentBaseline::Hanging),
38            "mathematical" => Some(AlignmentBaseline::Mathematical),
39            _ => None,
40        }
41    }
42}
43
44impl<'a, 'input: 'a> FromValue<'a, 'input> for DominantBaseline {
45    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
46        match value {
47            "auto" => Some(DominantBaseline::Auto),
48            "use-script" => Some(DominantBaseline::UseScript),
49            "no-change" => Some(DominantBaseline::NoChange),
50            "reset-size" => Some(DominantBaseline::ResetSize),
51            "ideographic" => Some(DominantBaseline::Ideographic),
52            "alphabetic" => Some(DominantBaseline::Alphabetic),
53            "hanging" => Some(DominantBaseline::Hanging),
54            "mathematical" => Some(DominantBaseline::Mathematical),
55            "central" => Some(DominantBaseline::Central),
56            "middle" => Some(DominantBaseline::Middle),
57            "text-after-edge" => Some(DominantBaseline::TextAfterEdge),
58            "text-before-edge" => Some(DominantBaseline::TextBeforeEdge),
59            _ => None,
60        }
61    }
62}
63
64impl<'a, 'input: 'a> FromValue<'a, 'input> for LengthAdjust {
65    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
66        match value {
67            "spacing" => Some(LengthAdjust::Spacing),
68            "spacingAndGlyphs" => Some(LengthAdjust::SpacingAndGlyphs),
69            _ => None,
70        }
71    }
72}
73
74impl<'a, 'input: 'a> FromValue<'a, 'input> for FontStyle {
75    fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {
76        match value {
77            "normal" => Some(FontStyle::Normal),
78            "italic" => Some(FontStyle::Italic),
79            "oblique" => Some(FontStyle::Oblique),
80            _ => None,
81        }
82    }
83}
84
85/// A text character position.
86///
87/// _Character_ is a Unicode codepoint.
88#[derive(Clone, Copy, Debug)]
89struct CharacterPosition {
90    /// An absolute X axis position.
91    x: Option<f32>,
92    /// An absolute Y axis position.
93    y: Option<f32>,
94    /// A relative X axis offset.
95    dx: Option<f32>,
96    /// A relative Y axis offset.
97    dy: Option<f32>,
98}
99
100pub(crate) fn convert(
101    text_node: SvgNode,
102    state: &converter::State,
103    cache: &mut converter::Cache,
104    parent: &mut Group,
105) {
106    let pos_list = resolve_positions_list(text_node, state);
107    let rotate_list = resolve_rotate_list(text_node);
108    let writing_mode = convert_writing_mode(text_node);
109
110    let chunks = collect_text_chunks(text_node, &pos_list, state, cache);
111
112    let rendering_mode: TextRendering = text_node
113        .find_attribute(AId::TextRendering)
114        .unwrap_or(state.opt.text_rendering);
115
116    // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.
117    let id = if !state.inside_marker {
118        text_node.element_id().to_string()
119    } else {
120        String::new()
121    };
122
123    let dummy = Rect::from_xywh(0.0, 0.0, 0.0, 0.0).unwrap();
124
125    let mut text = Text {
126        id,
127        rendering_mode,
128        dx: pos_list.iter().map(|v| v.dx.unwrap_or(0.0)).collect(),
129        dy: pos_list.iter().map(|v| v.dy.unwrap_or(0.0)).collect(),
130        rotate: rotate_list,
131        writing_mode,
132        chunks,
133        abs_transform: parent.abs_transform,
134        // All fields below will be reset by `text_to_paths`.
135        bounding_box: dummy,
136        abs_bounding_box: dummy,
137        stroke_bounding_box: dummy,
138        abs_stroke_bounding_box: dummy,
139        flattened: Box::new(Group::empty()),
140        layouted: vec![],
141    };
142
143    if text::convert(&mut text, &state.opt.font_resolver, cache).is_none() {
144        return;
145    }
146
147    parent.children.push(Node::Text(Box::new(text)));
148}
149
150struct IterState {
151    chars_count: usize,
152    chunk_bytes_count: usize,
153    split_chunk: bool,
154    text_flow: TextFlow,
155    chunks: Vec<TextChunk>,
156}
157
158fn collect_text_chunks(
159    text_node: SvgNode,
160    pos_list: &[CharacterPosition],
161    state: &converter::State,
162    cache: &mut converter::Cache,
163) -> Vec<TextChunk> {
164    let mut iter_state = IterState {
165        chars_count: 0,
166        chunk_bytes_count: 0,
167        split_chunk: false,
168        text_flow: TextFlow::Linear,
169        chunks: Vec::new(),
170    };
171
172    collect_text_chunks_impl(text_node, pos_list, state, cache, &mut iter_state);
173
174    iter_state.chunks
175}
176
177fn collect_text_chunks_impl(
178    parent: SvgNode,
179    pos_list: &[CharacterPosition],
180    state: &converter::State,
181    cache: &mut converter::Cache,
182    iter_state: &mut IterState,
183) {
184    for child in parent.children() {
185        if child.is_element() {
186            if child.tag_name() == Some(EId::TextPath) {
187                if parent.tag_name() != Some(EId::Text) {
188                    // `textPath` can be set only as a direct `text` element child.
189                    iter_state.chars_count += count_chars(child);
190                    continue;
191                }
192
193                match resolve_text_flow(child, state, cache) {
194                    Some(v) => {
195                        iter_state.text_flow = v;
196                    }
197                    None => {
198                        // Skip an invalid text path and all it's children.
199                        // We have to update the chars count,
200                        // because `pos_list` was calculated including this text path.
201                        iter_state.chars_count += count_chars(child);
202                        continue;
203                    }
204                }
205
206                iter_state.split_chunk = true;
207            }
208
209            collect_text_chunks_impl(child, pos_list, state, cache, iter_state);
210
211            iter_state.text_flow = TextFlow::Linear;
212
213            // Next char after `textPath` should be split too.
214            if child.tag_name() == Some(EId::TextPath) {
215                iter_state.split_chunk = true;
216            }
217
218            continue;
219        }
220
221        if !parent.is_visible_element(state.opt) {
222            iter_state.chars_count += child.text().chars().count();
223            continue;
224        }
225
226        let anchor = parent.find_attribute(AId::TextAnchor).unwrap_or_default();
227
228        // TODO: what to do when <= 0? UB?
229        let font_size = super::units::resolve_font_size(parent, state);
230        let font_size = match NonZeroPositiveF32::new(font_size) {
231            Some(n) => n,
232            None => {
233                // Skip this span.
234                iter_state.chars_count += child.text().chars().count();
235                continue;
236            }
237        };
238
239        let font = convert_font(parent, state);
240
241        let raw_paint_order: svgtypes::PaintOrder =
242            parent.find_attribute(AId::PaintOrder).unwrap_or_default();
243        let paint_order = super::converter::svg_paint_order_to_usvg(raw_paint_order);
244
245        let mut dominant_baseline = parent
246            .find_attribute(AId::DominantBaseline)
247            .unwrap_or_default();
248
249        // `no-change` means "use parent".
250        if dominant_baseline == DominantBaseline::NoChange {
251            dominant_baseline = parent
252                .parent_element()
253                .unwrap()
254                .find_attribute(AId::DominantBaseline)
255                .unwrap_or_default();
256        }
257
258        let mut apply_kerning = true;
259        #[allow(clippy::if_same_then_else)]
260        if parent.resolve_length(AId::Kerning, state, -1.0) == 0.0 {
261            apply_kerning = false;
262        } else if parent.find_attribute::<&str>(AId::FontKerning) == Some("none") {
263            apply_kerning = false;
264        }
265
266        let font_optical_sizing = match parent.find_attribute::<&str>(AId::FontOpticalSizing) {
267            Some("none") => crate::FontOpticalSizing::None,
268            _ => crate::FontOpticalSizing::Auto, // "auto" or missing (browser default)
269        };
270
271        let mut text_length =
272            parent.try_convert_length(AId::TextLength, Units::UserSpaceOnUse, state);
273        // Negative values should be ignored.
274        if let Some(n) = text_length {
275            if n < 0.0 {
276                text_length = None;
277            }
278        }
279
280        let visibility: Visibility = parent.find_attribute(AId::Visibility).unwrap_or_default();
281
282        let span = TextSpan {
283            start: 0,
284            end: 0,
285            fill: style::resolve_fill(parent, true, state, cache),
286            stroke: style::resolve_stroke(parent, true, state, cache),
287            paint_order,
288            font,
289            font_size,
290            small_caps: parent.find_attribute::<&str>(AId::FontVariant) == Some("small-caps"),
291            apply_kerning,
292            font_optical_sizing,
293            decoration: resolve_decoration(parent, state, cache),
294            visible: visibility == Visibility::Visible,
295            dominant_baseline,
296            alignment_baseline: parent
297                .find_attribute(AId::AlignmentBaseline)
298                .unwrap_or_default(),
299            baseline_shift: convert_baseline_shift(parent, state),
300            letter_spacing: parent.resolve_length(AId::LetterSpacing, state, 0.0),
301            word_spacing: parent.resolve_length(AId::WordSpacing, state, 0.0),
302            text_length,
303            length_adjust: parent.find_attribute(AId::LengthAdjust).unwrap_or_default(),
304        };
305
306        let mut is_new_span = true;
307        for c in child.text().chars() {
308            let char_len = c.len_utf8();
309
310            // Create a new chunk if:
311            // - this is the first span (yes, position can be None)
312            // - text character has an absolute coordinate assigned to it (via x/y attribute)
313            // - `c` is the first char of the `textPath`
314            // - `c` is the first char after `textPath`
315            let is_new_chunk = pos_list[iter_state.chars_count].x.is_some()
316                || pos_list[iter_state.chars_count].y.is_some()
317                || iter_state.split_chunk
318                || iter_state.chunks.is_empty();
319
320            iter_state.split_chunk = false;
321
322            if is_new_chunk {
323                iter_state.chunk_bytes_count = 0;
324
325                let mut span2 = span.clone();
326                span2.start = 0;
327                span2.end = char_len;
328
329                iter_state.chunks.push(TextChunk {
330                    x: pos_list[iter_state.chars_count].x,
331                    y: pos_list[iter_state.chars_count].y,
332                    anchor,
333                    spans: vec![span2],
334                    text_flow: iter_state.text_flow.clone(),
335                    text: c.to_string(),
336                });
337            } else if is_new_span {
338                // Add this span to the last text chunk.
339                let mut span2 = span.clone();
340                span2.start = iter_state.chunk_bytes_count;
341                span2.end = iter_state.chunk_bytes_count + char_len;
342
343                if let Some(chunk) = iter_state.chunks.last_mut() {
344                    chunk.text.push(c);
345                    chunk.spans.push(span2);
346                }
347            } else {
348                // Extend the last span.
349                if let Some(chunk) = iter_state.chunks.last_mut() {
350                    chunk.text.push(c);
351                    if let Some(span) = chunk.spans.last_mut() {
352                        debug_assert_ne!(span.end, 0);
353                        span.end += char_len;
354                    }
355                }
356            }
357
358            is_new_span = false;
359            iter_state.chars_count += 1;
360            iter_state.chunk_bytes_count += char_len;
361        }
362    }
363}
364
365fn resolve_text_flow(
366    node: SvgNode,
367    state: &converter::State,
368    cache: &mut converter::Cache,
369) -> Option<TextFlow> {
370    let (id, path) = resolve_text_flow_path(node, state, cache)?;
371
372    let start_offset: Length = node.attribute(AId::StartOffset).unwrap_or_default();
373    let start_offset = if start_offset.unit == LengthUnit::Percent {
374        // 'If a percentage is given, then the `startOffset` represents
375        // a percentage distance along the entire path.'
376        let path_len = path_length(&path);
377        (path_len * (start_offset.number / 100.0)) as f32
378    } else {
379        node.resolve_length(AId::StartOffset, state, 0.0)
380    };
381
382    Some(TextFlow::Path(Arc::new(TextPath {
383        id,
384        start_offset,
385        path,
386    })))
387}
388
389fn resolve_text_flow_path(
390    node: SvgNode,
391    state: &converter::State,
392    cache: &mut converter::Cache,
393) -> Option<(NonEmptyString, Arc<tiny_skia_path::Path>)> {
394    // `path` takes precedence over `href`, unless it yields no path data.
395    if let Some(path_data) = node.attribute::<&str>(AId::Path) {
396        if let Some(path) = super::shapes::convert_path_data(path_data) {
397            // The writer references text paths by ID, so an inline path needs one too.
398            let id = NonEmptyString::new(node.element_id().to_string())
399                .unwrap_or_else(|| cache.gen_text_path_id());
400            return Some((id, path));
401        }
402    }
403
404    resolve_text_flow_href(node, state)
405}
406
407fn resolve_text_flow_href(
408    node: SvgNode,
409    state: &converter::State,
410) -> Option<(NonEmptyString, Arc<tiny_skia_path::Path>)> {
411    let linked_node = node.attribute::<SvgNode>(AId::Href)?;
412    let path = super::shapes::convert(linked_node, state)?;
413
414    // The reference path's transform needs to be applied
415    let transform = linked_node.resolve_transform(AId::Transform, state);
416    let path = if !transform.is_identity() {
417        let mut path_copy = path.as_ref().clone();
418        path_copy = path_copy.transform(transform)?;
419        Arc::new(path_copy)
420    } else {
421        path
422    };
423
424    let id = NonEmptyString::new(linked_node.element_id().to_string())?;
425    Some((id, path))
426}
427
428fn convert_font(node: SvgNode, state: &converter::State) -> Font {
429    let style: FontStyle = node.find_attribute(AId::FontStyle).unwrap_or_default();
430    let stretch = conv_font_stretch(node);
431    let weight = resolve_font_weight(node);
432    let mut variations = parse_font_variation_settings(node);
433
434    // Auto-map standard font properties to variation axes if not explicitly set.
435    // This allows variable fonts to work with regular font-weight/font-stretch properties.
436    let has_wght = variations.iter().any(|v| &v.tag == b"wght");
437    let has_wdth = variations.iter().any(|v| &v.tag == b"wdth");
438    let has_ital = variations.iter().any(|v| &v.tag == b"ital");
439    let has_slnt = variations.iter().any(|v| &v.tag == b"slnt");
440
441    // Map font-weight to wght axis (if not already set)
442    if !has_wght {
443        variations.push(FontVariation::new(*b"wght", weight as f32));
444    }
445
446    // Map font-stretch to wdth axis (if not already set)
447    // CSS font-stretch percentages: ultra-condensed=50%, condensed=75%, normal=100%, expanded=125%, ultra-expanded=200%
448    if !has_wdth {
449        let wdth = match stretch {
450            FontStretch::UltraCondensed => 50.0,
451            FontStretch::ExtraCondensed => 62.5,
452            FontStretch::Condensed => 75.0,
453            FontStretch::SemiCondensed => 87.5,
454            FontStretch::Normal => 100.0,
455            FontStretch::SemiExpanded => 112.5,
456            FontStretch::Expanded => 125.0,
457            FontStretch::ExtraExpanded => 150.0,
458            FontStretch::UltraExpanded => 200.0,
459        };
460        if wdth != 100.0 {
461            variations.push(FontVariation::new(*b"wdth", wdth));
462        }
463    }
464
465    // Map font-style: italic to ital axis (if not already set)
466    if !has_ital && style == FontStyle::Italic {
467        variations.push(FontVariation::new(*b"ital", 1.0));
468    }
469
470    // Map font-style: oblique to slnt axis (if not already set)
471    // Default oblique angle is typically 12-14 degrees
472    if !has_slnt && style == FontStyle::Oblique {
473        variations.push(FontVariation::new(*b"slnt", -12.0));
474    }
475
476    let font_families = if let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::FontFamily))
477    {
478        n.attribute(AId::FontFamily).unwrap_or("")
479    } else {
480        ""
481    };
482
483    let mut families = parse_font_families(font_families)
484        .ok()
485        .log_none(|| {
486            log::warn!(
487                "Failed to parse {} value: '{}'. Falling back to {}.",
488                AId::FontFamily,
489                font_families,
490                state.opt.font_family
491            );
492        })
493        .unwrap_or_default();
494
495    if families.is_empty() {
496        families.push(FontFamily::Named(state.opt.font_family.clone()));
497    }
498
499    Font {
500        families,
501        style,
502        stretch,
503        weight,
504        variations,
505    }
506}
507
508/// Parses the `font-variation-settings` CSS property.
509///
510/// Syntax: `normal | [ <string> <number> ]#`
511/// Example: `"wght" 700, "wdth" 50`
512fn parse_font_variation_settings(node: SvgNode) -> Vec<FontVariation> {
513    let value = if let Some(n) = node
514        .ancestors()
515        .find(|n| n.has_attribute(AId::FontVariationSettings))
516    {
517        let v = n.attribute(AId::FontVariationSettings).unwrap_or("");
518        log::debug!("Found font-variation-settings: '{}'", v);
519        v
520    } else {
521        return Vec::new();
522    };
523
524    // "normal" means no variations
525    if value.eq_ignore_ascii_case("normal") || value.is_empty() {
526        return Vec::new();
527    }
528
529    let mut variations = Vec::new();
530
531    // Parse comma-separated list of "tag" value pairs
532    for part in value.split(',') {
533        let part = part.trim();
534        if part.is_empty() {
535            continue;
536        }
537
538        // Find the tag (quoted string) and value
539        // Format: "wght" 700 or 'wght' 700
540        let mut chars = part.chars().peekable();
541
542        // Skip whitespace
543        while chars.peek().map_or(false, |c| c.is_whitespace()) {
544            chars.next();
545        }
546
547        // Parse quoted tag
548        let quote = match chars.next() {
549            Some('"') => '"',
550            Some('\'') => '\'',
551            _ => continue, // Invalid format
552        };
553
554        let mut tag_str = String::new();
555        for c in chars.by_ref() {
556            if c == quote {
557                break;
558            }
559            tag_str.push(c);
560        }
561
562        // Tag must be exactly 4 characters
563        if tag_str.len() != 4 {
564            log::warn!(
565                "Invalid font-variation-settings tag: '{}' (must be 4 characters)",
566                tag_str
567            );
568            continue;
569        }
570
571        // Skip whitespace before value
572        while chars.peek().map_or(false, |c| c.is_whitespace()) {
573            chars.next();
574        }
575
576        // Parse the numeric value
577        let value_str: String = chars.collect();
578        let value_str = value_str.trim();
579
580        let value = match value_str.parse::<f32>() {
581            Ok(v) => v,
582            Err(_) => {
583                log::warn!("Invalid font-variation-settings value: '{}'", value_str);
584                continue;
585            }
586        };
587
588        let tag_bytes = tag_str.as_bytes();
589        let tag = [tag_bytes[0], tag_bytes[1], tag_bytes[2], tag_bytes[3]];
590
591        variations.push(FontVariation::new(tag, value));
592    }
593
594    variations
595}
596
597// TODO: properly resolve narrower/wider
598fn conv_font_stretch(node: SvgNode) -> FontStretch {
599    if let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::FontStretch)) {
600        match n.attribute(AId::FontStretch).unwrap_or("") {
601            "narrower" | "condensed" => FontStretch::Condensed,
602            "ultra-condensed" => FontStretch::UltraCondensed,
603            "extra-condensed" => FontStretch::ExtraCondensed,
604            "semi-condensed" => FontStretch::SemiCondensed,
605            "semi-expanded" => FontStretch::SemiExpanded,
606            "wider" | "expanded" => FontStretch::Expanded,
607            "extra-expanded" => FontStretch::ExtraExpanded,
608            "ultra-expanded" => FontStretch::UltraExpanded,
609            _ => FontStretch::Normal,
610        }
611    } else {
612        FontStretch::Normal
613    }
614}
615
616fn resolve_font_weight(node: SvgNode) -> u16 {
617    fn bound(min: usize, val: usize, max: usize) -> usize {
618        std::cmp::max(min, std::cmp::min(max, val))
619    }
620
621    let nodes: Vec<_> = node.ancestors().collect();
622    let mut weight = 400;
623    for n in nodes.iter().rev().skip(1) {
624        // skip Root
625        weight = match n.attribute(AId::FontWeight).unwrap_or("") {
626            "normal" => 400,
627            "bold" => 700,
628            "100" => 100,
629            "200" => 200,
630            "300" => 300,
631            "400" => 400,
632            "500" => 500,
633            "600" => 600,
634            "700" => 700,
635            "800" => 800,
636            "900" => 900,
637            "bolder" => {
638                // By the CSS2 spec the default value should be 400
639                // so `bolder` will result in 500.
640                // But Chrome and Inkscape will give us 700.
641                // Have no idea is it a bug or something, but
642                // we will follow such behavior for now.
643                let step = if weight == 400 { 300 } else { 100 };
644
645                bound(100, weight + step, 900)
646            }
647            "lighter" => {
648                // By the CSS2 spec the default value should be 400
649                // so `lighter` will result in 300.
650                // But Chrome and Inkscape will give us 200.
651                // Have no idea is it a bug or something, but
652                // we will follow such behavior for now.
653                let step = if weight == 400 { 200 } else { 100 };
654
655                bound(100, weight - step, 900)
656            }
657            _ => weight,
658        };
659    }
660
661    weight as u16
662}
663
664/// Resolves text's character positions.
665///
666/// This includes: x, y, dx, dy.
667///
668/// # The character
669///
670/// The first problem with this task is that the *character* itself
671/// is basically undefined in the SVG spec. Sometimes it's an *XML character*,
672/// sometimes a *glyph*, and sometimes just a *character*.
673///
674/// There is an ongoing [discussion](https://github.com/w3c/svgwg/issues/537)
675/// on the SVG working group that addresses this by stating that a character
676/// is a Unicode code point. But it's not final.
677///
678/// Also, according to the SVG 2 spec, *character* is *a Unicode code point*.
679///
680/// Anyway, we treat a character as a Unicode code point.
681///
682/// # Algorithm
683///
684/// To resolve positions, we have to iterate over descendant nodes and
685/// if the current node is a `tspan` and has x/y/dx/dy attribute,
686/// than the positions from this attribute should be assigned to the characters
687/// of this `tspan` and it's descendants.
688///
689/// Positions list can have more values than characters in the `tspan`,
690/// so we have to clamp it, because values should not overlap, e.g.:
691///
692/// (we ignore whitespaces for example purposes,
693/// so the `text` content is `Text` and not `T ex t`)
694///
695/// ```text
696/// <text>
697///   a
698///   <tspan x="10 20 30">
699///     bc
700///   </tspan>
701///   d
702/// </text>
703/// ```
704///
705/// In this example, the `d` position should not be set to `30`.
706/// And the result should be: `[None, 10, 20, None]`
707///
708/// Another example:
709///
710/// ```text
711/// <text>
712///   <tspan x="100 110 120 130">
713///     a
714///     <tspan x="50">
715///       bc
716///     </tspan>
717///   </tspan>
718///   d
719/// </text>
720/// ```
721///
722/// The result should be: `[100, 50, 120, None]`
723fn resolve_positions_list(text_node: SvgNode, state: &converter::State) -> Vec<CharacterPosition> {
724    // Allocate a list that has all characters positions set to `None`.
725    let total_chars = count_chars(text_node);
726    let mut list = vec![
727        CharacterPosition {
728            x: None,
729            y: None,
730            dx: None,
731            dy: None,
732        };
733        total_chars
734    ];
735
736    let mut offset = 0;
737    for child in text_node.descendants() {
738        if child.is_element() {
739            // We must ignore text positions on `textPath`.
740            if !matches!(child.tag_name(), Some(EId::Text) | Some(EId::Tspan)) {
741                continue;
742            }
743
744            let child_chars = count_chars(child);
745            macro_rules! push_list {
746                ($aid:expr, $field:ident) => {
747                    if let Some(num_list) = super::units::convert_list(child, $aid, state) {
748                        // Note that we are using not the total count,
749                        // but the amount of characters in the current `tspan` (with children).
750                        let len = std::cmp::min(num_list.len(), child_chars);
751                        for i in 0..len {
752                            list[offset + i].$field = Some(num_list[i]);
753                        }
754                    }
755                };
756            }
757
758            push_list!(AId::X, x);
759            push_list!(AId::Y, y);
760            push_list!(AId::Dx, dx);
761            push_list!(AId::Dy, dy);
762        } else if child.is_text() {
763            // Advance the offset.
764            offset += child.text().chars().count();
765        }
766    }
767
768    list
769}
770
771/// Resolves characters rotation.
772///
773/// The algorithm is well explained
774/// [in the SVG spec](https://www.w3.org/TR/SVG11/text.html#TSpanElement) (scroll down a bit).
775///
776/// ![](https://www.w3.org/TR/SVG11/images/text/tspan05-diagram.png)
777///
778/// Note: this algorithm differs from the position resolving one.
779fn resolve_rotate_list(text_node: SvgNode) -> Vec<f32> {
780    // Allocate a list that has all characters angles set to `0.0`.
781    let mut list = vec![0.0; count_chars(text_node)];
782    let mut last = 0.0;
783    let mut offset = 0;
784    for child in text_node.descendants() {
785        if child.is_element() {
786            if let Some(rotate) = child.attribute::<Vec<f32>>(AId::Rotate) {
787                for i in 0..count_chars(child) {
788                    if let Some(a) = rotate.get(i).cloned() {
789                        list[offset + i] = a;
790                        last = a;
791                    } else {
792                        // If the rotate list doesn't specify the rotation for
793                        // this character - use the last one.
794                        list[offset + i] = last;
795                    }
796                }
797            }
798        } else if child.is_text() {
799            // Advance the offset.
800            offset += child.text().chars().count();
801        }
802    }
803
804    list
805}
806
807/// Resolves node's `text-decoration` property.
808fn resolve_decoration(
809    tspan: SvgNode,
810    state: &converter::State,
811    cache: &mut converter::Cache,
812) -> TextDecoration {
813    // Checks if a decoration is present in a single node.
814    fn find_decoration(node: SvgNode, value: &str) -> bool {
815        if let Some(str_value) = node.attribute::<&str>(AId::TextDecoration) {
816            str_value.split(' ').any(|v| v == value)
817        } else {
818            false
819        }
820    }
821
822    // The algorithm is as follows: First, we check whether the given text decoration appears in ANY
823    // ancestor, i.e. it can also appear in ancestors outside of the <text> element. If the text
824    // decoration is declared somewhere, it means that this tspan will have it. However, we still
825    // need to find the corresponding fill/stroke for it. To do this, we iterate through all
826    // ancestors (i.e. tspans) until we find the text decoration declared. If not, we will
827    // stop at latest at the text node, and use its fill/stroke.
828    let mut gen_style = |text_decoration: &str| {
829        if !tspan
830            .ancestors()
831            .any(|n| find_decoration(n, text_decoration))
832        {
833            return None;
834        }
835
836        let mut fill_node = None;
837        let mut stroke_node = None;
838
839        for node in tspan.ancestors() {
840            if find_decoration(node, text_decoration) || node.tag_name() == Some(EId::Text) {
841                fill_node = fill_node.map_or(Some(node), Some);
842                stroke_node = stroke_node.map_or(Some(node), Some);
843                break;
844            }
845        }
846
847        Some(TextDecorationStyle {
848            fill: fill_node.and_then(|node| style::resolve_fill(node, true, state, cache)),
849            stroke: stroke_node.and_then(|node| style::resolve_stroke(node, true, state, cache)),
850        })
851    };
852
853    TextDecoration {
854        underline: gen_style("underline"),
855        overline: gen_style("overline"),
856        line_through: gen_style("line-through"),
857    }
858}
859
860fn convert_baseline_shift(node: SvgNode, state: &converter::State) -> Vec<BaselineShift> {
861    let mut shift = Vec::new();
862    let nodes: Vec<_> = node
863        .ancestors()
864        .take_while(|n| n.tag_name() != Some(EId::Text))
865        .collect();
866    for n in nodes {
867        if let Some(len) = n.try_attribute::<Length>(AId::BaselineShift) {
868            if len.unit == LengthUnit::Percent {
869                let n = super::units::resolve_font_size(n, state) * (len.number as f32 / 100.0);
870                shift.push(BaselineShift::Number(n));
871            } else {
872                let n = super::units::convert_length(
873                    len,
874                    n,
875                    AId::BaselineShift,
876                    Units::ObjectBoundingBox,
877                    state,
878                );
879                shift.push(BaselineShift::Number(n));
880            }
881        } else if let Some(s) = n.attribute(AId::BaselineShift) {
882            match s {
883                "sub" => shift.push(BaselineShift::Subscript),
884                "super" => shift.push(BaselineShift::Superscript),
885                _ => shift.push(BaselineShift::Baseline),
886            }
887        }
888    }
889
890    if shift
891        .iter()
892        .all(|base| matches!(base, BaselineShift::Baseline))
893    {
894        shift.clear();
895    }
896
897    shift
898}
899
900fn count_chars(node: SvgNode) -> usize {
901    node.descendants()
902        .filter(|n| n.is_text())
903        .fold(0, |w, n| w + n.text().chars().count())
904}
905
906/// Converts the writing mode.
907///
908/// [SVG 2] references [CSS Writing Modes Level 3] for the definition of the
909/// 'writing-mode' property, there are only two writing modes:
910/// horizontal left-to-right and vertical right-to-left.
911///
912/// That specification introduces new values for the property. The SVG 1.1
913/// values are obsolete but must still be supported by converting the specified
914/// values to computed values as follows:
915///
916/// - `lr`, `lr-tb`, `rl`, `rl-tb` => `horizontal-tb`
917/// - `tb`, `tb-rl` => `vertical-rl`
918///
919/// The current `vertical-lr` behaves exactly the same as `vertical-rl`.
920///
921/// Also, looks like no one really supports the `rl` and `rl-tb`, except `Batik`.
922/// And I'm not sure if its behaviour is correct.
923///
924/// So we will ignore it as well, mainly because I have no idea how exactly
925/// it should affect the rendering.
926///
927/// [SVG 2]: https://www.w3.org/TR/SVG2/text.html#WritingModeProperty
928/// [CSS Writing Modes Level 3]: https://www.w3.org/TR/css-writing-modes-3/#svg-writing-mode-css
929fn convert_writing_mode(text_node: SvgNode) -> WritingMode {
930    if let Some(n) = text_node
931        .ancestors()
932        .find(|n| n.has_attribute(AId::WritingMode))
933    {
934        match n.attribute(AId::WritingMode).unwrap_or("lr-tb") {
935            "tb" | "tb-rl" | "vertical-rl" | "vertical-lr" => WritingMode::TopToBottom,
936            _ => WritingMode::LeftToRight,
937        }
938    } else {
939        WritingMode::LeftToRight
940    }
941}
942
943fn path_length(path: &tiny_skia_path::Path) -> f64 {
944    let mut prev_mx = path.points()[0].x;
945    let mut prev_my = path.points()[0].y;
946    let mut prev_x = prev_mx;
947    let mut prev_y = prev_my;
948
949    fn create_curve_from_line(px: f32, py: f32, x: f32, y: f32) -> kurbo::CubicBez {
950        let line = kurbo::Line::new(
951            kurbo::Point::new(px as f64, py as f64),
952            kurbo::Point::new(x as f64, y as f64),
953        );
954        let p1 = line.eval(0.33);
955        let p2 = line.eval(0.66);
956        kurbo::CubicBez::new(line.p0, p1, p2, line.p1)
957    }
958
959    let mut length = 0.0;
960    for seg in path.segments() {
961        let curve = match seg {
962            tiny_skia_path::PathSegment::MoveTo(p) => {
963                prev_mx = p.x;
964                prev_my = p.y;
965                prev_x = p.x;
966                prev_y = p.y;
967                continue;
968            }
969            tiny_skia_path::PathSegment::LineTo(p) => {
970                create_curve_from_line(prev_x, prev_y, p.x, p.y)
971            }
972            tiny_skia_path::PathSegment::QuadTo(p1, p) => kurbo::QuadBez::new(
973                kurbo::Point::new(prev_x as f64, prev_y as f64),
974                kurbo::Point::new(p1.x as f64, p1.y as f64),
975                kurbo::Point::new(p.x as f64, p.y as f64),
976            )
977            .raise(),
978            tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => kurbo::CubicBez::new(
979                kurbo::Point::new(prev_x as f64, prev_y as f64),
980                kurbo::Point::new(p1.x as f64, p1.y as f64),
981                kurbo::Point::new(p2.x as f64, p2.y as f64),
982                kurbo::Point::new(p.x as f64, p.y as f64),
983            ),
984            tiny_skia_path::PathSegment::Close => {
985                create_curve_from_line(prev_x, prev_y, prev_mx, prev_my)
986            }
987        };
988
989        length += curve.arclen(0.5);
990        prev_x = curve.p3.x as f32;
991        prev_y = curve.p3.y as f32;
992    }
993
994    length
995}