Skip to main content

usvg/
writer.rs

1// Copyright 2023 the Resvg Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::fmt::Display;
5use std::io::Write;
6
7use svgtypes::{FontFamily, parse_font_families};
8use xmlwriter::XmlWriter;
9
10use crate::parser::{AId, EId};
11use crate::*;
12
13impl Tree {
14    /// Writes `usvg::Tree` back to SVG.
15    pub fn to_string(&self, opt: &WriteOptions) -> String {
16        convert(self, opt)
17    }
18}
19
20/// Checks that type has a default value.
21trait IsDefault: Default {
22    /// Checks that type has a default value.
23    fn is_default(&self) -> bool;
24}
25
26impl<T: Default + PartialEq + Copy> IsDefault for T {
27    #[inline]
28    fn is_default(&self) -> bool {
29        *self == Self::default()
30    }
31}
32
33/// XML writing options.
34#[derive(Clone, Debug)]
35pub struct WriteOptions {
36    /// Used to add a custom prefix to each element ID during writing.
37    pub id_prefix: Option<String>,
38
39    /// Do not convert text into paths.
40    ///
41    /// Default: false
42    pub preserve_text: bool,
43
44    /// Set the coordinates numeric precision.
45    ///
46    /// Smaller precision can lead to a malformed output in some cases.
47    ///
48    /// Default: 8
49    pub coordinates_precision: u8,
50
51    /// Set the transform values numeric precision.
52    ///
53    /// Smaller precision can lead to a malformed output in some cases.
54    ///
55    /// Default: 8
56    pub transforms_precision: u8,
57
58    /// Use single quote marks instead of double quote.
59    ///
60    /// # Examples
61    ///
62    /// Before:
63    ///
64    /// ```text
65    /// <rect fill="red"/>
66    /// ```
67    ///
68    /// After:
69    ///
70    /// ```text
71    /// <rect fill='red'/>
72    /// ```
73    ///
74    /// Default: disabled
75    pub use_single_quote: bool,
76
77    /// Set XML nodes indention.
78    ///
79    /// # Examples
80    ///
81    /// `Indent::None`
82    /// Before:
83    ///
84    /// ```text
85    /// <svg>
86    ///     <rect fill="red"/>
87    /// </svg>
88    /// ```
89    ///
90    /// After:
91    ///
92    /// ```text
93    /// <svg><rect fill="red"/></svg>
94    /// ```
95    ///
96    /// Default: 4 spaces
97    pub indent: Indent,
98
99    /// Set XML attributes indention.
100    ///
101    /// # Examples
102    ///
103    /// `Indent::Spaces(2)`
104    ///
105    /// Before:
106    ///
107    /// ```text
108    /// <svg>
109    ///     <rect fill="red" stroke="black"/>
110    /// </svg>
111    /// ```
112    ///
113    /// After:
114    ///
115    /// ```text
116    /// <svg>
117    ///     <rect
118    ///       fill="red"
119    ///       stroke="black"/>
120    /// </svg>
121    /// ```
122    ///
123    /// Default: `None`
124    pub attributes_indent: Indent,
125}
126
127impl Default for WriteOptions {
128    fn default() -> Self {
129        Self {
130            id_prefix: Default::default(),
131            preserve_text: false,
132            coordinates_precision: 8,
133            transforms_precision: 8,
134            use_single_quote: false,
135            indent: Indent::Spaces(4),
136            attributes_indent: Indent::None,
137        }
138    }
139}
140
141pub(crate) fn convert(tree: &Tree, opt: &WriteOptions) -> String {
142    let mut xml = XmlWriter::new(xmlwriter::Options {
143        use_single_quote: opt.use_single_quote,
144        indent: opt.indent,
145        attributes_indent: opt.attributes_indent,
146    });
147
148    xml.start_svg_element(EId::Svg);
149    xml.write_svg_attribute(AId::Width, &tree.size.width());
150    xml.write_svg_attribute(AId::Height, &tree.size.height());
151    xml.write_attribute("xmlns", "http://www.w3.org/2000/svg");
152    if has_xlink(&tree.root) {
153        xml.write_attribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
154    }
155
156    let has_text_paths = has_text_paths(&tree.root);
157    if tree.has_defs_nodes() || has_text_paths {
158        write_defs(tree, opt, &mut xml, has_text_paths);
159    }
160
161    write_elements(&tree.root, false, opt, &mut xml);
162
163    xml.end_document()
164}
165
166fn write_filters(tree: &Tree, opt: &WriteOptions, xml: &mut XmlWriter) {
167    let mut written_fe_image_nodes: Vec<String> = Vec::new();
168    for filter in tree.filters() {
169        for fe in &filter.primitives {
170            if let filter::Kind::Image(ref img) = fe.kind {
171                if let Some(child) = img.root().children.first() {
172                    if !written_fe_image_nodes.iter().any(|id| id == child.id()) {
173                        write_element(child, false, opt, xml);
174                        written_fe_image_nodes.push(child.id().to_string());
175                    }
176                }
177            }
178        }
179
180        xml.start_svg_element(EId::Filter);
181        xml.write_id_attribute(filter.id(), opt);
182        xml.write_rect_attrs(filter.rect);
183        xml.write_units(
184            AId::FilterUnits,
185            Units::UserSpaceOnUse,
186            Units::ObjectBoundingBox,
187        );
188
189        for fe in &filter.primitives {
190            match fe.kind {
191                filter::Kind::DropShadow(ref shadow) => {
192                    xml.start_svg_element(EId::FeDropShadow);
193                    xml.write_filter_primitive_attrs(filter.rect(), fe);
194                    xml.write_filter_input(AId::In, &shadow.input);
195                    xml.write_attribute_fmt(
196                        AId::StdDeviation.to_str(),
197                        format_args!("{} {}", shadow.std_dev_x.get(), shadow.std_dev_y.get()),
198                    );
199                    xml.write_svg_attribute(AId::Dx, &shadow.dx);
200                    xml.write_svg_attribute(AId::Dy, &shadow.dy);
201                    xml.write_color(AId::FloodColor, shadow.color);
202                    xml.write_svg_attribute(AId::FloodOpacity, &shadow.opacity.get());
203                    xml.write_svg_attribute(AId::Result, &fe.result);
204                    xml.end_element();
205                }
206                filter::Kind::GaussianBlur(ref blur) => {
207                    xml.start_svg_element(EId::FeGaussianBlur);
208                    xml.write_filter_primitive_attrs(filter.rect(), fe);
209                    xml.write_filter_input(AId::In, &blur.input);
210                    xml.write_attribute_fmt(
211                        AId::StdDeviation.to_str(),
212                        format_args!("{} {}", blur.std_dev_x.get(), blur.std_dev_y.get()),
213                    );
214                    xml.write_svg_attribute(AId::Result, &fe.result);
215                    xml.end_element();
216                }
217                filter::Kind::Offset(ref offset) => {
218                    xml.start_svg_element(EId::FeOffset);
219                    xml.write_filter_primitive_attrs(filter.rect(), fe);
220                    xml.write_filter_input(AId::In, &offset.input);
221                    xml.write_svg_attribute(AId::Dx, &offset.dx);
222                    xml.write_svg_attribute(AId::Dy, &offset.dy);
223                    xml.write_svg_attribute(AId::Result, &fe.result);
224                    xml.end_element();
225                }
226                filter::Kind::Blend(ref blend) => {
227                    xml.start_svg_element(EId::FeBlend);
228                    xml.write_filter_primitive_attrs(filter.rect(), fe);
229                    xml.write_filter_input(AId::In, &blend.input1);
230                    xml.write_filter_input(AId::In2, &blend.input2);
231                    xml.write_svg_attribute(AId::Mode, &blend.mode.to_string());
232                    xml.write_svg_attribute(AId::Result, &fe.result);
233                    xml.end_element();
234                }
235                filter::Kind::Flood(ref flood) => {
236                    xml.start_svg_element(EId::FeFlood);
237                    xml.write_filter_primitive_attrs(filter.rect(), fe);
238                    xml.write_color(AId::FloodColor, flood.color);
239                    xml.write_svg_attribute(AId::FloodOpacity, &flood.opacity.get());
240                    xml.write_svg_attribute(AId::Result, &fe.result);
241                    xml.end_element();
242                }
243                filter::Kind::Composite(ref composite) => {
244                    xml.start_svg_element(EId::FeComposite);
245                    xml.write_filter_primitive_attrs(filter.rect(), fe);
246                    xml.write_filter_input(AId::In, &composite.input1);
247                    xml.write_filter_input(AId::In2, &composite.input2);
248                    xml.write_svg_attribute(
249                        AId::Operator,
250                        match composite.operator {
251                            filter::CompositeOperator::Over => "over",
252                            filter::CompositeOperator::In => "in",
253                            filter::CompositeOperator::Out => "out",
254                            filter::CompositeOperator::Atop => "atop",
255                            filter::CompositeOperator::Xor => "xor",
256                            filter::CompositeOperator::Lighter => "lighter",
257                            filter::CompositeOperator::Arithmetic { .. } => "arithmetic",
258                        },
259                    );
260
261                    if let filter::CompositeOperator::Arithmetic { k1, k2, k3, k4 } =
262                        composite.operator
263                    {
264                        xml.write_svg_attribute(AId::K1, &k1);
265                        xml.write_svg_attribute(AId::K2, &k2);
266                        xml.write_svg_attribute(AId::K3, &k3);
267                        xml.write_svg_attribute(AId::K4, &k4);
268                    }
269
270                    xml.write_svg_attribute(AId::Result, &fe.result);
271                    xml.end_element();
272                }
273                filter::Kind::Merge(ref merge) => {
274                    xml.start_svg_element(EId::FeMerge);
275                    xml.write_filter_primitive_attrs(filter.rect(), fe);
276                    xml.write_svg_attribute(AId::Result, &fe.result);
277                    for input in &merge.inputs {
278                        xml.start_svg_element(EId::FeMergeNode);
279                        xml.write_filter_input(AId::In, input);
280                        xml.end_element();
281                    }
282
283                    xml.end_element();
284                }
285                filter::Kind::Tile(ref tile) => {
286                    xml.start_svg_element(EId::FeTile);
287                    xml.write_filter_primitive_attrs(filter.rect(), fe);
288                    xml.write_filter_input(AId::In, &tile.input);
289                    xml.write_svg_attribute(AId::Result, &fe.result);
290                    xml.end_element();
291                }
292                filter::Kind::Image(ref img) => {
293                    xml.start_svg_element(EId::FeImage);
294                    xml.write_filter_primitive_attrs(filter.rect(), fe);
295                    if let Some(child) = img.root.children.first() {
296                        let prefix = opt.id_prefix.as_deref().unwrap_or_default();
297                        xml.write_attribute_fmt(
298                            "xlink:href",
299                            format_args!("#{}{}", prefix, child.id()),
300                        );
301                    }
302
303                    xml.write_svg_attribute(AId::Result, &fe.result);
304                    xml.end_element();
305                }
306                filter::Kind::ComponentTransfer(ref transfer) => {
307                    xml.start_svg_element(EId::FeComponentTransfer);
308                    xml.write_filter_primitive_attrs(filter.rect(), fe);
309                    xml.write_filter_input(AId::In, &transfer.input);
310                    xml.write_svg_attribute(AId::Result, &fe.result);
311
312                    xml.write_filter_transfer_function(EId::FeFuncR, &transfer.func_r);
313                    xml.write_filter_transfer_function(EId::FeFuncG, &transfer.func_g);
314                    xml.write_filter_transfer_function(EId::FeFuncB, &transfer.func_b);
315                    xml.write_filter_transfer_function(EId::FeFuncA, &transfer.func_a);
316
317                    xml.end_element();
318                }
319                filter::Kind::ColorMatrix(ref matrix) => {
320                    xml.start_svg_element(EId::FeColorMatrix);
321                    xml.write_filter_primitive_attrs(filter.rect(), fe);
322                    xml.write_filter_input(AId::In, &matrix.input);
323                    xml.write_svg_attribute(AId::Result, &fe.result);
324
325                    match matrix.kind {
326                        filter::ColorMatrixKind::Matrix(ref values) => {
327                            xml.write_svg_attribute(AId::Type, "matrix");
328                            xml.write_numbers(AId::Values, values);
329                        }
330                        filter::ColorMatrixKind::Saturate(value) => {
331                            xml.write_svg_attribute(AId::Type, "saturate");
332                            xml.write_svg_attribute(AId::Values, &value.get());
333                        }
334                        filter::ColorMatrixKind::HueRotate(angle) => {
335                            xml.write_svg_attribute(AId::Type, "hueRotate");
336                            xml.write_svg_attribute(AId::Values, &angle);
337                        }
338                        filter::ColorMatrixKind::LuminanceToAlpha => {
339                            xml.write_svg_attribute(AId::Type, "luminanceToAlpha");
340                        }
341                    }
342
343                    xml.end_element();
344                }
345                filter::Kind::ConvolveMatrix(ref matrix) => {
346                    xml.start_svg_element(EId::FeConvolveMatrix);
347                    xml.write_filter_primitive_attrs(filter.rect(), fe);
348                    xml.write_filter_input(AId::In, &matrix.input);
349                    xml.write_svg_attribute(AId::Result, &fe.result);
350
351                    xml.write_attribute_fmt(
352                        AId::Order.to_str(),
353                        format_args!("{} {}", matrix.matrix.columns, matrix.matrix.rows),
354                    );
355                    xml.write_numbers(AId::KernelMatrix, &matrix.matrix.data);
356                    xml.write_svg_attribute(AId::Divisor, &matrix.divisor.get());
357                    xml.write_svg_attribute(AId::Bias, &matrix.bias);
358                    xml.write_svg_attribute(AId::TargetX, &matrix.matrix.target_x);
359                    xml.write_svg_attribute(AId::TargetY, &matrix.matrix.target_y);
360                    xml.write_svg_attribute(
361                        AId::EdgeMode,
362                        match matrix.edge_mode {
363                            filter::EdgeMode::None => "none",
364                            filter::EdgeMode::Duplicate => "duplicate",
365                            filter::EdgeMode::Wrap => "wrap",
366                        },
367                    );
368                    xml.write_svg_attribute(
369                        AId::PreserveAlpha,
370                        if matrix.preserve_alpha {
371                            "true"
372                        } else {
373                            "false"
374                        },
375                    );
376
377                    xml.end_element();
378                }
379                filter::Kind::Morphology(ref morphology) => {
380                    xml.start_svg_element(EId::FeMorphology);
381                    xml.write_filter_primitive_attrs(filter.rect(), fe);
382                    xml.write_filter_input(AId::In, &morphology.input);
383                    xml.write_svg_attribute(AId::Result, &fe.result);
384
385                    xml.write_svg_attribute(
386                        AId::Operator,
387                        match morphology.operator {
388                            filter::MorphologyOperator::Erode => "erode",
389                            filter::MorphologyOperator::Dilate => "dilate",
390                        },
391                    );
392                    xml.write_attribute_fmt(
393                        AId::Radius.to_str(),
394                        format_args!(
395                            "{} {}",
396                            morphology.radius_x.get(),
397                            morphology.radius_y.get()
398                        ),
399                    );
400
401                    xml.end_element();
402                }
403                filter::Kind::DisplacementMap(ref map) => {
404                    xml.start_svg_element(EId::FeDisplacementMap);
405                    xml.write_filter_primitive_attrs(filter.rect(), fe);
406                    xml.write_filter_input(AId::In, &map.input1);
407                    xml.write_filter_input(AId::In2, &map.input2);
408                    xml.write_svg_attribute(AId::Result, &fe.result);
409
410                    xml.write_svg_attribute(AId::Scale, &map.scale);
411
412                    let mut write_channel = |c, aid| {
413                        xml.write_svg_attribute(
414                            aid,
415                            match c {
416                                filter::ColorChannel::R => "R",
417                                filter::ColorChannel::G => "G",
418                                filter::ColorChannel::B => "B",
419                                filter::ColorChannel::A => "A",
420                            },
421                        );
422                    };
423                    write_channel(map.x_channel_selector, AId::XChannelSelector);
424                    write_channel(map.y_channel_selector, AId::YChannelSelector);
425
426                    xml.end_element();
427                }
428                filter::Kind::Turbulence(ref turbulence) => {
429                    xml.start_svg_element(EId::FeTurbulence);
430                    xml.write_filter_primitive_attrs(filter.rect(), fe);
431                    xml.write_svg_attribute(AId::Result, &fe.result);
432
433                    xml.write_attribute_fmt(
434                        AId::BaseFrequency.to_str(),
435                        format_args!(
436                            "{} {}",
437                            turbulence.base_frequency_x.get(),
438                            turbulence.base_frequency_y.get()
439                        ),
440                    );
441                    xml.write_svg_attribute(AId::NumOctaves, &turbulence.num_octaves);
442                    xml.write_svg_attribute(AId::Seed, &turbulence.seed);
443                    xml.write_svg_attribute(
444                        AId::StitchTiles,
445                        match turbulence.stitch_tiles {
446                            true => "stitch",
447                            false => "noStitch",
448                        },
449                    );
450                    xml.write_svg_attribute(
451                        AId::Type,
452                        match turbulence.kind {
453                            filter::TurbulenceKind::FractalNoise => "fractalNoise",
454                            filter::TurbulenceKind::Turbulence => "turbulence",
455                        },
456                    );
457
458                    xml.end_element();
459                }
460                filter::Kind::DiffuseLighting(ref light) => {
461                    xml.start_svg_element(EId::FeDiffuseLighting);
462                    xml.write_filter_primitive_attrs(filter.rect(), fe);
463                    xml.write_svg_attribute(AId::Result, &fe.result);
464
465                    xml.write_svg_attribute(AId::SurfaceScale, &light.surface_scale);
466                    xml.write_svg_attribute(AId::DiffuseConstant, &light.diffuse_constant);
467                    xml.write_color(AId::LightingColor, light.lighting_color);
468                    write_light_source(&light.light_source, xml);
469
470                    xml.end_element();
471                }
472                filter::Kind::SpecularLighting(ref light) => {
473                    xml.start_svg_element(EId::FeSpecularLighting);
474                    xml.write_filter_primitive_attrs(filter.rect(), fe);
475                    xml.write_svg_attribute(AId::Result, &fe.result);
476
477                    xml.write_svg_attribute(AId::SurfaceScale, &light.surface_scale);
478                    xml.write_svg_attribute(AId::SpecularConstant, &light.specular_constant);
479                    xml.write_svg_attribute(AId::SpecularExponent, &light.specular_exponent);
480                    xml.write_color(AId::LightingColor, light.lighting_color);
481                    write_light_source(&light.light_source, xml);
482
483                    xml.end_element();
484                }
485            };
486        }
487
488        xml.end_element();
489    }
490}
491
492fn write_defs(tree: &Tree, opt: &WriteOptions, xml: &mut XmlWriter, write_text_paths: bool) {
493    xml.start_svg_element(EId::Defs);
494    for lg in tree.linear_gradients() {
495        xml.start_svg_element(EId::LinearGradient);
496        xml.write_id_attribute(lg.id(), opt);
497        xml.write_svg_attribute(AId::X1, &lg.x1);
498        xml.write_svg_attribute(AId::Y1, &lg.y1);
499        xml.write_svg_attribute(AId::X2, &lg.x2);
500        xml.write_svg_attribute(AId::Y2, &lg.y2);
501        write_base_grad(&lg.base, opt, xml);
502        xml.end_element();
503    }
504
505    for rg in tree.radial_gradients() {
506        xml.start_svg_element(EId::RadialGradient);
507        xml.write_id_attribute(rg.id(), opt);
508        xml.write_svg_attribute(AId::Cx, &rg.cx);
509        xml.write_svg_attribute(AId::Cy, &rg.cy);
510        xml.write_svg_attribute(AId::R, &rg.r.get());
511        xml.write_svg_attribute(AId::Fx, &rg.fx);
512        xml.write_svg_attribute(AId::Fy, &rg.fy);
513        write_base_grad(&rg.base, opt, xml);
514        xml.end_element();
515    }
516
517    for pattern in tree.patterns() {
518        xml.start_svg_element(EId::Pattern);
519        xml.write_id_attribute(pattern.id(), opt);
520        xml.write_rect_attrs(pattern.rect);
521        xml.write_units(AId::PatternUnits, pattern.units, Units::ObjectBoundingBox);
522        xml.write_units(
523            AId::PatternContentUnits,
524            pattern.content_units,
525            Units::UserSpaceOnUse,
526        );
527        xml.write_transform(AId::PatternTransform, pattern.transform, opt);
528
529        write_elements(&pattern.root, false, opt, xml);
530
531        xml.end_element();
532    }
533
534    if write_text_paths {
535        write_text_path_paths(&tree.root, opt, xml);
536    }
537
538    write_filters(tree, opt, xml);
539
540    for clip in tree.clip_paths() {
541        xml.start_svg_element(EId::ClipPath);
542        xml.write_id_attribute(clip.id(), opt);
543        xml.write_transform(AId::Transform, clip.transform, opt);
544
545        if let Some(ref clip) = clip.clip_path {
546            xml.write_func_iri(AId::ClipPath, clip.id(), opt);
547        }
548
549        write_elements(&clip.root, true, opt, xml);
550
551        xml.end_element();
552    }
553
554    for mask in tree.masks() {
555        xml.start_svg_element(EId::Mask);
556        xml.write_id_attribute(mask.id(), opt);
557        if mask.kind == MaskType::Alpha {
558            xml.write_svg_attribute(AId::MaskType, "alpha");
559        }
560        xml.write_units(
561            AId::MaskUnits,
562            Units::UserSpaceOnUse,
563            Units::ObjectBoundingBox,
564        );
565        xml.write_rect_attrs(mask.rect);
566
567        if let Some(ref mask) = mask.mask {
568            xml.write_func_iri(AId::Mask, mask.id(), opt);
569        }
570
571        write_elements(&mask.root, false, opt, xml);
572
573        xml.end_element();
574    }
575    xml.end_element(); // end EId::Defs
576}
577
578fn has_text_paths(parent: &Group) -> bool {
579    for node in &parent.children {
580        if let Node::Group(group) = node {
581            if has_text_paths(group) {
582                return true;
583            }
584        } else if let Node::Text(text) = node {
585            for chunk in &text.chunks {
586                if let TextFlow::Path(_) = &chunk.text_flow {
587                    return true;
588                }
589            }
590        }
591        let mut need_path = false;
592        node.subroots(|subroot| {
593            if !need_path && has_text_paths(subroot) {
594                need_path = true;
595            }
596        });
597        if need_path {
598            return true;
599        }
600    }
601    false
602}
603
604/// Write the `path` elements for text paths.
605fn write_text_path_paths(parent: &Group, opt: &WriteOptions, xml: &mut XmlWriter) {
606    for node in &parent.children {
607        if let Node::Group(group) = node {
608            write_text_path_paths(group, opt, xml);
609        } else if let Node::Text(text) = node {
610            for chunk in &text.chunks {
611                if let TextFlow::Path(text_path) = &chunk.text_flow {
612                    let path = Path::new(
613                        text_path.id().into(),
614                        true,
615                        None,
616                        None,
617                        PaintOrder::default(),
618                        ShapeRendering::default(),
619                        text_path.path.clone(),
620                        Transform::default(),
621                    );
622                    write_path(&path, false, Transform::default(), None, opt, xml);
623                }
624            }
625        }
626
627        node.subroots(|subroot| write_text_path_paths(subroot, opt, xml));
628    }
629}
630
631fn write_elements(parent: &Group, is_clip_path: bool, opt: &WriteOptions, xml: &mut XmlWriter) {
632    for n in &parent.children {
633        write_element(n, is_clip_path, opt, xml);
634    }
635}
636
637fn write_element(node: &Node, is_clip_path: bool, opt: &WriteOptions, xml: &mut XmlWriter) {
638    match node {
639        Node::Path(p) => {
640            write_path(p, is_clip_path, Transform::default(), None, opt, xml);
641        }
642        Node::Image(img) => {
643            xml.start_svg_element(EId::Image);
644            if !img.id.is_empty() {
645                xml.write_id_attribute(&img.id, opt);
646            }
647
648            xml.write_svg_attribute(AId::Width, &img.size().width());
649            xml.write_svg_attribute(AId::Height, &img.size().height());
650
651            xml.write_visibility(img.visible);
652
653            match img.rendering_mode {
654                ImageRendering::OptimizeQuality => {}
655                ImageRendering::OptimizeSpeed => {
656                    xml.write_svg_attribute(AId::ImageRendering, "optimizeSpeed");
657                }
658                ImageRendering::Smooth => {
659                    xml.write_attribute(AId::Style.to_str(), "image-rendering:smooth");
660                }
661                ImageRendering::HighQuality => {
662                    xml.write_attribute(AId::Style.to_str(), "image-rendering:high-quality");
663                }
664                ImageRendering::CrispEdges => {
665                    xml.write_attribute(AId::Style.to_str(), "image-rendering:crisp-edges");
666                }
667                ImageRendering::Pixelated => {
668                    xml.write_attribute(AId::Style.to_str(), "image-rendering:pixelated");
669                }
670            }
671
672            xml.write_image_data(&img.kind);
673
674            xml.end_element();
675        }
676        Node::Group(g) => {
677            write_group_element(g, is_clip_path, opt, xml);
678        }
679        Node::Text(text) => {
680            if opt.preserve_text {
681                xml.start_svg_element(EId::Text);
682
683                if !text.id.is_empty() {
684                    xml.write_id_attribute(&text.id, opt);
685                }
686
687                xml.write_attribute("xml:space", "preserve");
688
689                match text.writing_mode {
690                    WritingMode::LeftToRight => {}
691                    WritingMode::TopToBottom => xml.write_svg_attribute(AId::WritingMode, "tb"),
692                }
693
694                match text.rendering_mode {
695                    TextRendering::OptimizeSpeed => {
696                        xml.write_svg_attribute(AId::TextRendering, "optimizeSpeed");
697                    }
698                    TextRendering::GeometricPrecision => {
699                        xml.write_svg_attribute(AId::TextRendering, "geometricPrecision");
700                    }
701                    TextRendering::OptimizeLegibility => {}
702                }
703
704                if text.rotate.iter().any(|r| *r != 0.0) {
705                    xml.write_numbers(AId::Rotate, &text.rotate);
706                }
707
708                if text.dx.iter().any(|dx| *dx != 0.0) {
709                    xml.write_numbers(AId::Dx, &text.dx);
710                }
711
712                if text.dy.iter().any(|dy| *dy != 0.0) {
713                    xml.write_numbers(AId::Dy, &text.dy);
714                }
715
716                xml.set_preserve_whitespaces(true);
717
718                for chunk in &text.chunks {
719                    if let TextFlow::Path(text_path) = &chunk.text_flow {
720                        xml.start_svg_element(EId::TextPath);
721
722                        let prefix = opt.id_prefix.as_deref().unwrap_or_default();
723                        xml.write_attribute_fmt(
724                            "xlink:href",
725                            format_args!("#{}{}", prefix, text_path.id()),
726                        );
727
728                        if text_path.start_offset != 0.0 {
729                            xml.write_svg_attribute(AId::StartOffset, &text_path.start_offset);
730                        }
731                    }
732
733                    xml.start_svg_element(EId::Tspan);
734
735                    if let Some(x) = chunk.x {
736                        xml.write_svg_attribute(AId::X, &x);
737                    }
738
739                    if let Some(y) = chunk.y {
740                        xml.write_svg_attribute(AId::Y, &y);
741                    }
742
743                    match chunk.anchor {
744                        TextAnchor::Start => {}
745                        TextAnchor::Middle => xml.write_svg_attribute(AId::TextAnchor, "middle"),
746                        TextAnchor::End => xml.write_svg_attribute(AId::TextAnchor, "end"),
747                    }
748
749                    for span in &chunk.spans {
750                        let decorations: Vec<_> = [
751                            ("underline", &span.decoration.underline),
752                            ("line-through", &span.decoration.line_through),
753                            ("overline", &span.decoration.overline),
754                        ]
755                        .iter()
756                        .filter_map(|&(key, option_value)| {
757                            option_value.as_ref().map(|value| (key, value))
758                        })
759                        .collect();
760
761                        // Decorations need to be dumped BEFORE we write the actual span data
762                        // (so that for example stroke color of span doesn't affect the text
763                        // itself while baseline shifts need to be written after (since they are
764                        // affected by the font size)
765                        for (deco_name, deco) in &decorations {
766                            xml.start_svg_element(EId::Tspan);
767                            xml.write_svg_attribute(AId::TextDecoration, deco_name);
768                            write_fill(&deco.fill, false, opt, xml);
769                            write_stroke(&deco.stroke, opt, xml);
770                        }
771
772                        write_span(is_clip_path, opt, xml, chunk, span);
773
774                        // End for each tspan we needed to create for decorations
775                        for _ in &decorations {
776                            xml.end_element();
777                        }
778                    }
779                    xml.end_element();
780
781                    // End textPath element
782                    if matches!(&chunk.text_flow, TextFlow::Path(_)) {
783                        xml.end_element();
784                    }
785                }
786
787                xml.end_element();
788                xml.set_preserve_whitespaces(false);
789            } else {
790                write_group_element(text.flattened(), is_clip_path, opt, xml);
791            }
792        }
793    }
794}
795
796fn write_group_element(g: &Group, is_clip_path: bool, opt: &WriteOptions, xml: &mut XmlWriter) {
797    if is_clip_path {
798        // The `clipPath` element in SVG doesn't allow groups, only shapes and text.
799        // The problem is that in `usvg` we can set a `clip-path` only on groups.
800        // So in cases when a `clipPath` child has a `clip-path` as well,
801        // it would be inside a group. And we have to skip this group during writing.
802        //
803        // Basically, the following SVG:
804        //
805        // <clipPath id="clip">
806        //   <path clip-path="url(#clip-nested)"/>
807        // </clipPath>
808        //
809        // will be represented in usvg as:
810        //
811        // <clipPath id="clip">
812        //   <g clip-path="url(#clip-nested)">
813        //      <path/>
814        //   </g>
815        // </clipPath>
816        //
817        //
818        // Same with text. Text elements will be converted into groups,
819        // but only the group's children should be written.
820        for child in &g.children {
821            match child {
822                Node::Group(child_group) => {
823                    write_group_element(child_group, is_clip_path, opt, xml);
824                }
825                Node::Path(child_path) => {
826                    let clip_id = g.clip_path.as_ref().map(|cp| cp.id().to_string());
827                    write_path(
828                        child_path,
829                        is_clip_path,
830                        g.transform,
831                        clip_id.as_deref(),
832                        opt,
833                        xml,
834                    );
835                }
836                _ => {}
837            }
838        }
839        return;
840    }
841
842    xml.start_svg_element(EId::G);
843    if !g.id.is_empty() {
844        xml.write_id_attribute(&g.id, opt);
845    };
846
847    if let Some(ref clip) = g.clip_path {
848        xml.write_func_iri(AId::ClipPath, clip.id(), opt);
849    }
850
851    if let Some(ref mask) = g.mask {
852        xml.write_func_iri(AId::Mask, mask.id(), opt);
853    }
854
855    if !g.filters.is_empty() {
856        let prefix = opt.id_prefix.as_deref().unwrap_or_default();
857        let ids: Vec<_> = g
858            .filters
859            .iter()
860            .map(|filter| format!("url(#{}{})", prefix, filter.id()))
861            .collect();
862        xml.write_svg_attribute(AId::Filter, &ids.join(" "));
863    }
864
865    if g.opacity != Opacity::ONE {
866        xml.write_svg_attribute(AId::Opacity, &g.opacity.get());
867    }
868
869    xml.write_transform(AId::Transform, g.transform, opt);
870
871    if g.blend_mode != BlendMode::Normal || g.isolate {
872        // For reasons unknown, `mix-blend-mode` and `isolation` must be written
873        // as `style` attribute.
874        let isolation = if g.isolate { "isolate" } else { "auto" };
875        xml.write_attribute_fmt(
876            AId::Style.to_str(),
877            format_args!("mix-blend-mode:{};isolation:{}", g.blend_mode, isolation),
878        );
879    }
880
881    write_elements(g, false, opt, xml);
882
883    xml.end_element();
884}
885
886trait XmlWriterExt {
887    fn start_svg_element(&mut self, id: EId);
888    fn write_svg_attribute<V: Display + ?Sized>(&mut self, id: AId, value: &V);
889    fn write_id_attribute(&mut self, id: &str, opt: &WriteOptions);
890    fn write_color(&mut self, id: AId, color: Color);
891    fn write_units(&mut self, id: AId, units: Units, def: Units);
892    fn write_transform(&mut self, id: AId, units: Transform, opt: &WriteOptions);
893    fn write_visibility(&mut self, value: bool);
894    fn write_func_iri(&mut self, aid: AId, id: &str, opt: &WriteOptions);
895    fn write_rect_attrs(&mut self, r: NonZeroRect);
896    fn write_numbers(&mut self, aid: AId, list: &[f32]);
897    fn write_image_data(&mut self, kind: &ImageKind);
898    fn write_filter_input(&mut self, id: AId, input: &filter::Input);
899    fn write_filter_primitive_attrs(&mut self, parent_rect: NonZeroRect, fe: &filter::Primitive);
900    fn write_filter_transfer_function(&mut self, eid: EId, fe: &filter::TransferFunction);
901}
902
903impl XmlWriterExt for XmlWriter {
904    #[inline(never)]
905    fn start_svg_element(&mut self, id: EId) {
906        self.start_element(id.to_str());
907    }
908
909    #[inline(never)]
910    fn write_svg_attribute<V: Display + ?Sized>(&mut self, id: AId, value: &V) {
911        self.write_attribute(id.to_str(), value);
912    }
913
914    #[inline(never)]
915    fn write_id_attribute(&mut self, id: &str, opt: &WriteOptions) {
916        debug_assert!(!id.is_empty());
917
918        if let Some(ref prefix) = opt.id_prefix {
919            let full_id = format!("{}{}", prefix, id);
920            self.write_attribute("id", &full_id);
921        } else {
922            self.write_attribute("id", id);
923        }
924    }
925
926    #[inline(never)]
927    fn write_color(&mut self, id: AId, c: Color) {
928        static CHARS: &[u8] = b"0123456789abcdef";
929
930        #[inline]
931        fn int2hex(n: u8) -> (u8, u8) {
932            (CHARS[(n >> 4) as usize], CHARS[(n & 0xf) as usize])
933        }
934
935        let (r1, r2) = int2hex(c.red);
936        let (g1, g2) = int2hex(c.green);
937        let (b1, b2) = int2hex(c.blue);
938
939        self.write_attribute_raw(id.to_str(), |buf| {
940            buf.extend_from_slice(&[b'#', r1, r2, g1, g2, b1, b2]);
941        });
942    }
943
944    fn write_units(&mut self, id: AId, units: Units, def: Units) {
945        if units != def {
946            self.write_attribute(id.to_str(), &units);
947        }
948    }
949
950    fn write_transform(&mut self, id: AId, ts: Transform, opt: &WriteOptions) {
951        if !ts.is_default() {
952            self.write_attribute_raw(id.to_str(), |buf| {
953                buf.extend_from_slice(b"matrix(");
954                write_num(ts.sx, buf, opt.transforms_precision);
955                buf.push(b' ');
956                write_num(ts.ky, buf, opt.transforms_precision);
957                buf.push(b' ');
958                write_num(ts.kx, buf, opt.transforms_precision);
959                buf.push(b' ');
960                write_num(ts.sy, buf, opt.transforms_precision);
961                buf.push(b' ');
962                write_num(ts.tx, buf, opt.transforms_precision);
963                buf.push(b' ');
964                write_num(ts.ty, buf, opt.transforms_precision);
965                buf.extend_from_slice(b")");
966            });
967        }
968    }
969
970    fn write_visibility(&mut self, value: bool) {
971        if !value {
972            self.write_attribute(AId::Visibility.to_str(), "hidden");
973        }
974    }
975
976    fn write_func_iri(&mut self, aid: AId, id: &str, opt: &WriteOptions) {
977        debug_assert!(!id.is_empty());
978        let prefix = opt.id_prefix.as_deref().unwrap_or_default();
979        self.write_attribute_fmt(aid.to_str(), format_args!("url(#{}{})", prefix, id));
980    }
981
982    fn write_rect_attrs(&mut self, r: NonZeroRect) {
983        self.write_svg_attribute(AId::X, &r.x());
984        self.write_svg_attribute(AId::Y, &r.y());
985        self.write_svg_attribute(AId::Width, &r.width());
986        self.write_svg_attribute(AId::Height, &r.height());
987    }
988
989    fn write_numbers(&mut self, aid: AId, list: &[f32]) {
990        self.write_attribute_raw(aid.to_str(), |buf| {
991            for n in list {
992                buf.write_fmt(format_args!("{} ", n)).unwrap();
993            }
994
995            if !list.is_empty() {
996                buf.pop();
997            }
998        });
999    }
1000
1001    fn write_filter_input(&mut self, id: AId, input: &filter::Input) {
1002        self.write_attribute(
1003            id.to_str(),
1004            match input {
1005                filter::Input::SourceGraphic => "SourceGraphic",
1006                filter::Input::SourceAlpha => "SourceAlpha",
1007                filter::Input::Reference(s) => s,
1008            },
1009        );
1010    }
1011
1012    fn write_filter_primitive_attrs(&mut self, parent_rect: NonZeroRect, fe: &filter::Primitive) {
1013        if parent_rect.x() != fe.rect().x() {
1014            self.write_svg_attribute(AId::X, &fe.rect().x());
1015        }
1016        if parent_rect.y() != fe.rect().y() {
1017            self.write_svg_attribute(AId::Y, &fe.rect().y());
1018        }
1019        if parent_rect.width() != fe.rect().width() {
1020            self.write_svg_attribute(AId::Width, &fe.rect().width());
1021        }
1022        if parent_rect.height() != fe.rect().height() {
1023            self.write_svg_attribute(AId::Height, &fe.rect().height());
1024        }
1025
1026        self.write_attribute(
1027            AId::ColorInterpolationFilters.to_str(),
1028            match fe.color_interpolation {
1029                filter::ColorInterpolation::SRGB => "sRGB",
1030                filter::ColorInterpolation::LinearRGB => "linearRGB",
1031            },
1032        );
1033    }
1034
1035    fn write_filter_transfer_function(&mut self, eid: EId, fe: &filter::TransferFunction) {
1036        self.start_svg_element(eid);
1037
1038        match fe {
1039            filter::TransferFunction::Identity => {
1040                self.write_svg_attribute(AId::Type, "identity");
1041            }
1042            filter::TransferFunction::Table(values) => {
1043                self.write_svg_attribute(AId::Type, "table");
1044                self.write_numbers(AId::TableValues, values);
1045            }
1046            filter::TransferFunction::Discrete(values) => {
1047                self.write_svg_attribute(AId::Type, "discrete");
1048                self.write_numbers(AId::TableValues, values);
1049            }
1050            filter::TransferFunction::Linear { slope, intercept } => {
1051                self.write_svg_attribute(AId::Type, "linear");
1052                self.write_svg_attribute(AId::Slope, &slope);
1053                self.write_svg_attribute(AId::Intercept, &intercept);
1054            }
1055            filter::TransferFunction::Gamma {
1056                amplitude,
1057                exponent,
1058                offset,
1059            } => {
1060                self.write_svg_attribute(AId::Type, "gamma");
1061                self.write_svg_attribute(AId::Amplitude, &amplitude);
1062                self.write_svg_attribute(AId::Exponent, &exponent);
1063                self.write_svg_attribute(AId::Offset, &offset);
1064            }
1065        }
1066
1067        self.end_element();
1068    }
1069
1070    fn write_image_data(&mut self, kind: &ImageKind) {
1071        let svg_string;
1072        let (mime, data) = match kind {
1073            ImageKind::JPEG(data) => ("jpeg", data.as_slice()),
1074            ImageKind::PNG(data) => ("png", data.as_slice()),
1075            ImageKind::GIF(data) => ("gif", data.as_slice()),
1076            ImageKind::WEBP(data) => ("webp", data.as_slice()),
1077            ImageKind::SVG(tree) => {
1078                svg_string = tree.to_string(&WriteOptions::default());
1079                ("svg+xml", svg_string.as_bytes())
1080            }
1081        };
1082
1083        self.write_attribute_raw("xlink:href", |buf| {
1084            buf.extend_from_slice(b"data:image/");
1085            buf.extend_from_slice(mime.as_bytes());
1086            buf.extend_from_slice(b";base64, ");
1087
1088            let mut enc =
1089                base64::write::EncoderWriter::new(buf, &base64::engine::general_purpose::STANDARD);
1090            enc.write_all(data).unwrap();
1091            enc.finish().unwrap();
1092        });
1093    }
1094}
1095
1096fn has_xlink(parent: &Group) -> bool {
1097    for node in &parent.children {
1098        match node {
1099            Node::Group(g) => {
1100                for filter in &g.filters {
1101                    if filter
1102                        .primitives
1103                        .iter()
1104                        .any(|p| matches!(p.kind, filter::Kind::Image(_)))
1105                    {
1106                        return true;
1107                    }
1108                }
1109
1110                if let Some(mask) = &g.mask {
1111                    if has_xlink(mask.root()) {
1112                        return true;
1113                    }
1114
1115                    if let Some(sub_mask) = &mask.mask {
1116                        if has_xlink(&sub_mask.root) {
1117                            return true;
1118                        }
1119                    }
1120                }
1121
1122                if has_xlink(g) {
1123                    return true;
1124                }
1125            }
1126            Node::Image(_) => {
1127                return true;
1128            }
1129            Node::Text(text) => {
1130                if text
1131                    .chunks
1132                    .iter()
1133                    .any(|t| matches!(t.text_flow, TextFlow::Path(_)))
1134                {
1135                    return true;
1136                }
1137            }
1138            _ => {}
1139        }
1140
1141        let mut present = false;
1142        node.subroots(|root| present |= has_xlink(root));
1143        if present {
1144            return true;
1145        }
1146    }
1147
1148    false
1149}
1150
1151fn write_base_grad(g: &BaseGradient, opt: &WriteOptions, xml: &mut XmlWriter) {
1152    xml.write_units(AId::GradientUnits, g.units, Units::ObjectBoundingBox);
1153    xml.write_transform(AId::GradientTransform, g.transform, opt);
1154
1155    match g.spread_method {
1156        SpreadMethod::Pad => {}
1157        SpreadMethod::Reflect => xml.write_svg_attribute(AId::SpreadMethod, "reflect"),
1158        SpreadMethod::Repeat => xml.write_svg_attribute(AId::SpreadMethod, "repeat"),
1159    }
1160
1161    for s in &g.stops {
1162        xml.start_svg_element(EId::Stop);
1163        xml.write_svg_attribute(AId::Offset, &s.offset.get());
1164        xml.write_color(AId::StopColor, s.color);
1165        if s.opacity != Opacity::ONE {
1166            xml.write_svg_attribute(AId::StopOpacity, &s.opacity.get());
1167        }
1168
1169        xml.end_element();
1170    }
1171}
1172
1173fn write_path(
1174    path: &Path,
1175    is_clip_path: bool,
1176    path_transform: Transform,
1177    clip_path: Option<&str>,
1178    opt: &WriteOptions,
1179    xml: &mut XmlWriter,
1180) {
1181    xml.start_svg_element(EId::Path);
1182    if !path.id.is_empty() {
1183        xml.write_id_attribute(&path.id, opt);
1184    }
1185
1186    write_fill(&path.fill, is_clip_path, opt, xml);
1187    write_stroke(&path.stroke, opt, xml);
1188
1189    xml.write_visibility(path.visible);
1190
1191    if path.paint_order == PaintOrder::StrokeAndFill {
1192        xml.write_svg_attribute(AId::PaintOrder, "stroke");
1193    }
1194
1195    match path.rendering_mode {
1196        ShapeRendering::OptimizeSpeed => {
1197            xml.write_svg_attribute(AId::ShapeRendering, "optimizeSpeed");
1198        }
1199        ShapeRendering::CrispEdges => xml.write_svg_attribute(AId::ShapeRendering, "crispEdges"),
1200        ShapeRendering::GeometricPrecision => {}
1201    }
1202
1203    if let Some(id) = clip_path {
1204        xml.write_func_iri(AId::ClipPath, id, opt);
1205    }
1206
1207    xml.write_transform(AId::Transform, path_transform, opt);
1208
1209    xml.write_attribute_raw("d", |buf| {
1210        use tiny_skia_path::PathSegment;
1211
1212        for seg in path.data.segments() {
1213            match seg {
1214                PathSegment::MoveTo(p) => {
1215                    buf.extend_from_slice(b"M ");
1216                    write_num(p.x, buf, opt.coordinates_precision);
1217                    buf.push(b' ');
1218                    write_num(p.y, buf, opt.coordinates_precision);
1219                    buf.push(b' ');
1220                }
1221                PathSegment::LineTo(p) => {
1222                    buf.extend_from_slice(b"L ");
1223                    write_num(p.x, buf, opt.coordinates_precision);
1224                    buf.push(b' ');
1225                    write_num(p.y, buf, opt.coordinates_precision);
1226                    buf.push(b' ');
1227                }
1228                PathSegment::QuadTo(p1, p) => {
1229                    buf.extend_from_slice(b"Q ");
1230                    write_num(p1.x, buf, opt.coordinates_precision);
1231                    buf.push(b' ');
1232                    write_num(p1.y, buf, opt.coordinates_precision);
1233                    buf.push(b' ');
1234                    write_num(p.x, buf, opt.coordinates_precision);
1235                    buf.push(b' ');
1236                    write_num(p.y, buf, opt.coordinates_precision);
1237                    buf.push(b' ');
1238                }
1239                PathSegment::CubicTo(p1, p2, p) => {
1240                    buf.extend_from_slice(b"C ");
1241                    write_num(p1.x, buf, opt.coordinates_precision);
1242                    buf.push(b' ');
1243                    write_num(p1.y, buf, opt.coordinates_precision);
1244                    buf.push(b' ');
1245                    write_num(p2.x, buf, opt.coordinates_precision);
1246                    buf.push(b' ');
1247                    write_num(p2.y, buf, opt.coordinates_precision);
1248                    buf.push(b' ');
1249                    write_num(p.x, buf, opt.coordinates_precision);
1250                    buf.push(b' ');
1251                    write_num(p.y, buf, opt.coordinates_precision);
1252                    buf.push(b' ');
1253                }
1254                PathSegment::Close => {
1255                    buf.extend_from_slice(b"Z ");
1256                }
1257            }
1258        }
1259
1260        buf.pop();
1261    });
1262
1263    xml.end_element();
1264}
1265
1266fn write_fill(fill: &Option<Fill>, is_clip_path: bool, opt: &WriteOptions, xml: &mut XmlWriter) {
1267    if let Some(fill) = fill {
1268        write_paint(AId::Fill, &fill.paint, opt, xml);
1269
1270        if fill.opacity != Opacity::ONE {
1271            xml.write_svg_attribute(AId::FillOpacity, &fill.opacity.get());
1272        }
1273
1274        if !fill.rule.is_default() {
1275            let name = if is_clip_path {
1276                AId::ClipRule
1277            } else {
1278                AId::FillRule
1279            };
1280
1281            xml.write_svg_attribute(name, "evenodd");
1282        }
1283    } else {
1284        xml.write_svg_attribute(AId::Fill, "none");
1285    }
1286}
1287
1288fn write_stroke(stroke: &Option<Stroke>, opt: &WriteOptions, xml: &mut XmlWriter) {
1289    if let Some(stroke) = stroke {
1290        write_paint(AId::Stroke, &stroke.paint, opt, xml);
1291
1292        if stroke.opacity != Opacity::ONE {
1293            xml.write_svg_attribute(AId::StrokeOpacity, &stroke.opacity.get());
1294        }
1295
1296        if !stroke.dashoffset.approx_zero_ulps(4) {
1297            xml.write_svg_attribute(AId::StrokeDashoffset, &stroke.dashoffset);
1298        }
1299
1300        if !stroke.miterlimit.is_default() {
1301            xml.write_svg_attribute(AId::StrokeMiterlimit, &stroke.miterlimit.get());
1302        }
1303
1304        if stroke.width.get() != 1.0 {
1305            xml.write_svg_attribute(AId::StrokeWidth, &stroke.width.get());
1306        }
1307
1308        match stroke.linecap {
1309            LineCap::Butt => {}
1310            LineCap::Round => xml.write_svg_attribute(AId::StrokeLinecap, "round"),
1311            LineCap::Square => xml.write_svg_attribute(AId::StrokeLinecap, "square"),
1312        }
1313
1314        match stroke.linejoin {
1315            LineJoin::Miter => {}
1316            LineJoin::MiterClip => xml.write_svg_attribute(AId::StrokeLinejoin, "miter-clip"),
1317            LineJoin::Round => xml.write_svg_attribute(AId::StrokeLinejoin, "round"),
1318            LineJoin::Bevel => xml.write_svg_attribute(AId::StrokeLinejoin, "bevel"),
1319        }
1320
1321        if let Some(ref array) = stroke.dasharray {
1322            xml.write_numbers(AId::StrokeDasharray, array);
1323        }
1324    } else {
1325        // Always set `stroke` to `none` to override the parent value.
1326        // In 99.9% of the cases it's redundant, but a group with `filter` with `StrokePaint`
1327        // will set `stroke`, which will interfere with children nodes.
1328        xml.write_svg_attribute(AId::Stroke, "none");
1329    }
1330}
1331
1332fn write_paint(aid: AId, paint: &Paint, opt: &WriteOptions, xml: &mut XmlWriter) {
1333    match paint {
1334        Paint::Color(c) => xml.write_color(aid, *c),
1335        Paint::LinearGradient(lg) => {
1336            xml.write_func_iri(aid, lg.id(), opt);
1337        }
1338        Paint::RadialGradient(rg) => {
1339            xml.write_func_iri(aid, rg.id(), opt);
1340        }
1341        Paint::Pattern(patt) => {
1342            xml.write_func_iri(aid, patt.id(), opt);
1343        }
1344    }
1345}
1346
1347fn write_light_source(light: &filter::LightSource, xml: &mut XmlWriter) {
1348    match light {
1349        filter::LightSource::DistantLight(light) => {
1350            xml.start_svg_element(EId::FeDistantLight);
1351            xml.write_svg_attribute(AId::Azimuth, &light.azimuth);
1352            xml.write_svg_attribute(AId::Elevation, &light.elevation);
1353        }
1354        filter::LightSource::PointLight(light) => {
1355            xml.start_svg_element(EId::FePointLight);
1356            xml.write_svg_attribute(AId::X, &light.x);
1357            xml.write_svg_attribute(AId::Y, &light.y);
1358            xml.write_svg_attribute(AId::Z, &light.z);
1359        }
1360        filter::LightSource::SpotLight(light) => {
1361            xml.start_svg_element(EId::FeSpotLight);
1362            xml.write_svg_attribute(AId::X, &light.x);
1363            xml.write_svg_attribute(AId::Y, &light.y);
1364            xml.write_svg_attribute(AId::Z, &light.z);
1365            xml.write_svg_attribute(AId::PointsAtX, &light.points_at_x);
1366            xml.write_svg_attribute(AId::PointsAtY, &light.points_at_y);
1367            xml.write_svg_attribute(AId::PointsAtZ, &light.points_at_z);
1368            xml.write_svg_attribute(AId::SpecularExponent, &light.specular_exponent);
1369            if let Some(n) = light.limiting_cone_angle {
1370                xml.write_svg_attribute(AId::LimitingConeAngle, &n);
1371            }
1372        }
1373    }
1374
1375    xml.end_element();
1376}
1377
1378static POW_VEC: &[f32] = &[
1379    1.0,
1380    10.0,
1381    100.0,
1382    1_000.0,
1383    10_000.0,
1384    100_000.0,
1385    1_000_000.0,
1386    10_000_000.0,
1387    100_000_000.0,
1388    1_000_000_000.0,
1389    10_000_000_000.0,
1390    100_000_000_000.0,
1391    1_000_000_000_000.0,
1392];
1393
1394fn write_num(num: f32, buf: &mut Vec<u8>, precision: u8) {
1395    // If number is an integer, it's faster to write it as i32.
1396    if num.fract().approx_zero_ulps(4) {
1397        write!(buf, "{}", num as i32).unwrap();
1398        return;
1399    }
1400
1401    // Round numbers up to the specified precision to prevent writing
1402    // ugly numbers like 29.999999999999996.
1403    // It's not 100% correct, but differences are insignificant.
1404    //
1405    // Note that at least in Rust 1.64 the number formatting in debug and release modes
1406    // can be slightly different. So having a lower precision makes
1407    // our output and tests reproducible.
1408    let v = (num * POW_VEC[precision as usize]).round() / POW_VEC[precision as usize];
1409
1410    write!(buf, "{}", v).unwrap();
1411}
1412
1413/// Write all of the tspan attributes except for decorations.
1414fn write_span(
1415    is_clip_path: bool,
1416    opt: &WriteOptions,
1417    xml: &mut XmlWriter,
1418    chunk: &TextChunk,
1419    span: &TextSpan,
1420) {
1421    xml.start_svg_element(EId::Tspan);
1422
1423    let font_family_to_str = |font_family: &FontFamily| match font_family {
1424        FontFamily::Monospace => "monospace".to_string(),
1425        FontFamily::Serif => "serif".to_string(),
1426        FontFamily::SansSerif => "sans-serif".to_string(),
1427        FontFamily::Cursive => "cursive".to_string(),
1428        FontFamily::Fantasy => "fantasy".to_string(),
1429        FontFamily::Named(s) => {
1430            // Only quote if absolutely necessary
1431            match parse_font_families(s) {
1432                Ok(_) => s.clone(),
1433                Err(_) => {
1434                    if opt.use_single_quote {
1435                        format!("\"{}\"", s)
1436                    } else {
1437                        format!("'{}'", s)
1438                    }
1439                }
1440            }
1441        }
1442    };
1443
1444    if !span.font.families.is_empty() {
1445        let families = span
1446            .font
1447            .families
1448            .iter()
1449            .map(font_family_to_str)
1450            .collect::<Vec<_>>()
1451            .join(", ");
1452        xml.write_svg_attribute(AId::FontFamily, &families);
1453    }
1454
1455    match span.font.style {
1456        FontStyle::Normal => {}
1457        FontStyle::Italic => xml.write_svg_attribute(AId::FontStyle, "italic"),
1458        FontStyle::Oblique => xml.write_svg_attribute(AId::FontStyle, "oblique"),
1459    }
1460
1461    if span.font.weight != 400 {
1462        xml.write_svg_attribute(AId::FontWeight, &span.font.weight);
1463    }
1464
1465    if span.font.stretch != FontStretch::Normal {
1466        let name = match span.font.stretch {
1467            FontStretch::Condensed => "condensed",
1468            FontStretch::ExtraCondensed => "extra-condensed",
1469            FontStretch::UltraCondensed => "ultra-condensed",
1470            FontStretch::SemiCondensed => "semi-condensed",
1471            FontStretch::Expanded => "expanded",
1472            FontStretch::SemiExpanded => "semi-expanded",
1473            FontStretch::ExtraExpanded => "extra-expanded",
1474            FontStretch::UltraExpanded => "ultra-expanded",
1475            FontStretch::Normal => unreachable!(),
1476        };
1477        xml.write_svg_attribute(AId::FontStretch, name);
1478    }
1479
1480    xml.write_svg_attribute(AId::FontSize, &span.font_size);
1481
1482    xml.write_visibility(span.visible);
1483
1484    if span.letter_spacing != 0.0 {
1485        xml.write_svg_attribute(AId::LetterSpacing, &span.letter_spacing);
1486    }
1487
1488    if span.word_spacing != 0.0 {
1489        xml.write_svg_attribute(AId::WordSpacing, &span.word_spacing);
1490    }
1491
1492    if let Some(text_length) = span.text_length {
1493        xml.write_svg_attribute(AId::TextLength, &text_length);
1494    }
1495
1496    if span.length_adjust == LengthAdjust::SpacingAndGlyphs {
1497        xml.write_svg_attribute(AId::LengthAdjust, "spacingAndGlyphs");
1498    }
1499
1500    if span.small_caps {
1501        xml.write_svg_attribute(AId::FontVariant, "small-caps");
1502    }
1503
1504    if span.paint_order == PaintOrder::StrokeAndFill {
1505        xml.write_svg_attribute(AId::PaintOrder, "stroke fill");
1506    }
1507
1508    if !span.apply_kerning {
1509        xml.write_attribute("style", "font-kerning:none");
1510    }
1511
1512    if span.dominant_baseline != DominantBaseline::Auto {
1513        let name = match span.dominant_baseline {
1514            DominantBaseline::UseScript => "use-script",
1515            DominantBaseline::NoChange => "no-change",
1516            DominantBaseline::ResetSize => "reset-size",
1517            DominantBaseline::TextBeforeEdge => "text-before-edge",
1518            DominantBaseline::Middle => "middle",
1519            DominantBaseline::Central => "central",
1520            DominantBaseline::TextAfterEdge => "text-after-edge",
1521            DominantBaseline::Ideographic => "ideographic",
1522            DominantBaseline::Alphabetic => "alphabetic",
1523            DominantBaseline::Hanging => "hanging",
1524            DominantBaseline::Mathematical => "mathematical",
1525            DominantBaseline::Auto => unreachable!(),
1526        };
1527        xml.write_svg_attribute(AId::DominantBaseline, name);
1528    }
1529
1530    if span.alignment_baseline != AlignmentBaseline::Auto {
1531        let name = match span.alignment_baseline {
1532            AlignmentBaseline::Baseline => "baseline",
1533            AlignmentBaseline::BeforeEdge => "before-edge",
1534            AlignmentBaseline::TextBeforeEdge => "text-before-edge",
1535            AlignmentBaseline::Middle => "middle",
1536            AlignmentBaseline::Central => "central",
1537            AlignmentBaseline::AfterEdge => "after-edge",
1538            AlignmentBaseline::TextAfterEdge => "text-after-edge",
1539            AlignmentBaseline::Ideographic => "ideographic",
1540            AlignmentBaseline::Alphabetic => "alphabetic",
1541            AlignmentBaseline::Hanging => "hanging",
1542            AlignmentBaseline::Mathematical => "mathematical",
1543            AlignmentBaseline::Auto => unreachable!(),
1544        };
1545        xml.write_svg_attribute(AId::AlignmentBaseline, name);
1546    }
1547
1548    write_fill(&span.fill, is_clip_path, opt, xml);
1549    write_stroke(&span.stroke, opt, xml);
1550
1551    for baseline_shift in &span.baseline_shift {
1552        xml.start_svg_element(EId::Tspan);
1553        match baseline_shift {
1554            BaselineShift::Baseline => {}
1555            BaselineShift::Number(num) => xml.write_svg_attribute(AId::BaselineShift, num),
1556            BaselineShift::Subscript => xml.write_svg_attribute(AId::BaselineShift, "sub"),
1557            BaselineShift::Superscript => xml.write_svg_attribute(AId::BaselineShift, "super"),
1558        }
1559    }
1560
1561    let cur_text = &chunk.text[span.start..span.end];
1562
1563    xml.write_text(&cur_text.replace('&', "&amp;"));
1564
1565    // End for each tspan we needed to create for baseline_shift
1566    for _ in &span.baseline_shift {
1567        xml.end_element();
1568    }
1569
1570    xml.end_element();
1571}