Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
LR10: svg text spaces its last letter as Chrome does. usvg 0.48.1 left letter-spacing off a text chunk's last cluster, so an svg <text> with letter-spacing and a middle or end anchor was drawn half or a whole spacing off where Chrome draws it, and its box was a spacing short. vendor/usvg patches apply_letter_spacing (marked raea:), canvas.svgText's length drops the tracking it added to make up for it, and the layout-reads box reader skips an svg's <title> and <desc>, which are never drawn. snapcn: drop-line 1.3 -> 0.2 and hello-zoom pass; P26 unchanged (the six fixtures under the bar fail the same frames at the same SSIM on a binary without the patch)
shinyobjectz8a51aa04330e
diff --git a/Cargo.lock b/Cargo.lockindex bbc33376..a742c0c0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -20858,8 +20858,6 @@ dependencies = [[[package]]name = "usvg"version = "0.48.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91"dependencies = ["base64 0.23.1","data-url 0.3.2",diff --git a/Cargo.toml b/Cargo.tomlindex c57da15a..9fec479f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -288,6 +288,8 @@ split-debuginfo = "packed"[patch.crates-io]# the MP4 muxer, vendoredmuxide = { path = "vendor/muxide" }+# usvg 0.48.1 spacing a chunk's last letter as Chrome does (changes marked "raea:", docs/layout-reads.feature LR10)+usvg = { path = "vendor/usvg" }# bevy_seedling 0.8.0 without its cpal 0.18 paths, ported to Bevy 0.20 (changes marked "raea:")bevy_seedling = { path = "vendor/bevy_seedling" }# bevy_text 0.20.0 on parley 0.12, so one parley builds (changes marked "raea:", docs/bevy-upgrade.md)diff --git a/bench/layout-reads/boxes.ts b/bench/layout-reads/boxes.tsindex cb369767..a2e84df6 100644--- a/bench/layout-reads/boxes.ts+++ b/bench/layout-reads/boxes.ts@@ -22,7 +22,8 @@ export function runs(root: Element): Run[] {const walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);for (let n = walk.nextNode() as Text | null; n; n = walk.nextNode() as Text | null) {if (!n.data || !n.parentElement) continue;- if (n.parentElement.closest("style, script")) continue;+ // (an svg's <title> and <desc> are never drawn: they name the picture for a screen reader)+ if (n.parentElement.closest("style, script, svg title, svg desc")) continue;// an svg's words belong to their <text>, as the manifest has them (the page draws an svg as one picture, usvg's)const svgText = n.parentElement.closest("svg text");let up: Element | null = svgText ?? n.parentElement;diff --git a/systems/canvas/src/svgtext.rs b/systems/canvas/src/svgtext.rsindex 68a83c3c..80a059bb 100644--- a/systems/canvas/src/svgtext.rs+++ b/systems/canvas/src/svgtext.rs@@ -30,13 +30,9 @@ pub fn svg_text(opt: &usvg::Options, args: &Value) -> Value {starts.extend(g.text.chars().map(|_| x));}}- // usvg's box ends at the last glyph's advance; Chrome's length tracks every character, the last one too- // (a computed letter-spacing is px, or "normal", which is none)- let tracking: f32 = match args["style"]["letter-spacing"].as_str() {- Some(v) if v.ends_with("px") => v.trim_end_matches("px").trim().parse().unwrap_or(0.0),- _ => 0.0,- };- let length = if text.is_empty() { 0.0 } else { t.bounding_box().width() + tracking };+ // its box's width: every character's advance and spacing, the last one's too, as Chrome's length has it (raea's+ // usvg spaces the last letter: vendor/usvg)+ let length = if text.is_empty() { 0.0 } else { t.bounding_box().width() };json!({ "length": length, "starts": starts })}diff --git a/vendor/usvg/Cargo.toml b/vendor/usvg/Cargo.tomlnew file mode 100644index 00000000..79ce5aae--- /dev/null+++ b/vendor/usvg/Cargo.toml@@ -0,0 +1,152 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2024"+rust-version = "1.85.0"+name = "usvg"+version = "0.48.1"+build = false+exclude = ["tests"]+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "An SVG simplification library."+documentation = "https://docs.rs/usvg/"+readme = "README.md"+keywords = ["svg"]+categories = ["multimedia::images"]+license = "Apache-2.0 OR MIT"+repository = "https://github.com/linebender/resvg"+resolver = "2"++[features]+default = [+ "svgz",+ "text",+ "system-fonts",+ "memmap-fonts",+ "writer",+]+memmap-fonts = ["fontdb/memmap"]+svgz = ["flate2"]+system-fonts = [+ "fontdb/fs",+ "fontdb/fontconfig",+]+text = [+ "fontdb",+ "harfrust",+ "skrifa",+ "unicode-bidi",+ "unicode-script",+ "unicode-vo",+ "writer",+]+writer = [+ "xmlwriter",+ "base64",+]++[lib]+name = "usvg"+path = "src/lib.rs"++[[bin]]+name = "usvg"+path = "src/main.rs"+required-features = [+ "svgz",+ "text",+ "system-fonts",+ "memmap-fonts",+ "writer",+]++[dependencies.base64]+version = "0.23"+optional = true++[dependencies.data-url]+version = "0.3"++[dependencies.flate2]+version = "1.1"+features = ["rust_backend"]+optional = true+default-features = false++[dependencies.fontdb]+version = "0.24"+optional = true+default-features = false++[dependencies.harfrust]+version = "0.12.0"+optional = true++[dependencies.imagesize]+version = "0.15.0"++[dependencies.kurbo]+version = "0.13.0"++[dependencies.log]+version = "0.4"++[dependencies.pico-args]+version = "0.5"+features = ["eq-separator"]++[dependencies.roxmltree]+version = "0.21.1"++[dependencies.simplecss]+version = "0.2"++[dependencies.siphasher]+version = "1.0"++[dependencies.skrifa]+version = "0.44"+features = ["std"]+optional = true+default-features = false++[dependencies.strict-num]+version = "0.1.1"++[dependencies.svgtypes]+version = "0.16.1"++[dependencies.tiny-skia-path]+version = "0.12.0"++[dependencies.unicode-bidi]+version = "0.3"+optional = true++[dependencies.unicode-script]+version = "0.5"+optional = true++[dependencies.unicode-vo]+version = "0.1"+optional = true++[dependencies.xmlwriter]+version = "0.1"+optional = true++[dev-dependencies.once_cell]+version = "1.21"diff --git a/vendor/usvg/Cargo.toml.orig b/vendor/usvg/Cargo.toml.orignew file mode 100644index 00000000..1eeb2c6c--- /dev/null+++ b/vendor/usvg/Cargo.toml.orig@@ -0,0 +1,61 @@+[package]+name = "usvg"+version = "0.48.1"+keywords = ["svg"]+license.workspace = true+edition = "2024"+rust-version = "1.85.0"+description = "An SVG simplification library."+categories = ["multimedia::images"]+repository = "https://github.com/linebender/resvg"+documentation = "https://docs.rs/usvg/"+readme = "README.md"+exclude = ["tests"]+workspace = "../.."++[[bin]]+name = "usvg"+required-features = ["svgz", "text", "system-fonts", "memmap-fonts", "writer"]++[dependencies]+base64 = { version = "0.23", optional = true } # for embedded images+log = "0.4"+pico-args = { version = "0.5", features = ["eq-separator"] }+strict-num = "0.1.1"+svgtypes = "0.16.1"+tiny-skia-path = "0.12.0"+xmlwriter = { version = "0.1", optional = true }++# parser+data-url = "0.3" # for href parsing+flate2 = { version = "1.1", default-features = false, features = ["rust_backend"], optional = true } # SVGZ decoding+imagesize = "0.15.0" # raster images size detection+kurbo = "0.13.0" # Bezier curves utils+roxmltree = "0.21.1"+simplecss = "0.2"+siphasher = "1.0" # perfect hash implementation++# text+fontdb = { version = "0.24", default-features = false, optional = true }+harfrust = { version = "0.12.0", optional = true }+skrifa = { version = "0.44", optional = true, default-features = false, features = ["std"] }+unicode-bidi = { version = "0.3", optional = true }+unicode-script = { version = "0.5", optional = true }+unicode-vo = { version = "0.1", optional = true }++[dev-dependencies]+once_cell = "1.21"++[features]+default = ["svgz", "text", "system-fonts", "memmap-fonts", "writer"]+# Enables SVGZ decoding+svgz = ["flate2"]+# Enables text-to-path conversion support.+# Adds around 400KiB to your binary.+text = ["fontdb", "harfrust", "skrifa", "unicode-bidi", "unicode-script", "unicode-vo", "writer"]+# Enables system fonts loading.+system-fonts = ["fontdb/fs", "fontdb/fontconfig"]+# Enables font files memmaping for faster loading.+memmap-fonts = ["fontdb/memmap"]+# Enables converting trees back to SVG.+writer = ["xmlwriter", "base64"]diff --git a/vendor/usvg/LICENSE-APACHE b/vendor/usvg/LICENSE-APACHEnew file mode 100644index 00000000..d9a10c0d--- /dev/null+++ b/vendor/usvg/LICENSE-APACHE@@ -0,0 +1,176 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONSdiff --git a/vendor/usvg/LICENSE-MIT b/vendor/usvg/LICENSE-MITnew file mode 100644index 00000000..6f7cc66b--- /dev/null+++ b/vendor/usvg/LICENSE-MIT@@ -0,0 +1,25 @@+Copyright 2017 the Resvg Authors++Permission is hereby granted, free of charge, to any+person obtaining a copy of this software and associated+documentation files (the "Software"), to deal in the+Software without restriction, including without+limitation the rights to use, copy, modify, merge,+publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software+is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice+shall be included in all copies or substantial portions+of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/vendor/usvg/README.md b/vendor/usvg/README.mdnew file mode 100644index 00000000..1e6ba6d2--- /dev/null+++ b/vendor/usvg/README.md@@ -0,0 +1,64 @@+# usvg+[](https://crates.io/crates/usvg)+[](https://docs.rs/usvg)+[](https://www.rust-lang.org)++`usvg` (micro SVG) is an [SVG] parser that tries to solve most of SVG complexity.++SVG is notoriously hard to parse. `usvg` presents a layer between an XML library and+a potential SVG rendering library. It will parse an input SVG into a strongly-typed tree structure+were all the elements, attributes, references and other SVG features are already resolved+and presented in the simplest way possible.+So a caller doesn't have to worry about most of the issues related to SVG parsing+and can focus just on the rendering part.++## Features++- All supported attributes are resolved.+ No need to worry about inheritable, implicit and default attributes+- CSS will be applied+- Only simple paths+ - Basic shapes (like `rect` and `circle`) will be converted into paths+ - Paths contain only absolute *MoveTo*, *LineTo*, *QuadTo*, *CurveTo* and *ClosePath* segments.+ ArcTo, implicit and relative segments will be converted+- `use` will be resolved and replaced with the reference content+- Nested `svg` will be resolved+- Invalid, malformed elements will be removed+- Relative length units (mm, em, etc.) will be converted into pixels/points+- External images will be loaded+- Internal, base64 images will be decoded+- All references (like `#elem` and `url(#elem)`) will be resolved+- `switch` will be resolved+- Text elements, which are probably the hardest part of SVG, will be completely resolved.+ This includes all the attributes resolving, whitespaces preprocessing (`xml:space`),+ text chunks and spans resolving+- Markers will be converted into regular elements. No need to place them manually+- All filters are supported. Including filter functions, like `filter="contrast(50%)"`+- Recursive elements will be detected and removed+- `objectBoundingBox` will be replaced with `userSpaceOnUse`++## Limitations++- Unsupported SVG features will be ignored+- CSS support is minimal+- Only [static](http://www.w3.org/TR/SVG11/feature#SVG-static) SVG features,+ e.g. no `a`, `view`, `cursor`, `script`, no events and no animations++## License++Licensed under either of++- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)+- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)++at your option.++## Contribution++Contributions are welcome by pull request.+The [Rust code of conduct] applies.++Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions.++[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct+[SVG]: https://en.wikipedia.org/wiki/Scalable_Vector_Graphicsdiff --git a/vendor/usvg/docs/post-processing.md b/vendor/usvg/docs/post-processing.mdnew file mode 100644index 00000000..33c184d9--- /dev/null+++ b/vendor/usvg/docs/post-processing.md@@ -0,0 +1,207 @@+# XML Post-processing Steps++## No namespaces++In an SVG tree all elements and attributes belong to the SVG namespace.++## No non-SVG elements and attributes++Only SVG elements and attributes are preserved.++And their names are stored as `enum`s and not strings.+This increases performance and makes typos impossible.++## Only elements and text nodes++XML can contain elements, text nodes, comments and processing instructions.+Our tree contains only elements and text nodes inside the `text` element.++## Whitespaces trimming++Not only text nodes can be present only inside the `text` element,+but they are also trimmed according to the SVG rules, including `xml:space`.++For example:++```xml+<text>+ Text+</text>+```++becomes++```xml+<text>Text</text>+```++And++```xml+<text>+ <tspan>+ Text+ </tspan>+ <tspan>+ Text+ </tspan>+</text>+```++becomes++```xml+<text><tspan>Text</tspan> <tspan>Text</tspan></text>+```++## `style` attribute splitting++The `style` attribute content will be converted into normal attributes.++```xml+<rect style="fill:green"/>+```++will become++```xml+<rect fill="green"/>+```++The produced SVG tree never has `style` attributes.++## CSS will be applied++All _supported_ CSS rules will be applied.++```xml+<style>rect { fill:green } </style>+<rect/>+```++will become++```xml+<rect fill="green"/>+```++The produced SVG tree never has `style` elements and `class` attributes.++## `inherit` will be resolved++SVG allows setting some attribute values to `inherit`,+in which case the actual value should be taken from a parent element.++Not only it applies only to some attributes.+But some attributes also allow `inherit` only from the direct parent.++`rosvgtree` handles this for us.++## Recursive links removal++SVG supports referencing other elements via IRI and FuncIRI value types.+IRI is `xlink:href="#id"` and FuncIRI is `url(#id)`.++As in any link-based system this could lead to recursive references,+which when handled incorrectly can crash your app.++We're trying to detect all common cases, but it's+not 100% guarantee that there will be no recursive links left, but we're pretty close.++This includes simple cases like++```xml+<use id="use1" xlink:href="#use1"/>+```++and more complex one like++```xml+<clipPath id="clip1">+ <rect clip-path="url(#clip2)"/>+</clipPath>+<clipPath id="clip2">+ <rect clip-path="url(#clip1)"/>+</clipPath>+```++## Remember all elements with an ID++As mentioned above, SVG supports references. And it can reference any element in the document.<br>+Instead of checking each element in the tree each time, which would be pretty slow,+we have an ID<->Node HashMap to quickly retrieve a requested element.++## Links are groups++The `<a>` element in SVG is just a `<g>` with a URL.<br>+Since we really support only the static SVG subset, we can replace `<a>` with `<g>`.++## `tref` resolving++[`tref`](https://www.w3.org/TR/SVG11/text.html#TRefElement) is a pretty weird SVG element.+It's basically a way to reference text nodes.++We resolve them automatically and replace them with `tspan`.++```xml+<defs>+ <text id="text1">Text</text>+</defs>+<text><tref xlink:href="#text1"/></text>+```++will become++```xml+<text><tspan>Text</tspan></text>+```++## `use` will be resolved++This is probably the only breaking change to the SVG structure.++The way the `use` works, is that it creates a shadow tree of nodes+that it's referencing. This is a great way to save space,+but it makes style properties resolving way harder.++This is because when you want to get a parent element from inside the `use`,+the tree should return `use`'s parent and not the referenced element parent.++To illustrate:++```xml+<g fill="red">+ <rect id="rect1"/>+</g>+<g fill="green">+ <!-- rect's fill should be resolved to green -->+ <use href="#rect"/>+</g>+```++If you simply call `node.parent().attribute("fill")` it will return `red`, not `green`.+Because the current node is `rect1`.++As you can imagine, this is pretty hard to handle using a typical DOM model.+So instead we're simply coping referenced elements inside+the `use` so it can be treated as a regular group.++```xml+<rect id="rect1"/>+<use href="#rect"/>+```++will become++```xml+<rect id="rect1"/>+<use href="#rect">+ <rect/>+</use>+```++<br>++The main limitation of this approach, excluding the fact we're creating way more elements+that we had initially, is that copied elements must not have an `id` attribute,+otherwise we would end up with multiple duplicates.diff --git a/vendor/usvg/docs/spec.adoc b/vendor/usvg/docs/spec.adocnew file mode 100644index 00000000..02a5b039--- /dev/null+++ b/vendor/usvg/docs/spec.adoc@@ -0,0 +1,773 @@+= Micro SVG Document Structure+:toc:++== Intro++SVG Micro represents a strip down SVG Full 1.1 subset.++Here is the main differences between SVG Full and SVG Micro.++- No XML DTD.+- No CSS.+- `use`, `marker` and nested `svg` will be resolved.+- Simplified path notation. Only absolute MoveTo, LineTo, CurveTo+ and ClosePath segments are allowed.+- No inheritable attributes.+- No `xlink:href`, except the `image` element.+- No recursive references.+- Only valid elements and attributes.+- No unused elements.+- No redundant groups.+- No units.+- No `objectBoundingBox` units.+- No `viewBox` and `preserveAspectRatio` attributes.+- No `style` attribute, except for `mix-blend-mode` and `isolation`+- Default attributes are implicit.++You can use+https://github.com/linebender/resvg/tree/main/crates/usvg[usvg]+to convert a random SVG into a SVG Micro almost losslessly.++== Elements++[[svg-element]]++=== The `svg` element++The `svg` element is the root element of the document.+It's defined only once and can't be nested, unlike by the SVG spec.++*Children:*++* <<defs-element,defs>>+* <<g-element,g>>+* <<path-element,path>>+* <<image-element,image>>++*Attributes:*++* `width` = <<positive-number-type,<positive-number> >> ++ The width of the rectangular region into which the referenced document is placed.+* `height` = <<positive-number-type,<positive-number> >> ++ The height of the rectangular region into which the referenced document is placed.++[[defs-element]]++=== The `defs` element++Always present. Always the first `svg` child. Can be empty.++*Children:*++* <<linearGradient-element,linearGradient>>+* <<radialGradient-element,radialGradient>>+* <<clipPath-element,clipPath>>+* <<mask-element,mask>>+* <<pattern-element,pattern>>+* <<filter-element,filter>>+* <<g-element,g>>+* <<path-element,path>>+* <<image-element,image>>++*Attributes:*++* none++[[linearGradient-element]]++=== The `linearGradient` element++Doesn't have a `xlink:href` attribute because all attributes and `stop`+children will be resolved.++*Children:*++* At least two <<stop-element,stop>>++*Attributes:*++* `id` = <<string-type,<string> >> ++ The element ID. Always set. Guarantee to be unique.+* `x1` = <<number-type,<number> >>+* `y1` = <<number-type,<number> >>+* `x2` = <<number-type,<number> >>+* `y2` = <<number-type,<number> >>+* `gradientUnits` = `userSpaceOnUse`?+* `spreadMethod` = `reflect | repeat`?+* `gradientTransform` = <<transform-type,<transform> >>?++[[radialGradient-element]]++=== The `radialGradient` element++Doesn't have a `xlink:href` attribute because all attributes and `stop`+children will be resolved.++*Children:*++* At least two <<stop-element,stop>>++*Attributes:*++* `id` = <<string-type,<string> >> ++ The element ID. Always set. Guarantee to be unique.+* `cx` = <<number-type,<number> >>+* `cy` = <<number-type,<number> >>+* `fx` = <<number-type,<number> >> ++ Guarantee to be the circle defined by `cx`, `cy` and `r`.+* `fy` = <<number-type,<number> >> ++ Guarantee to be inside the circle defined by `cx`, `cy` and `r`.+* `r` = <<positive-number-type,<positive-number> >>+* `gradientUnits` = `userSpaceOnUse`+* `spreadMethod` = `reflect | repeat`?+* `gradientTransform` = <<transform-type,<transform> >>?++[[stop-element]]++=== The `stop` element++Gradient's `stop` children will always have unique, ordered `offset` values+in the 0..1 range.++*Children:*++* none++*Attributes:*++* `offset` = <<offset-type,<offset> >>+* `stop-color` = <<color-type,<color> >>+* `stop-opacity` = <<opacity-type,<opacity> >>? ++ Default: 1++[[pattern-element]]++=== The `pattern` element++Doesn't have a `xlink:href` attribute because all attributes and children will be resolved.++*Children:*++* `g`+* `path`+* `image`++*Attributes:*++* `id` = <<string-type,<string> >> ++ The element ID. Always set. Guarantee to be unique.+* `x` = <<number-type,<number> >>+* `y` = <<number-type,<number> >>+* `width` = <<positive-number-type,<positive-number> >>+* `height` = <<positive-number-type,<positive-number> >>+* `patternUnits` = `userSpaceOnUse`+* `patternTransform` = <<transform-type,<transform> >>?++[[clipPath-element]]++=== The `clipPath` element++*Children:*++* `path`++*Attributes:*++* `id` = <<string-type,<string> >> ++ The element ID. Always set. Guarantee to be unique.+* `clip-path` = <<func-iri-type,<FuncIRI> >>? ++ An optional reference to a supplemental `clipPath`. ++ Default: none+* `transform` = <<transform-type,<transform> >>?++[[mask-element]]++=== The `mask` element++*Children:*++* `g`+* `path`+* `image`++*Attributes:*++* `id` = <<string-type,<string> >> ++ The element ID. Always set. Guarantee to be unique.+* `mask` = <<func-iri-type,<FuncIRI> >>? ++ An optional reference to a supplemental `mask`. ++ Default: none+* `x` = <<number-type,<number> >>+* `y` = <<number-type,<number> >>+* `width` = <<positive-number-type,<positive-number> >>+* `height` = <<positive-number-type,<positive-number> >>+* `mask-type` = `alpha`? ++ Default: luminance+* `maskUnits` = `userSpaceOnUse`++[[filter-element]]++=== The `filter` element++Doesn't have a `xlink:href` attribute because all attributes and children will be resolved.++*Children:*++* <<Filter primitives>>++*Attributes:*++* `id` = <<string-type,<string> >> ++ The element ID. Always set. Guarantee to be unique.+* `x` = <<number-type,<number> >>+* `y` = <<number-type,<number> >>+* `width` = <<positive-number-type,<positive-number> >>+* `height` = <<positive-number-type,<positive-number> >>+* `filterUnits` = `userSpaceOnUse`++[[g-element]]++=== The `g` element++The group element indicates that a new canvas should be created.+All group's children elements will be rendered on it and then merged into+the parent canvas.++Since it's pretty expensive, especially memory wise, _usvg_+will remove as many groups as possible.+And all the remaining one will indicate that a new canvas must be created.++A group can have no children when it has a `filter` attribute.++A group will have at least one of the attributes present.++*Children:*++* <<g-element,g>>+* <<path-element,path>>+* <<image-element,image>>++*Attributes:*++* `id` = <<string-type,<string> >>? ++ An optional, but never empty, element ID.+* `opacity` = <<opacity-type,<opacity> >>?+* `clip-path` = <<func-iri-type,<FuncIRI> >>? ++ Cannot be set to `none`.+* `mask` = <<func-iri-type,<FuncIRI> >>? ++ Cannot be set to `none`.+* `filter` = <<func-iri-type,<FuncIRI> >>+ ++ Cannot be set to `none`.+* `transform` = <<transform-type,<transform> >>?+* `style` = <<string-type,<string> >>? ++ This is the only place where the `style` attribute is used.+ For reasons unknown, `mix-blend-mode` and `isolation` properties must not be set as attributes,+ only as part of the `style` attribute. ++ The set attribute will look like `mix-blend-mode:screen;isolation:isolate`.+ Both properties are always set. ++ The attribute is not present only in case of `mix-blend-mode:norma;isolation:auto`++[[path-element]]++=== The `path` element++*Children:*++* none++*Attributes:*++* `id` = <<string-type,<string> >>? ++ An optional, but never empty, element ID.+* `d` = <<path-data-type,<path-data> >> ++* `fill` = `none` | <<color-type,<color> >> | <<func-iri-type,<FuncIRI> >> ++ If set to `none` than all fill-* attributes will not be set too. ++ Default: black+* `fill-opacity` = <<opacity-type,<opacity> >>? ++ Default: 1+* `fill-rule` = `evenodd`? ++ Default: nonzero+* `stroke` = `none` | <<color-type,<color> >> | <<func-iri-type,<FuncIRI> >> ++ If set to `none` than all stroke-* attributes will not be set too. ++ Default: none+* `stroke-width` = <<positive-number-type,<positive-number> >>? ++ Default: 1+* `stroke-linecap` = `round | square`? ++ Default: butt+* `stroke-linejoin` = `round | bevel`? ++ Default: miter+* `stroke-miterlimit` = <<positive-number-type,<positive-number> >>? ++ Guarantee to be > 1. ++ Default: 4+* `stroke-dasharray` = `<list-of-numbers>`? ++ Guarantee to have even amount of numbers. ++ Default: none+* `stroke-dashoffset` = <<number-type,<number> >>?+* `stroke-opacity` = <<opacity-type,<opacity> >>? ++ Default: 1+* `paint-order` = `normal | stroke`? ++ Default: `normal` ++ Only `stroke` will be written.+* `clip-rule` = `evenodd`? ++ Will be set only inside the <<clipPath-element,clipPath>>, instead of `fill-rule`.+* `clip-path` = <<func-iri-type,<FuncIRI> >>? ++ Available only inside the <<clipPath-element,clipPath>>.+* `shape-rendering` = `optimizeSpeed | crispEdges`? ++ Default: geometricPrecision+* `visibility` = `hidden`? ++ Default: visible+* `transform` = <<transform-type,<transform> >>? ++ Can only be set on paths inside of `clipPath`.++[[image-element]]++=== The `image` element++*Children:*++* none++*Attributes:*++* `id` = <<string-type,<string> >>? ++ An optional, but never empty, element ID.+* `xlink:href` = <<iri-type,<IRI> >> ++ The IRI contains a base64 encoded image.+* `width` = <<positive-number-type,<positive-number> >>+* `height` = <<positive-number-type,<positive-number> >>+* `image-rendering` = `optimizeSpeed`? ++ Default: optimizeQuality+* `visibility` = `hidden`? ++ Default: visible++== Filter primitives++=== Filter primitive attributes++The attributes below are the same for all filter primitives.++* `color-interpolation-filters` = `sRGB`? ++ Default: linearRGB+* `x` = <<number-type,<number> >>?+* `y` = <<number-type,<number> >>?+* `width` = <<number-type,<number> >>?+* `height` = <<number-type,<number> >>?+* `result` = <<string-type,<string> >>++The `x`, `y`, `width` and `height` attributes can be omitted.+SVG has a pretty complex+https://www.w3.org/TR/SVG11/filters.html#FilterPrimitiveSubRegion[rules of resolving them]+and I don't fully understand them yet.+Neither do others, because they are pretty poorly implemented.++=== Filter primitive `feBlend`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `in2` = <<filter-input-type,<filter-input> >>+* `mode` = `normal | multiply | screen | overlay | darken | lighten | color-dodge |color-burn |+hard-light | soft-light | difference | exclusion | hue | saturation | color | luminosity`+* <<Filter primitive attributes>>++=== Filter primitive `feColorMatrix`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `type` = `matrix | saturate | hueRotate | luminanceToAlpha`+* `values` = `<list-of-numbers>`? ++** For `type=matrix`, contains 20 numbers.+** For `type=saturate`, contains a single number in a 0..1 range.+** For `type=hueRotate`, contains a single number.+** Not present for `type=luminanceToAlpha`.+* <<Filter primitive attributes>>++=== Filter primitive `feComponentTransfer`++*Children:*++* `feFuncR`+* `feFuncG`+* `feFuncB`+* `feFuncA`++The all four will always be present.++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* <<Filter primitive attributes>>++*`feFunc(R|G|B|A)` attributes:*++* `type` = `identity | table | discrete | linear | gamma`+* `tableValues` = `<list-of-numbers>`? ++ Present only when `type=table | discrete`. Can be empty.+* `slope` = <<number-type,<number> >>? ++ Present only when `type=linear`.+* `intercept` = <<number-type,<number> >>? ++ Present only when `type=linear`.+* `amplitude` = <<number-type,<number> >>? ++ Present only when `type=gamma`.+* `exponent` = <<number-type,<number> >>? ++ Present only when `type=gamma`.+* `offset` = <<number-type,<number> >>? ++ Present only when `type=gamma`.++=== Filter primitive `feComposite`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `in2` = <<filter-input-type,<filter-input> >>+* `operator` = `over | in | out | atop | xor | arithmetic`+* `k1` = <<number-type,<number> >>? ++ Present only when `operator=arithmetic`.+* `k2` = <<number-type,<number> >>? ++ Present only when `operator=arithmetic`.+* `k3` = <<number-type,<number> >>? ++ Present only when `operator=arithmetic`.+* `k4` = <<number-type,<number> >>? ++ Present only when `operator=arithmetic`.+* <<Filter primitive attributes>>++=== Filter primitive `feConvolveMatrix`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `order` = <<positive-integer-type,<positive-integer> >> " " <<positive-integer-type,<positive-integer> >> ++ Both numbers are never 0.+* `kernelMatrix` = `<list-of-numbers>`+* `divisor` = <<number-type,<number> >> ++ Never 0.+* `bias` = <<number-type,<number> >>+* `targetX` = <<positive-integer-type,<positive-integer> >> ++ Always smaller than the number of columns in the matrix.+* `targetY` = <<positive-integer-type,<positive-integer> >> ++ Always smaller than the number of rows in the matrix.+* `edgeMode` = `none | duplicate | wrap`+* `preserveAlpha` = `true | false`+* <<Filter primitive attributes>>++=== Filter primitive `feDiffuseLighting`++*Children:*++Only one of:++* `feDistantLight`+* `fePointLight`+* `feSpotLight`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `surfaceScale` = <<number-type,<number> >>+* `diffuseConstant` = <<number-type,<number> >>+* `lighting-color` = <<color-type,<color> >>+* <<Filter primitive attributes>>++`feDistantLight` *attributes:*++* `azimuth` = <<number-type,<number> >>+* `elevation` = <<number-type,<number> >>++`fePointLight` *attributes:*++* `x` = <<number-type,<number> >>+* `y` = <<number-type,<number> >>+* `z` = <<number-type,<number> >>++`feSpotLight` *attributes:*++* `x` = <<number-type,<number> >>+* `y` = <<number-type,<number> >>+* `z` = <<number-type,<number> >>+* `pointsAtX` = <<number-type,<number> >>+* `pointsAtY` = <<number-type,<number> >>+* `pointsAtZ` = <<number-type,<number> >>+* `specularExponent` = <<positive-number-type,<positive-number> >>+* `limitingConeAngle` = <<number-type,<number> >>?++=== Filter primitive `feDisplacementMap`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `in2` = <<filter-input-type,<filter-input> >>+* `scale` = <<number-type,<number> >>+* `xChannelSelector` = `R | G | B | A`+* `yChannelSelector` = `R | G | B | A`+* <<Filter primitive attributes>>++=== Filter primitive `feDropShadow`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `stdDeviation` = <<positive-number-type,<positive-number> >> " " <<positive-number-type,<positive-number> >>+* `dx` = <<number-type,<number> >>+* `dy` = <<number-type,<number> >>+* `flood-color` = <<color-type,<color> >>+* `flood-opacity` = <<opacity-type,<opacity> >>+* <<Filter primitive attributes>>++=== Filter primitive `feFlood`++*Attributes:*++* `flood-color` = <<color-type,<color> >>+* `flood-opacity` = <<opacity-type,<opacity> >>+* <<Filter primitive attributes>>++=== Filter primitive `feGaussianBlur`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `stdDeviation` = <<positive-number-type,<positive-number> >> " " <<positive-number-type,<positive-number> >>+* <<Filter primitive attributes>>++=== Filter primitive `feImage`++*Attributes:*++* `xlink:href` = <<iri-type,<IRI> >> ++ The IRI contains a link to an element (like `use`).+ base64 encoded is not allowed and will be represented as a link to an `image`.+* <<Filter primitive attributes>>++=== Filter primitive `feMerge`++*Children:*++* `feMergeNode`++*Attributes:*++* <<Filter primitive attributes>>++*`feMergeNode` attributes:*++* `in` = <<filter-input-type,<filter-input> >>++=== Filter primitive `feMorphology`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `operator` = `erode | dilate`+* `radius` = <<positive-number-type,<positive-number> >> " " <<positive-number-type,<positive-number> >>+* <<Filter primitive attributes>>++=== Filter primitive `feOffset`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `dx` = <<number-type,<number> >>+* `dy` = <<number-type,<number> >>+* <<Filter primitive attributes>>++=== Filter primitive `feSpecularLighting`++*Children:*++Only one of:++* `feDistantLight`+* `fePointLight`+* `feSpotLight`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* `surfaceScale` = <<number-type,<number> >>+* `specularConstant` = <<number-type,<number> >>+* `specularExponent` = <<number-type,<number> >> ++ Number in a 1..128 range.+* `lighting-color` = <<color-type,<color> >>+* <<Filter primitive attributes>>++`feDistantLight` *attributes:*++* `azimuth` = <<number-type,<number> >>+* `elevation` = <<number-type,<number> >>++`fePointLight` *attributes:*++* `x` = <<number-type,<number> >>+* `y` = <<number-type,<number> >>+* `z` = <<number-type,<number> >>++`feSpotLight` *attributes:*++* `x` = <<number-type,<number> >>+* `y` = <<number-type,<number> >>+* `z` = <<number-type,<number> >>+* `pointsAtX` = <<number-type,<number> >>+* `pointsAtY` = <<number-type,<number> >>+* `pointsAtZ` = <<number-type,<number> >>+* `specularExponent` = <<positive-number-type,<positive-number> >>+* `limitingConeAngle` = <<number-type,<number> >>?++=== Filter primitive `feTile`++*Attributes:*++* `in` = <<filter-input-type,<filter-input> >>+* <<Filter primitive attributes>>++=== Filter primitive `feTurbulence`++*Attributes:*++* `baseFrequency` = <<positive-number-type,<positive-number> >> " " <<positive-number-type,<positive-number> >>+* `numOctaves` = <<positive-integer-type,<positive-integer> >>+* `seed` = <<integer-type,<integer> >>+* `stitchTiles` = `stitch | noStitch`+* `type` = `fractalNoise | turbulence`+* <<Filter primitive attributes>>++== Data types++If an attribute has the `?` symbol after the type that's mean that+that this attribute is optional.++[[string-type]]++*<string>* - A Unicode (UTF-8) string.+++[[number-type]]++*<number>* - A real number. ++`number ::= [-]? [0-9]+ "." [0-9]+`+++[[positive-number-type]]++*<positive-number>* - A positive real <<number-type,number>>. ++`positive-number ::= [0-9]+ "." [0-9]+`+++[[integer-type]]++*<integer>* - An integer. ++`integer ::= [-]? [0-9]+`+++[[positive-integer-type]]++*<positive-integer>* - A positive integer. ++`positive-integer ::= [0-9]+`+++[[opacity-type]]++*<opacity>* - A real <<number-type,number>> in a 0..1 range. ++`opacity ::= positive-number`+++[[offset-type]]++*<offset>* - A real <<number-type,number>> in a 0..1 range. ++`offset ::= positive-number`+++[[color-type]]++*<color>* - A hex-encoded RGB color.+```+color ::= "#" hexdigit hexdigit hexdigit hexdigit hexdigit hexdigit+hexdigit ::= [0-9a-f]+```+++[[iri-type]]++*<IRI>* - An Internationalized Resource Identifier.+Always a valid, local reference. ++`IRI ::= string`+++[[func-iri-type]]++*<FuncIRI>* - Functional notation for an <<iri-type,IRI>>.+Always a valid, local reference. ++`FuncIRI ::= url( <IRI> )`+++[[filter-input-type]]++*<filter-input>* - A filter source. A reference to a _result_ guarantee to be valid.++```+filter-input ::= SourceGraphic | SourceAlpha | <string>+```++We do not support `FillPaint`, `StrokePaint`, `BackgroundImage` and `BackgroundAlpha`.+++[[transform-type]]++*<transform>* - A transformation matrix.+Always a `matrix` and not `translate`, `scale`, etc.+Numbers are space-separated. ++`transform ::= matrix( <number> " " <number> " " <number> " " <number> " " <number> " " <number> )`+++[[path-data-type]]++*<path-data>* - A path data.++* Contains only absolute MoveTo, LineTo, CurveTo and ClosePath segments.+* All segments are explicit.+* The first segment is guarantee to be MoveTo.+* Segments, commands and coordinates are separated only by space.+* Path and all subpaths are guarantee to have at least two segments.++Grammar:++```+svg-path:+ moveto-drawto-command-groups+moveto-drawto-command-groups:+ moveto-drawto-command-group+ | moveto-drawto-command-group " " moveto-drawto-command-groups+moveto-drawto-command-group:+ moveto " " drawto-commands+drawto-commands:+ drawto-command+ | drawto-command " " drawto-commands+drawto-command:+ closepath+ | lineto+ | curveto+moveto:+ "M " coordinate-pair+lineto:+ "L " coordinate-pair+curveto:+ "C " coordinate-pair " " coordinate-pair " " coordinate-pair+closepath:+ "Z"+coordinate-pair:+ coordinate " " coordinate+coordinate:+ sign? digit-sequence "." digit-sequence+sign:+ "-"+digit-sequence:+ digit+ | digit digit-sequence+digit:+ "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"+```++Basically, a path looks like this: `M 10.5 20 L 30 40`.+Commands and numbers are separated by a space.+Numbers with an exponent are not allowed.+Trimmed numbers like `-.5` are not allowed.diff --git a/vendor/usvg/src/lib.rs b/vendor/usvg/src/lib.rsnew file mode 100644index 00000000..1987daae--- /dev/null+++ b/vendor/usvg/src/lib.rs@@ -0,0 +1,74 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++/*!+`usvg` (micro SVG) is an [SVG] parser that tries to solve most of SVG complexity.++SVG is notoriously hard to parse. `usvg` presents a layer between an XML library and+a potential SVG rendering library. It will parse an input SVG into a strongly-typed tree structure+were all the elements, attributes, references and other SVG features are already resolved+and presented in the simplest way possible.+So a caller doesn't have to worry about most of the issues related to SVG parsing+and can focus just on the rendering part.++## Features++- All supported attributes are resolved.+ No need to worry about inheritable, implicit and default attributes+- CSS will be applied+- Only simple paths+ - Basic shapes (like `rect` and `circle`) will be converted into paths+ - Paths contain only absolute *MoveTo*, *LineTo*, *QuadTo*, *CurveTo* and *ClosePath* segments.+ ArcTo, implicit and relative segments will be converted+- `use` will be resolved and replaced with the reference content+- Nested `svg` will be resolved+- Invalid, malformed elements will be removed+- Relative length units (mm, em, etc.) will be converted into pixels/points+- External images will be loaded+- Internal, base64 images will be decoded+- All references (like `#elem` and `url(#elem)`) will be resolved+- `switch` will be resolved+- Text elements, which are probably the hardest part of SVG, will be completely resolved.+ This includes all the attributes resolving, whitespaces preprocessing (`xml:space`),+ text chunks and spans resolving+- Markers will be converted into regular elements. No need to place them manually+- All filters are supported. Including filter functions, like `filter="contrast(50%)"`+- Recursive elements will be detected and removed+- `objectBoundingBox` will be replaced with `userSpaceOnUse`++## Limitations++- Unsupported SVG features will be ignored+- CSS support is minimal+- Only [static](http://www.w3.org/TR/SVG11/feature#SVG-static) SVG features,+ e.g. no `a`, `view`, `cursor`, `script`, no events and no animations++[SVG]: https://en.wikipedia.org/wiki/Scalable_Vector_Graphics+*/++#![forbid(unsafe_code)]+#![warn(missing_docs)]+#![warn(missing_debug_implementations)]+#![warn(missing_copy_implementations)]++mod parser;+#[cfg(feature = "text")]+mod text;+mod tree;+#[cfg(feature = "writer")]+mod writer;++pub use parser::*;+#[cfg(feature = "text")]+pub use text::*;+pub use tree::*;++pub use roxmltree;++#[cfg(feature = "text")]+pub use fontdb;++#[cfg(feature = "writer")]+pub use writer::WriteOptions;+#[cfg(feature = "writer")]+pub use xmlwriter::Indent;diff --git a/vendor/usvg/src/main.rs b/vendor/usvg/src/main.rsnew file mode 100644index 00000000..8dcaca08--- /dev/null+++ b/vendor/usvg/src/main.rs@@ -0,0 +1,514 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::fs::File;+use std::io::{self, Read, Write};+use std::path::PathBuf;+use std::process;+use std::sync::Arc;++use pico_args::Arguments;++const HELP: &str = "\+usvg (micro SVG) is an SVG simplification tool.++USAGE:+ usvg [OPTIONS] <in-svg> <out-svg> # from file to file+ usvg [OPTIONS] <in-svg> -c # from file to stdout+ usvg [OPTIONS] - <out-svg> # from stdin to file+ usvg [OPTIONS] - -c # from stdin to stdout++OPTIONS:+ -h, --help Prints help information+ -V, --version Prints version information+ -c Prints the output SVG to the stdout++ --dpi DPI Sets the resolution+ [default: 96] [possible values: 10..4000 (inclusive)]+ --stylesheet PATH Inject a stylesheet that should be used when resolving+ CSS attributes.+ --languages LANG Sets a comma-separated list of languages that+ will be used during the 'systemLanguage'+ attribute resolving+ Examples: 'en-US', 'en-US, ru-RU', 'en, ru'+ [default: en]+ --shape-rendering HINT Selects the default shape rendering method+ [default: geometricPrecision]+ [possible values: optimizeSpeed, crispEdges,+ geometricPrecision]+ --text-rendering HINT Selects the default text rendering method+ [default: optimizeLegibility]+ [possible values: optimizeSpeed, optimizeLegibility,+ geometricPrecision]+ --image-rendering HINT Selects the default image rendering method+ [default: optimizeQuality]+ [possible values: optimizeQuality, optimizeSpeed, smooth, high-quality, crisp-edges, pixelated]+ --resources-dir DIR Sets a directory that will be used during+ relative paths resolving.+ Expected to be the same as the directory that+ contains the SVG file, but can be set to any.+ [default: input file directory+ or none when reading from stdin]++ --font-family FAMILY Sets the default font family that will be+ used when no 'font-family' is present+ [default: Times New Roman]+ --font-size SIZE Sets the default font size that will be+ used when no 'font-size' is present+ [default: 12] [possible values: 1..192 (inclusive)]+ --serif-family FAMILY Sets the 'serif' font family.+ Will be used when no 'font-family' is present+ [default: Times New Roman]+ --sans-serif-family FAMILY Sets the 'sans-serif' font family+ [default: Arial]+ --cursive-family FAMILY Sets the 'cursive' font family+ [default: Comic Sans MS]+ --fantasy-family FAMILY Sets the 'fantasy' font family+ [default: Impact]+ --monospace-family FAMILY Sets the 'monospace' font family+ [default: Courier New]+ --use-font-file PATH Load a specified font file into the fonts database.+ Will be used during text to path conversion.+ This option can be set multiple times+ --use-fonts-dir PATH Loads all fonts from the specified directory+ into the fonts database.+ Will be used during text to path conversion.+ This option can be set multiple times+ --skip-system-fonts Disables system fonts loading.+ You should add some fonts manually using+ --use-font-file and/or --use-fonts-dir+ Otherwise, text elements will not be processes+ --list-fonts Lists successfully loaded font faces.+ Useful for debugging+ --default-width LENGTH Sets the default width of the SVG viewport. Like+ the '--default-height' option, this option+ controls what size relative units in the document+ will use as a base if there is no viewBox and+ document width or height are relative.+ [values: 1..4294967295 (inclusive)] [default: 100]+ --default-height LENGTH Sets the default height of the SVG viewport.+ Refer to the explanation of the '--default-width'+ option. [values: 1..4294967295 (inclusive)] [default: 100]++ --preserve-text Do not convert text into paths.+ --id-prefix Adds a prefix to each ID attribute+ --indent INDENT Sets the XML nodes indent+ [values: none, 0, 1, 2, 3, 4, tabs] [default: 4]+ --attrs-indent INDENT Sets the XML attributes indent+ [values: none, 0, 1, 2, 3, 4, tabs] [default: none]+ --coordinates-precision NUM Set the coordinates numeric precision.+ Smaller precision can lead to a malformed output in some cases+ [values: 2..8 (inclusive)] [default: 8]+ --transforms-precision NUM Set the transform values numeric precision.+ Smaller precision can lead to a malformed output in some cases+ [values: 2..8 (inclusive)] [default: 8]+ --quiet Disables warnings++ARGS:+ <in-svg> Input file+ <out-svg> Output file+";++#[derive(Debug)]+struct Args {+ dpi: u32,+ languages: Vec<String>,+ shape_rendering: usvg::ShapeRendering,+ text_rendering: usvg::TextRendering,+ image_rendering: usvg::ImageRendering,+ resources_dir: Option<PathBuf>,++ font_family: Option<String>,+ font_size: u32,+ serif_family: Option<String>,+ sans_serif_family: Option<String>,+ cursive_family: Option<String>,+ fantasy_family: Option<String>,+ monospace_family: Option<String>,+ font_files: Vec<PathBuf>,+ font_dirs: Vec<PathBuf>,+ skip_system_fonts: bool,+ preserve_text: bool,+ list_fonts: bool,+ default_width: u32,+ default_height: u32,++ id_prefix: Option<String>,+ indent: xmlwriter::Indent,+ attrs_indent: xmlwriter::Indent,+ coordinates_precision: Option<u8>,+ transforms_precision: Option<u8>,+ style_sheet: Option<PathBuf>,++ quiet: bool,++ input: String,+ output: String,+}++fn collect_args() -> Result<Args, pico_args::Error> {+ let mut input = Arguments::from_env();++ if input.contains(["-h", "--help"]) {+ print!("{}", HELP);+ process::exit(0);+ }++ if input.contains(["-V", "--version"]) {+ println!("{}", env!("CARGO_PKG_VERSION"));+ process::exit(0);+ }++ Ok(Args {+ dpi: input.opt_value_from_fn("--dpi", parse_dpi)?.unwrap_or(96),+ languages: input+ .opt_value_from_fn("--languages", parse_languages)?+ .unwrap_or(vec!["en".to_string()]), // TODO: use system language+ shape_rendering: input+ .opt_value_from_str("--shape-rendering")?+ .unwrap_or_default(),+ text_rendering: input+ .opt_value_from_str("--text-rendering")?+ .unwrap_or_default(),+ image_rendering: input+ .opt_value_from_str("--image-rendering")?+ .unwrap_or_default(),+ resources_dir: input+ .opt_value_from_str("--resources-dir")+ .unwrap_or_default(),++ font_family: input.opt_value_from_str("--font-family")?,+ font_size: input+ .opt_value_from_fn("--font-size", parse_font_size)?+ .unwrap_or(12),+ serif_family: input.opt_value_from_str("--serif-family")?,+ sans_serif_family: input.opt_value_from_str("--sans-serif-family")?,+ cursive_family: input.opt_value_from_str("--cursive-family")?,+ fantasy_family: input.opt_value_from_str("--fantasy-family")?,+ monospace_family: input.opt_value_from_str("--monospace-family")?,+ font_files: input.values_from_str("--use-font-file")?,+ font_dirs: input.values_from_str("--use-fonts-dir")?,+ skip_system_fonts: input.contains("--skip-system-fonts"),+ preserve_text: input.contains("--preserve-text"),+ list_fonts: input.contains("--list-fonts"),+ default_width: input+ .opt_value_from_fn("--default-width", parse_length)?+ .unwrap_or(100),+ default_height: input+ .opt_value_from_fn("--default-height", parse_length)?+ .unwrap_or(100),++ id_prefix: input.opt_value_from_str("--id-prefix")?,+ indent: input+ .opt_value_from_fn("--indent", parse_indent)?+ .unwrap_or(xmlwriter::Indent::Spaces(4)),+ attrs_indent: input+ .opt_value_from_fn("--attrs-indent", parse_indent)?+ .unwrap_or(xmlwriter::Indent::None),+ coordinates_precision: input+ .opt_value_from_fn("--coordinates-precision", parse_precision)?,+ transforms_precision: input.opt_value_from_fn("--transforms-precision", parse_precision)?,+ style_sheet: input.opt_value_from_str("--stylesheet").unwrap_or_default(),++ quiet: input.contains("--quiet"),++ input: input.free_from_str()?,+ output: input.free_from_str()?,+ })+}++fn parse_dpi(s: &str) -> Result<u32, String> {+ let n: u32 = s.parse().map_err(|_| "invalid number")?;++ if n >= 10 && n <= 4000 {+ Ok(n)+ } else {+ Err("DPI out of bounds".to_string())+ }+}++fn parse_font_size(s: &str) -> Result<u32, String> {+ let n: u32 = s.parse().map_err(|_| "invalid number")?;++ if n > 0 && n <= 192 {+ Ok(n)+ } else {+ Err("font size out of bounds".to_string())+ }+}++fn parse_languages(s: &str) -> Result<Vec<String>, String> {+ let mut langs = Vec::new();+ for lang in s.split(',') {+ langs.push(lang.trim().to_string());+ }++ if langs.is_empty() {+ return Err("languages list cannot be empty".to_string());+ }++ Ok(langs)+}++fn parse_indent(s: &str) -> Result<xmlwriter::Indent, String> {+ let indent = match s {+ "none" => xmlwriter::Indent::None,+ "0" => xmlwriter::Indent::Spaces(0),+ "1" => xmlwriter::Indent::Spaces(1),+ "2" => xmlwriter::Indent::Spaces(2),+ "3" => xmlwriter::Indent::Spaces(3),+ "4" => xmlwriter::Indent::Spaces(4),+ "tabs" => xmlwriter::Indent::Tabs,+ _ => return Err("invalid INDENT value".to_string()),+ };++ Ok(indent)+}++fn parse_length(s: &str) -> Result<u32, String> {+ let n: u32 = s.parse().map_err(|_| "invalid length")?;++ if n > 0 {+ Ok(n)+ } else {+ Err("LENGTH cannot be zero".to_string())+ }+}++fn parse_precision(s: &str) -> Result<u8, String> {+ let n: u8 = s.parse().map_err(|_| "invalid precision NUM value")?;++ if (2..=8).contains(&n) {+ Ok(n)+ } else {+ Err("precision NUM cannot be smaller than 2 or larger than 8".to_string())+ }+}++#[derive(Clone, PartialEq, Debug)]+enum InputFrom<'a> {+ Stdin,+ File(&'a str),+}++#[derive(Clone, PartialEq, Debug)]+enum OutputTo<'a> {+ Stdout,+ File(&'a str),+}++fn main() {+ let args = match collect_args() {+ Ok(v) => v,+ Err(e) => {+ eprintln!("Error: {}.", e);+ process::exit(1);+ }+ };++ if !args.quiet {+ if let Ok(()) = log::set_logger(&LOGGER) {+ log::set_max_level(log::LevelFilter::Warn);+ }+ }++ if let Err(e) = process(args) {+ eprintln!("Error: {}.", e);+ process::exit(1);+ }+}++fn process(args: Args) -> Result<(), String> {+ let (in_svg, out_svg) = {+ let in_svg = args.input.as_str();+ let out_svg = args.output.as_str();++ let svg_from = if in_svg == "-" {+ InputFrom::Stdin+ } else if in_svg == "-c" {+ return Err("-c should be set after input".to_string());+ } else {+ InputFrom::File(in_svg)+ };++ let svg_to = if out_svg == "-c" {+ OutputTo::Stdout+ } else {+ OutputTo::File(out_svg)+ };++ (svg_from, svg_to)+ };++ let mut fontdb = usvg::fontdb::Database::new();+ if !args.skip_system_fonts {+ // TODO: only when needed+ fontdb.load_system_fonts();+ }++ for path in &args.font_files {+ if let Err(e) = fontdb.load_font_file(path) {+ log::warn!("Failed to load '{}' cause {}.", path.display(), e);+ }+ }++ for path in &args.font_dirs {+ fontdb.load_fonts_dir(path);+ }++ let take_or = |mut family: Option<String>, fallback: &str| {+ family.take().unwrap_or_else(|| fallback.to_string())+ };++ fontdb.set_serif_family(take_or(args.serif_family, "Times New Roman"));+ fontdb.set_sans_serif_family(take_or(args.sans_serif_family, "Arial"));+ fontdb.set_cursive_family(take_or(args.cursive_family, "Comic Sans MS"));+ fontdb.set_fantasy_family(take_or(args.fantasy_family, "Impact"));+ fontdb.set_monospace_family(take_or(args.monospace_family, "Courier New"));++ if args.list_fonts {+ for face in fontdb.faces() {+ if let usvg::fontdb::Source::File(path) = &face.source {+ let families: Vec<_> = face+ .families+ .iter()+ .map(|f| format!("{} ({}, {})", f.0, f.1.primary_language(), f.1.region()))+ .collect();++ println!(+ "{}: '{}', {}, {:?}, {:?}, {:?}",+ path.display(),+ families.join("', '"),+ face.index,+ face.style,+ face.weight.0,+ face.stretch+ );+ }+ }+ }++ let resources_dir = match args.resources_dir {+ Some(v) => Some(v),+ None => {+ match in_svg {+ InputFrom::Stdin => None,+ InputFrom::File(ref f) => {+ // Get input file absolute directory.+ std::fs::canonicalize(f)+ .ok()+ .and_then(|p| p.parent().map(|p| p.to_path_buf()))+ }+ }+ }+ };++ let style_sheet = match args.style_sheet.as_ref() {+ Some(p) => Some(+ std::fs::read(&p)+ .ok()+ .and_then(|s| std::str::from_utf8(&s).ok().map(|s| s.to_string()))+ .ok_or("failed to read stylesheet".to_string())?,+ ),+ None => None,+ };++ let re_opt = usvg::Options {+ resources_dir,+ dpi: args.dpi as f32,+ font_family: args+ .font_family+ .as_deref()+ .unwrap_or("Times New Roman")+ .to_string(),+ font_size: args.font_size as f32,+ languages: args.languages,+ shape_rendering: args.shape_rendering,+ text_rendering: args.text_rendering,+ image_rendering: args.image_rendering,+ default_size: usvg::Size::from_wh(args.default_width as f32, args.default_height as f32)+ .unwrap(),+ image_href_resolver: usvg::ImageHrefResolver::default(),+ font_resolver: usvg::FontResolver::default(),+ fontdb: Arc::new(fontdb),+ style_sheet,+ };++ let input_svg = match in_svg {+ InputFrom::Stdin => load_stdin(),+ InputFrom::File(ref path) => std::fs::read(path).map_err(|e| e.to_string()),+ }?;++ let tree = usvg::Tree::from_data(&input_svg, &re_opt).map_err(|e| format!("{}", e))?;++ let xml_opt = usvg::WriteOptions {+ id_prefix: args.id_prefix,+ preserve_text: args.preserve_text,+ coordinates_precision: args.coordinates_precision.unwrap_or(8),+ transforms_precision: args.transforms_precision.unwrap_or(8),+ use_single_quote: false,+ indent: args.indent,+ attributes_indent: args.attrs_indent,+ };++ let s = tree.to_string(&xml_opt);+ match out_svg {+ OutputTo::Stdout => {+ io::stdout()+ .write_all(s.as_bytes())+ .map_err(|_| "failed to write to the stdout".to_string())?;+ }+ OutputTo::File(path) => {+ let mut f =+ File::create(path).map_err(|_| "failed to create the output file".to_string())?;+ f.write_all(s.as_bytes())+ .map_err(|_| "failed to write to the output file".to_string())?;+ }+ }++ Ok(())+}++fn load_stdin() -> Result<Vec<u8>, String> {+ let mut buf = Vec::new();+ let stdin = io::stdin();+ let mut handle = stdin.lock();++ handle+ .read_to_end(&mut buf)+ .map_err(|_| "failed to read from stdin".to_string())?;++ Ok(buf)+}++/// A simple stderr logger.+static LOGGER: SimpleLogger = SimpleLogger;+struct SimpleLogger;+impl log::Log for SimpleLogger {+ fn enabled(&self, metadata: &log::Metadata) -> bool {+ metadata.level() <= log::LevelFilter::Warn+ }++ fn log(&self, record: &log::Record) {+ if self.enabled(record.metadata()) {+ let target = if record.target().len() > 0 {+ record.target()+ } else {+ record.module_path().unwrap_or_default()+ };++ let line = record.line().unwrap_or(0);+ let args = record.args();++ match record.level() {+ log::Level::Error => eprintln!("Error (in {}:{}): {}", target, line, args),+ log::Level::Warn => eprintln!("Warning (in {}:{}): {}", target, line, args),+ log::Level::Info => eprintln!("Info (in {}:{}): {}", target, line, args),+ log::Level::Debug => eprintln!("Debug (in {}:{}): {}", target, line, args),+ log::Level::Trace => eprintln!("Trace (in {}:{}): {}", target, line, args),+ }+ }+ }++ fn flush(&self) {}+}diff --git a/vendor/usvg/src/parser/clippath.rs b/vendor/usvg/src/parser/clippath.rsnew file mode 100644index 00000000..03f6b91f--- /dev/null+++ b/vendor/usvg/src/parser/clippath.rs@@ -0,0 +1,125 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::str::FromStr;+use std::sync::Arc;++use super::converter;+use super::svgtree::{AId, EId, SvgNode};+use crate::{ClipPath, Group, NonEmptyString, NonZeroRect, Transform, Units};++pub(crate) fn convert(+ node: SvgNode,+ state: &converter::State,+ object_bbox: Option<NonZeroRect>,+ cache: &mut converter::Cache,+) -> Option<Arc<ClipPath>> {+ // A `clip-path` attribute must reference a `clipPath` element.+ if node.tag_name() != Some(EId::ClipPath) {+ return None;+ }++ // The whole clip path should be ignored when a transform is invalid.+ let mut transform = resolve_clip_path_transform(node, state)?;++ let units = node+ .attribute(AId::ClipPathUnits)+ .unwrap_or(Units::UserSpaceOnUse);++ // Check if this element was already converted.+ //+ // Only `userSpaceOnUse` clipPaths can be shared,+ // because `objectBoundingBox` one will be converted into user one+ // and will become node-specific.+ let cacheable = units == Units::UserSpaceOnUse;+ if cacheable {+ if let Some(clip) = cache.clip_paths.get(node.element_id()) {+ return Some(clip.clone());+ }+ }++ if units == Units::ObjectBoundingBox {+ let object_bbox = match object_bbox {+ Some(v) => v,+ None => {+ log::warn!("Clipping of zero-sized shapes is not allowed.");+ return None;+ }+ };++ let ts = Transform::from_bbox(object_bbox);+ transform = transform.pre_concat(ts);+ }++ // Resolve linked clip path.+ let mut clip_path = None;+ if let Some(link) = node.attribute::<SvgNode>(AId::ClipPath) {+ clip_path = convert(link, state, object_bbox, cache);++ // Linked `clipPath` must be valid.+ if clip_path.is_none() {+ return None;+ }+ }++ let mut id = NonEmptyString::new(node.element_id().to_string())?;+ // Generate ID only when we're parsing `objectBoundingBox` clip for the second time.+ if !cacheable && cache.clip_paths.contains_key(id.get()) {+ id = cache.gen_clip_path_id();+ }+ let id_copy = id.get().to_string();++ let mut clip = ClipPath {+ id,+ transform,+ clip_path,+ root: Group::empty(),+ };++ let mut clip_state = state.clone();+ clip_state.parent_clip_path = Some(node);+ converter::convert_clip_path_elements(node, &clip_state, cache, &mut clip.root);++ if clip.root.has_children() {+ clip.root.calculate_bounding_boxes();+ let clip = Arc::new(clip);+ cache.clip_paths.insert(id_copy, clip.clone());+ Some(clip)+ } else {+ // A clip path without children is invalid.+ None+ }+}++fn resolve_clip_path_transform(node: SvgNode, state: &converter::State) -> Option<Transform> {+ // Do not use Node::attribute::<Transform>, because it will always+ // return a valid transform.++ let value: &str = match node.attribute(AId::Transform) {+ Some(v) => v,+ None => return Some(Transform::default()),+ };++ let ts = match svgtypes::Transform::from_str(value) {+ Ok(v) => v,+ Err(_) => {+ log::warn!("Failed to parse {} value: '{}'.", AId::Transform, value);+ return None;+ }+ };++ let ts = Transform::from_row(+ ts.a as f32,+ ts.b as f32,+ ts.c as f32,+ ts.d as f32,+ ts.e as f32,+ ts.f as f32,+ );++ if ts.is_valid() {+ Some(node.resolve_transform(AId::Transform, state))+ } else {+ None+ }+}diff --git a/vendor/usvg/src/parser/converter.rs b/vendor/usvg/src/parser/converter.rsnew file mode 100644index 00000000..2908e28d--- /dev/null+++ b/vendor/usvg/src/parser/converter.rs@@ -0,0 +1,1127 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::collections::{HashMap, HashSet};+use std::hash::{Hash, Hasher};+use std::str::FromStr;+use std::sync::Arc;++#[cfg(feature = "text")]+use crate::{FontVariation, GlyphId};+#[cfg(feature = "text")]+use fontdb::Database;+#[cfg(feature = "text")]+use fontdb::ID;+use svgtypes::{Length, LengthUnit as Unit, PaintOrderKind, TransformOrigin};+use tiny_skia_path::PathBuilder;++use super::svgtree::{self, AId, EId, FromValue, SvgNode};+use super::units::{self, convert_length};+use super::{Error, Options, marker};+#[cfg(feature = "text")]+use crate::flatten::BitmapImage;+use crate::parser::paint_server::process_paint;+#[cfg(feature = "text")]+use crate::text::flatten::DatabaseExt;+use crate::*;++#[derive(Clone)]+pub struct State<'a> {+ pub(crate) parent_clip_path: Option<SvgNode<'a, 'a>>,+ pub(crate) parent_markers: Vec<SvgNode<'a, 'a>>,+ /// Stores the resolved fill and stroke of a use node+ /// or a path element (for markers)+ pub(crate) context_element: Option<(Option<Fill>, Option<Stroke>)>,+ pub(crate) fe_image_link: bool,+ /// A viewBox of the parent SVG element.+ pub(crate) view_box: NonZeroRect,+ /// A size of the parent `use` element.+ /// Used only during nested `svg` size resolving.+ /// Width and height can be set independently.+ pub(crate) use_size: (Option<f32>, Option<f32>),+ pub(crate) opt: &'a Options<'a>,+}++#[derive(Clone)]+pub struct Cache {+ /// This fontdb is initialized from [`Options::fontdb`] and then populated+ /// over the course of conversion.+ #[cfg(feature = "text")]+ pub fontdb: Arc<Database>,++ #[cfg(feature = "text")]+ cache_outline: HashMap<(ID, GlyphId, Vec<FontVariation>), Option<tiny_skia_path::Path>>,+ #[cfg(feature = "text")]+ cache_colr: HashMap<(ID, GlyphId, Vec<FontVariation>), Option<Tree>>,+ #[cfg(feature = "text")]+ cache_svg: HashMap<(ID, GlyphId), Option<Node>>,+ #[cfg(feature = "text")]+ cache_raster: HashMap<(ID, GlyphId), Option<BitmapImage>>,+ #[cfg(feature = "text")]+ cache_has_opsz: HashMap<ID, bool>,++ pub clip_paths: HashMap<String, Arc<ClipPath>>,+ pub masks: HashMap<String, Arc<Mask>>,+ pub filters: HashMap<String, Arc<filter::Filter>>,+ pub paint: HashMap<String, Paint>,++ // used for ID generation+ all_ids: HashSet<u64>,+ linear_gradient_index: usize,+ radial_gradient_index: usize,+ pattern_index: usize,+ clip_path_index: usize,+ mask_index: usize,+ filter_index: usize,+ image_index: usize,+}++macro_rules! font_lookup {+ ($method_name:ident, $cache_map:ident, $font_variant:ident, $return_type:ty) => {+ #[cfg(feature = "text")]+ pub(crate) fn $method_name(&mut self, font: ID, glyph: GlyphId) -> Option<$return_type> {+ let key = (font, glyph);+ match self.$cache_map.get(&key) {+ Some(cache_hit) => cache_hit.clone(),+ None => {+ let lookup = self.fontdb.$font_variant(font, glyph);+ self.$cache_map.insert(key, lookup.clone());+ lookup+ }+ }+ }+ };+}++impl Cache {+ pub(crate) fn new(#[cfg(feature = "text")] fontdb: Arc<Database>) -> Self {+ Self {+ #[cfg(feature = "text")]+ fontdb,++ #[cfg(feature = "text")]+ cache_outline: HashMap::new(),+ #[cfg(feature = "text")]+ cache_colr: HashMap::new(),+ #[cfg(feature = "text")]+ cache_svg: HashMap::new(),+ #[cfg(feature = "text")]+ cache_raster: HashMap::new(),+ #[cfg(feature = "text")]+ cache_has_opsz: HashMap::new(),++ clip_paths: HashMap::new(),+ masks: HashMap::new(),+ filters: HashMap::new(),+ paint: HashMap::new(),++ all_ids: HashSet::new(),+ linear_gradient_index: 0,+ radial_gradient_index: 0,+ pattern_index: 0,+ clip_path_index: 0,+ mask_index: 0,+ filter_index: 0,+ image_index: 0,+ }+ }++ // TODO: macros?+ pub(crate) fn gen_linear_gradient_id(&mut self) -> NonEmptyString {+ loop {+ self.linear_gradient_index += 1;+ let new_id = format!("linearGradient{}", self.linear_gradient_index);+ let new_hash = string_hash(&new_id);+ if !self.all_ids.contains(&new_hash) {+ return NonEmptyString::new(new_id).unwrap();+ }+ }+ }++ pub(crate) fn gen_radial_gradient_id(&mut self) -> NonEmptyString {+ loop {+ self.radial_gradient_index += 1;+ let new_id = format!("radialGradient{}", self.radial_gradient_index);+ let new_hash = string_hash(&new_id);+ if !self.all_ids.contains(&new_hash) {+ return NonEmptyString::new(new_id).unwrap();+ }+ }+ }++ pub(crate) fn gen_pattern_id(&mut self) -> NonEmptyString {+ loop {+ self.pattern_index += 1;+ let new_id = format!("pattern{}", self.pattern_index);+ let new_hash = string_hash(&new_id);+ if !self.all_ids.contains(&new_hash) {+ return NonEmptyString::new(new_id).unwrap();+ }+ }+ }++ pub(crate) fn gen_clip_path_id(&mut self) -> NonEmptyString {+ loop {+ self.clip_path_index += 1;+ let new_id = format!("clipPath{}", self.clip_path_index);+ let new_hash = string_hash(&new_id);+ if !self.all_ids.contains(&new_hash) {+ return NonEmptyString::new(new_id).unwrap();+ }+ }+ }++ pub(crate) fn gen_mask_id(&mut self) -> NonEmptyString {+ loop {+ self.mask_index += 1;+ let new_id = format!("mask{}", self.mask_index);+ let new_hash = string_hash(&new_id);+ if !self.all_ids.contains(&new_hash) {+ return NonEmptyString::new(new_id).unwrap();+ }+ }+ }++ pub(crate) fn gen_filter_id(&mut self) -> NonEmptyString {+ loop {+ self.filter_index += 1;+ let new_id = format!("filter{}", self.filter_index);+ let new_hash = string_hash(&new_id);+ if !self.all_ids.contains(&new_hash) {+ return NonEmptyString::new(new_id).unwrap();+ }+ }+ }++ pub(crate) fn gen_image_id(&mut self) -> NonEmptyString {+ loop {+ self.image_index += 1;+ let new_id = format!("image{}", self.image_index);+ let new_hash = string_hash(&new_id);+ if !self.all_ids.contains(&new_hash) {+ return NonEmptyString::new(new_id).unwrap();+ }+ }+ }++ font_lookup!(fontdb_svg, cache_svg, svg, Node);+ font_lookup!(fontdb_raster, cache_raster, raster, BitmapImage);++ #[cfg(feature = "text")]+ pub(crate) fn fontdb_outline(+ &mut self,+ font: ID,+ glyph: GlyphId,+ variations: &[FontVariation],+ ) -> Option<tiny_skia_path::Path> {+ let key = (font, glyph, variations.to_vec());+ match self.cache_outline.get(&key) {+ Some(cache_hit) => cache_hit.clone(),+ None => {+ let lookup = self.fontdb.outline(font, glyph, variations);+ self.cache_outline.insert(key, lookup.clone());+ lookup+ }+ }+ }++ #[cfg(feature = "text")]+ pub(crate) fn fontdb_colr(+ &mut self,+ font: ID,+ glyph: GlyphId,+ variations: &[FontVariation],+ ) -> Option<Tree> {+ let key = (font, glyph, variations.to_vec());+ match self.cache_colr.get(&key) {+ Some(cache_hit) => cache_hit.clone(),+ None => {+ let lookup = self.fontdb.colr(font, glyph, variations);+ self.cache_colr.insert(key, lookup.clone());+ lookup+ }+ }+ }++ #[cfg(feature = "text")]+ pub(crate) fn has_opsz_axis(&mut self, font: ID) -> bool {+ if let Some(&cached) = self.cache_has_opsz.get(&font) {+ return cached;+ }+ let has_opsz = self.fontdb.has_opsz_axis(font);+ self.cache_has_opsz.insert(font, has_opsz);+ has_opsz+ }+}++// TODO: is there a simpler way?+fn string_hash(s: &str) -> u64 {+ let mut h = std::collections::hash_map::DefaultHasher::new();+ s.hash(&mut h);+ h.finish()+}++impl<'a, 'input: 'a> SvgNode<'a, 'input> {+ pub(crate) fn convert_length(+ &self,+ aid: AId,+ object_units: Units,+ state: &State,+ def: Length,+ ) -> f32 {+ units::convert_length(+ self.attribute(aid).unwrap_or(def),+ *self,+ aid,+ object_units,+ state,+ )+ }++ pub fn convert_user_length(&self, aid: AId, state: &State, def: Length) -> f32 {+ self.convert_length(aid, Units::UserSpaceOnUse, state, def)+ }++ pub fn parse_viewbox(&self) -> Option<NonZeroRect> {+ let vb: svgtypes::ViewBox = self.attribute(AId::ViewBox)?;+ NonZeroRect::from_xywh(vb.x as f32, vb.y as f32, vb.w as f32, vb.h as f32)+ }++ pub fn resolve_length(&self, aid: AId, state: &State, def: f32) -> f32 {+ debug_assert!(+ !matches!(aid, AId::BaselineShift | AId::FontSize),+ "{} cannot be resolved via this function",+ aid+ );++ if let Some(n) = self.ancestors().find(|n| n.has_attribute(aid)) {+ if let Some(length) = n.attribute(aid) {+ return units::convert_user_length(length, n, aid, state);+ }+ }++ def+ }++ pub fn resolve_valid_length(+ &self,+ aid: AId,+ state: &State,+ def: f32,+ ) -> Option<NonZeroPositiveF32> {+ let n = self.resolve_length(aid, state, def);+ NonZeroPositiveF32::new(n)+ }++ pub(crate) fn try_convert_length(+ &self,+ aid: AId,+ object_units: Units,+ state: &State,+ ) -> Option<f32> {+ Some(units::convert_length(+ self.attribute(aid)?,+ *self,+ aid,+ object_units,+ state,+ ))+ }++ pub fn has_valid_transform(&self, aid: AId) -> bool {+ // Do not use Node::attribute::<Transform>, because it will always+ // return a valid transform.++ let attr = match self.attribute(aid) {+ Some(attr) => attr,+ None => return true,+ };++ let ts = match svgtypes::Transform::from_str(attr) {+ Ok(v) => v,+ Err(_) => return true,+ };++ let ts = Transform::from_row(+ ts.a as f32,+ ts.b as f32,+ ts.c as f32,+ ts.d as f32,+ ts.e as f32,+ ts.f as f32,+ );+ ts.is_valid()+ }++ pub fn is_visible_element(&self, opt: &crate::Options) -> bool {+ self.attribute(AId::Display) != Some("none")+ && self.has_valid_transform(AId::Transform)+ && super::switch::is_condition_passed(*self, opt)+ }+}++pub trait SvgColorExt {+ fn split_alpha(self) -> (Color, Opacity);+}++impl SvgColorExt for svgtypes::Color {+ fn split_alpha(self) -> (Color, Opacity) {+ (+ Color::new_rgb(self.red, self.green, self.blue),+ Opacity::new_u8(self.alpha),+ )+ }+}++/// Converts an input `Document` into a `Tree`.+///+/// # Errors+///+/// - If `Document` doesn't have an SVG node - returns an empty tree.+/// - If `Document` doesn't have a valid size - returns `Error::InvalidSize`.+pub(crate) fn convert_doc(svg_doc: &svgtree::Document, opt: &Options) -> Result<Tree, Error> {+ let svg = svg_doc.root_element();+ let (size, restore_viewbox) = resolve_svg_size(&svg, opt);+ let size = size?;+ let view_box = ViewBox {+ rect: svg+ .parse_viewbox()+ .unwrap_or_else(|| size.to_non_zero_rect(0.0, 0.0)),+ aspect: svg.attribute(AId::PreserveAspectRatio).unwrap_or_default(),+ };++ let background_color = svg+ .attribute::<&str>(AId::BackgroundColor)+ .and_then(|s| svgtypes::Paint::from_str(s).ok())+ .and_then(|paint| match paint {+ svgtypes::Paint::Color(c) => Some(c),+ _ => None,+ });++ let mut tree = Tree {+ size,+ root: Group::empty(),+ linear_gradients: Vec::new(),+ radial_gradients: Vec::new(),+ patterns: Vec::new(),+ clip_paths: Vec::new(),+ masks: Vec::new(),+ filters: Vec::new(),+ #[cfg(feature = "text")]+ fontdb: opt.fontdb.clone(),+ };++ if !svg.is_visible_element(opt) {+ return Ok(tree);+ }++ let state = State {+ parent_clip_path: None,+ context_element: None,+ parent_markers: Vec::new(),+ fe_image_link: false,+ view_box: view_box.rect,+ use_size: (None, None),+ opt,+ };++ let mut cache = Cache::new(+ #[cfg(feature = "text")]+ opt.fontdb.clone(),+ );++ for node in svg_doc.descendants() {+ if let Some(tag) = node.tag_name() {+ if matches!(+ tag,+ EId::ClipPath+ | EId::Filter+ | EId::LinearGradient+ | EId::Mask+ | EId::Pattern+ | EId::RadialGradient+ | EId::Image+ ) {+ if !node.element_id().is_empty() {+ cache.all_ids.insert(string_hash(node.element_id()));+ }+ }+ }+ }++ let root_ts = view_box.to_transform(tree.size());+ if root_ts.is_identity() && background_color.is_none() {+ convert_children(svg_doc.root(), &state, &mut cache, &mut tree.root);+ } else {+ let mut g = Group::empty();++ if let Some(background_color) = background_color {+ if let Some(path) = background_path(background_color, view_box.rect.to_rect()) {+ g.children.push(Node::Path(Box::new(path)));+ }+ }++ g.transform = root_ts;+ g.abs_transform = root_ts;+ convert_children(svg_doc.root(), &state, &mut cache, &mut g);+ g.calculate_bounding_boxes();+ tree.root.children.push(Node::Group(Box::new(g)));+ }++ // Clear cache to make sure that all `Arc<T>` objects have a single strong reference.+ cache.clip_paths.clear();+ cache.masks.clear();+ cache.filters.clear();+ cache.paint.clear();++ super::paint_server::update_paint_servers(+ &mut tree.root,+ Transform::default(),+ None,+ None,+ &mut cache,+ );+ tree.collect_paint_servers();+ tree.root.collect_clip_paths(&mut tree.clip_paths);+ tree.root.collect_masks(&mut tree.masks);+ tree.root.collect_filters(&mut tree.filters);+ tree.root.calculate_bounding_boxes();++ // The fontdb might have been mutated and we want to apply these changes to+ // the tree's fontdb.+ #[cfg(feature = "text")]+ {+ tree.fontdb = cache.fontdb;+ }++ if restore_viewbox {+ calculate_svg_bbox(&mut tree);+ }++ Ok(tree)+}++fn background_path(background_color: svgtypes::Color, area: Rect) -> Option<Path> {+ let path = PathBuilder::from_rect(area);++ let fill = Fill {+ paint: Paint::Color(Color::new_rgb(+ background_color.red,+ background_color.green,+ background_color.blue,+ )),+ opacity: NormalizedF32::new(background_color.alpha as f32 / 255.0)?,+ ..Default::default()+ };++ let mut path = Path::new_simple(Arc::new(path))?;+ path.fill = Some(fill);++ Some(path)+}++fn resolve_svg_size(svg: &SvgNode, opt: &Options) -> (Result<Size, Error>, bool) {+ let mut state = State {+ parent_clip_path: None,+ context_element: None,+ parent_markers: Vec::new(),+ fe_image_link: false,+ view_box: NonZeroRect::from_xywh(0.0, 0.0, 100.0, 100.0).unwrap(),+ use_size: (None, None),+ opt,+ };++ let def = Length::new(100.0, Unit::Percent);+ let mut width: Length = svg.attribute(AId::Width).unwrap_or(def);+ let mut height: Length = svg.attribute(AId::Height).unwrap_or(def);++ let view_box = svg.parse_viewbox();++ let restore_viewbox =+ if (width.unit == Unit::Percent || height.unit == Unit::Percent) && view_box.is_none() {+ // Apply the percentages to the fallback size.+ if width.unit == Unit::Percent {+ width = Length::new(+ (width.number / 100.0) * state.opt.default_size.width() as f64,+ Unit::None,+ );+ }++ if height.unit == Unit::Percent {+ height = Length::new(+ (height.number / 100.0) * state.opt.default_size.height() as f64,+ Unit::None,+ );+ }++ true+ } else {+ false+ };++ let size = if let Some(vbox) = view_box {+ state.view_box = vbox;++ let w = if width.unit == Unit::Percent {+ vbox.width() * (width.number as f32 / 100.0)+ } else {+ svg.convert_user_length(AId::Width, &state, def)+ };++ let h = if height.unit == Unit::Percent {+ vbox.height() * (height.number as f32 / 100.0)+ } else {+ svg.convert_user_length(AId::Height, &state, def)+ };++ // If exactly one of width and height is specified, compute the missing+ // dimension from the specified one and the viewBox aspect ratio.+ match (+ svg.attribute::<Length>(AId::Width),+ svg.attribute::<Length>(AId::Height),+ ) {+ (Some(_), None) => Size::from_wh(w, vbox.height() * w / vbox.width()),+ (None, Some(_)) => Size::from_wh(vbox.width() * h / vbox.height(), h),+ (_, _) => Size::from_wh(w, h),+ }+ } else {+ Size::from_wh(+ svg.convert_user_length(AId::Width, &state, def),+ svg.convert_user_length(AId::Height, &state, def),+ )+ };++ (size.ok_or(Error::InvalidSize), restore_viewbox)+}++/// Calculates SVG's size and viewBox in case there were not set.+///+/// Simply iterates over all nodes and calculates a bounding box.+fn calculate_svg_bbox(tree: &mut Tree) {+ let bbox = tree.root.abs_bounding_box();+ if let Some(size) = Size::from_wh(bbox.right(), bbox.bottom()) {+ tree.size = size;+ }+}++#[inline(never)]+pub(crate) fn convert_children(+ parent_node: SvgNode,+ state: &State,+ cache: &mut Cache,+ parent: &mut Group,+) {+ for node in parent_node.children() {+ convert_element(node, state, cache, parent);+ }+}++#[inline(never)]+pub(crate) fn convert_element(node: SvgNode, state: &State, cache: &mut Cache, parent: &mut Group) {+ let tag_name = match node.tag_name() {+ Some(v) => v,+ None => return,+ };++ if !tag_name.is_graphic() && !matches!(tag_name, EId::G | EId::Switch | EId::Svg) {+ return;+ }++ if !node.is_visible_element(state.opt) {+ return;+ }++ if tag_name == EId::Use {+ super::use_node::convert(node, state, cache, parent);+ return;+ }++ if tag_name == EId::Switch {+ super::switch::convert(node, state, cache, parent);+ return;+ }++ // A nested `svg` is handled just like `use`: it must not be wrapped in an+ // additional `convert_group`, otherwise its `transform` (and other group+ // properties) would be applied twice, since `convert_svg`+ // already creates its own group. The outermost `svg` (no parent element)+ // is intentionally not handled here - it's processed directly in+ // `convert_doc`.+ if tag_name == EId::Svg && node.parent_element().is_some() {+ super::use_node::convert_svg(node, state, cache, parent);++ return;+ }++ if let Some(g) = convert_group(node, state, false, cache, parent, &|cache, g| {+ convert_element_impl(tag_name, node, state, cache, g);+ }) {+ parent.children.push(Node::Group(Box::new(g)));+ }+}++#[inline(never)]+fn convert_element_impl(+ tag_name: EId,+ node: SvgNode,+ state: &State,+ cache: &mut Cache,+ parent: &mut Group,+) {+ match tag_name {+ EId::Rect+ | EId::Circle+ | EId::Ellipse+ | EId::Line+ | EId::Polyline+ | EId::Polygon+ | EId::Path => {+ if let Some(path) = super::shapes::convert(node, state) {+ convert_path(node, path, state, cache, parent);+ }+ }+ EId::Image => {+ super::image::convert(node, state, cache, parent);+ }+ EId::Text => {+ #[cfg(feature = "text")]+ {+ super::text::convert(node, state, cache, parent);+ }+ }+ EId::Svg => {+ // Only the outermost `svg` reaches this point; nested `svg` elements are+ // handled earlier in `convert_element`. The root `svg` itself is+ // skipped and only its children are converted.+ convert_children(node, state, cache, parent);+ }+ EId::G => {+ convert_children(node, state, cache, parent);+ }+ _ => {}+ }+}++// `clipPath` can have only shape and `text` children.+//+// `line` doesn't impact rendering because stroke is always disabled+// for `clipPath` children.+#[inline(never)]+pub(crate) fn convert_clip_path_elements(+ clip_node: SvgNode,+ state: &State,+ cache: &mut Cache,+ parent: &mut Group,+) {+ for node in clip_node.children() {+ let tag_name = match node.tag_name() {+ Some(v) => v,+ None => continue,+ };++ if !tag_name.is_graphic() {+ continue;+ }++ if !node.is_visible_element(state.opt) {+ continue;+ }++ if tag_name == EId::Use {+ super::use_node::convert(node, state, cache, parent);+ continue;+ }++ if let Some(g) = convert_group(node, state, false, cache, parent, &|cache, g| {+ convert_clip_path_elements_impl(tag_name, node, state, cache, g);+ }) {+ parent.children.push(Node::Group(Box::new(g)));+ }+ }+}++#[inline(never)]+fn convert_clip_path_elements_impl(+ tag_name: EId,+ node: SvgNode,+ state: &State,+ cache: &mut Cache,+ parent: &mut Group,+) {+ match tag_name {+ EId::Rect | EId::Circle | EId::Ellipse | EId::Polyline | EId::Polygon | EId::Path => {+ if let Some(path) = super::shapes::convert(node, state) {+ convert_path(node, path, state, cache, parent);+ }+ }+ EId::Text => {+ #[cfg(feature = "text")]+ {+ super::text::convert(node, state, cache, parent);+ }+ }+ _ => {+ log::warn!("'{}' is no a valid 'clip-path' child.", tag_name);+ }+ }+}++#[derive(Clone, Copy, PartialEq, Debug)]+enum Isolation {+ Auto,+ Isolate,+}++impl Default for Isolation {+ fn default() -> Self {+ Self::Auto+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for Isolation {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "auto" => Some(Isolation::Auto),+ "isolate" => Some(Isolation::Isolate),+ _ => None,+ }+ }+}++// TODO: explain+pub(crate) fn convert_group(+ node: SvgNode,+ state: &State,+ force: bool,+ cache: &mut Cache,+ parent: &mut Group,+ collect_children: &dyn Fn(&mut Cache, &mut Group),+) -> Option<Group> {+ // A `clipPath` child cannot have an opacity.+ let opacity = if state.parent_clip_path.is_none() {+ node.attribute::<Opacity>(AId::Opacity)+ .unwrap_or(Opacity::ONE)+ } else {+ Opacity::ONE+ };++ let transform = node.resolve_transform(AId::Transform, state);+ let blend_mode: BlendMode = node.attribute(AId::MixBlendMode).unwrap_or_default();+ let isolation: Isolation = node.attribute(AId::Isolation).unwrap_or_default();+ let isolate = isolation == Isolation::Isolate;++ // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.+ let is_g_or_use = matches!(node.tag_name(), Some(EId::G) | Some(EId::Use));+ let id = if is_g_or_use && state.parent_markers.is_empty() {+ node.element_id().to_string()+ } else {+ String::new()+ };++ let abs_transform = parent.abs_transform.pre_concat(transform);+ let dummy = Rect::from_xywh(0.0, 0.0, 0.0, 0.0).unwrap();+ let mut g = Group {+ id,+ transform,+ abs_transform,+ opacity,+ blend_mode,+ isolate,+ clip_path: None,+ mask: None,+ filters: Vec::new(),+ is_context_element: false,+ bounding_box: dummy,+ abs_bounding_box: dummy,+ stroke_bounding_box: dummy,+ abs_stroke_bounding_box: dummy,+ layer_bounding_box: NonZeroRect::from_xywh(0.0, 0.0, 1.0, 1.0).unwrap(),+ abs_layer_bounding_box: NonZeroRect::from_xywh(0.0, 0.0, 1.0, 1.0).unwrap(),+ children: Vec::new(),+ };+ collect_children(cache, &mut g);++ // We need to know group's bounding box before converting+ // clipPaths, masks and filters.+ let object_bbox = g.calculate_object_bbox();++ // `mask` and `filter` cannot be set on `clipPath` children.+ // But `clip-path` can.++ let mut clip_path = None;+ if let Some(link) = node.attribute::<SvgNode>(AId::ClipPath) {+ clip_path = super::clippath::convert(link, state, object_bbox, cache);+ if clip_path.is_none() {+ return None;+ }+ }++ let mut mask = None;+ if state.parent_clip_path.is_none() {+ if let Some(link) = node.attribute::<SvgNode>(AId::Mask) {+ mask = super::mask::convert(link, state, object_bbox, cache);+ if mask.is_none() {+ return None;+ }+ }+ }++ let filters = {+ let mut filters = Vec::new();+ if state.parent_clip_path.is_none() {+ if node.attribute(AId::Filter) == Some("none") {+ // Do nothing.+ } else if node.has_attribute(AId::Filter) {+ if let Ok(f) = super::filter::convert(node, state, object_bbox, cache) {+ filters = f;+ } else {+ // A filter that not a link or a filter with a link to a non existing element.+ //+ // Unlike `clip-path` and `mask`, when a `filter` link is invalid+ // then the whole element should be ignored.+ //+ // This is kinda an undefined behaviour.+ // In most cases, Chrome, Firefox and rsvg will ignore such elements,+ // but in some cases Chrome allows it. Not sure why.+ // Inkscape (0.92) simply ignores such attributes, rendering element as is.+ // Batik (1.12) crashes.+ //+ // Test file: e-filter-051.svg+ return None;+ }+ }+ }++ filters+ };++ let required = opacity.get().approx_ne_ulps(&1.0, 4)+ || clip_path.is_some()+ || mask.is_some()+ || !filters.is_empty()+ || !transform.is_identity()+ || blend_mode != BlendMode::Normal+ || isolate+ || is_g_or_use+ || force;++ if !required {+ parent.children.append(&mut g.children);+ return None;+ }++ g.clip_path = clip_path;+ g.mask = mask;+ g.filters = filters;++ // Must be called after we set Group::filters+ g.calculate_bounding_boxes();++ Some(g)+}++fn convert_path(+ node: SvgNode,+ tiny_skia_path: Arc<tiny_skia_path::Path>,+ state: &State,+ cache: &mut Cache,+ parent: &mut Group,+) {+ debug_assert!(tiny_skia_path.len() >= 2);+ if tiny_skia_path.len() < 2 {+ return;+ }++ let has_bbox = tiny_skia_path.bounds().width() > 0.0 && tiny_skia_path.bounds().height() > 0.0;+ let mut fill = super::style::resolve_fill(node, has_bbox, state, cache);+ let mut stroke = super::style::resolve_stroke(node, has_bbox, state, cache);+ let visibility: Visibility = node.find_attribute(AId::Visibility).unwrap_or_default();+ let mut visible = visibility == Visibility::Visible;+ let rendering_mode: ShapeRendering = node+ .find_attribute(AId::ShapeRendering)+ .unwrap_or(state.opt.shape_rendering);++ // TODO: handle `markers` before `stroke`+ let raw_paint_order: svgtypes::PaintOrder =+ node.find_attribute(AId::PaintOrder).unwrap_or_default();+ let paint_order = svg_paint_order_to_usvg(raw_paint_order);+ let path_transform = parent.abs_transform;++ // If a path doesn't have a fill or a stroke then it's invisible.+ // By setting `visibility` to `hidden` we are disabling rendering of this path.+ if fill.is_none() && stroke.is_none() {+ visible = false;+ }++ if let Some(fill) = fill.as_mut() {+ if let Some(ContextElement::PathNode(context_transform, context_bbox)) =+ fill.context_element+ {+ process_paint(+ &mut fill.paint,+ true,+ context_transform,+ context_bbox.map(|r| r.to_rect()),+ path_transform,+ tiny_skia_path.bounds(),+ cache,+ );+ fill.context_element = None;+ }+ }++ if let Some(stroke) = stroke.as_mut() {+ if let Some(ContextElement::PathNode(context_transform, context_bbox)) =+ stroke.context_element+ {+ process_paint(+ &mut stroke.paint,+ true,+ context_transform,+ context_bbox.map(|r| r.to_rect()),+ path_transform,+ tiny_skia_path.bounds(),+ cache,+ );+ stroke.context_element = None;+ }+ }++ let mut marker = None;+ if marker::is_valid(node) && visibility == Visibility::Visible {+ let mut marker_group = Group {+ abs_transform: parent.abs_transform,+ ..Group::empty()+ };++ let mut marker_state = state.clone();++ let bbox = tiny_skia_path+ .compute_tight_bounds()+ .and_then(|r| r.to_non_zero_rect());++ let fill = fill.clone().map(|mut f| {+ f.context_element = Some(ContextElement::PathNode(path_transform, bbox));+ f+ });++ let stroke = stroke.clone().map(|mut s| {+ s.context_element = Some(ContextElement::PathNode(path_transform, bbox));+ s+ });++ marker_state.context_element = Some((fill, stroke));++ marker::convert(+ node,+ &tiny_skia_path,+ &marker_state,+ cache,+ &mut marker_group,+ );+ marker_group.calculate_bounding_boxes();+ marker = Some(marker_group);+ }++ // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.+ let id = if state.parent_markers.is_empty() {+ node.element_id().to_string()+ } else {+ String::new()+ };++ let path = Path::new(+ id,+ visible,+ fill,+ stroke,+ paint_order,+ rendering_mode,+ tiny_skia_path,+ path_transform,+ );++ let path = match path {+ Some(v) => v,+ None => return,+ };++ match (raw_paint_order.order, marker) {+ ([PaintOrderKind::Markers, _, _], Some(markers_node)) => {+ parent.children.push(Node::Group(Box::new(markers_node)));+ parent.children.push(Node::Path(Box::new(path.clone())));+ }+ ([first, PaintOrderKind::Markers, last], Some(markers_node)) => {+ append_single_paint_path(first, &path, parent);+ parent.children.push(Node::Group(Box::new(markers_node)));+ append_single_paint_path(last, &path, parent);+ }+ ([_, _, PaintOrderKind::Markers], Some(markers_node)) => {+ parent.children.push(Node::Path(Box::new(path.clone())));+ parent.children.push(Node::Group(Box::new(markers_node)));+ }+ _ => parent.children.push(Node::Path(Box::new(path.clone()))),+ }+}++fn append_single_paint_path(paint_order_kind: PaintOrderKind, path: &Path, parent: &mut Group) {+ match paint_order_kind {+ PaintOrderKind::Fill => {+ if path.fill.is_some() {+ let mut fill_path = path.clone();+ fill_path.stroke = None;+ fill_path.id = String::new();+ parent.children.push(Node::Path(Box::new(fill_path)));+ }+ }+ PaintOrderKind::Stroke => {+ if path.stroke.is_some() {+ let mut stroke_path = path.clone();+ stroke_path.fill = None;+ stroke_path.id = String::new();+ parent.children.push(Node::Path(Box::new(stroke_path)));+ }+ }+ _ => {}+ }+}++pub fn svg_paint_order_to_usvg(order: svgtypes::PaintOrder) -> PaintOrder {+ match (order.order[0], order.order[1]) {+ (svgtypes::PaintOrderKind::Stroke, _) => PaintOrder::StrokeAndFill,+ (svgtypes::PaintOrderKind::Markers, svgtypes::PaintOrderKind::Stroke) => {+ PaintOrder::StrokeAndFill+ }+ _ => PaintOrder::FillAndStroke,+ }+}++impl SvgNode<'_, '_> {+ pub(crate) fn resolve_transform(&self, transform_aid: AId, state: &State) -> Transform {+ let mut transform: Transform = self.attribute(transform_aid).unwrap_or_default();+ let transform_origin: Option<TransformOrigin> = self.attribute(AId::TransformOrigin);++ if let Some(transform_origin) = transform_origin {+ let dx = convert_length(+ transform_origin.x_offset,+ *self,+ AId::Width,+ Units::UserSpaceOnUse,+ state,+ );+ let dy = convert_length(+ transform_origin.y_offset,+ *self,+ AId::Height,+ Units::UserSpaceOnUse,+ state,+ );+ transform = Transform::default()+ .pre_translate(dx, dy)+ .pre_concat(transform)+ .pre_translate(-dx, -dy);+ }++ transform+ }+}diff --git a/vendor/usvg/src/parser/filter.rs b/vendor/usvg/src/parser/filter.rsnew file mode 100644index 00000000..52985c89--- /dev/null+++ b/vendor/usvg/src/parser/filter.rs@@ -0,0 +1,1279 @@+// Copyright 2022 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++//! A collection of SVG filters.++use std::collections::HashSet;+use std::str::FromStr;+use std::sync::Arc;++use strict_num::PositiveF32;+use svgtypes::{AspectRatio, Length, LengthUnit as Unit};++use crate::{+ ApproxZeroUlps, Color, Group, Node, NonEmptyString, NonZeroF32, NonZeroRect, Opacity, Size,+ Units,+ filter::{self, *},+};++use super::OptionLog;+use super::converter::{self, SvgColorExt};+use super::paint_server::{convert_units, resolve_number};+use super::svgtree::{AId, EId, FromValue, SvgNode};++impl<'a, 'input: 'a> FromValue<'a, 'input> for filter::ColorInterpolation {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "sRGB" => Some(filter::ColorInterpolation::SRGB),+ "linearRGB" => Some(filter::ColorInterpolation::LinearRGB),+ _ => None,+ }+ }+}++pub(crate) fn convert(+ node: SvgNode,+ state: &converter::State,+ object_bbox: Option<NonZeroRect>,+ cache: &mut converter::Cache,+) -> Result<Vec<Arc<Filter>>, ()> {+ let value = match node.attribute::<&str>(AId::Filter) {+ Some(v) => v,+ None => return Ok(Vec::new()),+ };++ let mut has_invalid_urls = false;+ let mut filters = Vec::new();++ let create_base_filter_func =+ |kind, filters: &mut Vec<Arc<Filter>>, cache: &mut converter::Cache| {+ // Filter functions, unlike `filter` elements, do not have a filter region.+ // We're currently do not support an unlimited region, so we simply use a fairly large one.+ // This if far from ideal, but good for now.+ // TODO: Should be fixed eventually.+ let mut rect = match kind {+ Kind::DropShadow(_) | Kind::GaussianBlur(_) => {+ NonZeroRect::from_xywh(-0.5, -0.5, 2.0, 2.0).unwrap()+ }+ _ => NonZeroRect::from_xywh(-0.1, -0.1, 1.2, 1.2).unwrap(),+ };++ let object_bbox = match object_bbox {+ Some(v) => v,+ None => {+ log::warn!(+ "Filter '{}' has an invalid region. Skipped.",+ node.element_id()+ );+ return;+ }+ };++ rect = rect.bbox_transform(object_bbox);++ filters.push(Arc::new(Filter {+ id: cache.gen_filter_id(),+ rect,+ primitives: vec![Primitive {+ rect,+ // Unlike `filter` elements, filter functions use sRGB colors by default.+ color_interpolation: ColorInterpolation::SRGB,+ result: "result".to_string(),+ kind,+ }],+ }));+ };++ for func in svgtypes::FilterValueListParser::from(value) {+ let func = match func {+ Ok(v) => v,+ Err(e) => {+ // Skip the whole attribute list on error.+ log::warn!("Failed to parse a filter value cause {}. Skipping.", e);+ return Ok(Vec::new());+ }+ };++ match func {+ svgtypes::FilterValue::Blur(std_dev) => create_base_filter_func(+ convert_blur_function(node, std_dev, state),+ &mut filters,+ cache,+ ),+ svgtypes::FilterValue::DropShadow {+ color,+ dx,+ dy,+ std_dev,+ } => create_base_filter_func(+ convert_drop_shadow_function(node, color, dx, dy, std_dev, state),+ &mut filters,+ cache,+ ),+ svgtypes::FilterValue::Brightness(amount) => {+ create_base_filter_func(convert_brightness_function(amount), &mut filters, cache);+ }+ svgtypes::FilterValue::Contrast(amount) => {+ create_base_filter_func(convert_contrast_function(amount), &mut filters, cache);+ }+ svgtypes::FilterValue::Grayscale(amount) => {+ create_base_filter_func(convert_grayscale_function(amount), &mut filters, cache);+ }+ svgtypes::FilterValue::HueRotate(angle) => {+ create_base_filter_func(convert_hue_rotate_function(angle), &mut filters, cache);+ }+ svgtypes::FilterValue::Invert(amount) => {+ create_base_filter_func(convert_invert_function(amount), &mut filters, cache);+ }+ svgtypes::FilterValue::Opacity(amount) => {+ create_base_filter_func(convert_opacity_function(amount), &mut filters, cache);+ }+ svgtypes::FilterValue::Sepia(amount) => {+ create_base_filter_func(convert_sepia_function(amount), &mut filters, cache);+ }+ svgtypes::FilterValue::Saturate(amount) => {+ create_base_filter_func(convert_saturate_function(amount), &mut filters, cache);+ }+ svgtypes::FilterValue::Url(url) => {+ if let Some(link) = node.document().element_by_id(url) {+ if let Ok(res) = convert_url(link, state, object_bbox, cache) {+ if let Some(f) = res {+ filters.push(f);+ }+ } else {+ has_invalid_urls = true;+ }+ } else {+ has_invalid_urls = true;+ }+ }+ }+ }++ // If a `filter` attribute had urls pointing to a missing elements+ // and there are no valid filters at all - this is an error.+ //+ // Note that an invalid url is not an error in general.+ if filters.is_empty() && has_invalid_urls {+ return Err(());+ }++ Ok(filters)+}++fn convert_url(+ node: SvgNode,+ state: &converter::State,+ object_bbox: Option<NonZeroRect>,+ cache: &mut converter::Cache,+) -> Result<Option<Arc<Filter>>, ()> {+ let units = convert_units(node, AId::FilterUnits, Units::ObjectBoundingBox);+ let primitive_units = convert_units(node, AId::PrimitiveUnits, Units::UserSpaceOnUse);++ // Check if this element was already converted.+ //+ // Only `userSpaceOnUse` clipPaths can be shared,+ // because `objectBoundingBox` one will be converted into user one+ // and will become node-specific.+ let cacheable = units == Units::UserSpaceOnUse && primitive_units == Units::UserSpaceOnUse;+ if cacheable {+ if let Some(filter) = cache.filters.get(node.element_id()) {+ return Ok(Some(filter.clone()));+ }+ }++ let rect = NonZeroRect::from_xywh(+ resolve_number(+ node,+ AId::X,+ units,+ state,+ Length::new(-10.0, Unit::Percent),+ ),+ resolve_number(+ node,+ AId::Y,+ units,+ state,+ Length::new(-10.0, Unit::Percent),+ ),+ resolve_number(+ node,+ AId::Width,+ units,+ state,+ Length::new(120.0, Unit::Percent),+ ),+ resolve_number(+ node,+ AId::Height,+ units,+ state,+ Length::new(120.0, Unit::Percent),+ ),+ );++ let mut rect = rect+ .log_none(|| {+ log::warn!(+ "Filter '{}' has an invalid region. Skipped.",+ node.element_id()+ );+ })+ .ok_or(())?;++ if units == Units::ObjectBoundingBox {+ if let Some(object_bbox) = object_bbox {+ rect = rect.bbox_transform(object_bbox);+ } else {+ log::warn!("Filters on zero-sized shapes are not allowed.");+ return Err(());+ }+ }++ let node_with_primitives = match find_filter_with_primitives(node) {+ Some(v) => v,+ None => return Err(()),+ };+ let primitives = collect_children(+ &node_with_primitives,+ primitive_units,+ state,+ object_bbox,+ rect,+ cache,+ );+ if primitives.is_empty() {+ return Err(());+ }++ let mut id = NonEmptyString::new(node.element_id().to_string()).ok_or(())?;+ // Generate ID only when we're parsing `objectBoundingBox` filter for the second time.+ if !cacheable && cache.filters.contains_key(id.get()) {+ id = cache.gen_filter_id();+ }+ let id_copy = id.get().to_string();++ let filter = Arc::new(Filter {+ id,+ rect,+ primitives,+ });++ cache.filters.insert(id_copy, filter.clone());++ Ok(Some(filter))+}++fn find_filter_with_primitives<'a>(node: SvgNode<'a, 'a>) -> Option<SvgNode<'a, 'a>> {+ for link in node.href_iter() {+ if link.tag_name() != Some(EId::Filter) {+ log::warn!(+ "Filter '{}' cannot reference '{}' via 'xlink:href'.",+ node.element_id(),+ link.tag_name().unwrap()+ );+ return None;+ }++ if link.has_children() {+ return Some(link);+ }+ }++ None+}++struct FilterResults {+ names: HashSet<String>,+ idx: usize,+}++fn collect_children(+ filter: &SvgNode,+ units: Units,+ state: &converter::State,+ object_bbox: Option<NonZeroRect>,+ filter_region: NonZeroRect,+ cache: &mut converter::Cache,+) -> Vec<Primitive> {+ let mut primitives = Vec::new();++ let mut results = FilterResults {+ names: HashSet::new(),+ idx: 1,+ };++ let scale = if units == Units::ObjectBoundingBox {+ if let Some(object_bbox) = object_bbox {+ object_bbox.size()+ } else {+ // No need to warn. Already checked.+ return Vec::new();+ }+ } else {+ Size::from_wh(1.0, 1.0).unwrap()+ };++ for child in filter.children() {+ let tag_name = match child.tag_name() {+ Some(v) => v,+ None => continue,+ };++ let filter_subregion = match resolve_primitive_region(+ child,+ tag_name,+ units,+ state,+ object_bbox,+ filter_region,+ ) {+ Some(v) => v,+ None => break,+ };++ let kind =+ match tag_name {+ EId::FeDropShadow => convert_drop_shadow(child, scale, &primitives),+ EId::FeGaussianBlur => convert_gaussian_blur(child, scale, &primitives),+ EId::FeOffset => convert_offset(child, scale, &primitives),+ EId::FeBlend => convert_blend(child, &primitives),+ EId::FeFlood => convert_flood(child),+ EId::FeComposite => convert_composite(child, &primitives),+ EId::FeMerge => convert_merge(child, &primitives),+ EId::FeTile => convert_tile(child, &primitives),+ EId::FeImage => convert_image(child, filter_subregion, state, cache),+ EId::FeComponentTransfer => convert_component_transfer(child, &primitives),+ EId::FeColorMatrix => convert_color_matrix(child, &primitives),+ EId::FeConvolveMatrix => convert_convolve_matrix(child, &primitives)+ .unwrap_or_else(create_dummy_primitive),+ EId::FeMorphology => convert_morphology(child, scale, &primitives),+ EId::FeDisplacementMap => convert_displacement_map(child, scale, &primitives),+ EId::FeTurbulence => convert_turbulence(child),+ EId::FeDiffuseLighting => convert_diffuse_lighting(child, &primitives)+ .unwrap_or_else(create_dummy_primitive),+ EId::FeSpecularLighting => convert_specular_lighting(child, &primitives)+ .unwrap_or_else(create_dummy_primitive),+ tag_name => {+ log::warn!("'{}' is not a valid filter primitive. Skipped.", tag_name);+ continue;+ }+ };++ let color_interpolation = child+ .find_attribute(AId::ColorInterpolationFilters)+ .unwrap_or_default();++ primitives.push(Primitive {+ rect: filter_subregion,+ color_interpolation,+ result: gen_result(child, &mut results),+ kind,+ });+ }++ // TODO: remove primitives which results are not used++ primitives+}++// TODO: rewrite/simplify/explain/whatever+fn resolve_primitive_region(+ fe: SvgNode,+ kind: EId,+ units: Units,+ state: &converter::State,+ bbox: Option<NonZeroRect>,+ filter_region: NonZeroRect,+) -> Option<NonZeroRect> {+ let x = fe.try_convert_length(AId::X, units, state);+ let y = fe.try_convert_length(AId::Y, units, state);+ let width = fe.try_convert_length(AId::Width, units, state);+ let height = fe.try_convert_length(AId::Height, units, state);++ let region = match kind {+ EId::FeFlood | EId::FeImage => {+ // `feImage` uses the object bbox.+ if units == Units::ObjectBoundingBox {+ let bbox = bbox?;++ // TODO: wrong+ // let ts_bbox = tiny_skia::Rect::new(ts.e, ts.f, ts.a, ts.d).unwrap();++ let r = NonZeroRect::from_xywh(+ x.unwrap_or(0.0),+ y.unwrap_or(0.0),+ width.unwrap_or(1.0),+ height.unwrap_or(1.0),+ )?;++ return Some(r.bbox_transform(bbox));+ } else {+ filter_region+ }+ }+ _ => filter_region,+ };++ // TODO: Wrong! Does not account rotate and skew.+ if units == Units::ObjectBoundingBox {+ let subregion_bbox = NonZeroRect::from_xywh(+ x.unwrap_or(0.0),+ y.unwrap_or(0.0),+ width.unwrap_or(1.0),+ height.unwrap_or(1.0),+ )?;++ Some(region.bbox_transform(subregion_bbox))+ } else {+ NonZeroRect::from_xywh(+ x.unwrap_or(region.x()),+ y.unwrap_or(region.y()),+ width.unwrap_or(region.width()),+ height.unwrap_or(region.height()),+ )+ }+}++// A malformed filter primitive usually should produce a transparent image.+// But since `FilterKind` structs are designed to always be valid,+// we are using `FeFlood` as fallback.+#[inline(never)]+pub(crate) fn create_dummy_primitive() -> Kind {+ Kind::Flood(Flood {+ color: Color::black(),+ opacity: Opacity::ZERO,+ })+}++#[inline(never)]+fn resolve_input(node: SvgNode, aid: AId, primitives: &[Primitive]) -> Input {+ match node.attribute(aid) {+ Some(s) => {+ let input = parse_in(s);++ // If `in` references an unknown `result` than fallback+ // to previous result or `SourceGraphic`.+ if let Input::Reference(ref name) = input {+ if !primitives.iter().any(|p| p.result == *name) {+ return if let Some(prev) = primitives.last() {+ Input::Reference(prev.result.clone())+ } else {+ Input::SourceGraphic+ };+ }+ }++ input+ }+ None => {+ if let Some(prev) = primitives.last() {+ // If `in` is not set and this is not the first primitive+ // than the input is a result of the previous primitive.+ Input::Reference(prev.result.clone())+ } else {+ // If `in` is not set and this is the first primitive+ // than the input is `SourceGraphic`.+ Input::SourceGraphic+ }+ }+ }+}++fn parse_in(s: &str) -> Input {+ match s {+ "SourceGraphic" => Input::SourceGraphic,+ "SourceAlpha" => Input::SourceAlpha,+ "BackgroundImage" | "BackgroundAlpha" | "FillPaint" | "StrokePaint" => {+ log::warn!("{} filter input isn't supported and not planed.", s);+ Input::SourceGraphic+ }+ _ => Input::Reference(s.to_string()),+ }+}++fn gen_result(node: SvgNode, results: &mut FilterResults) -> String {+ match node.attribute::<&str>(AId::Result) {+ Some(s) => {+ // Remember predefined result.+ results.names.insert(s.to_string());+ results.idx += 1;++ s.to_string()+ }+ None => {+ // Generate an unique name for `result`.+ loop {+ let name = format!("result{}", results.idx);+ results.idx += 1;++ if !results.names.contains(&name) {+ return name;+ }+ }+ }+ }+}++fn convert_blend(fe: SvgNode, primitives: &[Primitive]) -> Kind {+ let mode = fe.attribute(AId::Mode).unwrap_or_default();+ let input1 = resolve_input(fe, AId::In, primitives);+ let input2 = resolve_input(fe, AId::In2, primitives);+ Kind::Blend(Blend {+ mode,+ input1,+ input2,+ })+}++fn convert_color_matrix(fe: SvgNode, primitives: &[Primitive]) -> Kind {+ let kind = convert_color_matrix_kind(fe).unwrap_or_default();+ Kind::ColorMatrix(ColorMatrix {+ input: resolve_input(fe, AId::In, primitives),+ kind,+ })+}++fn convert_color_matrix_kind(fe: SvgNode) -> Option<ColorMatrixKind> {+ match fe.attribute(AId::Type) {+ Some("saturate") => {+ if let Some(list) = fe.attribute::<Vec<f32>>(AId::Values) {+ if !list.is_empty() {+ let n = crate::f32_bound(0.0, list[0], 1.0);+ return Some(ColorMatrixKind::Saturate(PositiveF32::new(n).unwrap()));+ } else {+ return Some(ColorMatrixKind::Saturate(PositiveF32::new(1.0).unwrap()));+ }+ }+ }+ Some("hueRotate") => {+ if let Some(list) = fe.attribute::<Vec<f32>>(AId::Values) {+ if !list.is_empty() {+ return Some(ColorMatrixKind::HueRotate(list[0]));+ } else {+ return Some(ColorMatrixKind::HueRotate(0.0));+ }+ }+ }+ Some("luminanceToAlpha") => {+ return Some(ColorMatrixKind::LuminanceToAlpha);+ }+ _ => {+ // Fallback to `matrix`.+ if let Some(list) = fe.attribute::<Vec<f32>>(AId::Values) {+ if list.len() == 20 {+ return Some(ColorMatrixKind::Matrix(list));+ }+ }+ }+ }++ None+}++fn convert_component_transfer(fe: SvgNode, primitives: &[Primitive]) -> Kind {+ let mut kind = ComponentTransfer {+ input: resolve_input(fe, AId::In, primitives),+ func_r: TransferFunction::Identity,+ func_g: TransferFunction::Identity,+ func_b: TransferFunction::Identity,+ func_a: TransferFunction::Identity,+ };++ for child in fe.children().filter(|n| n.is_element()) {+ if let Some(func) = convert_transfer_function(child) {+ match child.tag_name().unwrap() {+ EId::FeFuncR => kind.func_r = func,+ EId::FeFuncG => kind.func_g = func,+ EId::FeFuncB => kind.func_b = func,+ EId::FeFuncA => kind.func_a = func,+ _ => {}+ }+ }+ }++ Kind::ComponentTransfer(kind)+}++fn convert_transfer_function(node: SvgNode) -> Option<TransferFunction> {+ match node.attribute(AId::Type)? {+ "identity" => Some(TransferFunction::Identity),+ "table" => match node.attribute::<Vec<f32>>(AId::TableValues) {+ Some(values) => Some(TransferFunction::Table(values)),+ None => Some(TransferFunction::Table(Vec::new())),+ },+ "discrete" => match node.attribute::<Vec<f32>>(AId::TableValues) {+ Some(values) => Some(TransferFunction::Discrete(values)),+ None => Some(TransferFunction::Discrete(Vec::new())),+ },+ "linear" => Some(TransferFunction::Linear {+ slope: node.attribute(AId::Slope).unwrap_or(1.0),+ intercept: node.attribute(AId::Intercept).unwrap_or(0.0),+ }),+ "gamma" => Some(TransferFunction::Gamma {+ amplitude: node.attribute(AId::Amplitude).unwrap_or(1.0),+ exponent: node.attribute(AId::Exponent).unwrap_or(1.0),+ offset: node.attribute(AId::Offset).unwrap_or(0.0),+ }),+ _ => None,+ }+}++fn convert_composite(fe: SvgNode, primitives: &[Primitive]) -> Kind {+ let operator = match fe.attribute(AId::Operator).unwrap_or("over") {+ "in" => CompositeOperator::In,+ "out" => CompositeOperator::Out,+ "atop" => CompositeOperator::Atop,+ "xor" => CompositeOperator::Xor,+ "arithmetic" => CompositeOperator::Arithmetic {+ k1: fe.attribute(AId::K1).unwrap_or(0.0),+ k2: fe.attribute(AId::K2).unwrap_or(0.0),+ k3: fe.attribute(AId::K3).unwrap_or(0.0),+ k4: fe.attribute(AId::K4).unwrap_or(0.0),+ },+ _ => CompositeOperator::Over,+ };++ let input1 = resolve_input(fe, AId::In, primitives);+ let input2 = resolve_input(fe, AId::In2, primitives);++ Kind::Composite(Composite {+ operator,+ input1,+ input2,+ })+}++fn convert_convolve_matrix(fe: SvgNode, primitives: &[Primitive]) -> Option<Kind> {+ fn parse_target(target: Option<f32>, order: u32) -> Option<u32> {+ let default_target = (order as f32 / 2.0).floor() as u32;+ let target = target.unwrap_or(default_target as f32) as i32;+ if target < 0 || target >= order as i32 {+ None+ } else {+ Some(target as u32)+ }+ }++ let mut order_x = 3;+ let mut order_y = 3;+ if let Some(value) = fe.attribute::<&str>(AId::Order) {+ let mut s = svgtypes::NumberListParser::from(value);+ let x = s.next().and_then(|a| a.ok()).map(|n| n as i32).unwrap_or(3);+ let y = s.next().and_then(|a| a.ok()).map(|n| n as i32).unwrap_or(x);+ if x > 0 && y > 0 {+ order_x = x as u32;+ order_y = y as u32;+ }+ }++ let mut matrix = Vec::new();+ if let Some(list) = fe.attribute::<Vec<f32>>(AId::KernelMatrix) {+ if list.len() == (order_x * order_y) as usize {+ matrix = list;+ }+ }++ let mut kernel_sum: f32 = matrix.iter().sum();+ // Round up to prevent float precision issues.+ kernel_sum = (kernel_sum * 1_000_000.0).round() / 1_000_000.0;+ if kernel_sum.approx_zero_ulps(4) {+ kernel_sum = 1.0;+ }++ let divisor = fe.attribute(AId::Divisor).unwrap_or(kernel_sum);+ if divisor.approx_zero_ulps(4) {+ return None;+ }++ let bias = fe.attribute(AId::Bias).unwrap_or(0.0);++ let target_x = parse_target(fe.attribute(AId::TargetX), order_x)?;+ let target_y = parse_target(fe.attribute(AId::TargetY), order_y)?;++ let kernel_matrix = ConvolveMatrixData::new(target_x, target_y, order_x, order_y, matrix)?;++ let edge_mode = match fe.attribute(AId::EdgeMode).unwrap_or("duplicate") {+ "none" => EdgeMode::None,+ "wrap" => EdgeMode::Wrap,+ _ => EdgeMode::Duplicate,+ };++ let preserve_alpha = fe.attribute(AId::PreserveAlpha).unwrap_or("false") == "true";++ Some(Kind::ConvolveMatrix(ConvolveMatrix {+ input: resolve_input(fe, AId::In, primitives),+ matrix: kernel_matrix,+ divisor: NonZeroF32::new(divisor).unwrap(),+ bias,+ edge_mode,+ preserve_alpha,+ }))+}++fn convert_displacement_map(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {+ let parse_channel = |aid| match fe.attribute(aid).unwrap_or("A") {+ "R" => ColorChannel::R,+ "G" => ColorChannel::G,+ "B" => ColorChannel::B,+ _ => ColorChannel::A,+ };++ // TODO: should probably split scale to scale_x and scale_y,+ // but resvg doesn't support displacement map anyway...+ let scale = (scale.width() + scale.height()) / 2.0;++ Kind::DisplacementMap(DisplacementMap {+ input1: resolve_input(fe, AId::In, primitives),+ input2: resolve_input(fe, AId::In2, primitives),+ scale: fe.attribute(AId::Scale).unwrap_or(0.0) * scale,+ x_channel_selector: parse_channel(AId::XChannelSelector),+ y_channel_selector: parse_channel(AId::YChannelSelector),+ })+}++fn convert_drop_shadow(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {+ let (std_dev_x, std_dev_y) = convert_std_dev_attr(fe, scale, "2 2");++ let (color, opacity) = fe+ .attribute(AId::FloodColor)+ .unwrap_or_else(svgtypes::Color::black)+ .split_alpha();++ let flood_opacity = fe+ .attribute::<Opacity>(AId::FloodOpacity)+ .unwrap_or(Opacity::ONE);++ Kind::DropShadow(DropShadow {+ input: resolve_input(fe, AId::In, primitives),+ dx: fe.attribute(AId::Dx).unwrap_or(2.0) * scale.width(),+ dy: fe.attribute(AId::Dy).unwrap_or(2.0) * scale.height(),+ std_dev_x,+ std_dev_y,+ color,+ opacity: opacity * flood_opacity,+ })+}++fn convert_flood(fe: SvgNode) -> Kind {+ let (color, opacity) = fe+ .attribute(AId::FloodColor)+ .unwrap_or_else(svgtypes::Color::black)+ .split_alpha();++ let flood_opacity = fe+ .attribute::<Opacity>(AId::FloodOpacity)+ .unwrap_or(Opacity::ONE);++ Kind::Flood(Flood {+ color,+ opacity: opacity * flood_opacity,+ })+}++fn convert_gaussian_blur(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {+ let (std_dev_x, std_dev_y) = convert_std_dev_attr(fe, scale, "0 0");+ Kind::GaussianBlur(GaussianBlur {+ input: resolve_input(fe, AId::In, primitives),+ std_dev_x,+ std_dev_y,+ })+}++fn convert_std_dev_attr(fe: SvgNode, scale: Size, default: &str) -> (PositiveF32, PositiveF32) {+ let text = fe.attribute(AId::StdDeviation).unwrap_or(default);+ let mut parser = svgtypes::NumberListParser::from(text);++ let n1 = parser.next().and_then(|n| n.ok());+ let n2 = parser.next().and_then(|n| n.ok());+ // `stdDeviation` must have no more than two values.+ // Otherwise we should fallback to `0 0`.+ let n3 = parser.next().and_then(|n| n.ok());++ let (std_dev_x, std_dev_y) = match (n1, n2, n3) {+ (Some(n1), Some(n2), None) => (n1, n2),+ (Some(n1), None, None) => (n1, n1),+ _ => (0.0, 0.0),+ };++ let std_dev_x = (std_dev_x as f32) * scale.width();+ let std_dev_y = (std_dev_y as f32) * scale.height();++ let std_dev_x = PositiveF32::new(std_dev_x).unwrap_or(PositiveF32::ZERO);+ let std_dev_y = PositiveF32::new(std_dev_y).unwrap_or(PositiveF32::ZERO);++ (std_dev_x, std_dev_y)+}++fn convert_image(+ fe: SvgNode,+ filter_subregion: NonZeroRect,+ state: &converter::State,+ cache: &mut converter::Cache,+) -> Kind {+ match convert_image_inner(fe, filter_subregion, state, cache) {+ Some(kind) => kind,+ None => create_dummy_primitive(),+ }+}++fn convert_image_inner(+ fe: SvgNode,+ filter_subregion: NonZeroRect,+ state: &converter::State,+ cache: &mut converter::Cache,+) -> Option<Kind> {+ let rendering_mode = fe+ .find_attribute(AId::ImageRendering)+ .unwrap_or(state.opt.image_rendering);++ if let Some(node) = fe.try_attribute::<SvgNode>(AId::Href) {+ let mut state = state.clone();+ state.fe_image_link = true;+ let mut root = Group::empty();+ super::converter::convert_element(node, &state, cache, &mut root);+ return if root.has_children() {+ root.calculate_bounding_boxes();+ // Transfer node id from group's child to the group itself if needed.+ if let Some(Node::Group(g)) = root.children.first_mut() {+ if let Some(child2) = g.children.first_mut() {+ g.id = child2.id().to_string();+ match child2 {+ Node::Group(g2) => g2.id.clear(),+ Node::Path(path) => path.id.clear(),+ Node::Image(image) => image.id.clear(),+ Node::Text(text) => text.id.clear(),+ }+ }+ }++ Some(Kind::Image(Image { root }))+ } else {+ None+ };+ }++ let href = fe.try_attribute(AId::Href).log_none(|| {+ log::warn!("The 'feImage' element lacks the 'xlink:href' attribute. Skipped.");+ })?;+ let img_data = super::image::get_href_data(href, state)?;+ let actual_size = img_data.actual_size()?;++ let aspect: AspectRatio = fe.attribute(AId::PreserveAspectRatio).unwrap_or_default();++ let mut root = Group::empty();+ super::image::convert_inner(+ img_data,+ cache.gen_image_id().take(),+ true,+ rendering_mode,+ aspect,+ actual_size,+ filter_subregion.translate_to(0.0, 0.0)?,+ cache,+ &mut root,+ );+ root.calculate_bounding_boxes();++ Some(Kind::Image(Image { root }))+}++fn convert_diffuse_lighting(fe: SvgNode, primitives: &[Primitive]) -> Option<Kind> {+ let light_source = convert_light_source(fe)?;+ Some(Kind::DiffuseLighting(DiffuseLighting {+ input: resolve_input(fe, AId::In, primitives),+ surface_scale: fe.attribute(AId::SurfaceScale).unwrap_or(1.0),+ diffuse_constant: fe.attribute(AId::DiffuseConstant).unwrap_or(1.0),+ lighting_color: convert_lighting_color(fe),+ light_source,+ }))+}++fn convert_specular_lighting(fe: SvgNode, primitives: &[Primitive]) -> Option<Kind> {+ let light_source = convert_light_source(fe)?;++ let specular_exponent = fe.attribute(AId::SpecularExponent).unwrap_or(1.0);+ if !(1.0..=128.0).contains(&specular_exponent) {+ // When exponent is out of range, the whole filter primitive should be ignored.+ return None;+ }++ let specular_exponent = crate::f32_bound(1.0, specular_exponent, 128.0);++ Some(Kind::SpecularLighting(SpecularLighting {+ input: resolve_input(fe, AId::In, primitives),+ surface_scale: fe.attribute(AId::SurfaceScale).unwrap_or(1.0),+ specular_constant: fe.attribute(AId::SpecularConstant).unwrap_or(1.0),+ specular_exponent,+ lighting_color: convert_lighting_color(fe),+ light_source,+ }))+}++#[inline(never)]+fn convert_lighting_color(node: SvgNode) -> Color {+ // Color's alpha doesn't affect lighting-color. Simply skip it.+ match node.attribute(AId::LightingColor) {+ Some("currentColor") => {+ node.find_attribute(AId::Color)+ // Yes, a missing `currentColor` resolves to black and not white.+ .unwrap_or(svgtypes::Color::black())+ .split_alpha()+ .0+ }+ Some(value) => {+ if let Ok(c) = svgtypes::Color::from_str(value) {+ c.split_alpha().0+ } else {+ log::warn!("Failed to parse lighting-color value: '{}'.", value);+ Color::white()+ }+ }+ _ => Color::white(),+ }+}++#[inline(never)]+fn convert_light_source(parent: SvgNode) -> Option<LightSource> {+ let child = parent.children().find(|n| {+ matches!(+ n.tag_name(),+ Some(EId::FeDistantLight) | Some(EId::FePointLight) | Some(EId::FeSpotLight)+ )+ })?;++ match child.tag_name() {+ Some(EId::FeDistantLight) => Some(LightSource::DistantLight(DistantLight {+ azimuth: child.attribute(AId::Azimuth).unwrap_or(0.0),+ elevation: child.attribute(AId::Elevation).unwrap_or(0.0),+ })),+ Some(EId::FePointLight) => Some(LightSource::PointLight(PointLight {+ x: child.attribute(AId::X).unwrap_or(0.0),+ y: child.attribute(AId::Y).unwrap_or(0.0),+ z: child.attribute(AId::Z).unwrap_or(0.0),+ })),+ Some(EId::FeSpotLight) => {+ let specular_exponent = child.attribute(AId::SpecularExponent).unwrap_or(1.0);+ let specular_exponent = PositiveF32::new(specular_exponent)+ .unwrap_or_else(|| PositiveF32::new(1.0).unwrap());++ Some(LightSource::SpotLight(SpotLight {+ x: child.attribute(AId::X).unwrap_or(0.0),+ y: child.attribute(AId::Y).unwrap_or(0.0),+ z: child.attribute(AId::Z).unwrap_or(0.0),+ points_at_x: child.attribute(AId::PointsAtX).unwrap_or(0.0),+ points_at_y: child.attribute(AId::PointsAtY).unwrap_or(0.0),+ points_at_z: child.attribute(AId::PointsAtZ).unwrap_or(0.0),+ specular_exponent,+ limiting_cone_angle: child.attribute(AId::LimitingConeAngle),+ }))+ }+ _ => None,+ }+}++fn convert_merge(fe: SvgNode, primitives: &[Primitive]) -> Kind {+ let mut inputs = Vec::new();+ for child in fe.children() {+ inputs.push(resolve_input(child, AId::In, primitives));+ }++ Kind::Merge(Merge { inputs })+}++fn convert_morphology(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {+ let operator = match fe.attribute(AId::Operator).unwrap_or("erode") {+ "dilate" => MorphologyOperator::Dilate,+ _ => MorphologyOperator::Erode,+ };++ let mut radius_x = PositiveF32::new(scale.width()).unwrap();+ let mut radius_y = PositiveF32::new(scale.height()).unwrap();+ if let Some(list) = fe.attribute::<Vec<f32>>(AId::Radius) {+ let mut rx = 0.0;+ let mut ry = 0.0;+ if list.len() == 2 {+ rx = list[0];+ ry = list[1];+ } else if list.len() == 1 {+ rx = list[0];+ ry = list[0]; // The same as `rx`.+ }++ if rx.approx_zero_ulps(4) && ry.approx_zero_ulps(4) {+ rx = 1.0;+ ry = 1.0;+ }++ // If only one of the values is zero, reset it to 1.0+ // This is not specified in the spec, but this is how Chrome and Safari work.+ if rx.approx_zero_ulps(4) && !ry.approx_zero_ulps(4) {+ rx = 1.0;+ }+ if !rx.approx_zero_ulps(4) && ry.approx_zero_ulps(4) {+ ry = 1.0;+ }++ // Both values must be positive.+ if rx.is_sign_positive() && ry.is_sign_positive() {+ radius_x = PositiveF32::new(rx * scale.width()).unwrap();+ radius_y = PositiveF32::new(ry * scale.height()).unwrap();+ }+ }++ Kind::Morphology(Morphology {+ input: resolve_input(fe, AId::In, primitives),+ operator,+ radius_x,+ radius_y,+ })+}++fn convert_offset(fe: SvgNode, scale: Size, primitives: &[Primitive]) -> Kind {+ Kind::Offset(Offset {+ input: resolve_input(fe, AId::In, primitives),+ dx: fe.attribute(AId::Dx).unwrap_or(0.0) * scale.width(),+ dy: fe.attribute(AId::Dy).unwrap_or(0.0) * scale.height(),+ })+}++fn convert_tile(fe: SvgNode, primitives: &[Primitive]) -> Kind {+ Kind::Tile(Tile {+ input: resolve_input(fe, AId::In, primitives),+ })+}++fn convert_turbulence(fe: SvgNode) -> Kind {+ let mut base_frequency_x = PositiveF32::ZERO;+ let mut base_frequency_y = PositiveF32::ZERO;+ if let Some(list) = fe.attribute::<Vec<f32>>(AId::BaseFrequency) {+ let mut x = 0.0;+ let mut y = 0.0;+ if list.len() == 2 {+ x = list[0];+ y = list[1];+ } else if list.len() == 1 {+ x = list[0];+ y = list[0]; // The same as `x`.+ }++ if x.is_sign_positive() && y.is_sign_positive() {+ base_frequency_x = PositiveF32::new(x).unwrap();+ base_frequency_y = PositiveF32::new(y).unwrap();+ }+ }++ let mut num_octaves = fe.attribute(AId::NumOctaves).unwrap_or(1.0);+ if num_octaves.is_sign_negative() {+ num_octaves = 0.0;+ }++ let kind = match fe.attribute(AId::Type).unwrap_or("turbulence") {+ "fractalNoise" => TurbulenceKind::FractalNoise,+ _ => TurbulenceKind::Turbulence,+ };++ Kind::Turbulence(Turbulence {+ base_frequency_x,+ base_frequency_y,+ num_octaves: num_octaves.round() as u32,+ seed: fe.attribute::<f32>(AId::Seed).unwrap_or(0.0).trunc() as i32,+ stitch_tiles: fe.attribute(AId::StitchTiles) == Some("stitch"),+ kind,+ })+}++#[inline(never)]+fn convert_grayscale_function(amount: f64) -> Kind {+ let amount = amount.min(1.0) as f32;+ Kind::ColorMatrix(ColorMatrix {+ input: Input::SourceGraphic,+ kind: ColorMatrixKind::Matrix(vec![+ (0.2126 + 0.7874 * (1.0 - amount)),+ (0.7152 - 0.7152 * (1.0 - amount)),+ (0.0722 - 0.0722 * (1.0 - amount)),+ 0.0,+ 0.0,+ (0.2126 - 0.2126 * (1.0 - amount)),+ (0.7152 + 0.2848 * (1.0 - amount)),+ (0.0722 - 0.0722 * (1.0 - amount)),+ 0.0,+ 0.0,+ (0.2126 - 0.2126 * (1.0 - amount)),+ (0.7152 - 0.7152 * (1.0 - amount)),+ (0.0722 + 0.9278 * (1.0 - amount)),+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0,+ 0.0,+ ]),+ })+}++#[inline(never)]+fn convert_sepia_function(amount: f64) -> Kind {+ let amount = amount.min(1.0) as f32;+ Kind::ColorMatrix(ColorMatrix {+ input: Input::SourceGraphic,+ kind: ColorMatrixKind::Matrix(vec![+ (0.393 + 0.607 * (1.0 - amount)),+ (0.769 - 0.769 * (1.0 - amount)),+ (0.189 - 0.189 * (1.0 - amount)),+ 0.0,+ 0.0,+ (0.349 - 0.349 * (1.0 - amount)),+ (0.686 + 0.314 * (1.0 - amount)),+ (0.168 - 0.168 * (1.0 - amount)),+ 0.0,+ 0.0,+ (0.272 - 0.272 * (1.0 - amount)),+ (0.534 - 0.534 * (1.0 - amount)),+ (0.131 + 0.869 * (1.0 - amount)),+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0,+ 0.0,+ ]),+ })+}++#[inline(never)]+fn convert_saturate_function(amount: f64) -> Kind {+ let amount = PositiveF32::new(amount as f32).unwrap_or(PositiveF32::ZERO);+ Kind::ColorMatrix(ColorMatrix {+ input: Input::SourceGraphic,+ kind: ColorMatrixKind::Saturate(amount),+ })+}++#[inline(never)]+fn convert_hue_rotate_function(amount: svgtypes::Angle) -> Kind {+ Kind::ColorMatrix(ColorMatrix {+ input: Input::SourceGraphic,+ kind: ColorMatrixKind::HueRotate(amount.to_degrees() as f32),+ })+}++#[inline(never)]+fn convert_invert_function(amount: f64) -> Kind {+ let amount = amount.min(1.0) as f32;+ Kind::ComponentTransfer(ComponentTransfer {+ input: Input::SourceGraphic,+ func_r: TransferFunction::Table(vec![amount, 1.0 - amount]),+ func_g: TransferFunction::Table(vec![amount, 1.0 - amount]),+ func_b: TransferFunction::Table(vec![amount, 1.0 - amount]),+ func_a: TransferFunction::Identity,+ })+}++#[inline(never)]+fn convert_opacity_function(amount: f64) -> Kind {+ let amount = amount.min(1.0) as f32;+ Kind::ComponentTransfer(ComponentTransfer {+ input: Input::SourceGraphic,+ func_r: TransferFunction::Identity,+ func_g: TransferFunction::Identity,+ func_b: TransferFunction::Identity,+ func_a: TransferFunction::Table(vec![0.0, amount]),+ })+}++#[inline(never)]+fn convert_brightness_function(amount: f64) -> Kind {+ let amount = amount as f32;+ Kind::ComponentTransfer(ComponentTransfer {+ input: Input::SourceGraphic,+ func_r: TransferFunction::Linear {+ slope: amount,+ intercept: 0.0,+ },+ func_g: TransferFunction::Linear {+ slope: amount,+ intercept: 0.0,+ },+ func_b: TransferFunction::Linear {+ slope: amount,+ intercept: 0.0,+ },+ func_a: TransferFunction::Identity,+ })+}++#[inline(never)]+fn convert_contrast_function(amount: f64) -> Kind {+ let amount = amount as f32;+ Kind::ComponentTransfer(ComponentTransfer {+ input: Input::SourceGraphic,+ func_r: TransferFunction::Linear {+ slope: amount,+ intercept: -(0.5 * amount) + 0.5,+ },+ func_g: TransferFunction::Linear {+ slope: amount,+ intercept: -(0.5 * amount) + 0.5,+ },+ func_b: TransferFunction::Linear {+ slope: amount,+ intercept: -(0.5 * amount) + 0.5,+ },+ func_a: TransferFunction::Identity,+ })+}++#[inline(never)]+fn convert_blur_function(node: SvgNode, std_dev: Length, state: &converter::State) -> Kind {+ let std_dev = PositiveF32::new(super::units::convert_user_length(+ std_dev,+ node,+ AId::Dx,+ state,+ ))+ .unwrap_or(PositiveF32::ZERO);+ Kind::GaussianBlur(GaussianBlur {+ input: Input::SourceGraphic,+ std_dev_x: std_dev,+ std_dev_y: std_dev,+ })+}++#[inline(never)]+fn convert_drop_shadow_function(+ node: SvgNode,+ color: Option<svgtypes::Color>,+ dx: Length,+ dy: Length,+ std_dev: Length,+ state: &converter::State,+) -> Kind {+ let std_dev = PositiveF32::new(super::units::convert_user_length(+ std_dev,+ node,+ AId::Dx,+ state,+ ))+ .unwrap_or(PositiveF32::ZERO);++ let (color, opacity) = color+ .unwrap_or_else(|| {+ node.find_attribute(AId::Color)+ .unwrap_or_else(svgtypes::Color::black)+ })+ .split_alpha();++ Kind::DropShadow(DropShadow {+ input: Input::SourceGraphic,+ dx: super::units::convert_user_length(dx, node, AId::Dx, state),+ dy: super::units::convert_user_length(dy, node, AId::Dy, state),+ std_dev_x: std_dev,+ std_dev_y: std_dev,+ color,+ opacity,+ })+}diff --git a/vendor/usvg/src/parser/image.rs b/vendor/usvg/src/parser/image.rsnew file mode 100644index 00000000..35a908b9--- /dev/null+++ b/vendor/usvg/src/parser/image.rs@@ -0,0 +1,348 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::sync::Arc;++use svgtypes::{AspectRatio, Length};++use super::svgtree::{AId, SvgNode};+use super::{OptionLog, Options, converter};+use crate::{+ ClipPath, Group, Image, ImageKind, ImageRendering, Node, NonZeroRect, Path, Size, Transform,+ Tree, Visibility,+};++/// A shorthand for [ImageHrefResolver]'s data function.+pub type ImageHrefDataResolverFn<'a> =+ Box<dyn Fn(&str, Arc<Vec<u8>>, &Options) -> Option<ImageKind> + Send + Sync + 'a>;++/// A shorthand for [ImageHrefResolver]'s string function.+pub type ImageHrefStringResolverFn<'a> =+ Box<dyn Fn(&str, &Options) -> Option<ImageKind> + Send + Sync + 'a>;++/// An `xlink:href` resolver for `<image>` elements.+///+/// This type can be useful if you want to have an alternative `xlink:href` handling+/// to the default one. For example, you can forbid access to local files (which is allowed by default)+/// or add support for resolving actual URLs (usvg doesn't do any network requests).+pub struct ImageHrefResolver<'a> {+ /// Resolver function that will be used when `xlink:href` contains a+ /// [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs).+ ///+ /// A function would be called with mime, decoded base64 data and parsing options.+ pub resolve_data: ImageHrefDataResolverFn<'a>,++ /// Resolver function that will be used to handle an arbitrary string in `xlink:href`.+ pub resolve_string: ImageHrefStringResolverFn<'a>,+}++impl Default for ImageHrefResolver<'_> {+ fn default() -> Self {+ ImageHrefResolver {+ resolve_data: ImageHrefResolver::default_data_resolver(),+ resolve_string: ImageHrefResolver::default_string_resolver(),+ }+ }+}++impl ImageHrefResolver<'_> {+ /// Creates a default+ /// [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs)+ /// resolver closure.+ ///+ /// base64 encoded data is already decoded.+ ///+ /// The default implementation would try to load JPEG, PNG, GIF, WebP, SVG and SVGZ types.+ /// Note that it will simply match the `mime` or data's magic.+ /// The actual images would not be decoded. It's up to the renderer.+ pub fn default_data_resolver() -> ImageHrefDataResolverFn<'static> {+ Box::new(+ move |mime: &str, data: Arc<Vec<u8>>, opts: &Options| match mime {+ "image/jpg" | "image/jpeg" => Some(ImageKind::JPEG(data)),+ "image/png" => Some(ImageKind::PNG(data)),+ "image/gif" => Some(ImageKind::GIF(data)),+ "image/webp" => Some(ImageKind::WEBP(data)),+ "image/svg+xml" => load_sub_svg(&data, opts),+ "text/plain" => match get_image_data_format(&data) {+ Some(ImageFormat::JPEG) => Some(ImageKind::JPEG(data)),+ Some(ImageFormat::PNG) => Some(ImageKind::PNG(data)),+ Some(ImageFormat::GIF) => Some(ImageKind::GIF(data)),+ Some(ImageFormat::WEBP) => Some(ImageKind::WEBP(data)),+ _ => load_sub_svg(&data, opts),+ },+ _ => None,+ },+ )+ }++ /// Creates a default string resolver.+ ///+ /// The default implementation treats an input string as a file path and tries to open.+ /// If a string is an URL or something else it would be ignored.+ ///+ /// Paths have to be absolute or relative to the input SVG file or relative to+ /// [Options::resources_dir](crate::Options::resources_dir).+ pub fn default_string_resolver() -> ImageHrefStringResolverFn<'static> {+ Box::new(move |href: &str, opts: &Options| {+ let path = opts.get_abs_path(std::path::Path::new(href));++ if path.exists() {+ let data = match std::fs::read(&path) {+ Ok(data) => data,+ Err(_) => {+ log::warn!("Failed to load '{}'. Skipped.", href);+ return None;+ }+ };++ match get_image_file_format(&path, &data) {+ Some(ImageFormat::JPEG) => Some(ImageKind::JPEG(Arc::new(data))),+ Some(ImageFormat::PNG) => Some(ImageKind::PNG(Arc::new(data))),+ Some(ImageFormat::GIF) => Some(ImageKind::GIF(Arc::new(data))),+ Some(ImageFormat::WEBP) => Some(ImageKind::WEBP(Arc::new(data))),+ Some(ImageFormat::SVG) => load_sub_svg(&data, opts),+ _ => {+ log::warn!("'{}' is not a PNG, JPEG, GIF, WebP or SVG(Z) image.", href);+ None+ }+ }+ } else {+ log::warn!("'{}' is not a path to an image.", href);+ None+ }+ })+ }+}++impl std::fmt::Debug for ImageHrefResolver<'_> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("ImageHrefResolver { .. }")+ }+}++#[derive(Clone, Copy, PartialEq, Debug)]+enum ImageFormat {+ PNG,+ JPEG,+ GIF,+ WEBP,+ SVG,+}++pub(crate) fn convert(+ node: SvgNode,+ state: &converter::State,+ cache: &mut converter::Cache,+ parent: &mut Group,+) -> Option<()> {+ let href = node+ .try_attribute(AId::Href)+ .log_none(|| log::warn!("Image lacks the 'xlink:href' attribute. Skipped."))?;++ let kind = get_href_data(href, state)?;++ let visibility: Visibility = node.find_attribute(AId::Visibility).unwrap_or_default();+ let visible = visibility == Visibility::Visible;++ let rendering_mode = node+ .find_attribute(AId::ImageRendering)+ .unwrap_or(state.opt.image_rendering);++ // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.+ let id = if state.parent_markers.is_empty() {+ node.element_id().to_string()+ } else {+ String::new()+ };++ let actual_size = kind.actual_size()?;++ let x = node.convert_user_length(AId::X, state, Length::zero());+ let y = node.convert_user_length(AId::Y, state, Length::zero());+ let mut width = node.convert_user_length(+ AId::Width,+ state,+ Length::new_number(actual_size.width() as f64),+ );+ let mut height = node.convert_user_length(+ AId::Height,+ state,+ Length::new_number(actual_size.height() as f64),+ );++ match (+ node.attribute::<Length>(AId::Width),+ node.attribute::<Length>(AId::Height),+ ) {+ (Some(_), None) => {+ // Only width was defined, so we need to scale height accordingly.+ height = actual_size.height() * (width / actual_size.width());+ }+ (None, Some(_)) => {+ // Only height was defined, so we need to scale width accordingly.+ width = actual_size.width() * (height / actual_size.height());+ }+ _ => {}+ };++ let aspect: AspectRatio = node.attribute(AId::PreserveAspectRatio).unwrap_or_default();++ let rect = NonZeroRect::from_xywh(x, y, width, height);+ let rect = rect.log_none(|| log::warn!("Image has an invalid size. Skipped."))?;++ convert_inner(+ kind,+ id,+ visible,+ rendering_mode,+ aspect,+ actual_size,+ rect,+ cache,+ parent,+ )+}++pub(crate) fn convert_inner(+ kind: ImageKind,+ id: String,+ visible: bool,+ rendering_mode: ImageRendering,+ aspect: AspectRatio,+ actual_size: Size,+ rect: NonZeroRect,+ cache: &mut converter::Cache,+ parent: &mut Group,+) -> Option<()> {+ let aligned_size = fit_view_box(actual_size, rect, aspect);+ let (aligned_x, aligned_y) = crate::aligned_pos(+ aspect.align,+ rect.x(),+ rect.y(),+ rect.width() - aligned_size.width(),+ rect.height() - aligned_size.height(),+ );+ let view_box = aligned_size.to_non_zero_rect(aligned_x, aligned_y);++ let image_ts = Transform::from_row(+ view_box.width() / actual_size.width(),+ 0.0,+ 0.0,+ view_box.height() / actual_size.height(),+ view_box.x(),+ view_box.y(),+ );++ let abs_transform = parent.abs_transform.pre_concat(image_ts);+ let abs_bounding_box = view_box.transform(parent.abs_transform)?;++ let mut g = Group::empty();+ g.id = id;+ g.children.push(Node::Image(Box::new(Image {+ id: String::new(),+ visible,+ size: actual_size,+ rendering_mode,+ kind,+ abs_transform,+ abs_bounding_box,+ })));+ g.transform = image_ts;+ g.abs_transform = abs_transform;+ g.calculate_bounding_boxes();++ if aspect.slice {+ // Image slice acts like a rectangular clip.+ let mut path = Path::new_simple(Arc::new(tiny_skia_path::PathBuilder::from_rect(+ rect.to_rect(),+ )))+ .unwrap();+ path.fill = Some(crate::Fill::default());++ let mut clip = ClipPath::empty(cache.gen_clip_path_id());+ clip.root.children.push(Node::Path(Box::new(path)));++ // Clip path should not be affected by the image viewbox transform.+ // The final structure should look like:+ // <g clip-path="url(#clipPath1)">+ // <g transform="matrix(1 0 0 1 10 20)">+ // <image/>+ // </g>+ // </g>++ let mut g2 = Group::empty();+ std::mem::swap(&mut g.id, &mut g2.id);+ g2.abs_transform = parent.abs_transform;+ g2.clip_path = Some(Arc::new(clip));+ g2.children.push(Node::Group(Box::new(g)));+ g2.calculate_bounding_boxes();++ parent.children.push(Node::Group(Box::new(g2)));+ } else {+ parent.children.push(Node::Group(Box::new(g)));+ }++ Some(())+}++pub(crate) fn get_href_data(href: &str, state: &converter::State) -> Option<ImageKind> {+ if let Ok(url) = data_url::DataUrl::process(href) {+ let (data, _) = url.decode_to_vec().ok()?;++ let mime = format!(+ "{}/{}",+ url.mime_type().type_.as_str(),+ url.mime_type().subtype.as_str()+ );++ (state.opt.image_href_resolver.resolve_data)(&mime, Arc::new(data), state.opt)+ } else {+ (state.opt.image_href_resolver.resolve_string)(href, state.opt)+ }+}++/// Checks that file has a PNG, a GIF, a JPEG or a WebP magic bytes.+/// Or an SVG(Z) extension.+fn get_image_file_format(path: &std::path::Path, data: &[u8]) -> Option<ImageFormat> {+ let ext = path.extension().and_then(|e| e.to_str())?.to_lowercase();+ if ext == "svg" || ext == "svgz" {+ return Some(ImageFormat::SVG);+ }++ get_image_data_format(data)+}++/// Checks that file has a PNG, a GIF, a JPEG or a WebP magic bytes.+fn get_image_data_format(data: &[u8]) -> Option<ImageFormat> {+ match imagesize::image_type(data).ok()? {+ imagesize::ImageType::Gif => Some(ImageFormat::GIF),+ imagesize::ImageType::Jpeg => Some(ImageFormat::JPEG),+ imagesize::ImageType::Png => Some(ImageFormat::PNG),+ imagesize::ImageType::Webp => Some(ImageFormat::WEBP),+ _ => None,+ }+}++/// Tries to load the `ImageData` content as an SVG image or emits a warning and returns `None`.+pub(crate) fn load_sub_svg(data: &[u8], opt: &Options) -> Option<ImageKind> {+ match Tree::from_data_nested(data, opt) {+ Ok(tree) => Some(ImageKind::SVG(tree)),+ Err(_) => {+ log::warn!("Failed to load nested SVG image.");+ None+ }+ }+}++/// Fits size into a viewbox.+fn fit_view_box(size: Size, rect: NonZeroRect, aspect: AspectRatio) -> Size {+ let s = rect.size();++ if aspect.align == svgtypes::Align::None {+ s+ } else if aspect.slice {+ size.expand_to(s)+ } else {+ size.scale_to(s)+ }+}diff --git a/vendor/usvg/src/parser/marker.rs b/vendor/usvg/src/parser/marker.rsnew file mode 100644index 00000000..dd9ab33e--- /dev/null+++ b/vendor/usvg/src/parser/marker.rs@@ -0,0 +1,489 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::sync::Arc;++use strict_num::NonZeroPositiveF32;+use svgtypes::Length;+use tiny_skia_path::Point;++use super::converter;+use super::svgtree::{AId, EId, SvgNode};+use crate::{+ ApproxEqUlps, ApproxZeroUlps, ClipPath, Fill, Group, Node, NonZeroRect, Path, Size, Transform,+ ViewBox,+};++// Similar to `tiny_skia_path::PathSegment`, but without the `QuadTo`.+#[derive(Copy, Clone, Debug)]+enum Segment {+ MoveTo(Point),+ LineTo(Point),+ CubicTo(Point, Point, Point),+ Close,+}++pub(crate) fn is_valid(node: SvgNode) -> bool {+ // `marker-*` attributes cannot be set on shapes inside a `clipPath`.+ if node+ .ancestors()+ .any(|n| n.tag_name() == Some(EId::ClipPath))+ {+ return false;+ }++ let start = node.find_attribute::<SvgNode>(AId::MarkerStart);+ let mid = node.find_attribute::<SvgNode>(AId::MarkerMid);+ let end = node.find_attribute::<SvgNode>(AId::MarkerEnd);+ start.is_some() || mid.is_some() || end.is_some()+}++pub(crate) fn convert(+ node: SvgNode,+ path: &tiny_skia_path::Path,+ state: &converter::State,+ cache: &mut converter::Cache,+ parent: &mut Group,+) {+ let list = [+ (AId::MarkerStart, MarkerKind::Start),+ (AId::MarkerMid, MarkerKind::Middle),+ (AId::MarkerEnd, MarkerKind::End),+ ];++ for (aid, kind) in &list {+ let mut marker = None;+ if let Some(link) = node.find_attribute::<SvgNode>(*aid) {+ if link.tag_name() == Some(EId::Marker) {+ marker = Some(link);+ }+ }++ if let Some(marker) = marker {+ // TODO: move to svgtree+ // Check for recursive marker.+ if state.parent_markers.contains(&marker) {+ log::warn!("Recursive marker detected: {}", marker.element_id());+ continue;+ }++ resolve(node, path, marker, *kind, state, cache, parent);+ }+ }+}++#[derive(Clone, Copy)]+enum MarkerKind {+ Start,+ Middle,+ End,+}++enum MarkerOrientation {+ Auto,+ AutoStartReverse,+ Angle(f32),+}++fn resolve(+ shape_node: SvgNode,+ path: &tiny_skia_path::Path,+ marker_node: SvgNode,+ marker_kind: MarkerKind,+ state: &converter::State,+ cache: &mut converter::Cache,+ parent: &mut Group,+) -> Option<()> {+ let stroke_scale = stroke_scale(shape_node, marker_node, state)?.get();++ let r = convert_rect(marker_node, state)?;++ let view_box = marker_node.parse_viewbox().map(|vb| ViewBox {+ rect: vb,+ aspect: marker_node+ .attribute(AId::PreserveAspectRatio)+ .unwrap_or_default(),+ });++ let has_overflow = {+ let overflow = marker_node.attribute(AId::Overflow);+ // `overflow` is `hidden` by default.+ overflow.is_none() || overflow == Some("hidden") || overflow == Some("scroll")+ };++ let clip_path = if has_overflow {+ let clip_rect = if let Some(vbox) = view_box {+ vbox.rect+ } else {+ r.size().to_non_zero_rect(0.0, 0.0)+ };++ let mut clip_path = ClipPath::empty(cache.gen_clip_path_id());++ let mut path = Path::new_simple(Arc::new(tiny_skia_path::PathBuilder::from_rect(+ clip_rect.to_rect(),+ )))?;+ path.fill = Some(Fill::default());++ clip_path.root.children.push(Node::Path(Box::new(path)));++ Some(Arc::new(clip_path))+ } else {+ None+ };++ // TODO: avoid allocation+ let mut segments: Vec<Segment> = Vec::with_capacity(path.len());+ let mut prev = Point::zero();+ let mut prev_move = Point::zero();+ for seg in path.segments() {+ match seg {+ tiny_skia_path::PathSegment::MoveTo(p) => {+ segments.push(Segment::MoveTo(p));+ prev = p;+ prev_move = p;+ }+ tiny_skia_path::PathSegment::LineTo(p) => {+ segments.push(Segment::LineTo(p));+ prev = p;+ }+ tiny_skia_path::PathSegment::QuadTo(p1, p) => {+ let (p1, p2, p) = quad_to_curve(prev, p1, p);+ segments.push(Segment::CubicTo(p1, p2, p));+ prev = p;+ }+ tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => {+ segments.push(Segment::CubicTo(p1, p2, p));+ prev = p;+ }+ tiny_skia_path::PathSegment::Close => {+ segments.push(Segment::Close);+ prev = prev_move;+ }+ }+ }++ let draw_marker = |p: tiny_skia_path::Point, idx: usize| {+ let mut ts = Transform::from_translate(p.x, p.y);++ let angle = match convert_orientation(marker_node) {+ MarkerOrientation::AutoStartReverse if idx == 0 => {+ (calc_vertex_angle(&segments, idx) + 180.0) % 360.0+ }+ MarkerOrientation::Auto | MarkerOrientation::AutoStartReverse => {+ calc_vertex_angle(&segments, idx)+ }+ MarkerOrientation::Angle(angle) => angle,+ };++ if !angle.approx_zero_ulps(4) {+ ts = ts.pre_rotate(angle);+ }++ if let Some(vbox) = view_box {+ let size = Size::from_wh(r.width() * stroke_scale, r.height() * stroke_scale).unwrap();+ let vbox_ts = vbox.to_transform(size);+ let (sx, sy) = vbox_ts.get_scale();+ ts = ts.pre_scale(sx, sy);+ } else {+ ts = ts.pre_scale(stroke_scale, stroke_scale);+ }++ ts = ts.pre_translate(-r.x(), -r.y());++ // TODO: do not create a group when no clipPath+ let mut g = Group {+ transform: ts,+ abs_transform: parent.abs_transform.pre_concat(ts),+ clip_path: clip_path.clone(),+ ..Group::empty()+ };++ let mut marker_state = state.clone();+ marker_state.parent_markers.push(marker_node);+ converter::convert_children(marker_node, &marker_state, cache, &mut g);+ g.calculate_bounding_boxes();++ if g.has_children() {+ parent.children.push(Node::Group(Box::new(g)));+ }+ };++ draw_markers(&segments, marker_kind, draw_marker);++ Some(())+}++fn stroke_scale(+ path_node: SvgNode,+ marker_node: SvgNode,+ state: &converter::State,+) -> Option<NonZeroPositiveF32> {+ match marker_node.attribute(AId::MarkerUnits) {+ Some("userSpaceOnUse") => NonZeroPositiveF32::new(1.0),+ _ => path_node.resolve_valid_length(AId::StrokeWidth, state, 1.0),+ }+}++fn draw_markers<P>(path: &[Segment], kind: MarkerKind, mut draw_marker: P)+where+ P: FnMut(tiny_skia_path::Point, usize),+{+ match kind {+ MarkerKind::Start => {+ if let Some(Segment::MoveTo(p)) = path.first().cloned() {+ draw_marker(p, 0);+ }+ }+ MarkerKind::Middle => {+ let total = path.len() - 1;+ let mut i = 1;+ while i < total {+ let p = match path[i] {+ Segment::MoveTo(p) => p,+ Segment::LineTo(p) => p,+ Segment::CubicTo(_, _, p) => p,+ _ => {+ i += 1;+ continue;+ }+ };++ draw_marker(p, i);++ i += 1;+ }+ }+ MarkerKind::End => {+ let idx = path.len() - 1;+ match path.last().cloned() {+ Some(Segment::LineTo(p)) => {+ draw_marker(p, idx);+ }+ Some(Segment::CubicTo(_, _, p)) => {+ draw_marker(p, idx);+ }+ Some(Segment::Close) => {+ let p = get_subpath_start(path, idx);+ draw_marker(p, idx);+ }+ _ => {}+ }+ }+ }+}++fn calc_vertex_angle(path: &[Segment], idx: usize) -> f32 {+ if idx == 0 {+ // First segment.++ debug_assert!(path.len() > 1);++ let seg1 = path[0];+ let seg2 = path[1];++ match (seg1, seg2) {+ (Segment::MoveTo(pm), Segment::LineTo(p)) => calc_line_angle(pm.x, pm.y, p.x, p.y),+ (Segment::MoveTo(pm), Segment::CubicTo(p1, _, p)) => {+ if pm.x.approx_eq_ulps(&p1.x, 4) && pm.y.approx_eq_ulps(&p1.y, 4) {+ calc_line_angle(pm.x, pm.y, p.x, p.y)+ } else {+ calc_line_angle(pm.x, pm.y, p1.x, p1.y)+ }+ }+ _ => 0.0,+ }+ } else if idx == path.len() - 1 {+ // Last segment.++ let seg1 = path[idx - 1];+ let seg2 = path[idx];++ match (seg1, seg2) {+ (_, Segment::MoveTo(_)) => 0.0, // unreachable+ (_, Segment::LineTo(p)) => {+ let prev = get_prev_vertex(path, idx);+ calc_line_angle(prev.x, prev.y, p.x, p.y)+ }+ (_, Segment::CubicTo(p1, p2, p)) => {+ if p2.x.approx_eq_ulps(&p.x, 4) && p2.y.approx_eq_ulps(&p.y, 4) {+ calc_line_angle(p1.x, p1.y, p.x, p.y)+ } else {+ calc_line_angle(p2.x, p2.y, p.x, p.y)+ }+ }+ (Segment::LineTo(p), Segment::Close) => {+ let next = get_subpath_start(path, idx);+ calc_line_angle(p.x, p.y, next.x, next.y)+ }+ (Segment::CubicTo(_, p2, p), Segment::Close) => {+ let prev = get_prev_vertex(path, idx);+ let next = get_subpath_start(path, idx);+ calc_curves_angle(+ prev.x, prev.y, p2.x, p2.y, p.x, p.y, next.x, next.y, next.x, next.y,+ )+ }+ (_, Segment::Close) => 0.0,+ }+ } else {+ // Middle segments.++ let seg1 = path[idx];+ let seg2 = path[idx + 1];++ // TODO: Not sure if there is a better way.+ match (seg1, seg2) {+ (Segment::MoveTo(pm), Segment::LineTo(p)) => calc_line_angle(pm.x, pm.y, p.x, p.y),+ (Segment::MoveTo(pm), Segment::CubicTo(p1, _, _)) => {+ calc_line_angle(pm.x, pm.y, p1.x, p1.y)+ }+ (Segment::LineTo(p1), Segment::LineTo(p2)) => {+ let prev = get_prev_vertex(path, idx);+ calc_angle(prev.x, prev.y, p1.x, p1.y, p1.x, p1.y, p2.x, p2.y)+ }+ (Segment::CubicTo(_, c1_p2, c1_p), Segment::CubicTo(c2_p1, _, c2_p)) => {+ let prev = get_prev_vertex(path, idx);+ calc_curves_angle(+ prev.x, prev.y, c1_p2.x, c1_p2.y, c1_p.x, c1_p.y, c2_p1.x, c2_p1.y, c2_p.x,+ c2_p.y,+ )+ }+ (Segment::LineTo(pl), Segment::CubicTo(p1, _, p)) => {+ let prev = get_prev_vertex(path, idx);+ calc_curves_angle(+ prev.x, prev.y, prev.x, prev.y, pl.x, pl.y, p1.x, p1.y, p.x, p.y,+ )+ }+ (Segment::CubicTo(_, p2, p), Segment::LineTo(pl)) => {+ let prev = get_prev_vertex(path, idx);+ calc_curves_angle(prev.x, prev.y, p2.x, p2.y, p.x, p.y, pl.x, pl.y, pl.x, pl.y)+ }+ (Segment::LineTo(p), Segment::MoveTo(_)) => {+ let prev = get_prev_vertex(path, idx);+ calc_line_angle(prev.x, prev.y, p.x, p.y)+ }+ (Segment::CubicTo(_, p2, p), Segment::MoveTo(_)) => {+ if p.x.approx_eq_ulps(&p2.x, 4) && p.y.approx_eq_ulps(&p2.y, 4) {+ let prev = get_prev_vertex(path, idx);+ calc_line_angle(prev.x, prev.y, p.x, p.y)+ } else {+ calc_line_angle(p2.x, p2.y, p.x, p.y)+ }+ }+ (Segment::LineTo(p), Segment::Close) => {+ let prev = get_prev_vertex(path, idx);+ let next = get_subpath_start(path, idx);+ calc_angle(prev.x, prev.y, p.x, p.y, p.x, p.y, next.x, next.y)+ }+ (_, Segment::Close) => {+ let prev = get_prev_vertex(path, idx);+ let next = get_subpath_start(path, idx);+ calc_line_angle(prev.x, prev.y, next.x, next.y)+ }+ (_, Segment::MoveTo(_)) | (Segment::Close, _) => 0.0,+ }+ }+}++fn calc_line_angle(x1: f32, y1: f32, x2: f32, y2: f32) -> f32 {+ calc_angle(x1, y1, x2, y2, x1, y1, x2, y2)+}++fn calc_curves_angle(+ px: f32,+ py: f32, // previous vertex+ cx1: f32,+ cy1: f32, // previous control point+ x: f32,+ y: f32, // current vertex+ cx2: f32,+ cy2: f32, // next control point+ nx: f32,+ ny: f32, // next vertex+) -> f32 {+ if cx1.approx_eq_ulps(&x, 4) && cy1.approx_eq_ulps(&y, 4) {+ calc_angle(px, py, x, y, x, y, cx2, cy2)+ } else if x.approx_eq_ulps(&cx2, 4) && y.approx_eq_ulps(&cy2, 4) {+ calc_angle(cx1, cy1, x, y, x, y, nx, ny)+ } else {+ calc_angle(cx1, cy1, x, y, x, y, cx2, cy2)+ }+}++fn calc_angle(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, x4: f32, y4: f32) -> f32 {+ use std::f32::consts::*;++ fn normalize(rad: f32) -> f32 {+ let v = rad % (PI * 2.0);+ if v < 0.0 { v + PI * 2.0 } else { v }+ }++ fn vector_angle(vx: f32, vy: f32) -> f32 {+ let rad = vy.atan2(vx);+ if rad.is_nan() { 0.0 } else { normalize(rad) }+ }++ let in_a = vector_angle(x2 - x1, y2 - y1);+ let out_a = vector_angle(x4 - x3, y4 - y3);+ let d = (out_a - in_a) * 0.5;++ let mut angle = in_a + d;+ if FRAC_PI_2 < d.abs() {+ angle -= PI;+ }++ normalize(angle).to_degrees()+}++fn get_subpath_start(segments: &[Segment], idx: usize) -> tiny_skia_path::Point {+ let offset = segments.len() - idx;+ for seg in segments.iter().rev().skip(offset) {+ if let Segment::MoveTo(p) = *seg {+ return p;+ }+ }++ tiny_skia_path::Point::zero()+}++fn get_prev_vertex(segments: &[Segment], idx: usize) -> tiny_skia_path::Point {+ match segments[idx - 1] {+ Segment::MoveTo(p) => p,+ Segment::LineTo(p) => p,+ Segment::CubicTo(_, _, p) => p,+ Segment::Close => get_subpath_start(segments, idx),+ }+}++fn convert_rect(node: SvgNode, state: &converter::State) -> Option<NonZeroRect> {+ NonZeroRect::from_xywh(+ node.convert_user_length(AId::RefX, state, Length::zero()),+ node.convert_user_length(AId::RefY, state, Length::zero()),+ node.convert_user_length(AId::MarkerWidth, state, Length::new_number(3.0)),+ node.convert_user_length(AId::MarkerHeight, state, Length::new_number(3.0)),+ )+}++fn convert_orientation(node: SvgNode) -> MarkerOrientation {+ match node.attribute(AId::Orient) {+ Some("auto") => MarkerOrientation::Auto,+ Some("auto-start-reverse") => MarkerOrientation::AutoStartReverse,+ _ => match node.attribute::<svgtypes::Angle>(AId::Orient) {+ Some(angle) => MarkerOrientation::Angle(angle.to_degrees() as f32),+ None => MarkerOrientation::Angle(0.0),+ },+ }+}++fn quad_to_curve(prev: Point, p1: Point, p: Point) -> (Point, Point, Point) {+ #[inline]+ fn calc(n1: f32, n2: f32) -> f32 {+ (n1 + n2 * 2.0) / 3.0+ }++ (+ Point::from_xy(calc(prev.x, p1.x), calc(prev.y, p1.y)),+ Point::from_xy(calc(p.x, p1.x), calc(p.y, p1.y)),+ p,+ )+}diff --git a/vendor/usvg/src/parser/mask.rs b/vendor/usvg/src/parser/mask.rsnew file mode 100644index 00000000..6e68e13d--- /dev/null+++ b/vendor/usvg/src/parser/mask.rs@@ -0,0 +1,150 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::sync::Arc;++use svgtypes::{Length, LengthUnit as Unit};++use super::svgtree::{AId, EId, SvgNode};+use super::{OptionLog, converter};+use crate::{Group, Mask, MaskType, Node, NonEmptyString, NonZeroRect, Transform, Units};++pub(crate) fn convert(+ node: SvgNode,+ state: &converter::State,+ object_bbox: Option<NonZeroRect>,+ cache: &mut converter::Cache,+) -> Option<Arc<Mask>> {+ // A `mask` attribute must reference a `mask` element.+ if node.tag_name() != Some(EId::Mask) {+ return None;+ }++ let units = node+ .attribute(AId::MaskUnits)+ .unwrap_or(Units::ObjectBoundingBox);++ let content_units = node+ .attribute(AId::MaskContentUnits)+ .unwrap_or(Units::UserSpaceOnUse);++ // Check if this element was already converted.+ //+ // Only `userSpaceOnUse` masks can be shared,+ // because `objectBoundingBox` one will be converted into user one+ // and will become node-specific.+ let cacheable = units == Units::UserSpaceOnUse && content_units == Units::UserSpaceOnUse;+ if cacheable {+ if let Some(mask) = cache.masks.get(node.element_id()) {+ return Some(mask.clone());+ }+ }++ let rect = NonZeroRect::from_xywh(+ node.convert_length(AId::X, units, state, Length::new(-10.0, Unit::Percent)),+ node.convert_length(AId::Y, units, state, Length::new(-10.0, Unit::Percent)),+ node.convert_length(AId::Width, units, state, Length::new(120.0, Unit::Percent)),+ node.convert_length(AId::Height, units, state, Length::new(120.0, Unit::Percent)),+ );+ let mut rect =+ rect.log_none(|| log::warn!("Mask '{}' has an invalid size. Skipped.", node.element_id()))?;++ let mut mask_all = false;+ if units == Units::ObjectBoundingBox {+ if let Some(bbox) = object_bbox {+ rect = rect.bbox_transform(bbox);+ } else {+ // When mask units are `objectBoundingBox` and bbox is zero-sized - the whole+ // element should be masked.+ // Technically an UB, but this is what Chrome and Firefox do.+ mask_all = true;+ }+ }++ let mut id = NonEmptyString::new(node.element_id().to_string())?;+ // Generate ID only when we're parsing `objectBoundingBox` mask for the second time.+ if !cacheable && cache.masks.contains_key(id.get()) {+ id = cache.gen_mask_id();+ }+ let id_copy = id.get().to_string();++ if mask_all {+ let mask = Arc::new(Mask {+ id,+ rect,+ kind: MaskType::Luminance,+ mask: None,+ root: Group::empty(),+ });+ cache.masks.insert(id_copy, mask.clone());+ return Some(mask);+ }++ // Resolve linked mask.+ let mut mask = None;+ if let Some(link) = node.attribute::<SvgNode>(AId::Mask) {+ mask = convert(link, state, object_bbox, cache);++ // Linked `mask` must be valid.+ if mask.is_none() {+ return None;+ }+ }++ let kind = if node.attribute(AId::MaskType) == Some("alpha") {+ MaskType::Alpha+ } else {+ MaskType::Luminance+ };++ let mut mask = Mask {+ id,+ rect,+ kind,+ mask,+ root: Group::empty(),+ };++ // To emulate content `objectBoundingBox` units we have to put+ // mask children into a group with a transform.+ let mut subroot = None;+ if content_units == Units::ObjectBoundingBox {+ let object_bbox = match object_bbox {+ Some(v) => v,+ None => {+ log::warn!("Masking of zero-sized shapes is not allowed.");+ return None;+ }+ };++ let mut g = Group::empty();+ g.transform = Transform::from_bbox(object_bbox);+ // Make sure to set `abs_transform`, because it must propagate to all children.+ g.abs_transform = g.transform;++ subroot = Some(g);+ }++ {+ // Prefer `subroot` to `mask.root`.+ let real_root = subroot.as_mut().unwrap_or(&mut mask.root);+ converter::convert_children(node, state, cache, real_root);++ // A mask without children at this point is invalid.+ // Only masks with zero bbox and `objectBoundingBox` can be empty.+ if !real_root.has_children() {+ return None;+ }+ }++ if let Some(mut subroot) = subroot {+ subroot.calculate_bounding_boxes();+ mask.root.children.push(Node::Group(Box::new(subroot)));+ }++ mask.root.calculate_bounding_boxes();++ let mask = Arc::new(mask);+ cache.masks.insert(id_copy, mask.clone());+ Some(mask)+}diff --git a/vendor/usvg/src/parser/mod.rs b/vendor/usvg/src/parser/mod.rsnew file mode 100644index 00000000..41d1b2d0--- /dev/null+++ b/vendor/usvg/src/parser/mod.rs@@ -0,0 +1,204 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++mod clippath;+mod converter;+mod filter;+mod image;+mod marker;+mod mask;+mod options;+mod paint_server;+mod shapes;+mod style;+mod svgtree;+mod switch;+mod units;+mod use_node;++#[cfg(feature = "text")]+mod text;+#[cfg(feature = "text")]+pub(crate) use converter::Cache;+pub use image::{ImageHrefDataResolverFn, ImageHrefResolver, ImageHrefStringResolverFn};+pub use options::Options;+#[cfg(feature = "writer")]+pub(crate) use svgtree::{AId, EId};++/// List of all errors.+#[derive(Debug)]+pub enum Error {+ /// Only UTF-8 content are supported.+ NotAnUtf8Str,++ /// `svgz` feature is required to parse SVGZ data.+ SvgzFeatureNotEnabled,++ /// Compressed SVG must use the GZip algorithm.+ MalformedGZip,++ /// We do not allow SVG with more than 1_000_000 elements for security reasons.+ ElementsLimitReached,++ /// SVG doesn't have a valid size.+ ///+ /// Occurs when width and/or height are <= 0.+ ///+ /// Also occurs if width, height and viewBox are not set.+ InvalidSize,++ /// Failed to parse an SVG data.+ ParsingFailed(roxmltree::Error),+}++impl From<roxmltree::Error> for Error {+ fn from(e: roxmltree::Error) -> Self {+ Error::ParsingFailed(e)+ }+}++impl std::fmt::Display for Error {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ match *self {+ Error::NotAnUtf8Str => {+ write!(f, "provided data has not an UTF-8 encoding")+ }+ Self::SvgzFeatureNotEnabled => {+ write!(f, "enable svgz cargo feature to decode SVGZ data")+ }+ Error::MalformedGZip => {+ write!(f, "provided data has a malformed GZip content")+ }+ Error::ElementsLimitReached => {+ write!(f, "the maximum number of SVG elements has been reached")+ }+ Error::InvalidSize => {+ write!(f, "SVG has an invalid size")+ }+ Error::ParsingFailed(ref e) => {+ write!(f, "SVG data parsing failed cause {}", e)+ }+ }+ }+}++impl std::error::Error for Error {}++pub(crate) trait OptionLog {+ fn log_none<F: FnOnce()>(self, f: F) -> Self;+}++impl<T> OptionLog for Option<T> {+ #[inline]+ fn log_none<F: FnOnce()>(self, f: F) -> Self {+ self.or_else(|| {+ f();+ None+ })+ }+}++impl crate::Tree {+ /// Parses `Tree` from an SVG data.+ ///+ /// Can contain an SVG string or a gzip compressed data.+ pub fn from_data(data: &[u8], opt: &Options) -> Result<Self, Error> {+ if data.starts_with(&[0x1f, 0x8b]) {+ #[cfg(feature = "svgz")]+ {+ let data = decompress_svgz(data)?;+ let text = std::str::from_utf8(&data).map_err(|_| Error::NotAnUtf8Str)?;+ Self::from_str(text, opt)+ }++ #[cfg(not(feature = "svgz"))]+ Err(Error::SvgzFeatureNotEnabled)+ } else {+ let text = std::str::from_utf8(data).map_err(|_| Error::NotAnUtf8Str)?;+ Self::from_str(text, opt)+ }+ }++ /// Similar to the `from_data` method, except that it ignores all `image` elements linking to+ /// external files, as required by the SVG specification when SVG files are loaded+ /// for `<image href="..." />` tags.+ pub fn from_data_nested(data: &[u8], opt: &Options) -> Result<Self, Error> {+ let nested_opt = Options {+ resources_dir: None,+ dpi: opt.dpi,+ font_size: opt.font_size,+ languages: opt.languages.clone(),+ shape_rendering: opt.shape_rendering,+ text_rendering: opt.text_rendering,+ image_rendering: opt.image_rendering,+ default_size: opt.default_size,+ image_href_resolver: ImageHrefResolver {+ resolve_data: Box::new(|a, b, c| (opt.image_href_resolver.resolve_data)(a, b, c)),+ // External images should be ignored.+ resolve_string: Box::new(|_, _| None),+ },+ // In the referenced SVG, we start with the unmodified user-provided+ // fontdb, not the one from the cache.+ #[cfg(feature = "text")]+ fontdb: opt.fontdb.clone(),+ // Can't clone the resolver, so we create a new one that forwards to it.+ #[cfg(feature = "text")]+ font_resolver: crate::FontResolver {+ select_font: Box::new(|font, db| (opt.font_resolver.select_font)(font, db)),+ select_fallback: Box::new(|c, used_fonts, db| {+ (opt.font_resolver.select_fallback)(c, used_fonts, db)+ }),+ },+ ..Options::default()+ };++ Self::from_data(data, &nested_opt)+ }++ /// Parses `Tree` from an SVG string.+ pub fn from_str(text: &str, opt: &Options) -> Result<Self, Error> {+ let xml_opt = roxmltree::ParsingOptions {+ allow_dtd: true,+ ..Default::default()+ };++ let doc =+ roxmltree::Document::parse_with_options(text, xml_opt).map_err(Error::ParsingFailed)?;++ Self::from_xmltree(&doc, opt)+ }++ /// Parses `Tree` from `roxmltree::Document`.+ pub fn from_xmltree(doc: &roxmltree::Document, opt: &Options) -> Result<Self, Error> {+ let doc = svgtree::Document::parse_tree(doc, opt.style_sheet.as_deref())?;+ self::converter::convert_doc(&doc, opt)+ }+}++/// Decompresses an SVGZ file.+#[cfg(feature = "svgz")]+pub fn decompress_svgz(data: &[u8]) -> Result<Vec<u8>, Error> {+ use std::io::Read;++ let mut decoder = flate2::read::GzDecoder::new(data);+ let mut decoded = Vec::with_capacity(data.len() * 2);+ decoder+ .read_to_end(&mut decoded)+ .map_err(|_| Error::MalformedGZip)?;+ Ok(decoded)+}++#[inline]+pub(crate) fn f32_bound(min: f32, val: f32, max: f32) -> f32 {+ debug_assert!(min.is_finite());+ debug_assert!(max.is_finite());++ if val > max {+ max+ } else if val >= min {+ val+ } else {+ // Catches `val < min` as well as a NaN `val`.+ min+ }+}diff --git a/vendor/usvg/src/parser/options.rs b/vendor/usvg/src/parser/options.rsnew file mode 100644index 00000000..fcf70b11--- /dev/null+++ b/vendor/usvg/src/parser/options.rs@@ -0,0 +1,144 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++#[cfg(feature = "text")]+use std::sync::Arc;++#[cfg(feature = "text")]+use crate::FontResolver;+use crate::{ImageHrefResolver, ImageRendering, ShapeRendering, Size, TextRendering};++/// Processing options.+#[derive(Debug)]+pub struct Options<'a> {+ /// Directory that will be used during relative paths resolving.+ ///+ /// Expected to be the same as the directory that contains the SVG file,+ /// but can be set to any.+ ///+ /// Default: `None`+ pub resources_dir: Option<std::path::PathBuf>,++ /// Target DPI.+ ///+ /// Impacts units conversion.+ ///+ /// Default: 96.0+ pub dpi: f32,++ /// A default font family.+ ///+ /// Will be used when no `font-family` attribute is set in the SVG.+ ///+ /// Default: Times New Roman+ pub font_family: String,++ /// A default font size.+ ///+ /// Will be used when no `font-size` attribute is set in the SVG.+ ///+ /// Default: 12+ pub font_size: f32,++ /// A list of languages.+ ///+ /// Will be used to resolve a `systemLanguage` conditional attribute.+ ///+ /// Format: en, en-US.+ ///+ /// Default: `[en]`+ pub languages: Vec<String>,++ /// Specifies the default shape rendering method.+ ///+ /// Will be used when an SVG element's `shape-rendering` property is set to `auto`.+ ///+ /// Default: GeometricPrecision+ pub shape_rendering: ShapeRendering,++ /// Specifies the default text rendering method.+ ///+ /// Will be used when an SVG element's `text-rendering` property is set to `auto`.+ ///+ /// Default: OptimizeLegibility+ pub text_rendering: TextRendering,++ /// Specifies the default image rendering method.+ ///+ /// Will be used when an SVG element's `image-rendering` property is set to `auto`.+ ///+ /// Default: OptimizeQuality+ pub image_rendering: ImageRendering,++ /// Default viewport size to assume if there is no `viewBox` attribute and+ /// the `width` or `height` attributes are relative.+ ///+ /// Default: `(100, 100)`+ pub default_size: Size,++ /// Specifies the way `xlink:href` in `<image>` elements should be handled.+ ///+ /// Default: see type's documentation for details+ pub image_href_resolver: ImageHrefResolver<'a>,++ /// Specifies how fonts should be resolved and loaded.+ #[cfg(feature = "text")]+ pub font_resolver: FontResolver<'a>,++ /// A database of fonts usable by text.+ ///+ /// This is a base database. If a custom `font_resolver` is specified,+ /// additional fonts can be loaded during parsing. Those will be added to a+ /// copy of this database. The full database containing all fonts referenced+ /// in a `Tree` becomes available as [`Tree::fontdb`](crate::Tree::fontdb)+ /// after parsing. If no fonts were loaded dynamically, that database will+ /// be the same as this one.+ #[cfg(feature = "text")]+ pub fontdb: Arc<fontdb::Database>,+ /// A CSS stylesheet that should be injected into the SVG. Can be used to overwrite+ /// certain attributes.+ pub style_sheet: Option<String>,+}++impl Default for Options<'_> {+ fn default() -> Options<'static> {+ Options {+ resources_dir: None,+ dpi: 96.0,+ // Default font is user-agent dependent so we can use whichever we like.+ font_family: "Times New Roman".to_owned(),+ font_size: 12.0,+ languages: vec!["en".to_string()],+ shape_rendering: ShapeRendering::default(),+ text_rendering: TextRendering::default(),+ image_rendering: ImageRendering::default(),+ default_size: Size::from_wh(100.0, 100.0).unwrap(),+ image_href_resolver: ImageHrefResolver::default(),+ #[cfg(feature = "text")]+ font_resolver: FontResolver::default(),+ #[cfg(feature = "text")]+ fontdb: Arc::new(fontdb::Database::new()),+ style_sheet: None,+ }+ }+}++impl Options<'_> {+ /// Converts a relative path into absolute relative to the SVG file itself.+ ///+ /// If `Options::resources_dir` is not set, returns itself.+ pub fn get_abs_path(&self, rel_path: &std::path::Path) -> std::path::PathBuf {+ match self.resources_dir {+ Some(ref dir) => dir.join(rel_path),+ None => rel_path.into(),+ }+ }++ /// Mutably acquires the database.+ ///+ /// This clones the database if it is currently shared.+ #[cfg(feature = "text")]+ pub fn fontdb_mut(&mut self) -> &mut fontdb::Database {+ Arc::make_mut(&mut self.fontdb)+ }+}diff --git a/vendor/usvg/src/parser/paint_server.rs b/vendor/usvg/src/parser/paint_server.rsnew file mode 100644index 00000000..3102899b--- /dev/null+++ b/vendor/usvg/src/parser/paint_server.rs@@ -0,0 +1,1092 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::str::FromStr;+use std::sync::Arc;++use strict_num::PositiveF32;+use svgtypes::{Length, LengthUnit as Unit};++use super::OptionLog;+use super::converter::{self, Cache, SvgColorExt};+use super::svgtree::{AId, EId, SvgNode};+use crate::*;++pub(crate) enum ServerOrColor {+ Server(Paint),+ Color { color: Color, opacity: Opacity },+}++pub(crate) fn convert(+ node: SvgNode,+ state: &converter::State,+ cache: &mut converter::Cache,+) -> Option<ServerOrColor> {+ // Check for existing.+ if let Some(paint) = cache.paint.get(node.element_id()) {+ return Some(ServerOrColor::Server(paint.clone()));+ }++ // Unwrap is safe, because we already checked for is_paint_server().+ let paint = match node.tag_name().unwrap() {+ EId::LinearGradient => convert_linear(node, state),+ EId::RadialGradient => convert_radial(node, state),+ EId::Pattern => convert_pattern(node, state, cache),+ _ => unreachable!(),+ };++ if let Some(ServerOrColor::Server(paint)) = &paint {+ cache+ .paint+ .insert(node.element_id().to_string(), paint.clone());+ }++ paint+}++#[inline(never)]+fn convert_linear(node: SvgNode, state: &converter::State) -> Option<ServerOrColor> {+ let id = NonEmptyString::new(node.element_id().to_string())?;++ let stops = convert_stops(find_gradient_with_stops(node)?);+ if stops.len() < 2 {+ return stops_to_color(&stops);+ }++ let units = convert_units(node, AId::GradientUnits, Units::ObjectBoundingBox);+ let transform = node.resolve_transform(AId::GradientTransform, state);++ let gradient = LinearGradient {+ x1: resolve_number(node, AId::X1, units, state, Length::zero()),+ y1: resolve_number(node, AId::Y1, units, state, Length::zero()),+ x2: resolve_number(+ node,+ AId::X2,+ units,+ state,+ Length::new(100.0, Unit::Percent),+ ),+ y2: resolve_number(node, AId::Y2, units, state, Length::zero()),+ base: BaseGradient {+ id,+ units,+ transform,+ spread_method: convert_spread_method(node),+ stops,+ },+ };++ Some(ServerOrColor::Server(Paint::LinearGradient(Arc::new(+ gradient,+ ))))+}++#[inline(never)]+fn convert_radial(node: SvgNode, state: &converter::State) -> Option<ServerOrColor> {+ let id = NonEmptyString::new(node.element_id().to_string())?;++ let stops = convert_stops(find_gradient_with_stops(node)?);+ if stops.len() < 2 {+ return stops_to_color(&stops);+ }++ let units = convert_units(node, AId::GradientUnits, Units::ObjectBoundingBox);+ let r = resolve_number(node, AId::R, units, state, Length::new(50.0, Unit::Percent));+ let fr = resolve_number(node, AId::Fr, units, state, Length::zero());++ // 'A value of zero will cause the area to be painted as a single color+ // using the color and opacity of the last gradient stop.'+ //+ // https://www.w3.org/TR/SVG11/pservers.html#RadialGradientElementRAttribute+ if !r.is_valid_length() {+ let stop = stops.last().unwrap();+ return Some(ServerOrColor::Color {+ color: stop.color,+ opacity: stop.opacity,+ });+ }++ let spread_method = convert_spread_method(node);+ let cx = resolve_number(+ node,+ AId::Cx,+ units,+ state,+ Length::new(50.0, Unit::Percent),+ );+ let cy = resolve_number(+ node,+ AId::Cy,+ units,+ state,+ Length::new(50.0, Unit::Percent),+ );+ let fx = resolve_number(node, AId::Fx, units, state, Length::new_number(cx as f64));+ let fy = resolve_number(node, AId::Fy, units, state, Length::new_number(cy as f64));+ let transform = node.resolve_transform(AId::GradientTransform, state);++ let gradient = RadialGradient {+ cx,+ cy,+ r: PositiveF32::new(r).unwrap(),+ fx,+ fy,+ fr: PositiveF32::new(fr).unwrap_or(PositiveF32::ZERO),+ base: BaseGradient {+ id,+ units,+ transform,+ spread_method,+ stops,+ },+ };++ Some(ServerOrColor::Server(Paint::RadialGradient(Arc::new(+ gradient,+ ))))+}++#[inline(never)]+fn convert_pattern(+ node: SvgNode,+ state: &converter::State,+ cache: &mut converter::Cache,+) -> Option<ServerOrColor> {+ let node_with_children = find_pattern_with_children(node)?;++ let id = NonEmptyString::new(node.element_id().to_string())?;++ let view_box = {+ let n1 = resolve_attr(node, AId::ViewBox);+ let n2 = resolve_attr(node, AId::PreserveAspectRatio);+ n1.parse_viewbox().map(|vb| ViewBox {+ rect: vb,+ aspect: n2.attribute(AId::PreserveAspectRatio).unwrap_or_default(),+ })+ };++ let units = convert_units(node, AId::PatternUnits, Units::ObjectBoundingBox);+ let content_units = convert_units(node, AId::PatternContentUnits, Units::UserSpaceOnUse);++ let transform = node.resolve_transform(AId::PatternTransform, state);++ let rect = NonZeroRect::from_xywh(+ resolve_number(node, AId::X, units, state, Length::zero()),+ resolve_number(node, AId::Y, units, state, Length::zero()),+ resolve_number(node, AId::Width, units, state, Length::zero()),+ resolve_number(node, AId::Height, units, state, Length::zero()),+ );+ let rect = rect.log_none(|| {+ log::warn!(+ "Pattern '{}' has an invalid size. Skipped.",+ node.element_id()+ );+ })?;++ let mut patt = Pattern {+ id,+ units,+ content_units,+ transform,+ rect,+ view_box,+ root: Group::empty(),+ };++ // We can apply viewbox transform only for user space coordinates.+ // Otherwise we need a bounding box, which is unknown at this point.+ if patt.view_box.is_some()+ && patt.units == Units::UserSpaceOnUse+ && patt.content_units == Units::UserSpaceOnUse+ {+ let mut g = Group::empty();+ g.transform = view_box.unwrap().to_transform(rect.size());+ g.abs_transform = g.transform;++ converter::convert_children(node_with_children, state, cache, &mut g);+ if !g.has_children() {+ return None;+ }++ g.calculate_bounding_boxes();+ patt.root.children.push(Node::Group(Box::new(g)));+ } else {+ converter::convert_children(node_with_children, state, cache, &mut patt.root);+ if !patt.root.has_children() {+ return None;+ }+ }++ patt.root.calculate_bounding_boxes();++ Some(ServerOrColor::Server(Paint::Pattern(Arc::new(patt))))+}++fn convert_spread_method(node: SvgNode) -> SpreadMethod {+ let node = resolve_attr(node, AId::SpreadMethod);+ node.attribute(AId::SpreadMethod).unwrap_or_default()+}++pub(crate) fn convert_units(node: SvgNode, name: AId, def: Units) -> Units {+ let node = resolve_attr(node, name);+ node.attribute(name).unwrap_or(def)+}++fn find_gradient_with_stops<'a, 'input: 'a>(+ node: SvgNode<'a, 'input>,+) -> Option<SvgNode<'a, 'input>> {+ for link in node.href_iter() {+ if !link.tag_name().unwrap().is_gradient() {+ log::warn!(+ "Gradient '{}' cannot reference '{}' via 'xlink:href'.",+ node.element_id(),+ link.tag_name().unwrap()+ );+ return None;+ }++ if link.children().any(|n| n.tag_name() == Some(EId::Stop)) {+ return Some(link);+ }+ }++ None+}++fn find_pattern_with_children<'a, 'input: 'a>(+ node: SvgNode<'a, 'input>,+) -> Option<SvgNode<'a, 'input>> {+ for link in node.href_iter() {+ if link.tag_name() != Some(EId::Pattern) {+ log::warn!(+ "Pattern '{}' cannot reference '{}' via 'xlink:href'.",+ node.element_id(),+ link.tag_name().unwrap()+ );+ return None;+ }++ if link.has_children() {+ return Some(link);+ }+ }++ None+}++fn convert_stops(grad: SvgNode) -> Vec<Stop> {+ let mut stops = Vec::new();++ {+ let mut prev_offset = Length::zero();+ for stop in grad.children() {+ if stop.tag_name() != Some(EId::Stop) {+ log::warn!("Invalid gradient child: '{:?}'.", stop.tag_name().unwrap());+ continue;+ }++ // `number` can be either a number or a percentage.+ let offset = stop.attribute(AId::Offset).unwrap_or(prev_offset);+ let offset = match offset.unit {+ Unit::None => offset.number,+ Unit::Percent => offset.number / 100.0,+ _ => prev_offset.number,+ };+ prev_offset = Length::new_number(offset);+ let offset = crate::f32_bound(0.0, offset as f32, 1.0);++ let (color, opacity) = match stop.attribute(AId::StopColor) {+ Some("currentColor") => stop+ .find_attribute(AId::Color)+ .unwrap_or_else(svgtypes::Color::black),+ Some(value) => {+ if let Ok(c) = svgtypes::Color::from_str(value) {+ c+ } else {+ log::warn!("Failed to parse stop-color value: '{}'.", value);+ svgtypes::Color::black()+ }+ }+ _ => svgtypes::Color::black(),+ }+ .split_alpha();++ let stop_opacity = stop+ .attribute::<Opacity>(AId::StopOpacity)+ .unwrap_or(Opacity::ONE);+ stops.push(Stop {+ offset: StopOffset::new_clamped(offset),+ color,+ opacity: opacity * stop_opacity,+ });+ }+ }++ // Remove stops with equal offset.+ //+ // Example:+ // offset="0.5"+ // offset="0.7"+ // offset="0.7" <-- this one should be removed+ // offset="0.7"+ // offset="0.9"+ if stops.len() >= 3 {+ let mut i = 0;+ while i < stops.len() - 2 {+ let offset1 = stops[i + 0].offset.get();+ let offset2 = stops[i + 1].offset.get();+ let offset3 = stops[i + 2].offset.get();++ if offset1.approx_eq_ulps(&offset2, 4) && offset2.approx_eq_ulps(&offset3, 4) {+ // Remove offset in the middle.+ stops.remove(i + 1);+ } else {+ i += 1;+ }+ }+ }++ // Remove zeros.+ //+ // From:+ // offset="0.0"+ // offset="0.0"+ // offset="0.7"+ //+ // To:+ // offset="0.0"+ // offset="0.00000001"+ // offset="0.7"+ if stops.len() >= 2 {+ let mut i = 0;+ while i < stops.len() - 1 {+ let offset1 = stops[i + 0].offset.get();+ let offset2 = stops[i + 1].offset.get();++ if offset1.approx_eq_ulps(&0.0, 4) && offset2.approx_eq_ulps(&0.0, 4) {+ stops[i + 1].offset = StopOffset::new_clamped(offset1 + f32::EPSILON);+ }++ i += 1;+ }+ }++ // Shift equal offsets.+ //+ // From:+ // offset="0.5"+ // offset="0.7"+ // offset="0.7"+ //+ // To:+ // offset="0.5"+ // offset="0.699999999"+ // offset="0.7"+ {+ let mut i = 1;+ while i < stops.len() {+ let offset1 = stops[i - 1].offset.get();+ let offset2 = stops[i - 0].offset.get();++ // Next offset must be smaller then previous.+ if offset1 > offset2 || offset1.approx_eq_ulps(&offset2, 4) {+ // Make previous offset a bit smaller.+ let new_offset = offset1 - f32::EPSILON;+ stops[i - 1].offset = StopOffset::new_clamped(new_offset);+ stops[i - 0].offset = StopOffset::new_clamped(offset1);+ }++ i += 1;+ }+ }++ stops+}++#[inline(never)]+pub(crate) fn resolve_number(+ node: SvgNode,+ name: AId,+ units: Units,+ state: &converter::State,+ def: Length,+) -> f32 {+ resolve_attr(node, name).convert_length(name, units, state, def)+}++fn resolve_attr<'a, 'input: 'a>(node: SvgNode<'a, 'input>, name: AId) -> SvgNode<'a, 'input> {+ if node.has_attribute(name) {+ return node;+ }++ match node.tag_name().unwrap() {+ EId::LinearGradient => resolve_lg_attr(node, name),+ EId::RadialGradient => resolve_rg_attr(node, name),+ EId::Pattern => resolve_pattern_attr(node, name),+ EId::Filter => resolve_filter_attr(node, name),+ _ => node,+ }+}++fn resolve_lg_attr<'a, 'input: 'a>(node: SvgNode<'a, 'input>, name: AId) -> SvgNode<'a, 'input> {+ for link in node.href_iter() {+ let tag_name = match link.tag_name() {+ Some(v) => v,+ None => return node,+ };++ match (name, tag_name) {+ // Coordinates can be resolved only from+ // ref element with the same type.+ (AId::X1, EId::LinearGradient)+ | (AId::Y1, EId::LinearGradient)+ | (AId::X2, EId::LinearGradient)+ | (AId::Y2, EId::LinearGradient)+ // Other attributes can be resolved+ // from any kind of gradient.+ | (AId::GradientUnits, EId::LinearGradient)+ | (AId::GradientUnits, EId::RadialGradient)+ | (AId::SpreadMethod, EId::LinearGradient)+ | (AId::SpreadMethod, EId::RadialGradient)+ | (AId::GradientTransform, EId::LinearGradient)+ | (AId::GradientTransform, EId::RadialGradient) => {+ if link.has_attribute(name) {+ return link;+ }+ }+ _ => break,+ }+ }++ node+}++fn resolve_rg_attr<'a, 'input>(node: SvgNode<'a, 'input>, name: AId) -> SvgNode<'a, 'input> {+ for link in node.href_iter() {+ let tag_name = match link.tag_name() {+ Some(v) => v,+ None => return node,+ };++ match (name, tag_name) {+ // Coordinates can be resolved only from+ // ref element with the same type.+ (AId::Cx, EId::RadialGradient)+ | (AId::Cy, EId::RadialGradient)+ | (AId::R, EId::RadialGradient)+ | (AId::Fx, EId::RadialGradient)+ | (AId::Fy, EId::RadialGradient)+ | (AId::Fr, EId::RadialGradient)+ // Other attributes can be resolved+ // from any kind of gradient.+ | (AId::GradientUnits, EId::LinearGradient)+ | (AId::GradientUnits, EId::RadialGradient)+ | (AId::SpreadMethod, EId::LinearGradient)+ | (AId::SpreadMethod, EId::RadialGradient)+ | (AId::GradientTransform, EId::LinearGradient)+ | (AId::GradientTransform, EId::RadialGradient) => {+ if link.has_attribute(name) {+ return link;+ }+ }+ _ => break,+ }+ }++ node+}++fn resolve_pattern_attr<'a, 'input: 'a>(+ node: SvgNode<'a, 'input>,+ name: AId,+) -> SvgNode<'a, 'input> {+ for link in node.href_iter() {+ let tag_name = match link.tag_name() {+ Some(v) => v,+ None => return node,+ };++ if tag_name != EId::Pattern {+ break;+ }++ if link.has_attribute(name) {+ return link;+ }+ }++ node+}++fn resolve_filter_attr<'a, 'input: 'a>(node: SvgNode<'a, 'input>, aid: AId) -> SvgNode<'a, 'input> {+ for link in node.href_iter() {+ let tag_name = match link.tag_name() {+ Some(v) => v,+ None => return node,+ };++ if tag_name != EId::Filter {+ break;+ }++ if link.has_attribute(aid) {+ return link;+ }+ }++ node+}++fn stops_to_color(stops: &[Stop]) -> Option<ServerOrColor> {+ if stops.is_empty() {+ None+ } else {+ Some(ServerOrColor::Color {+ color: stops[0].color,+ opacity: stops[0].opacity,+ })+ }+}++// Update paints servers by doing the following:+// 1. Replace context fills/strokes that are linked to+// a use node with their actual values.+// 2. Convert all object units to UserSpaceOnUse+pub fn update_paint_servers(+ group: &mut Group,+ context_transform: Transform,+ context_bbox: Option<Rect>,+ text_bbox: Option<Rect>,+ cache: &mut Cache,+) {+ for child in &mut group.children {+ // Set context transform and bbox if applicable if the+ // current group is a use node.+ let (context_transform, context_bbox) = if group.is_context_element {+ (group.abs_transform, Some(group.bounding_box))+ } else {+ (context_transform, context_bbox)+ };++ node_to_user_coordinates(child, context_transform, context_bbox, text_bbox, cache);+ }+}++// When parsing clipPaths, masks and filters we already know group's bounding box.+// But with gradients and patterns we don't, because we have to know text bounding box+// before we even parsed it. Which is impossible.+// Therefore our only choice is to parse gradients and patterns preserving their units+// and then replace them with `userSpaceOnUse` after the whole tree parsing is finished.+// So while gradients and patterns do still store their units,+// they are not exposed in the public API and for the caller they are always `userSpaceOnUse`.+fn node_to_user_coordinates(+ node: &mut Node,+ context_transform: Transform,+ context_bbox: Option<Rect>,+ text_bbox: Option<Rect>,+ cache: &mut Cache,+) {+ match node {+ Node::Group(g) => {+ // No need to check clip paths, because they cannot have paint servers.+ if let Some(mask) = &mut g.mask {+ if let Some(mask) = Arc::get_mut(mask) {+ update_paint_servers(+ &mut mask.root,+ context_transform,+ context_bbox,+ None,+ cache,+ );++ if let Some(sub_mask) = &mut mask.mask {+ if let Some(sub_mask) = Arc::get_mut(sub_mask) {+ update_paint_servers(+ &mut sub_mask.root,+ context_transform,+ context_bbox,+ None,+ cache,+ );+ }+ }+ }+ }++ for filter in &mut g.filters {+ if let Some(filter) = Arc::get_mut(filter) {+ for primitive in &mut filter.primitives {+ if let filter::Kind::Image(image) = &mut primitive.kind {+ update_paint_servers(+ &mut image.root,+ context_transform,+ context_bbox,+ None,+ cache,+ );+ }+ }+ }+ }++ update_paint_servers(g, context_transform, context_bbox, text_bbox, cache);+ }+ Node::Path(path) => {+ // Paths inside `Text::flattened` are special and must use text's bounding box+ // instead of their own.+ let bbox = text_bbox.unwrap_or(path.bounding_box);++ process_fill(+ &mut path.fill,+ path.abs_transform,+ context_transform,+ context_bbox,+ bbox,+ cache,+ );+ process_stroke(+ &mut path.stroke,+ path.abs_transform,+ context_transform,+ context_bbox,+ bbox,+ cache,+ );+ }+ Node::Image(image) => {+ if let ImageKind::SVG(tree) = &mut image.kind {+ update_paint_servers(&mut tree.root, context_transform, context_bbox, None, cache);+ }+ }+ Node::Text(text) => {+ // By the SVG spec, `tspan` doesn't have a bbox and uses the parent `text` bbox.+ // Therefore we have to use text's bbox when converting tspan and flatted text+ // paint servers.+ let bbox = text.bounding_box;++ // We need to update three things:+ // 1. The fills/strokes of the original elements in the usvg tree.+ // 2. The fills/strokes of the layouted elements of the text.+ // 3. The fills/strokes of the outlined text.++ // 1.+ for chunk in &mut text.chunks {+ for span in &mut chunk.spans {+ process_fill(+ &mut span.fill,+ text.abs_transform,+ context_transform,+ context_bbox,+ bbox,+ cache,+ );+ process_stroke(+ &mut span.stroke,+ text.abs_transform,+ context_transform,+ context_bbox,+ bbox,+ cache,+ );+ process_text_decoration(&mut span.decoration.underline, bbox, cache);+ process_text_decoration(&mut span.decoration.overline, bbox, cache);+ process_text_decoration(&mut span.decoration.line_through, bbox, cache);+ }+ }++ // 2.+ #[cfg(feature = "text")]+ for span in &mut text.layouted {+ process_fill(+ &mut span.fill,+ text.abs_transform,+ context_transform,+ context_bbox,+ bbox,+ cache,+ );+ process_stroke(+ &mut span.stroke,+ text.abs_transform,+ context_transform,+ context_bbox,+ bbox,+ cache,+ );++ let mut process_decoration = |path: &mut Path| {+ process_fill(+ &mut path.fill,+ text.abs_transform,+ context_transform,+ context_bbox,+ bbox,+ cache,+ );+ process_stroke(+ &mut path.stroke,+ text.abs_transform,+ context_transform,+ context_bbox,+ bbox,+ cache,+ );+ };++ if let Some(path) = &mut span.overline {+ process_decoration(path);+ }++ if let Some(path) = &mut span.underline {+ process_decoration(path);+ }++ if let Some(path) = &mut span.line_through {+ process_decoration(path);+ }+ }++ // 3.+ update_paint_servers(+ &mut text.flattened,+ context_transform,+ context_bbox,+ Some(bbox),+ cache,+ );+ }+ }+}++fn process_fill(+ fill: &mut Option<Fill>,+ path_transform: Transform,+ context_transform: Transform,+ context_bbox: Option<Rect>,+ bbox: Rect,+ cache: &mut Cache,+) {+ let mut ok = false;+ if let Some(fill) = fill.as_mut() {+ // Path context elements (i.e. for markers) have already been resolved,+ // so we only care about use nodes.+ ok = process_paint(+ &mut fill.paint,+ matches!(fill.context_element, Some(ContextElement::UseNode)),+ context_transform,+ context_bbox,+ path_transform,+ bbox,+ cache,+ );+ }+ if !ok {+ *fill = None;+ }+}++fn process_stroke(+ stroke: &mut Option<Stroke>,+ path_transform: Transform,+ context_transform: Transform,+ context_bbox: Option<Rect>,+ bbox: Rect,+ cache: &mut Cache,+) {+ let mut ok = false;+ if let Some(stroke) = stroke.as_mut() {+ // Path context elements (i.e. for markers) have already been resolved,+ // so we only care about use nodes.+ ok = process_paint(+ &mut stroke.paint,+ matches!(stroke.context_element, Some(ContextElement::UseNode)),+ context_transform,+ context_bbox,+ path_transform,+ bbox,+ cache,+ );+ }+ if !ok {+ *stroke = None;+ }+}++fn process_context_paint(+ paint: &mut Paint,+ context_transform: Transform,+ path_transform: Transform,+ cache: &mut Cache,+) -> Option<()> {+ // The idea is the following: We have a certain context element that has+ // a transform A, and further below in the tree we have for example a path+ // whose paint has a transform C. In order to get from A to C, there is some+ // transformation matrix B such that A x B = C. We now need to figure out+ // a way to get from C back to A, so that the transformation of the paint+ // matches the one from the context element, even if B was applied. How+ // do we do that? We calculate CxB^(-1), which will overall then have+ // the same effect as A. How do we calculate B^(-1)?+ // --> (A^(-1)xC)^(-1)+ let rev_transform = context_transform+ .invert()?+ .pre_concat(path_transform)+ .invert()?;++ match paint {+ Paint::Color(_) => {}+ Paint::LinearGradient(lg) => {+ let transform = lg.transform.post_concat(rev_transform);+ *paint = Paint::LinearGradient(Arc::new(LinearGradient {+ x1: lg.x1,+ y1: lg.y1,+ x2: lg.x2,+ y2: lg.y2,+ base: BaseGradient {+ id: cache.gen_linear_gradient_id(),+ units: lg.units,+ transform,+ spread_method: lg.spread_method,+ stops: lg.stops.clone(),+ },+ }));+ }+ Paint::RadialGradient(rg) => {+ let transform = rg.transform.post_concat(rev_transform);+ *paint = Paint::RadialGradient(Arc::new(RadialGradient {+ cx: rg.cx,+ cy: rg.cy,+ r: rg.r,+ fx: rg.fx,+ fy: rg.fy,+ fr: rg.fr,+ base: BaseGradient {+ id: cache.gen_radial_gradient_id(),+ units: rg.units,+ transform,+ spread_method: rg.spread_method,+ stops: rg.stops.clone(),+ },+ }));+ }+ Paint::Pattern(pat) => {+ let transform = pat.transform.post_concat(rev_transform);+ *paint = Paint::Pattern(Arc::new(Pattern {+ id: cache.gen_pattern_id(),+ units: pat.units,+ content_units: pat.content_units,+ transform,+ rect: pat.rect,+ view_box: pat.view_box,+ root: pat.root.clone(),+ }));+ }+ }++ Some(())+}++pub(crate) fn process_paint(+ paint: &mut Paint,+ has_context: bool,+ context_transform: Transform,+ context_bbox: Option<Rect>,+ path_transform: Transform,+ bbox: Rect,+ cache: &mut Cache,+) -> bool {+ if paint.units() == Units::ObjectBoundingBox+ || paint.content_units() == Units::ObjectBoundingBox+ {+ let bbox = if has_context {+ let Some(bbox) = context_bbox else {+ return false;+ };+ bbox+ } else {+ bbox+ };++ if paint.to_user_coordinates(bbox, cache).is_none() {+ return false;+ }+ }++ if let Paint::Pattern(patt) = paint {+ if let Some(patt) = Arc::get_mut(patt) {+ update_paint_servers(&mut patt.root, Transform::default(), None, None, cache);+ }+ }++ if has_context {+ process_context_paint(paint, context_transform, path_transform, cache);+ }++ true+}++fn process_text_decoration(style: &mut Option<TextDecorationStyle>, bbox: Rect, cache: &mut Cache) {+ if let Some(style) = style.as_mut() {+ process_fill(+ &mut style.fill,+ Transform::default(),+ Transform::default(),+ None,+ bbox,+ cache,+ );+ process_stroke(+ &mut style.stroke,+ Transform::default(),+ Transform::default(),+ None,+ bbox,+ cache,+ );+ }+}++impl Paint {+ fn to_user_coordinates(&mut self, bbox: Rect, cache: &mut Cache) -> Option<()> {+ let name = if matches!(self, Paint::Pattern(_)) {+ "Pattern"+ } else {+ "Gradient"+ };+ let bbox = bbox+ .to_non_zero_rect()+ .log_none(|| log::warn!("{} on zero-sized shapes is not allowed.", name))?;++ // `Arc::get_mut()` allow us to modify some paint servers in-place.+ // This reduces the amount of cloning and preserves the original ID as well.+ match self {+ Paint::Color(_) => {} // unreachable+ Paint::LinearGradient(lg) => {+ let transform = lg.transform.post_concat(Transform::from_bbox(bbox));+ if let Some(lg) = Arc::get_mut(lg) {+ lg.base.transform = transform;+ lg.base.units = Units::UserSpaceOnUse;+ } else {+ *lg = Arc::new(LinearGradient {+ x1: lg.x1,+ y1: lg.y1,+ x2: lg.x2,+ y2: lg.y2,+ base: BaseGradient {+ id: cache.gen_linear_gradient_id(),+ units: Units::UserSpaceOnUse,+ transform,+ spread_method: lg.spread_method,+ stops: lg.stops.clone(),+ },+ });+ }+ }+ Paint::RadialGradient(rg) => {+ let transform = rg.transform.post_concat(Transform::from_bbox(bbox));+ if let Some(rg) = Arc::get_mut(rg) {+ rg.base.transform = transform;+ rg.base.units = Units::UserSpaceOnUse;+ } else {+ *rg = Arc::new(RadialGradient {+ cx: rg.cx,+ cy: rg.cy,+ r: rg.r,+ fx: rg.fx,+ fy: rg.fy,+ fr: rg.fr,+ base: BaseGradient {+ id: cache.gen_radial_gradient_id(),+ units: Units::UserSpaceOnUse,+ transform,+ spread_method: rg.spread_method,+ stops: rg.stops.clone(),+ },+ });+ }+ }+ Paint::Pattern(patt) => {+ let rect = if patt.units == Units::ObjectBoundingBox {+ patt.rect.bbox_transform(bbox)+ } else {+ patt.rect+ };++ if let Some(patt) = Arc::get_mut(patt) {+ patt.rect = rect;+ patt.units = Units::UserSpaceOnUse;++ if patt.content_units == Units::ObjectBoundingBox && patt.view_box.is_none() {+ // No need to shift patterns.+ let transform = Transform::from_scale(bbox.width(), bbox.height());+ push_pattern_transform(&mut patt.root, transform);+ }++ if let Some(view_box) = patt.view_box {+ push_pattern_transform(&mut patt.root, view_box.to_transform(rect.size()));+ }++ patt.content_units = Units::UserSpaceOnUse;+ } else {+ let mut root = if patt.content_units == Units::ObjectBoundingBox+ && patt.view_box.is_none()+ {+ // No need to shift patterns.+ let transform = Transform::from_scale(bbox.width(), bbox.height());++ let mut g = patt.root.clone();+ push_pattern_transform(&mut g, transform);+ g+ } else {+ patt.root.clone()+ };++ if let Some(view_box) = patt.view_box {+ push_pattern_transform(&mut root, view_box.to_transform(rect.size()));+ }++ *patt = Arc::new(Pattern {+ id: cache.gen_pattern_id(),+ units: Units::UserSpaceOnUse,+ content_units: Units::UserSpaceOnUse,+ transform: patt.transform,+ rect,+ view_box: patt.view_box,+ root,+ });+ }+ }+ }++ Some(())+ }+}++fn push_pattern_transform(root: &mut Group, transform: Transform) {+ // TODO: we should update abs_transform in all descendants as well+ let mut g = std::mem::replace(root, Group::empty());+ g.transform = transform;+ g.abs_transform = transform;++ root.children.push(Node::Group(Box::new(g)));+ root.calculate_bounding_boxes();+}++impl Paint {+ #[inline]+ pub(crate) fn units(&self) -> Units {+ match self {+ Self::Color(_) => Units::UserSpaceOnUse,+ Self::LinearGradient(lg) => lg.units,+ Self::RadialGradient(rg) => rg.units,+ Self::Pattern(patt) => patt.units,+ }+ }++ #[inline]+ pub(crate) fn content_units(&self) -> Units {+ match self {+ Self::Pattern(patt) => patt.content_units,+ _ => Units::UserSpaceOnUse,+ }+ }+}diff --git a/vendor/usvg/src/parser/shapes.rs b/vendor/usvg/src/parser/shapes.rsnew file mode 100644index 00000000..b541ae1a--- /dev/null+++ b/vendor/usvg/src/parser/shapes.rs@@ -0,0 +1,332 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::sync::Arc;++use svgtypes::Length;+use tiny_skia_path::Path;++use super::svgtree::{AId, EId, SvgNode};+use super::{converter, units};+use crate::{ApproxEqUlps, IsValidLength, Rect};++pub(crate) fn convert(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {+ match node.tag_name()? {+ EId::Rect => convert_rect(node, state),+ EId::Circle => convert_circle(node, state),+ EId::Ellipse => convert_ellipse(node, state),+ EId::Line => convert_line(node, state),+ EId::Polyline => convert_polyline(node),+ EId::Polygon => convert_polygon(node),+ EId::Path => convert_path(node),+ _ => None,+ }+}++pub(crate) fn convert_path(node: SvgNode) -> Option<Arc<Path>> {+ let value: &str = node.attribute(AId::D)?;+ let mut builder = tiny_skia_path::PathBuilder::new();+ for segment in svgtypes::SimplifyingPathParser::from(value) {+ let segment = match segment {+ Ok(v) => v,+ Err(e) => {+ log::warn!("Error during path parsing: {e}");+ break;+ }+ };++ match segment {+ svgtypes::SimplePathSegment::MoveTo { x, y } => {+ builder.move_to(x as f32, y as f32);+ }+ svgtypes::SimplePathSegment::LineTo { x, y } => {+ builder.line_to(x as f32, y as f32);+ }+ svgtypes::SimplePathSegment::Quadratic { x1, y1, x, y } => {+ builder.quad_to(x1 as f32, y1 as f32, x as f32, y as f32);+ }+ svgtypes::SimplePathSegment::CurveTo {+ x1,+ y1,+ x2,+ y2,+ x,+ y,+ } => {+ builder.cubic_to(+ x1 as f32, y1 as f32, x2 as f32, y2 as f32, x as f32, y as f32,+ );+ }+ svgtypes::SimplePathSegment::ClosePath => {+ builder.close();+ }+ }+ }++ builder.finish().map(Arc::new)+}++fn convert_rect(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {+ // 'width' and 'height' attributes must be positive and non-zero.+ let width = node.convert_user_length(AId::Width, state, Length::zero());+ let height = node.convert_user_length(AId::Height, state, Length::zero());+ if !width.is_valid_length() {+ log::warn!(+ "Rect '{}' has an invalid 'width' value. Skipped.",+ node.element_id()+ );+ return None;+ }+ if !height.is_valid_length() {+ log::warn!(+ "Rect '{}' has an invalid 'height' value. Skipped.",+ node.element_id()+ );+ return None;+ }++ let x = node.convert_user_length(AId::X, state, Length::zero());+ let y = node.convert_user_length(AId::Y, state, Length::zero());++ let (mut rx, mut ry) = resolve_rx_ry(node, state);++ // Clamp rx/ry to the half of the width/height.+ //+ // Should be done only after resolving.+ if rx > width / 2.0 {+ rx = width / 2.0;+ }+ if ry > height / 2.0 {+ ry = height / 2.0;+ }++ // Conversion according to https://www.w3.org/TR/SVG11/shapes.html#RectElement+ let path = if rx.approx_eq_ulps(&0.0, 4) {+ tiny_skia_path::PathBuilder::from_rect(Rect::from_xywh(x, y, width, height)?)+ } else {+ let mut builder = tiny_skia_path::PathBuilder::new();+ builder.move_to(x + rx, y);++ builder.line_to(x + width - rx, y);+ builder.arc_to(rx, ry, 0.0, false, true, x + width, y + ry);++ builder.line_to(x + width, y + height - ry);+ builder.arc_to(rx, ry, 0.0, false, true, x + width - rx, y + height);++ builder.line_to(x + rx, y + height);+ builder.arc_to(rx, ry, 0.0, false, true, x, y + height - ry);++ builder.line_to(x, y + ry);+ builder.arc_to(rx, ry, 0.0, false, true, x + rx, y);++ builder.close();++ builder.finish()?+ };++ Some(Arc::new(path))+}++fn resolve_rx_ry(node: SvgNode, state: &converter::State) -> (f32, f32) {+ let mut rx_opt = node.attribute::<Length>(AId::Rx);+ let mut ry_opt = node.attribute::<Length>(AId::Ry);++ // Remove negative values first.+ if let Some(v) = rx_opt {+ if v.number.is_sign_negative() {+ rx_opt = None;+ }+ }+ if let Some(v) = ry_opt {+ if v.number.is_sign_negative() {+ ry_opt = None;+ }+ }++ // Resolve.+ match (rx_opt, ry_opt) {+ (None, None) => (0.0, 0.0),+ (Some(rx), None) => {+ let rx = units::convert_user_length(rx, node, AId::Rx, state);+ (rx, rx)+ }+ (None, Some(ry)) => {+ let ry = units::convert_user_length(ry, node, AId::Ry, state);+ (ry, ry)+ }+ (Some(rx), Some(ry)) => {+ let rx = units::convert_user_length(rx, node, AId::Rx, state);+ let ry = units::convert_user_length(ry, node, AId::Ry, state);+ (rx, ry)+ }+ }+}++fn convert_line(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {+ let x1 = node.convert_user_length(AId::X1, state, Length::zero());+ let y1 = node.convert_user_length(AId::Y1, state, Length::zero());+ let x2 = node.convert_user_length(AId::X2, state, Length::zero());+ let y2 = node.convert_user_length(AId::Y2, state, Length::zero());++ let mut builder = tiny_skia_path::PathBuilder::new();+ builder.move_to(x1, y1);+ builder.line_to(x2, y2);+ builder.finish().map(Arc::new)+}++fn convert_polyline(node: SvgNode) -> Option<Arc<Path>> {+ let builder = points_to_path(node, "Polyline")?;+ builder.finish().map(Arc::new)+}++fn convert_polygon(node: SvgNode) -> Option<Arc<Path>> {+ let mut builder = points_to_path(node, "Polygon")?;+ builder.close();+ builder.finish().map(Arc::new)+}++fn points_to_path(node: SvgNode, eid: &str) -> Option<tiny_skia_path::PathBuilder> {+ use svgtypes::PointsParser;++ let mut builder = tiny_skia_path::PathBuilder::new();+ match node.attribute::<&str>(AId::Points) {+ Some(text) => {+ for (x, y) in PointsParser::from(text) {+ if builder.is_empty() {+ builder.move_to(x as f32, y as f32);+ } else {+ builder.line_to(x as f32, y as f32);+ }+ }+ }+ _ => {+ log::warn!(+ "{} '{}' has an invalid 'points' value. Skipped.",+ eid,+ node.element_id()+ );+ return None;+ }+ };++ // 'polyline' and 'polygon' elements must contain at least 2 points.+ if builder.len() < 2 {+ log::warn!(+ "{} '{}' has less than 2 points. Skipped.",+ eid,+ node.element_id()+ );+ return None;+ }++ Some(builder)+}++fn convert_circle(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {+ let cx = node.convert_user_length(AId::Cx, state, Length::zero());+ let cy = node.convert_user_length(AId::Cy, state, Length::zero());+ let r = node.convert_user_length(AId::R, state, Length::zero());++ if !r.is_valid_length() {+ log::warn!(+ "Circle '{}' has an invalid 'r' value. Skipped.",+ node.element_id()+ );+ return None;+ }++ ellipse_to_path(cx, cy, r, r)+}++fn convert_ellipse(node: SvgNode, state: &converter::State) -> Option<Arc<Path>> {+ let cx = node.convert_user_length(AId::Cx, state, Length::zero());+ let cy = node.convert_user_length(AId::Cy, state, Length::zero());+ let (rx, ry) = resolve_rx_ry(node, state);++ if !rx.is_valid_length() {+ log::warn!(+ "Ellipse '{}' has an invalid 'rx' value. Skipped.",+ node.element_id()+ );+ return None;+ }++ if !ry.is_valid_length() {+ log::warn!(+ "Ellipse '{}' has an invalid 'ry' value. Skipped.",+ node.element_id()+ );+ return None;+ }++ ellipse_to_path(cx, cy, rx, ry)+}++fn ellipse_to_path(cx: f32, cy: f32, rx: f32, ry: f32) -> Option<Arc<Path>> {+ let mut builder = tiny_skia_path::PathBuilder::new();+ builder.move_to(cx + rx, cy);+ builder.arc_to(rx, ry, 0.0, false, true, cx, cy + ry);+ builder.arc_to(rx, ry, 0.0, false, true, cx - rx, cy);+ builder.arc_to(rx, ry, 0.0, false, true, cx, cy - ry);+ builder.arc_to(rx, ry, 0.0, false, true, cx + rx, cy);+ builder.close();+ builder.finish().map(Arc::new)+}++trait PathBuilderExt {+ fn arc_to(+ &mut self,+ rx: f32,+ ry: f32,+ x_axis_rotation: f32,+ large_arc: bool,+ sweep: bool,+ x: f32,+ y: f32,+ );+}++impl PathBuilderExt for tiny_skia_path::PathBuilder {+ fn arc_to(+ &mut self,+ rx: f32,+ ry: f32,+ x_axis_rotation: f32,+ large_arc: bool,+ sweep: bool,+ x: f32,+ y: f32,+ ) {+ let prev = match self.last_point() {+ Some(v) => v,+ None => return,+ };++ let svg_arc = kurbo::SvgArc {+ from: kurbo::Point::new(prev.x as f64, prev.y as f64),+ to: kurbo::Point::new(x as f64, y as f64),+ radii: kurbo::Vec2::new(rx as f64, ry as f64),+ x_rotation: (x_axis_rotation as f64).to_radians(),+ large_arc,+ sweep,+ };++ match kurbo::Arc::from_svg_arc(&svg_arc) {+ Some(arc) => {+ arc.to_cubic_beziers(0.1, |p1, p2, p| {+ self.cubic_to(+ p1.x as f32,+ p1.y as f32,+ p2.x as f32,+ p2.y as f32,+ p.x as f32,+ p.y as f32,+ );+ });+ }+ None => {+ self.line_to(x, y);+ }+ }+ }+}diff --git a/vendor/usvg/src/parser/style.rs b/vendor/usvg/src/parser/style.rsnew file mode 100644index 00000000..cefdc5c1--- /dev/null+++ b/vendor/usvg/src/parser/style.rs@@ -0,0 +1,296 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use super::converter::{self, SvgColorExt};+use super::paint_server;+use super::svgtree::{AId, FromValue, SvgNode};+use crate::tree::ContextElement;+use crate::{+ ApproxEqUlps, Color, Fill, FillRule, LineCap, LineJoin, Opacity, Paint, Stroke,+ StrokeMiterlimit, Units,+};++impl<'a, 'input: 'a> FromValue<'a, 'input> for LineCap {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "butt" => Some(LineCap::Butt),+ "round" => Some(LineCap::Round),+ "square" => Some(LineCap::Square),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for LineJoin {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "miter" => Some(LineJoin::Miter),+ "miter-clip" => Some(LineJoin::MiterClip),+ "round" => Some(LineJoin::Round),+ "bevel" => Some(LineJoin::Bevel),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for FillRule {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "nonzero" => Some(FillRule::NonZero),+ "evenodd" => Some(FillRule::EvenOdd),+ _ => None,+ }+ }+}++pub(crate) fn resolve_fill(+ node: SvgNode,+ has_bbox: bool,+ state: &converter::State,+ cache: &mut converter::Cache,+) -> Option<Fill> {+ if state.parent_clip_path.is_some() {+ // A `clipPath` child can be filled only with a black color.+ return Some(Fill {+ paint: Paint::Color(Color::black()),+ opacity: Opacity::ONE,+ rule: node.find_attribute(AId::ClipRule).unwrap_or_default(),+ context_element: None,+ });+ }++ let mut sub_opacity = Opacity::ONE;+ let (paint, context_element) =+ if let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::Fill)) {+ let value: &str = n.attribute(AId::Fill)?;+ convert_paint(+ node,+ value,+ AId::Fill,+ has_bbox,+ state,+ &mut sub_opacity,+ cache,+ )?+ } else {+ (Paint::Color(Color::black()), None)+ };++ let fill_opacity = node+ .find_attribute::<Opacity>(AId::FillOpacity)+ .unwrap_or(Opacity::ONE);++ Some(Fill {+ paint,+ opacity: sub_opacity * fill_opacity,+ rule: node.find_attribute(AId::FillRule).unwrap_or_default(),+ context_element,+ })+}++pub(crate) fn resolve_stroke(+ node: SvgNode,+ has_bbox: bool,+ state: &converter::State,+ cache: &mut converter::Cache,+) -> Option<Stroke> {+ if state.parent_clip_path.is_some() {+ // A `clipPath` child cannot be stroked.+ return None;+ }++ let mut sub_opacity = Opacity::ONE;+ let (paint, context_element) =+ if let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::Stroke)) {+ let value: &str = n.attribute(AId::Stroke)?;++ convert_paint(+ node,+ value,+ AId::Stroke,+ has_bbox,+ state,+ &mut sub_opacity,+ cache,+ )?+ } else {+ return None;+ };++ let width = node.resolve_valid_length(AId::StrokeWidth, state, 1.0)?;++ // Must be bigger than 1.+ let miterlimit = node.find_attribute(AId::StrokeMiterlimit).unwrap_or(4.0);+ let miterlimit = if miterlimit < 1.0 { 1.0 } else { miterlimit };+ let miterlimit = StrokeMiterlimit::new(miterlimit);++ let stroke_opacity = node+ .find_attribute::<Opacity>(AId::StrokeOpacity)+ .unwrap_or(Opacity::ONE);++ let stroke = Stroke {+ paint,+ dasharray: conv_dasharray(node, state),+ dashoffset: node.resolve_length(AId::StrokeDashoffset, state, 0.0),+ miterlimit,+ opacity: sub_opacity * stroke_opacity,+ width,+ linecap: node.find_attribute(AId::StrokeLinecap).unwrap_or_default(),+ linejoin: node.find_attribute(AId::StrokeLinejoin).unwrap_or_default(),+ context_element,+ };++ Some(stroke)+}++fn convert_paint(+ node: SvgNode,+ value: &str,+ aid: AId,+ has_bbox: bool,+ state: &converter::State,+ opacity: &mut Opacity,+ cache: &mut converter::Cache,+) -> Option<(Paint, Option<ContextElement>)> {+ let paint = match svgtypes::Paint::from_str(value) {+ Ok(v) => v,+ Err(_) => {+ if aid == AId::Fill {+ log::warn!(+ "Failed to parse fill value: '{}'. Fallback to black.",+ value+ );+ svgtypes::Paint::Color(svgtypes::Color::black())+ } else if aid == AId::Stroke {+ log::warn!(+ "Failed to parse stroke value: '{}'. Fallback to no stroke.",+ value+ );+ return None;+ } else {+ return None;+ }+ }+ };++ match paint {+ svgtypes::Paint::None => None,+ svgtypes::Paint::Inherit => None, // already resolved by svgtree+ svgtypes::Paint::ContextFill => state+ .context_element+ .clone()+ .and_then(|(f, _)| f)+ .map(|f| (f.paint, f.context_element)),+ svgtypes::Paint::ContextStroke => state+ .context_element+ .clone()+ .and_then(|(_, s)| s)+ .map(|s| (s.paint, s.context_element)),+ svgtypes::Paint::CurrentColor => {+ let svg_color: svgtypes::Color = node+ .find_attribute(AId::Color)+ .unwrap_or_else(svgtypes::Color::black);+ let (color, alpha) = svg_color.split_alpha();+ *opacity = alpha;+ Some((Paint::Color(color), None))+ }+ svgtypes::Paint::Color(svg_color) => {+ let (color, alpha) = svg_color.split_alpha();+ *opacity = alpha;+ Some((Paint::Color(color), None))+ }+ svgtypes::Paint::FuncIRI(func_iri, fallback) => {+ if let Some(link) = node.document().element_by_id(func_iri) {+ let tag_name = link.tag_name().unwrap();+ if tag_name.is_paint_server() {+ match paint_server::convert(link, state, cache) {+ Some(paint_server::ServerOrColor::Server(paint)) => {+ // We can use a paint server node with ObjectBoundingBox units+ // for painting only when the shape itself has a bbox.+ //+ // See SVG spec 7.11 for details.++ if !has_bbox && paint.units() == Units::ObjectBoundingBox {+ from_fallback(node, fallback, opacity).map(|p| (p, None))+ } else {+ Some((paint, None))+ }+ }+ Some(paint_server::ServerOrColor::Color { color, opacity: so }) => {+ *opacity = so;+ Some((Paint::Color(color), None))+ }+ None => from_fallback(node, fallback, opacity).map(|p| (p, None)),+ }+ } else {+ log::warn!("'{}' cannot be used to {} a shape.", tag_name, aid);+ None+ }+ } else {+ from_fallback(node, fallback, opacity).map(|p| (p, None))+ }+ }+ }+}++fn from_fallback(+ node: SvgNode,+ fallback: Option<svgtypes::PaintFallback>,+ opacity: &mut Opacity,+) -> Option<Paint> {+ match fallback? {+ svgtypes::PaintFallback::None => None,+ svgtypes::PaintFallback::CurrentColor => {+ let svg_color: svgtypes::Color = node+ .find_attribute(AId::Color)+ .unwrap_or_else(svgtypes::Color::black);+ let (color, alpha) = svg_color.split_alpha();+ *opacity = alpha;+ Some(Paint::Color(color))+ }+ svgtypes::PaintFallback::Color(svg_color) => {+ let (color, alpha) = svg_color.split_alpha();+ *opacity = alpha;+ Some(Paint::Color(color))+ }+ }+}++// Prepare the 'stroke-dasharray' according to:+// https://www.w3.org/TR/SVG11/painting.html#StrokeDasharrayProperty+fn conv_dasharray(node: SvgNode, state: &converter::State) -> Option<Vec<f32>> {+ let node = node+ .ancestors()+ .find(|n| n.has_attribute(AId::StrokeDasharray))?;+ let list = super::units::convert_list(node, AId::StrokeDasharray, state)?;++ // `A negative value is an error`+ if list.iter().any(|n| n.is_sign_negative()) {+ return None;+ }++ // `If the sum of the values is zero, then the stroke is rendered+ // as if a value of none were specified.`+ {+ // no Iter::sum(), because of f64++ let mut sum: f32 = 0.0;+ for n in list.iter() {+ sum += *n;+ }++ if sum.approx_eq_ulps(&0.0, 4) {+ return None;+ }+ }++ // `If an odd number of values is provided, then the list of values+ // is repeated to yield an even number of values.`+ if list.len() % 2 != 0 {+ let mut tmp_list = list.clone();+ tmp_list.extend_from_slice(&list);+ return Some(tmp_list);+ }++ Some(list)+}diff --git a/vendor/usvg/src/parser/svgtree/mod.rs b/vendor/usvg/src/parser/svgtree/mod.rsnew file mode 100644index 00000000..1618f322--- /dev/null+++ b/vendor/usvg/src/parser/svgtree/mod.rs@@ -0,0 +1,1083 @@+// Copyright 2021 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::collections::HashMap;+use std::num::NonZeroU32;+use std::str::FromStr;++#[rustfmt::skip] mod names;+mod parse;+mod text;++use tiny_skia_path::Transform;++use crate::{+ BlendMode, ImageRendering, Opacity, ShapeRendering, SpreadMethod, TextRendering, Units,+ Visibility,+};+pub use names::{AId, EId};++/// An SVG tree container.+///+/// Contains only element and text nodes.+/// Text nodes are present only inside the `text` element.+pub struct Document<'input> {+ nodes: Vec<NodeData>,+ attrs: Vec<Attribute<'input>>,+ links: HashMap<String, NodeId>,+}++impl<'input> Document<'input> {+ /// Returns the root node.+ #[inline]+ pub fn root<'a>(&'a self) -> SvgNode<'a, 'input> {+ SvgNode {+ id: NodeId::new(0),+ d: &self.nodes[0],+ doc: self,+ }+ }++ /// Returns the root element.+ #[inline]+ pub fn root_element<'a>(&'a self) -> SvgNode<'a, 'input> {+ // `unwrap` is safe, because `Document` is guarantee to have at least one element.+ self.root().first_element_child().unwrap()+ }++ /// Returns an iterator over document's descendant nodes.+ ///+ /// Shorthand for `doc.root().descendants()`.+ #[inline]+ pub fn descendants<'a>(&'a self) -> Descendants<'a, 'input> {+ self.root().descendants()+ }++ /// Returns an element by ID.+ ///+ /// Unlike the [`Descendants`] iterator, this is just a HashMap lookup.+ /// Meaning it's way faster.+ #[inline]+ pub fn element_by_id<'a>(&'a self, id: &str) -> Option<SvgNode<'a, 'input>> {+ let node_id = self.links.get(id)?;+ Some(self.get(*node_id))+ }++ #[inline]+ fn get<'a>(&'a self, id: NodeId) -> SvgNode<'a, 'input> {+ SvgNode {+ id,+ d: &self.nodes[id.get_usize()],+ doc: self,+ }+ }+}++impl std::fmt::Debug for Document<'_> {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {+ if !self.root().has_children() {+ return write!(f, "Document []");+ }++ macro_rules! writeln_indented {+ ($depth:expr, $f:expr, $fmt:expr) => {+ for _ in 0..$depth { write!($f, " ")?; }+ writeln!($f, $fmt)?;+ };+ ($depth:expr, $f:expr, $fmt:expr, $($arg:tt)*) => {+ for _ in 0..$depth { write!($f, " ")?; }+ writeln!($f, $fmt, $($arg)*)?;+ };+ }++ fn print_children(+ parent: SvgNode,+ depth: usize,+ f: &mut std::fmt::Formatter,+ ) -> Result<(), std::fmt::Error> {+ for child in parent.children() {+ if child.is_element() {+ writeln_indented!(depth, f, "Element {{");+ writeln_indented!(depth, f, " tag_name: {:?}", child.tag_name());++ if !child.attributes().is_empty() {+ writeln_indented!(depth + 1, f, "attributes: [");+ for attr in child.attributes() {+ writeln_indented!(depth + 2, f, "{:?}", attr);+ }+ writeln_indented!(depth + 1, f, "]");+ }++ if child.has_children() {+ writeln_indented!(depth, f, " children: [");+ print_children(child, depth + 2, f)?;+ writeln_indented!(depth, f, " ]");+ }++ writeln_indented!(depth, f, "}}");+ } else {+ writeln_indented!(depth, f, "{:?}", child);+ }+ }++ Ok(())+ }++ writeln!(f, "Document [")?;+ print_children(self.root(), 1, f)?;+ writeln!(f, "]")?;++ Ok(())+ }+}++#[derive(Clone, Copy, Debug)]+pub(crate) struct ShortRange {+ start: u32,+ end: u32,+}++impl ShortRange {+ #[inline]+ fn new(start: u32, end: u32) -> Self {+ ShortRange { start, end }+ }++ #[inline]+ fn to_urange(self) -> std::ops::Range<usize> {+ self.start as usize..self.end as usize+ }+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub(crate) struct NodeId(NonZeroU32);++impl NodeId {+ #[inline]+ fn new(id: u32) -> Self {+ debug_assert!(id < u32::MAX);++ // We are using `NonZeroU32` to reduce overhead of `Option<NodeId>`.+ NodeId(NonZeroU32::new(id + 1).unwrap())+ }++ #[inline]+ fn get(self) -> u32 {+ self.0.get() - 1+ }++ #[inline]+ fn get_usize(self) -> usize {+ self.get() as usize+ }+}++impl From<usize> for NodeId {+ #[inline]+ fn from(id: usize) -> Self {+ // We already checked that `id` is limited by u32::MAX.+ debug_assert!(id <= u32::MAX as usize);+ NodeId::new(id as u32)+ }+}++pub(crate) enum NodeKind {+ Root,+ Element {+ tag_name: EId,+ attributes: ShortRange,+ },+ Text(String),+}++struct NodeData {+ parent: Option<NodeId>,+ next_sibling: Option<NodeId>,+ children: Option<(NodeId, NodeId)>,+ kind: NodeKind,+}++/// An attribute.+#[derive(Clone)]+pub struct Attribute<'input> {+ /// Attribute's name.+ pub name: AId,+ /// Attribute's value.+ pub value: roxmltree::StringStorage<'input>,+ /// Attribute's importance+ pub important: bool,+}++impl std::fmt::Debug for Attribute<'_> {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {+ write!(+ f,+ "Attribute {{ name: {:?}, value: {}, important: {} }}",+ self.name, self.value, self.important+ )+ }+}++/// An SVG node.+#[derive(Clone, Copy)]+pub struct SvgNode<'a, 'input: 'a> {+ id: NodeId,+ doc: &'a Document<'input>,+ d: &'a NodeData,+}++impl Eq for SvgNode<'_, '_> {}++impl PartialEq for SvgNode<'_, '_> {+ #[inline]+ fn eq(&self, other: &Self) -> bool {+ self.id == other.id && std::ptr::eq(self.doc, other.doc) && std::ptr::eq(self.d, other.d)+ }+}++impl<'a, 'input: 'a> SvgNode<'a, 'input> {+ #[inline]+ fn id(&self) -> NodeId {+ self.id+ }++ /// Checks if the current node is an element.+ #[inline]+ pub fn is_element(&self) -> bool {+ matches!(self.d.kind, NodeKind::Element { .. })+ }++ /// Checks if the current node is a text.+ #[inline]+ pub fn is_text(&self) -> bool {+ matches!(self.d.kind, NodeKind::Text(_))+ }++ /// Returns node's document.+ #[inline]+ pub fn document(&self) -> &'a Document<'input> {+ self.doc+ }++ /// Returns element's tag name, unless the current node is text.+ #[inline]+ pub fn tag_name(&self) -> Option<EId> {+ match self.d.kind {+ NodeKind::Element { tag_name, .. } => Some(tag_name),+ _ => None,+ }+ }+ /// Returns element's `id` attribute value.+ ///+ /// Returns an empty string otherwise.+ #[inline]+ pub fn element_id(&self) -> &'a str {+ self.attribute(AId::Id).unwrap_or("")+ }++ /// Returns an attribute value.+ pub fn attribute<T: FromValue<'a, 'input>>(&self, aid: AId) -> Option<T> {+ let value = self+ .attributes()+ .iter()+ .find(|a| a.name == aid)+ .map(|a| a.value.as_str())?;+ // These AId have an initial value of none+ let is_possible_none = matches!(+ aid,+ AId::Mask+ | AId::MarkerStart+ | AId::MarkerMid+ | AId::MarkerEnd+ | AId::ClipPath+ | AId::Filter+ | AId::FontSizeAdjust+ | AId::TextDecoration+ | AId::Stroke+ | AId::StrokeDasharray+ );+ if is_possible_none && value == "none" {+ return None;+ }+ match T::parse(*self, aid, value) {+ Some(v) => Some(v),+ None => {+ // TODO: show position in XML+ log::warn!("Failed to parse {} value: '{}'.", aid, value);+ None+ }+ }+ }++ /// Returns an attribute value.+ ///+ /// Same as `SvgNode::attribute`, but doesn't show a warning.+ pub fn try_attribute<T: FromValue<'a, 'input>>(&self, aid: AId) -> Option<T> {+ let value = self+ .attributes()+ .iter()+ .find(|a| a.name == aid)+ .map(|a| a.value.as_str())?;+ T::parse(*self, aid, value)+ }++ #[inline]+ fn node_attribute(&self, aid: AId) -> Option<SvgNode<'a, 'input>> {+ let value = self.attribute(aid)?;+ let id = if aid == AId::Href {+ svgtypes::IRI::from_str(value).ok().map(|v| v.0)+ } else {+ svgtypes::FuncIRI::from_str(value).ok().map(|v| v.0)+ }?;++ self.document().element_by_id(id)+ }++ /// Checks if an attribute is present.+ #[inline]+ pub fn has_attribute(&self, aid: AId) -> bool {+ self.attributes().iter().any(|a| a.name == aid)+ }++ /// Returns a list of all element's attributes.+ #[inline]+ pub fn attributes(&self) -> &'a [Attribute<'input>] {+ match self.d.kind {+ NodeKind::Element { ref attributes, .. } => &self.doc.attrs[attributes.to_urange()],+ _ => &[],+ }+ }++ #[inline]+ fn attribute_id(&self, aid: AId) -> Option<usize> {+ match self.d.kind {+ NodeKind::Element { ref attributes, .. } => {+ let idx = self.attributes().iter().position(|attr| attr.name == aid)?;+ Some(attributes.start as usize + idx)+ }+ _ => None,+ }+ }++ /// Finds a [`Node`] that contains the required attribute.+ ///+ /// For inheritable attributes walks over ancestors until a node with+ /// the specified attribute is found.+ ///+ /// For non-inheritable attributes checks only the current node and the parent one.+ /// As per SVG spec.+ pub fn find_attribute<T: FromValue<'a, 'input>>(&self, aid: AId) -> Option<T> {+ self.find_attribute_impl(aid)?.attribute(aid)+ }++ fn find_attribute_impl(&self, aid: AId) -> Option<SvgNode<'a, 'input>> {+ if aid.is_inheritable() {+ for n in self.ancestors() {+ if n.has_attribute(aid) {+ return Some(n);+ }+ }++ None+ } else {+ if self.has_attribute(aid) {+ Some(*self)+ } else {+ // Non-inheritable attributes can inherit a value only from a direct parent.+ let n = self.parent_element()?;+ if n.has_attribute(aid) { Some(n) } else { None }+ }+ }+ }++ /// Returns node's text data.+ ///+ /// For text nodes returns its content. For elements returns the first child node text.+ #[inline]+ pub fn text(&self) -> &'a str {+ match self.d.kind {+ NodeKind::Element { .. } => match self.first_child() {+ Some(child) if child.is_text() => match self.doc.nodes[child.id.get_usize()].kind {+ NodeKind::Text(ref text) => text,+ _ => "",+ },+ _ => "",+ },+ NodeKind::Text(ref text) => text,+ _ => "",+ }+ }++ /// Returns a parent node.+ #[inline]+ pub fn parent(&self) -> Option<Self> {+ self.d.parent.map(|id| self.doc.get(id))+ }++ /// Returns the parent element.+ #[inline]+ pub fn parent_element(&self) -> Option<Self> {+ self.ancestors().skip(1).find(|n| n.is_element())+ }++ /// Returns the next sibling.+ #[inline]+ pub fn next_sibling(&self) -> Option<Self> {+ self.d.next_sibling.map(|id| self.doc.get(id))+ }++ /// Returns the first child.+ #[inline]+ pub fn first_child(&self) -> Option<Self> {+ self.d.children.map(|(id, _)| self.doc.get(id))+ }++ /// Returns the first child element.+ #[inline]+ pub fn first_element_child(&self) -> Option<Self> {+ self.children().find(|n| n.is_element())+ }++ /// Returns the last child.+ #[inline]+ pub fn last_child(&self) -> Option<Self> {+ self.d.children.map(|(_, id)| self.doc.get(id))+ }++ /// Checks if the node has child nodes.+ #[inline]+ pub fn has_children(&self) -> bool {+ self.d.children.is_some()+ }++ /// Returns an iterator over ancestor nodes starting at this node.+ #[inline]+ pub fn ancestors(&self) -> Ancestors<'a, 'input> {+ Ancestors(Some(*self))+ }++ /// Returns an iterator over children nodes.+ #[inline]+ pub fn children(&self) -> Children<'a, 'input> {+ Children {+ front: self.first_child(),+ back: self.last_child(),+ }+ }++ /// Returns an iterator which traverses the subtree starting at this node.+ #[inline]+ fn traverse(&self) -> Traverse<'a, 'input> {+ Traverse {+ root: *self,+ edge: None,+ }+ }++ /// Returns an iterator over this node and its descendants.+ #[inline]+ pub fn descendants(&self) -> Descendants<'a, 'input> {+ Descendants(self.traverse())+ }++ /// Returns an iterator over elements linked via `xlink:href`.+ #[inline]+ pub fn href_iter(&self) -> HrefIter<'a, 'input> {+ HrefIter {+ doc: self.document(),+ origin: self.id(),+ curr: self.id(),+ is_first: true,+ is_finished: false,+ }+ }+}++impl std::fmt::Debug for SvgNode<'_, '_> {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {+ match self.d.kind {+ NodeKind::Root => write!(f, "Root"),+ NodeKind::Element { .. } => {+ write!(+ f,+ "Element {{ tag_name: {:?}, attributes: {:?} }}",+ self.tag_name(),+ self.attributes()+ )+ }+ NodeKind::Text(ref text) => write!(f, "Text({:?})", text),+ }+ }+}++/// An iterator over ancestor nodes.+#[derive(Clone, Debug)]+pub struct Ancestors<'a, 'input: 'a>(Option<SvgNode<'a, 'input>>);++impl<'a, 'input: 'a> Iterator for Ancestors<'a, 'input> {+ type Item = SvgNode<'a, 'input>;++ #[inline]+ fn next(&mut self) -> Option<Self::Item> {+ let node = self.0.take();+ self.0 = node.as_ref().and_then(SvgNode::parent);+ node+ }+}++/// An iterator over children nodes.+#[derive(Clone, Debug)]+pub struct Children<'a, 'input: 'a> {+ front: Option<SvgNode<'a, 'input>>,+ back: Option<SvgNode<'a, 'input>>,+}++impl<'a, 'input: 'a> Iterator for Children<'a, 'input> {+ type Item = SvgNode<'a, 'input>;++ fn next(&mut self) -> Option<Self::Item> {+ let node = self.front.take();+ if self.front == self.back {+ self.back = None;+ } else {+ self.front = node.as_ref().and_then(SvgNode::next_sibling);+ }+ node+ }+}++#[derive(Clone, Copy, PartialEq, Debug)]+enum Edge<'a, 'input: 'a> {+ Open(SvgNode<'a, 'input>),+ Close(SvgNode<'a, 'input>),+}++#[derive(Clone, Debug)]+struct Traverse<'a, 'input: 'a> {+ root: SvgNode<'a, 'input>,+ edge: Option<Edge<'a, 'input>>,+}++impl<'a, 'input: 'a> Iterator for Traverse<'a, 'input> {+ type Item = Edge<'a, 'input>;++ fn next(&mut self) -> Option<Self::Item> {+ match self.edge {+ Some(Edge::Open(node)) => {+ self.edge = Some(match node.first_child() {+ Some(first_child) => Edge::Open(first_child),+ None => Edge::Close(node),+ });+ }+ Some(Edge::Close(node)) => {+ if node == self.root {+ self.edge = None;+ } else if let Some(next_sibling) = node.next_sibling() {+ self.edge = Some(Edge::Open(next_sibling));+ } else {+ self.edge = node.parent().map(Edge::Close);+ }+ }+ None => {+ self.edge = Some(Edge::Open(self.root));+ }+ }++ self.edge+ }+}++/// A descendants iterator.+#[derive(Clone, Debug)]+pub struct Descendants<'a, 'input: 'a>(Traverse<'a, 'input>);++impl<'a, 'input: 'a> Iterator for Descendants<'a, 'input> {+ type Item = SvgNode<'a, 'input>;++ #[inline]+ fn next(&mut self) -> Option<Self::Item> {+ for edge in &mut self.0 {+ if let Edge::Open(node) = edge {+ return Some(node);+ }+ }++ None+ }+}++/// An iterator over `xlink:href` references.+#[derive(Clone, Debug)]+pub struct HrefIter<'a, 'input: 'a> {+ doc: &'a Document<'input>,+ origin: NodeId,+ curr: NodeId,+ is_first: bool,+ is_finished: bool,+}++impl<'a, 'input: 'a> Iterator for HrefIter<'a, 'input> {+ type Item = SvgNode<'a, 'input>;++ fn next(&mut self) -> Option<Self::Item> {+ if self.is_finished {+ return None;+ }++ if self.is_first {+ self.is_first = false;+ return Some(self.doc.get(self.curr));+ }++ if let Some(link) = self.doc.get(self.curr).node_attribute(AId::Href) {+ if link.id() == self.curr || link.id() == self.origin {+ log::warn!(+ "Element '#{}' cannot reference itself via 'xlink:href'.",+ self.doc.get(self.origin).element_id()+ );+ self.is_finished = true;+ return None;+ }++ self.curr = link.id();+ Some(self.doc.get(self.curr))+ } else {+ None+ }+ }+}++impl EId {+ /// Checks if this is a+ /// [graphics element](https://www.w3.org/TR/SVG11/intro.html#TermGraphicsElement).+ pub fn is_graphic(&self) -> bool {+ matches!(+ self,+ EId::Circle+ | EId::Ellipse+ | EId::Image+ | EId::Line+ | EId::Path+ | EId::Polygon+ | EId::Polyline+ | EId::Rect+ | EId::Text+ | EId::Use+ )+ }++ /// Checks if this is a+ /// [gradient element](https://www.w3.org/TR/SVG11/intro.html#TermGradientElement).+ pub fn is_gradient(&self) -> bool {+ matches!(self, EId::LinearGradient | EId::RadialGradient)+ }++ /// Checks if this is a+ /// [paint server element](https://www.w3.org/TR/SVG11/intro.html#TermPaint).+ pub fn is_paint_server(&self) -> bool {+ matches!(+ self,+ EId::LinearGradient | EId::RadialGradient | EId::Pattern+ )+ }+}++impl AId {+ fn is_presentation(&self) -> bool {+ matches!(+ self,+ AId::AlignmentBaseline+ | AId::BaselineShift+ | AId::BackgroundColor // non-standard SVG attribute+ | AId::ClipPath+ | AId::ClipRule+ | AId::Color+ | AId::ColorInterpolation+ | AId::ColorInterpolationFilters+ | AId::ColorRendering+ | AId::Direction+ | AId::Display+ | AId::DominantBaseline+ | AId::Fill+ | AId::FillOpacity+ | AId::FillRule+ | AId::Filter+ | AId::FloodColor+ | AId::FloodOpacity+ | AId::FontFamily+ | AId::FontKerning // technically not presentation+ | AId::FontOpticalSizing // technically not presentation+ | AId::FontSize+ | AId::FontSizeAdjust+ | AId::FontStretch+ | AId::FontStyle+ | AId::FontVariant+ | AId::FontWeight+ | AId::FontVariationSettings+ | AId::GlyphOrientationHorizontal+ | AId::GlyphOrientationVertical+ | AId::ImageRendering+ | AId::Isolation // technically not presentation+ | AId::LetterSpacing+ | AId::LightingColor+ | AId::MarkerEnd+ | AId::MarkerMid+ | AId::MarkerStart+ | AId::Mask+ | AId::MaskType+ | AId::MixBlendMode // technically not presentation+ | AId::Opacity+ | AId::Overflow+ | AId::PaintOrder+ | AId::ShapeRendering+ | AId::StopColor+ | AId::StopOpacity+ | AId::Stroke+ | AId::StrokeDasharray+ | AId::StrokeDashoffset+ | AId::StrokeLinecap+ | AId::StrokeLinejoin+ | AId::StrokeMiterlimit+ | AId::StrokeOpacity+ | AId::StrokeWidth+ | AId::TextAnchor+ | AId::TextDecoration+ | AId::TextOverflow+ | AId::TextRendering+ | AId::Transform+ | AId::TransformOrigin+ | AId::UnicodeBidi+ | AId::VectorEffect+ | AId::Visibility+ | AId::WhiteSpace+ | AId::WordSpacing+ | AId::WritingMode+ )+ }++ /// Checks if the current attribute is inheritable.+ fn is_inheritable(&self) -> bool {+ if self.is_presentation() {+ !is_non_inheritable(*self)+ } else {+ false+ }+ }++ fn allows_inherit_value(&self) -> bool {+ matches!(+ self,+ AId::AlignmentBaseline+ | AId::BaselineShift+ | AId::ClipPath+ | AId::ClipRule+ | AId::Color+ | AId::ColorInterpolationFilters+ | AId::Direction+ | AId::Display+ | AId::DominantBaseline+ | AId::Fill+ | AId::FillOpacity+ | AId::FillRule+ | AId::Filter+ | AId::FloodColor+ | AId::FloodOpacity+ | AId::FontFamily+ | AId::FontKerning+ | AId::FontOpticalSizing+ | AId::FontSize+ | AId::FontStretch+ | AId::FontStyle+ | AId::FontVariant+ | AId::FontWeight+ | AId::ImageRendering+ | AId::Kerning+ | AId::LetterSpacing+ | AId::MarkerEnd+ | AId::MarkerMid+ | AId::MarkerStart+ | AId::Mask+ | AId::Opacity+ | AId::Overflow+ | AId::ShapeRendering+ | AId::StopColor+ | AId::StopOpacity+ | AId::Stroke+ | AId::StrokeDasharray+ | AId::StrokeDashoffset+ | AId::StrokeLinecap+ | AId::StrokeLinejoin+ | AId::StrokeMiterlimit+ | AId::StrokeOpacity+ | AId::StrokeWidth+ | AId::TextAnchor+ | AId::TextDecoration+ | AId::TextRendering+ | AId::Visibility+ | AId::WordSpacing+ | AId::WritingMode+ )+ }+}++fn is_non_inheritable(id: AId) -> bool {+ matches!(+ id,+ AId::AlignmentBaseline+ | AId::BaselineShift+ | AId::ClipPath+ | AId::Display+ | AId::DominantBaseline+ | AId::Filter+ | AId::FloodColor+ | AId::FloodOpacity+ | AId::Mask+ | AId::Opacity+ | AId::Overflow+ | AId::LightingColor+ | AId::StopColor+ | AId::StopOpacity+ | AId::TextDecoration+ | AId::Transform+ | AId::TransformOrigin+ )+}++// TODO: is there a way yo make it less ugly? Too many lifetimes.+/// A trait for parsing attribute values.+pub trait FromValue<'a, 'input: 'a>: Sized {+ /// Parses an attribute value.+ ///+ /// When `None` is returned, the attribute value will be logged as a parsing failure.+ fn parse(node: SvgNode<'a, 'input>, aid: AId, value: &'a str) -> Option<Self>;+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for &'a str {+ fn parse(_: SvgNode<'a, 'input>, _: AId, value: &'a str) -> Option<Self> {+ Some(value)+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for f32 {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ svgtypes::Number::from_str(value).ok().map(|v| v.0 as f32)+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::Length {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ svgtypes::Length::from_str(value).ok()+ }+}++// TODO: to svgtypes?+impl<'a, 'input: 'a> FromValue<'a, 'input> for Opacity {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ let length = svgtypes::Length::from_str(value).ok()?;+ if length.unit == svgtypes::LengthUnit::Percent {+ Some(Opacity::new_clamped(length.number as f32 / 100.0))+ } else if length.unit == svgtypes::LengthUnit::None {+ Some(Opacity::new_clamped(length.number as f32))+ } else {+ None+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for Transform {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ let ts = match svgtypes::Transform::from_str(value) {+ Ok(v) => v,+ Err(_) => return None,+ };++ let ts = Transform::from_row(+ ts.a as f32,+ ts.b as f32,+ ts.c as f32,+ ts.d as f32,+ ts.e as f32,+ ts.f as f32,+ );++ if ts.is_valid() {+ Some(ts)+ } else {+ Some(Transform::default())+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::TransformOrigin {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ Self::from_str(value).ok()+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::ViewBox {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ Self::from_str(value).ok()+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for Units {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "userSpaceOnUse" => Some(Units::UserSpaceOnUse),+ "objectBoundingBox" => Some(Units::ObjectBoundingBox),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::AspectRatio {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ Self::from_str(value).ok()+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::PaintOrder {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ Self::from_str(value).ok()+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::Color {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ Self::from_str(value).ok()+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::Angle {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ Self::from_str(value).ok()+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::EnableBackground {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ Self::from_str(value).ok()+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for svgtypes::Paint<'a> {+ fn parse(_: SvgNode, _: AId, value: &'a str) -> Option<Self> {+ Self::from_str(value).ok()+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for Vec<f32> {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ let mut list = Vec::new();+ for n in svgtypes::NumberListParser::from(value) {+ list.push(n.ok()? as f32);+ }++ Some(list)+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for Vec<svgtypes::Length> {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ let mut list = Vec::new();+ for n in svgtypes::LengthListParser::from(value) {+ list.push(n.ok()?);+ }++ Some(list)+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for Visibility {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "visible" => Some(Visibility::Visible),+ "hidden" => Some(Visibility::Hidden),+ "collapse" => Some(Visibility::Collapse),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for SpreadMethod {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "pad" => Some(SpreadMethod::Pad),+ "reflect" => Some(SpreadMethod::Reflect),+ "repeat" => Some(SpreadMethod::Repeat),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for ShapeRendering {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "optimizeSpeed" => Some(ShapeRendering::OptimizeSpeed),+ "crispEdges" => Some(ShapeRendering::CrispEdges),+ "auto" | "geometricPrecision" => Some(ShapeRendering::GeometricPrecision),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for TextRendering {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "optimizeSpeed" => Some(TextRendering::OptimizeSpeed),+ "auto" | "optimizeLegibility" => Some(TextRendering::OptimizeLegibility),+ "geometricPrecision" => Some(TextRendering::GeometricPrecision),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for ImageRendering {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "auto" | "optimizeQuality" => Some(ImageRendering::OptimizeQuality),+ "optimizeSpeed" => Some(ImageRendering::OptimizeSpeed),+ "smooth" => Some(ImageRendering::Smooth),+ "high-quality" => Some(ImageRendering::HighQuality),+ "crisp-edges" => Some(ImageRendering::CrispEdges),+ "pixelated" => Some(ImageRendering::Pixelated),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for BlendMode {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "normal" => Some(BlendMode::Normal),+ "multiply" => Some(BlendMode::Multiply),+ "screen" => Some(BlendMode::Screen),+ "overlay" => Some(BlendMode::Overlay),+ "darken" => Some(BlendMode::Darken),+ "lighten" => Some(BlendMode::Lighten),+ "color-dodge" => Some(BlendMode::ColorDodge),+ "color-burn" => Some(BlendMode::ColorBurn),+ "hard-light" => Some(BlendMode::HardLight),+ "soft-light" => Some(BlendMode::SoftLight),+ "difference" => Some(BlendMode::Difference),+ "exclusion" => Some(BlendMode::Exclusion),+ "hue" => Some(BlendMode::Hue),+ "saturation" => Some(BlendMode::Saturation),+ "color" => Some(BlendMode::Color),+ "luminosity" => Some(BlendMode::Luminosity),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for SvgNode<'a, 'input> {+ fn parse(node: SvgNode<'a, 'input>, aid: AId, value: &str) -> Option<Self> {+ let id = if aid == AId::Href {+ svgtypes::IRI::from_str(value).ok().map(|v| v.0)+ } else {+ svgtypes::FuncIRI::from_str(value).ok().map(|v| v.0)+ }?;++ node.document().element_by_id(id)+ }+}diff --git a/vendor/usvg/src/parser/svgtree/names.rs b/vendor/usvg/src/parser/svgtree/names.rsnew file mode 100644index 00000000..d2afec15--- /dev/null+++ b/vendor/usvg/src/parser/svgtree/names.rs@@ -0,0 +1,722 @@+// Copyright 2019 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++// This file is autogenerated. Do not edit it!+// See ./codegen for details.++/// An element ID.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq)]+pub enum EId {+ A,+ Circle,+ ClipPath,+ Defs,+ Ellipse,+ FeBlend,+ FeColorMatrix,+ FeComponentTransfer,+ FeComposite,+ FeConvolveMatrix,+ FeDiffuseLighting,+ FeDisplacementMap,+ FeDistantLight,+ FeDropShadow,+ FeFlood,+ FeFuncA,+ FeFuncB,+ FeFuncG,+ FeFuncR,+ FeGaussianBlur,+ FeImage,+ FeMerge,+ FeMergeNode,+ FeMorphology,+ FeOffset,+ FePointLight,+ FeSpecularLighting,+ FeSpotLight,+ FeTile,+ FeTurbulence,+ Filter,+ G,+ Image,+ Line,+ LinearGradient,+ Marker,+ Mask,+ Path,+ Pattern,+ Polygon,+ Polyline,+ RadialGradient,+ Rect,+ Stop,+ Style,+ Svg,+ Switch,+ Symbol,+ Text,+ TextPath,+ Tref,+ Tspan,+ Use+}++static ELEMENTS: Map<EId> = Map {+ key: 732231254413039614,+ disps: &[+ (0, 12),+ (1, 11),+ (10, 26),+ (2, 42),+ (1, 19),+ (0, 5),+ (1, 13),+ (8, 50),+ (0, 0),+ (1, 0),+ (7, 45),+ ],+ entries: &[+ ("feFlood", EId::FeFlood),+ ("radialGradient", EId::RadialGradient),+ ("feImage", EId::FeImage),+ ("stop", EId::Stop),+ ("fePointLight", EId::FePointLight),+ ("feConvolveMatrix", EId::FeConvolveMatrix),+ ("feComposite", EId::FeComposite),+ ("clipPath", EId::ClipPath),+ ("feMerge", EId::FeMerge),+ ("defs", EId::Defs),+ ("mask", EId::Mask),+ ("svg", EId::Svg),+ ("symbol", EId::Symbol),+ ("linearGradient", EId::LinearGradient),+ ("feSpecularLighting", EId::FeSpecularLighting),+ ("feFuncB", EId::FeFuncB),+ ("filter", EId::Filter),+ ("feFuncG", EId::FeFuncG),+ ("circle", EId::Circle),+ ("g", EId::G),+ ("tref", EId::Tref),+ ("feFuncA", EId::FeFuncA),+ ("image", EId::Image),+ ("text", EId::Text),+ ("line", EId::Line),+ ("pattern", EId::Pattern),+ ("use", EId::Use),+ ("feDropShadow", EId::FeDropShadow),+ ("feSpotLight", EId::FeSpotLight),+ ("marker", EId::Marker),+ ("style", EId::Style),+ ("switch", EId::Switch),+ ("tspan", EId::Tspan),+ ("feColorMatrix", EId::FeColorMatrix),+ ("feOffset", EId::FeOffset),+ ("path", EId::Path),+ ("feGaussianBlur", EId::FeGaussianBlur),+ ("feTile", EId::FeTile),+ ("feTurbulence", EId::FeTurbulence),+ ("feMergeNode", EId::FeMergeNode),+ ("feMorphology", EId::FeMorphology),+ ("a", EId::A),+ ("textPath", EId::TextPath),+ ("ellipse", EId::Ellipse),+ ("feComponentTransfer", EId::FeComponentTransfer),+ ("feDistantLight", EId::FeDistantLight),+ ("polyline", EId::Polyline),+ ("polygon", EId::Polygon),+ ("feBlend", EId::FeBlend),+ ("feDisplacementMap", EId::FeDisplacementMap),+ ("feDiffuseLighting", EId::FeDiffuseLighting),+ ("rect", EId::Rect),+ ("feFuncR", EId::FeFuncR),+ ],+};++impl EId {+ pub(crate) fn from_str(text: &str) -> Option<EId> {+ ELEMENTS.get(text).cloned()+ }++ /// Returns the original string.+ #[inline(never)]+ pub fn to_str(self) -> &'static str {+ ELEMENTS.key(&self)+ }+}++impl std::fmt::Debug for EId {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ write!(f, "{}", self.to_str())+ }+}++impl std::fmt::Display for EId {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ write!(f, "{:?}", self)+ }+}++/// An attribute ID.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq)]+pub enum AId {+ AlignmentBaseline,+ Amplitude,+ Azimuth,+ BackgroundColor,+ BaseFrequency,+ BaselineShift,+ Bias,+ Class,+ Clip,+ ClipPath,+ ClipRule,+ ClipPathUnits,+ Color,+ ColorInterpolation,+ ColorInterpolationFilters,+ ColorProfile,+ ColorRendering,+ Cx,+ Cy,+ D,+ DiffuseConstant,+ Direction,+ Display,+ Divisor,+ DominantBaseline,+ Dx,+ Dy,+ EdgeMode,+ Elevation,+ EnableBackground,+ Exponent,+ Fill,+ FillOpacity,+ FillRule,+ Filter,+ FilterUnits,+ FloodColor,+ FloodOpacity,+ Font,+ FontFamily,+ FontFeatureSettings,+ FontKerning,+ FontOpticalSizing,+ FontSize,+ FontSizeAdjust,+ FontStretch,+ FontStyle,+ FontSynthesis,+ FontVariant,+ FontVariantCaps,+ FontVariantEastAsian,+ FontVariantLigatures,+ FontVariantNumeric,+ FontVariantPosition,+ FontVariationSettings,+ FontWeight,+ Fr,+ Fx,+ Fy,+ GlyphOrientationHorizontal,+ GlyphOrientationVertical,+ GradientTransform,+ GradientUnits,+ Height,+ Href,+ Id,+ ImageRendering,+ In,+ In2,+ InlineSize,+ Intercept,+ Isolation,+ K1,+ K2,+ K3,+ K4,+ KernelMatrix,+ KernelUnitLength,+ Kerning,+ LengthAdjust,+ LetterSpacing,+ LightingColor,+ LimitingConeAngle,+ LineHeight,+ MarkerEnd,+ MarkerMid,+ MarkerStart,+ MarkerHeight,+ MarkerUnits,+ MarkerWidth,+ Mask,+ MaskBorder,+ MaskBorderMode,+ MaskBorderOutset,+ MaskBorderRepeat,+ MaskBorderSlice,+ MaskBorderSource,+ MaskBorderWidth,+ MaskClip,+ MaskComposite,+ MaskImage,+ MaskMode,+ MaskOrigin,+ MaskPosition,+ MaskSize,+ MaskType,+ MaskContentUnits,+ MaskUnits,+ MixBlendMode,+ Mode,+ NumOctaves,+ Offset,+ Opacity,+ Operator,+ Order,+ Orient,+ Overflow,+ PaintOrder,+ Path,+ PathLength,+ PatternContentUnits,+ PatternTransform,+ PatternUnits,+ Points,+ PointsAtX,+ PointsAtY,+ PointsAtZ,+ PreserveAlpha,+ PreserveAspectRatio,+ PrimitiveUnits,+ R,+ Radius,+ RefX,+ RefY,+ RequiredExtensions,+ RequiredFeatures,+ Result,+ Rotate,+ Rx,+ Ry,+ Scale,+ Seed,+ ShapeImageThreshold,+ ShapeInside,+ ShapeMargin,+ ShapePadding,+ ShapeRendering,+ ShapeSubtract,+ Side,+ Slope,+ Space,+ SpecularConstant,+ SpecularExponent,+ SpreadMethod,+ StartOffset,+ StdDeviation,+ StitchTiles,+ StopColor,+ StopOpacity,+ Stroke,+ StrokeDasharray,+ StrokeDashoffset,+ StrokeLinecap,+ StrokeLinejoin,+ StrokeMiterlimit,+ StrokeOpacity,+ StrokeWidth,+ Style,+ SurfaceScale,+ SystemLanguage,+ TableValues,+ TargetX,+ TargetY,+ TextAlign,+ TextAlignLast,+ TextAnchor,+ TextDecoration,+ TextDecorationColor,+ TextDecorationFill,+ TextDecorationLine,+ TextDecorationStroke,+ TextDecorationStyle,+ TextIndent,+ TextOrientation,+ TextOverflow,+ TextRendering,+ TextUnderlinePosition,+ TextLength,+ Transform,+ TransformBox,+ TransformOrigin,+ Type,+ UnicodeBidi,+ UnicodeRange,+ Values,+ VectorEffect,+ ViewBox,+ Visibility,+ WhiteSpace,+ Width,+ WordSpacing,+ WritingMode,+ X,+ X1,+ X2,+ XChannelSelector,+ Y,+ Y1,+ Y2,+ YChannelSelector,+ Z+}++static ATTRIBUTES: Map<AId> = Map {+ key: 3213172566270843353,+ disps: &[+ (0, 63),+ (4, 146),+ (0, 0),+ (3, 42),+ (2, 197),+ (0, 0),+ (0, 1),+ (0, 0),+ (0, 0),+ (0, 18),+ (0, 11),+ (1, 20),+ (0, 8),+ (17, 110),+ (1, 112),+ (1, 108),+ (5, 94),+ (2, 128),+ (4, 95),+ (0, 63),+ (0, 96),+ (0, 0),+ (1, 110),+ (0, 1),+ (40, 30),+ (17, 157),+ (0, 61),+ (0, 16),+ (7, 16),+ (0, 80),+ (0, 107),+ (6, 111),+ (0, 153),+ (6, 202),+ (18, 86),+ (0, 194),+ (0, 0),+ (0, 7),+ (0, 69),+ (0, 5),+ (0, 19),+ (0, 0),+ (4, 65),+ ],+ entries: &[+ ("alignment-baseline", AId::AlignmentBaseline),+ ("fx", AId::Fx),+ ("targetY", AId::TargetY),+ ("clip-path", AId::ClipPath),+ ("lengthAdjust", AId::LengthAdjust),+ ("mask-size", AId::MaskSize),+ ("unicode-bidi", AId::UnicodeBidi),+ ("z", AId::Z),+ ("font-variant-numeric", AId::FontVariantNumeric),+ ("clip-rule", AId::ClipRule),+ ("font", AId::Font),+ ("gradientUnits", AId::GradientUnits),+ ("style", AId::Style),+ ("font-stretch", AId::FontStretch),+ ("intercept", AId::Intercept),+ ("mask-border-slice", AId::MaskBorderSlice),+ ("y", AId::Y),+ ("xChannelSelector", AId::XChannelSelector),+ ("numOctaves", AId::NumOctaves),+ ("x1", AId::X1),+ ("fill-rule", AId::FillRule),+ ("image-rendering", AId::ImageRendering),+ ("surfaceScale", AId::SurfaceScale),+ ("seed", AId::Seed),+ ("mix-blend-mode", AId::MixBlendMode),+ ("path", AId::Path),+ ("mask-border-repeat", AId::MaskBorderRepeat),+ ("transform", AId::Transform),+ ("stroke", AId::Stroke),+ ("refX", AId::RefX),+ ("text-orientation", AId::TextOrientation),+ ("line-height", AId::LineHeight),+ ("display", AId::Display),+ ("kerning", AId::Kerning),+ ("transform-origin", AId::TransformOrigin),+ ("shape-subtract", AId::ShapeSubtract),+ ("width", AId::Width),+ ("stroke-miterlimit", AId::StrokeMiterlimit),+ ("dy", AId::Dy),+ ("text-decoration-color", AId::TextDecorationColor),+ ("white-space", AId::WhiteSpace),+ ("diffuseConstant", AId::DiffuseConstant),+ ("text-decoration-stroke", AId::TextDecorationStroke),+ ("values", AId::Values),+ ("font-size", AId::FontSize),+ ("shape-image-threshold", AId::ShapeImageThreshold),+ ("href", AId::Href),+ ("cy", AId::Cy),+ ("mask-image", AId::MaskImage),+ ("unicode-range", AId::UnicodeRange),+ ("specularConstant", AId::SpecularConstant),+ ("baseline-shift", AId::BaselineShift),+ ("k3", AId::K3),+ ("text-anchor", AId::TextAnchor),+ ("mask-border-mode", AId::MaskBorderMode),+ ("requiredFeatures", AId::RequiredFeatures),+ ("color-rendering", AId::ColorRendering),+ ("amplitude", AId::Amplitude),+ ("mask-border-width", AId::MaskBorderWidth),+ ("stroke-linecap", AId::StrokeLinecap),+ ("paint-order", AId::PaintOrder),+ ("lighting-color", AId::LightingColor),+ ("dx", AId::Dx),+ ("markerWidth", AId::MarkerWidth),+ ("scale", AId::Scale),+ ("id", AId::Id),+ ("color", AId::Color),+ ("in2", AId::In2),+ ("targetX", AId::TargetX),+ ("direction", AId::Direction),+ ("pointsAtX", AId::PointsAtX),+ ("stitchTiles", AId::StitchTiles),+ ("patternUnits", AId::PatternUnits),+ ("shape-padding", AId::ShapePadding),+ ("k2", AId::K2),+ ("font-optical-sizing", AId::FontOpticalSizing),+ ("k4", AId::K4),+ ("vector-effect", AId::VectorEffect),+ ("mask-composite", AId::MaskComposite),+ ("stroke-width", AId::StrokeWidth),+ ("font-variation-settings", AId::FontVariationSettings),+ ("mask-border-outset", AId::MaskBorderOutset),+ ("in", AId::In),+ ("stroke-linejoin", AId::StrokeLinejoin),+ ("stop-opacity", AId::StopOpacity),+ ("inline-size", AId::InlineSize),+ ("mask-type", AId::MaskType),+ ("filterUnits", AId::FilterUnits),+ ("color-profile", AId::ColorProfile),+ ("space", AId::Space),+ ("text-decoration-fill", AId::TextDecorationFill),+ ("font-kerning", AId::FontKerning),+ ("offset", AId::Offset),+ ("pointsAtZ", AId::PointsAtZ),+ ("text-align", AId::TextAlign),+ ("clip", AId::Clip),+ ("y1", AId::Y1),+ ("mask-origin", AId::MaskOrigin),+ ("mask-mode", AId::MaskMode),+ ("yChannelSelector", AId::YChannelSelector),+ ("font-variant-caps", AId::FontVariantCaps),+ ("marker-mid", AId::MarkerMid),+ ("shape-rendering", AId::ShapeRendering),+ ("text-rendering", AId::TextRendering),+ ("fill-opacity", AId::FillOpacity),+ ("word-spacing", AId::WordSpacing),+ ("fill", AId::Fill),+ ("mask-clip", AId::MaskClip),+ ("font-feature-settings", AId::FontFeatureSettings),+ ("radius", AId::Radius),+ ("kernelMatrix", AId::KernelMatrix),+ ("kernelUnitLength", AId::KernelUnitLength),+ ("mask-border-source", AId::MaskBorderSource),+ ("k1", AId::K1),+ ("mask", AId::Mask),+ ("opacity", AId::Opacity),+ ("markerUnits", AId::MarkerUnits),+ ("visibility", AId::Visibility),+ ("spreadMethod", AId::SpreadMethod),+ ("pointsAtY", AId::PointsAtY),+ ("d", AId::D),+ ("slope", AId::Slope),+ ("side", AId::Side),+ ("tableValues", AId::TableValues),+ ("order", AId::Order),+ ("text-align-last", AId::TextAlignLast),+ ("font-size-adjust", AId::FontSizeAdjust),+ ("rotate", AId::Rotate),+ ("shape-margin", AId::ShapeMargin),+ ("limitingConeAngle", AId::LimitingConeAngle),+ ("font-weight", AId::FontWeight),+ ("text-decoration-line", AId::TextDecorationLine),+ ("stop-color", AId::StopColor),+ ("requiredExtensions", AId::RequiredExtensions),+ ("enable-background", AId::EnableBackground),+ ("systemLanguage", AId::SystemLanguage),+ ("clipPathUnits", AId::ClipPathUnits),+ ("stroke-dashoffset", AId::StrokeDashoffset),+ ("ry", AId::Ry),+ ("overflow", AId::Overflow),+ ("class", AId::Class),+ ("mask-border", AId::MaskBorder),+ ("specularExponent", AId::SpecularExponent),+ ("text-decoration", AId::TextDecoration),+ ("startOffset", AId::StartOffset),+ ("stroke-dasharray", AId::StrokeDasharray),+ ("fr", AId::Fr),+ ("mask-position", AId::MaskPosition),+ ("writing-mode", AId::WritingMode),+ ("font-synthesis", AId::FontSynthesis),+ ("isolation", AId::Isolation),+ ("rx", AId::Rx),+ ("bias", AId::Bias),+ ("markerHeight", AId::MarkerHeight),+ ("edgeMode", AId::EdgeMode),+ ("r", AId::R),+ ("stroke-opacity", AId::StrokeOpacity),+ ("maskContentUnits", AId::MaskContentUnits),+ ("height", AId::Height),+ ("font-variant-position", AId::FontVariantPosition),+ ("operator", AId::Operator),+ ("font-family", AId::FontFamily),+ ("fy", AId::Fy),+ ("dominant-baseline", AId::DominantBaseline),+ ("y2", AId::Y2),+ ("shape-inside", AId::ShapeInside),+ ("letter-spacing", AId::LetterSpacing),+ ("azimuth", AId::Azimuth),+ ("stdDeviation", AId::StdDeviation),+ ("flood-color", AId::FloodColor),+ ("flood-opacity", AId::FloodOpacity),+ ("type", AId::Type),+ ("font-variant-east-asian", AId::FontVariantEastAsian),+ ("points", AId::Points),+ ("refY", AId::RefY),+ ("text-underline-position", AId::TextUnderlinePosition),+ ("patternContentUnits", AId::PatternContentUnits),+ ("baseFrequency", AId::BaseFrequency),+ ("color-interpolation", AId::ColorInterpolation),+ ("font-variant-ligatures", AId::FontVariantLigatures),+ ("font-style", AId::FontStyle),+ ("filter", AId::Filter),+ ("text-decoration-style", AId::TextDecorationStyle),+ ("preserveAlpha", AId::PreserveAlpha),+ ("mode", AId::Mode),+ ("divisor", AId::Divisor),+ ("cx", AId::Cx),+ ("patternTransform", AId::PatternTransform),+ ("background-color", AId::BackgroundColor),+ ("preserveAspectRatio", AId::PreserveAspectRatio),+ ("gradientTransform", AId::GradientTransform),+ ("x2", AId::X2),+ ("pathLength", AId::PathLength),+ ("marker-start", AId::MarkerStart),+ ("glyph-orientation-horizontal", AId::GlyphOrientationHorizontal),+ ("maskUnits", AId::MaskUnits),+ ("textLength", AId::TextLength),+ ("viewBox", AId::ViewBox),+ ("text-overflow", AId::TextOverflow),+ ("glyph-orientation-vertical", AId::GlyphOrientationVertical),+ ("result", AId::Result),+ ("primitiveUnits", AId::PrimitiveUnits),+ ("exponent", AId::Exponent),+ ("x", AId::X),+ ("font-variant", AId::FontVariant),+ ("elevation", AId::Elevation),+ ("color-interpolation-filters", AId::ColorInterpolationFilters),+ ("text-indent", AId::TextIndent),+ ("marker-end", AId::MarkerEnd),+ ("transform-box", AId::TransformBox),+ ("orient", AId::Orient),+ ],+};++impl AId {+ pub(crate) fn from_str(text: &str) -> Option<AId> {+ ATTRIBUTES.get(text).cloned()+ }++ /// Returns the original string.+ #[inline(never)]+ pub fn to_str(self) -> &'static str {+ ATTRIBUTES.key(&self)+ }+}++impl std::fmt::Debug for AId {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ write!(f, "{}", self.to_str())+ }+}++impl std::fmt::Display for AId {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ write!(f, "{:?}", self)+ }+}++// A stripped down `phf` crate fork.+//+// https://github.com/sfackler/rust-phf++struct Map<V: 'static> {+ pub key: u64,+ pub disps: &'static [(u32, u32)],+ pub entries: &'static [(&'static str, V)],+}++impl<V: PartialEq> Map<V> {+ fn get(&self, key: &str) -> Option<&V> {+ let hash = hash(key, self.key);+ let index = get_index(hash, self.disps, self.entries.len());+ let entry = &self.entries[index as usize];+ let b = entry.0;+ if b == key {+ Some(&entry.1)+ } else {+ None+ }+ }++ fn key(&self, value: &V) -> &'static str {+ self.entries.iter().find(|kv| kv.1 == *value).unwrap().0+ }+}++#[inline]+fn hash(x: &str, key: u64) -> u64 {+ use std::hash::Hasher;++ let mut hasher = siphasher::sip::SipHasher13::new_with_keys(0, key);+ hasher.write(x.as_bytes());+ hasher.finish()+}++#[inline]+fn get_index(hash: u64, disps: &[(u32, u32)], len: usize) -> u32 {+ let (g, f1, f2) = split(hash);+ let (d1, d2) = disps[(g % (disps.len() as u32)) as usize];+ displace(f1, f2, d1, d2) % (len as u32)+}++#[inline]+fn split(hash: u64) -> (u32, u32, u32) {+ const BITS: u32 = 21;+ const MASK: u64 = (1 << BITS) - 1;++ ((hash & MASK) as u32,+ ((hash >> BITS) & MASK) as u32,+ ((hash >> (2 * BITS)) & MASK) as u32)+}++#[inline]+fn displace(f1: u32, f2: u32, d1: u32, d2: u32) -> u32 {+ d2 + f1 * d1 + f2+}diff --git a/vendor/usvg/src/parser/svgtree/parse.rs b/vendor/usvg/src/parser/svgtree/parse.rsnew file mode 100644index 00000000..524654a7--- /dev/null+++ b/vendor/usvg/src/parser/svgtree/parse.rs@@ -0,0 +1,846 @@+// Copyright 2021 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::collections::HashMap;++use roxmltree::Error;+use simplecss::Declaration;+use svgtypes::FontShorthand;++use super::{AId, Attribute, Document, EId, NodeData, NodeId, NodeKind, ShortRange};++const SVG_NS: &str = "http://www.w3.org/2000/svg";+const XLINK_NS: &str = "http://www.w3.org/1999/xlink";+const XML_NAMESPACE_NS: &str = "http://www.w3.org/XML/1998/namespace";++impl<'input> Document<'input> {+ /// Parses a [`Document`] from a [`roxmltree::Document`].+ pub fn parse_tree(+ xml: &roxmltree::Document<'input>,+ injected_stylesheet: Option<&'input str>,+ ) -> Result<Document<'input>, Error> {+ parse(xml, injected_stylesheet)+ }++ pub(crate) fn append(&mut self, parent_id: NodeId, kind: NodeKind) -> NodeId {+ let new_child_id = NodeId::from(self.nodes.len());+ self.nodes.push(NodeData {+ parent: Some(parent_id),+ next_sibling: None,+ children: None,+ kind,+ });++ let last_child_id = self.nodes[parent_id.get_usize()].children.map(|(_, id)| id);++ if let Some(id) = last_child_id {+ self.nodes[id.get_usize()].next_sibling = Some(new_child_id);+ }++ self.nodes[parent_id.get_usize()].children = Some(+ if let Some((first_child_id, _)) = self.nodes[parent_id.get_usize()].children {+ (first_child_id, new_child_id)+ } else {+ (new_child_id, new_child_id)+ },+ );++ new_child_id+ }++ fn append_attribute(+ &mut self,+ name: AId,+ value: roxmltree::StringStorage<'input>,+ important: bool,+ ) {+ self.attrs.push(Attribute {+ name,+ value,+ important,+ });+ }+}++fn parse<'input>(+ xml: &roxmltree::Document<'input>,+ injected_stylesheet: Option<&'input str>,+) -> Result<Document<'input>, Error> {+ let mut doc = Document {+ nodes: Vec::new(),+ attrs: Vec::new(),+ links: HashMap::new(),+ };++ // build a map of id -> node for resolve_href+ let mut id_map = HashMap::new();+ for node in xml.descendants() {+ if let Some(id) = node.attribute("id") {+ if !id_map.contains_key(id) {+ id_map.insert(id, node);+ }+ }+ }++ // Add a root node.+ doc.nodes.push(NodeData {+ parent: None,+ next_sibling: None,+ children: None,+ kind: NodeKind::Root,+ });++ let style_sheet = resolve_css(xml, injected_stylesheet);++ parse_xml_node_children(+ xml.root(),+ xml.root(),+ doc.root().id,+ &style_sheet,+ false,+ 0,+ &mut doc,+ &id_map,+ )?;++ // Check that the root element is `svg`.+ match doc.root().first_element_child() {+ Some(child) => {+ if child.tag_name() != Some(EId::Svg) {+ return Err(roxmltree::Error::NoRootNode);+ }+ }+ None => return Err(roxmltree::Error::NoRootNode),+ }++ // Collect all elements with `id` attribute.+ let mut links = HashMap::new();+ for node in doc.descendants() {+ if let Some(id) = node.attribute::<&str>(AId::Id) {+ links.insert(id.to_string(), node.id);+ }+ }+ doc.links = links;++ fix_recursive_patterns(&mut doc);+ fix_recursive_links(EId::ClipPath, AId::ClipPath, &mut doc);+ fix_recursive_links(EId::Mask, AId::Mask, &mut doc);+ fix_recursive_links(EId::Filter, AId::Filter, &mut doc);+ fix_recursive_fe_image(&mut doc);++ Ok(doc)+}++pub(crate) fn parse_tag_name(node: roxmltree::Node) -> Option<EId> {+ if !node.is_element() {+ return None;+ }++ if !matches!(node.tag_name().namespace(), None | Some(SVG_NS)) {+ return None;+ }++ EId::from_str(node.tag_name().name())+}++fn parse_xml_node_children<'input>(+ parent: roxmltree::Node<'_, 'input>,+ origin: roxmltree::Node,+ parent_id: NodeId,+ style_sheet: &simplecss::StyleSheet,+ ignore_ids: bool,+ depth: u32,+ doc: &mut Document<'input>,+ id_map: &HashMap<&str, roxmltree::Node<'_, 'input>>,+) -> Result<(), Error> {+ for node in parent.children() {+ parse_xml_node(+ node,+ origin,+ parent_id,+ style_sheet,+ ignore_ids,+ depth,+ doc,+ id_map,+ )?;+ }++ Ok(())+}++fn parse_xml_node<'input>(+ node: roxmltree::Node<'_, 'input>,+ origin: roxmltree::Node,+ parent_id: NodeId,+ style_sheet: &simplecss::StyleSheet,+ ignore_ids: bool,+ depth: u32,+ doc: &mut Document<'input>,+ id_map: &HashMap<&str, roxmltree::Node<'_, 'input>>,+) -> Result<(), Error> {+ if depth > 1024 {+ return Err(Error::NodesLimitReached);+ }++ let mut tag_name = match parse_tag_name(node) {+ Some(id) => id,+ None => return Ok(()),+ };++ if tag_name == EId::Style {+ return Ok(());+ }++ // TODO: remove?+ // Treat links as groups.+ if tag_name == EId::A {+ tag_name = EId::G;+ }++ let node_id = parse_svg_element(node, parent_id, tag_name, style_sheet, ignore_ids, doc)?;+ if tag_name == EId::Text {+ super::text::parse_svg_text_element(node, node_id, style_sheet, doc)?;+ } else if tag_name == EId::Use {+ parse_svg_use_element(node, origin, node_id, style_sheet, depth + 1, doc, id_map)?;+ } else {+ parse_xml_node_children(+ node,+ origin,+ node_id,+ style_sheet,+ ignore_ids,+ depth + 1,+ doc,+ id_map,+ )?;+ }++ Ok(())+}++pub(crate) fn parse_svg_element<'input>(+ xml_node: roxmltree::Node<'_, 'input>,+ parent_id: NodeId,+ tag_name: EId,+ style_sheet: &simplecss::StyleSheet,+ ignore_ids: bool,+ doc: &mut Document<'input>,+) -> Result<NodeId, Error> {+ let attrs_start_idx = doc.attrs.len();+ let mut href_idx: Option<usize> = None;++ // Copy presentational attributes first.+ for attr in xml_node.attributes() {+ match attr.namespace() {+ None | Some(SVG_NS) | Some(XLINK_NS) | Some(XML_NAMESPACE_NS) => {}+ _ => continue,+ }++ let aid = match AId::from_str(attr.name()) {+ Some(v) => v,+ None => continue,+ };++ // During a `use` resolving, all `id` attributes must be ignored.+ // Otherwise we will get elements with duplicated id's.+ if ignore_ids && aid == AId::Id {+ continue;+ }++ // For some reason those properties are allowed only inside a `style` attribute and CSS.+ if matches!(aid, AId::MixBlendMode | AId::Isolation | AId::FontKerning) {+ continue;+ } else if aid == AId::ImageRendering+ && matches!(+ attr.value(),+ "smooth" | "high-quality" | "crisp-edges" | "pixelated"+ )+ {+ continue;+ }++ // SVG 2: when both `href` and `xlink:href` are present, the unprefixed+ // `href` takes precedence and the XLink one must be ignored, regardless+ // of their order in the source document.+ // https://www.w3.org/TR/SVG2/linking.html#XLinkRefAttrs+ if aid == AId::Href {+ let is_unprefixed = attr.namespace().is_none();+ let is_xlink = attr.namespace() == Some(XLINK_NS);+ if !is_unprefixed && !is_xlink {+ continue;+ }++ if let Some(idx) = href_idx {+ // An `href` was already stored. Only an unprefixed `href` is+ // allowed to override it; an `xlink:href` is ignored.+ if is_unprefixed {+ doc.attrs[idx].value = attr.value_storage().clone();+ }+ continue;+ }+ }++ let added = append_attribute(+ parent_id,+ tag_name,+ aid,+ attr.value_storage().clone(),+ false,+ doc,+ );+ if added && aid == AId::Href {+ href_idx = Some(doc.attrs.len() - 1);+ }+ }++ let mut insert_attribute = |aid, value: &str, important: bool| {+ // Check that attribute already exists.+ let idx = doc.attrs[attrs_start_idx..]+ .iter_mut()+ .position(|a| a.name == aid);++ // Append an attribute as usual.+ let added = append_attribute(+ parent_id,+ tag_name,+ aid,+ roxmltree::StringStorage::new_owned(value),+ important,+ doc,+ );++ // Check that attribute was actually added, because it could be skipped.+ if added {+ if let Some(idx) = idx {+ let last_idx = doc.attrs.len() - 1;+ let existing_idx = attrs_start_idx + idx;++ // See https://developer.mozilla.org/en-US/docs/Web/CSS/important+ // When a declaration is important, the order of precedence is reversed.+ // Declarations marked as important in the user-agent style sheets override+ // all important declarations in the user style sheets. Similarly, all important+ // declarations in the user style sheets override all important declarations in the+ // author's style sheets. Finally, all important declarations take precedence over+ // all animations.+ //+ // Which means:+ // 1) Existing is not important, new is not important -> swap+ // 2) Existing is important, new is not important -> don't swap+ // 3) Existing is not important, new is important -> swap+ // 4) Existing is important, new is important -> don't swap (since the order+ // is reversed, so existing important attributes take precedence over new+ // important attributes)+ let has_precedence = !doc.attrs[existing_idx].important;++ if has_precedence {+ doc.attrs.swap(existing_idx, last_idx);+ }++ // Remove last.+ doc.attrs.pop();+ }+ }+ };++ let mut write_declaration = |declaration: &Declaration| {+ // TODO: perform XML attribute normalization+ let imp = declaration.important;+ let val = declaration.value;++ if declaration.name == "marker" {+ insert_attribute(AId::MarkerStart, val, imp);+ insert_attribute(AId::MarkerMid, val, imp);+ insert_attribute(AId::MarkerEnd, val, imp);+ } else if declaration.name == "font" {+ if let Ok(shorthand) = FontShorthand::from_str(val) {+ // First we need to reset all values to their default.+ insert_attribute(AId::FontStyle, "normal", imp);+ insert_attribute(AId::FontVariant, "normal", imp);+ insert_attribute(AId::FontWeight, "normal", imp);+ insert_attribute(AId::FontStretch, "normal", imp);+ insert_attribute(AId::LineHeight, "normal", imp);+ insert_attribute(AId::FontSizeAdjust, "none", imp);+ insert_attribute(AId::FontKerning, "auto", imp);+ insert_attribute(AId::FontVariantCaps, "normal", imp);+ insert_attribute(AId::FontVariantLigatures, "normal", imp);+ insert_attribute(AId::FontVariantNumeric, "normal", imp);+ insert_attribute(AId::FontVariantEastAsian, "normal", imp);+ insert_attribute(AId::FontVariantPosition, "normal", imp);++ // Then, we set the properties that have been declared.+ shorthand+ .font_stretch+ .map(|s| insert_attribute(AId::FontStretch, s, imp));+ shorthand+ .font_weight+ .map(|s| insert_attribute(AId::FontWeight, s, imp));+ shorthand+ .font_variant+ .map(|s| insert_attribute(AId::FontVariant, s, imp));+ shorthand+ .font_style+ .map(|s| insert_attribute(AId::FontStyle, s, imp));+ insert_attribute(AId::FontSize, shorthand.font_size, imp);+ insert_attribute(AId::FontFamily, shorthand.font_family, imp);+ } else {+ log::warn!(+ "Failed to parse {} value: '{}'",+ AId::Font,+ declaration.value+ );+ }+ } else if let Some(aid) = AId::from_str(declaration.name) {+ // Parse only the presentation attributes.+ if aid.is_presentation() {+ insert_attribute(aid, val, imp);+ }+ }+ };++ // Apply CSS.+ for rule in &style_sheet.rules {+ if rule.selector.matches(&XmlNode(xml_node)) {+ for declaration in &rule.declarations {+ write_declaration(declaration);+ }+ }+ }++ // Split a `style` attribute.+ if let Some(value) = xml_node.attribute("style") {+ for declaration in simplecss::DeclarationTokenizer::from(value) {+ write_declaration(&declaration);+ }+ }++ if doc.nodes.len() > 1_000_000 {+ return Err(Error::NodesLimitReached);+ }++ let node_id = doc.append(+ parent_id,+ NodeKind::Element {+ tag_name,+ attributes: ShortRange::new(attrs_start_idx as u32, doc.attrs.len() as u32),+ },+ );++ Ok(node_id)+}++fn append_attribute<'input>(+ parent_id: NodeId,+ tag_name: EId,+ aid: AId,+ value: roxmltree::StringStorage<'input>,+ important: bool,+ doc: &mut Document<'input>,+) -> bool {+ match aid {+ // The `style` attribute will be split into attributes, so we don't need it.+ AId::Style |+ // No need to copy a `class` attribute since CSS were already resolved.+ AId::Class => return false,+ _ => {}+ }++ // Ignore `xlink:href` on `tspan` (which was originally `tref` or `a`),+ // because we will convert `tref` into `tspan` anyway.+ if tag_name == EId::Tspan && aid == AId::Href {+ return false;+ }++ if aid.allows_inherit_value() && &*value == "inherit" {+ return resolve_inherit(parent_id, aid, doc);+ }++ doc.append_attribute(aid, value, important);+ true+}++fn resolve_inherit(parent_id: NodeId, aid: AId, doc: &mut Document) -> bool {+ if aid.is_inheritable() {+ // Inheritable attributes can inherit a value from an any ancestor.+ let node_id = doc+ .get(parent_id)+ .ancestors()+ .find(|n| n.has_attribute(aid))+ .map(|n| n.id);+ if let Some(node_id) = node_id {+ if let Some(attr) = doc+ .get(node_id)+ .attributes()+ .iter()+ .find(|a| a.name == aid)+ .cloned()+ {+ doc.attrs.push(Attribute {+ name: aid,+ value: attr.value,+ important: attr.important,+ });++ return true;+ }+ }+ } else {+ // Non-inheritable attributes can inherit a value only from a direct parent.+ if let Some(attr) = doc+ .get(parent_id)+ .attributes()+ .iter()+ .find(|a| a.name == aid)+ .cloned()+ {+ doc.attrs.push(Attribute {+ name: aid,+ value: attr.value,+ important: attr.important,+ });++ return true;+ }+ }++ // Fallback to a default value if possible.+ let value = match aid {+ AId::ImageRendering | AId::ShapeRendering | AId::TextRendering => "auto",++ AId::ClipPath+ | AId::Filter+ | AId::MarkerEnd+ | AId::MarkerMid+ | AId::MarkerStart+ | AId::Mask+ | AId::Stroke+ | AId::StrokeDasharray+ | AId::TextDecoration => "none",++ AId::FontStretch+ | AId::FontStyle+ | AId::FontVariant+ | AId::FontWeight+ | AId::LetterSpacing+ | AId::WordSpacing => "normal",++ AId::Fill | AId::FloodColor | AId::StopColor => "black",++ AId::FillOpacity+ | AId::FloodOpacity+ | AId::Opacity+ | AId::StopOpacity+ | AId::StrokeOpacity => "1",++ AId::ClipRule | AId::FillRule => "nonzero",++ AId::BaselineShift => "baseline",+ AId::ColorInterpolationFilters => "linearRGB",+ AId::Direction => "ltr",+ AId::Display => "inline",+ AId::FontSize => "medium",+ AId::Overflow => "visible",+ AId::StrokeDashoffset => "0",+ AId::StrokeLinecap => "butt",+ AId::StrokeLinejoin => "miter",+ AId::StrokeMiterlimit => "4",+ AId::StrokeWidth => "1",+ AId::TextAnchor => "start",+ AId::Visibility => "visible",+ AId::WritingMode => "lr-tb",+ _ => return false,+ };++ doc.append_attribute(aid, roxmltree::StringStorage::Borrowed(value), false);+ true+}++fn resolve_href<'a, 'input: 'a>(+ node: roxmltree::Node<'a, 'input>,+ id_map: &HashMap<&str, roxmltree::Node<'a, 'input>>,+) -> Option<roxmltree::Node<'a, 'input>> {+ // See the comment in `parse_svg_element` about `href` precedence.+ //+ // Note: `roxmltree::Node::attribute("href")` matches by local name only and+ // would return whichever `href`/`xlink:href` comes first, so we have to+ // filter by namespace explicitly.+ let link_value = node+ .attributes()+ .find(|a| a.name() == "href" && a.namespace().is_none())+ .or_else(|| {+ node.attributes()+ .find(|a| a.name() == "href" && a.namespace() == Some(XLINK_NS))+ })+ .map(|a| a.value())?;++ let link_id = svgtypes::IRI::from_str(link_value).ok()?.0;++ id_map.get(link_id).copied()+}++fn parse_svg_use_element<'input>(+ node: roxmltree::Node<'_, 'input>,+ origin: roxmltree::Node,+ parent_id: NodeId,+ style_sheet: &simplecss::StyleSheet,+ depth: u32,+ doc: &mut Document<'input>,+ id_map: &HashMap<&str, roxmltree::Node<'_, 'input>>,+) -> Result<(), Error> {+ let link = match resolve_href(node, id_map) {+ Some(v) => v,+ None => return Ok(()),+ };++ if link == node || link == origin {+ log::warn!(+ "Recursive 'use' detected. '{}' will be skipped.",+ node.attribute((SVG_NS, "id")).unwrap_or_default()+ );+ return Ok(());+ }++ // Make sure we're linked to an SVG element.+ if parse_tag_name(link).is_none() {+ return Ok(());+ }++ // Check that none of the linked node's children reference current `use` node+ // via other `use` node.+ //+ // Example:+ // <g id="g1">+ // <use xlink:href="#use1" id="use2"/>+ // </g>+ // <use xlink:href="#g1" id="use1"/>+ //+ // `use2` should be removed.+ //+ // Also, child should not reference its parent:+ // <g id="g1">+ // <use xlink:href="#g1" id="use1"/>+ // </g>+ //+ // `use1` should be removed.+ let mut is_recursive = false;+ for link_child in link+ .descendants()+ .skip(1)+ .filter(|n| n.has_tag_name((SVG_NS, "use")))+ {+ if let Some(link2) = resolve_href(link_child, id_map) {+ if link2 == node || link2 == link {+ is_recursive = true;+ break;+ }+ }+ }++ if is_recursive {+ log::warn!(+ "Recursive 'use' detected. '{}' will be skipped.",+ node.attribute((SVG_NS, "id")).unwrap_or_default()+ );+ return Ok(());+ }++ parse_xml_node(+ link,+ node,+ parent_id,+ style_sheet,+ true,+ depth + 1,+ doc,+ id_map,+ )+}++fn resolve_css<'a>(+ xml: &'a roxmltree::Document<'a>,+ style_sheet: Option<&'a str>,+) -> simplecss::StyleSheet<'a> {+ let mut sheet = simplecss::StyleSheet::new();++ // Injected style sheets do not override internal ones (we mimic the logic of rsvg-convert),+ // so we need to parse it first.+ if let Some(style_sheet) = style_sheet {+ sheet.parse_more(style_sheet);+ }++ for node in xml.descendants().filter(|n| n.has_tag_name("style")) {+ match node.attribute("type") {+ Some("text/css") => {}+ Some(_) => continue,+ None => {}+ }++ let text = match node.text() {+ Some(v) => v,+ None => continue,+ };++ sheet.parse_more(text);+ }++ sheet+}++struct XmlNode<'a, 'input: 'a>(roxmltree::Node<'a, 'input>);++impl simplecss::Element for XmlNode<'_, '_> {+ fn parent_element(&self) -> Option<Self> {+ self.0.parent_element().map(XmlNode)+ }++ fn prev_sibling_element(&self) -> Option<Self> {+ self.0.prev_sibling_element().map(XmlNode)+ }++ fn has_local_name(&self, local_name: &str) -> bool {+ self.0.tag_name().name() == local_name+ }++ fn attribute_matches(&self, local_name: &str, operator: simplecss::AttributeOperator) -> bool {+ match self.0.attribute(local_name) {+ Some(value) => operator.matches(value),+ None => false,+ }+ }++ fn pseudo_class_matches(&self, class: simplecss::PseudoClass) -> bool {+ match class {+ simplecss::PseudoClass::FirstChild => self.prev_sibling_element().is_none(),+ // TODO: lang+ _ => false, // Since we are querying a static SVG we can ignore other pseudo-classes.+ }+ }+}++fn fix_recursive_patterns(doc: &mut Document) {+ while let Some(node_id) = find_recursive_pattern(AId::Fill, doc) {+ let idx = doc.get(node_id).attribute_id(AId::Fill).unwrap();+ doc.attrs[idx].value = roxmltree::StringStorage::Borrowed("none");+ }++ while let Some(node_id) = find_recursive_pattern(AId::Stroke, doc) {+ let idx = doc.get(node_id).attribute_id(AId::Stroke).unwrap();+ doc.attrs[idx].value = roxmltree::StringStorage::Borrowed("none");+ }+}++fn find_recursive_pattern(aid: AId, doc: &mut Document) -> Option<NodeId> {+ for pattern_node in doc+ .root()+ .descendants()+ .filter(|n| n.tag_name() == Some(EId::Pattern))+ {+ for node in pattern_node.descendants() {+ let value = match node.attribute(aid) {+ Some(v) => v,+ None => continue,+ };++ if let Ok(svgtypes::Paint::FuncIRI(link_id, _)) = svgtypes::Paint::from_str(value) {+ if link_id == pattern_node.element_id() {+ // If a pattern child has a link to the pattern itself+ // then we have to replace it with `none`.+ // Otherwise we will get endless loop/recursion and stack overflow.+ return Some(node.id);+ } else {+ // Check that linked node children doesn't link this pattern.+ if let Some(linked_node) = doc.element_by_id(link_id) {+ for node2 in linked_node.descendants() {+ let value2 = match node2.attribute(aid) {+ Some(v) => v,+ None => continue,+ };++ if let Ok(svgtypes::Paint::FuncIRI(link_id2, _)) =+ svgtypes::Paint::from_str(value2)+ {+ if link_id2 == pattern_node.element_id() {+ return Some(node2.id);+ }+ }+ }+ }+ }+ }+ }+ }++ None+}++fn fix_recursive_links(eid: EId, aid: AId, doc: &mut Document) {+ while let Some(node_id) = find_recursive_link(eid, aid, doc) {+ let idx = doc.get(node_id).attribute_id(aid).unwrap();+ doc.attrs[idx].value = roxmltree::StringStorage::Borrowed("none");+ }+}++fn find_recursive_link(eid: EId, aid: AId, doc: &Document) -> Option<NodeId> {+ for node in doc+ .root()+ .descendants()+ .filter(|n| n.tag_name() == Some(eid))+ {+ for child in node.descendants() {+ if let Some(link) = child.node_attribute(aid) {+ if link == node {+ // If an element child has a link to the element itself+ // then we have to replace it with `none`.+ // Otherwise we will get endless loop/recursion and stack overflow.+ return Some(child.id);+ } else {+ // Check that linked node children doesn't link this element.+ for node2 in link.descendants() {+ if let Some(link2) = node2.node_attribute(aid) {+ if link2 == node {+ return Some(node2.id);+ }+ }+ }+ }+ }+ }+ }++ None+}++/// Detects cases like:+///+/// ```xml+/// <filter id="filter1">+/// <feImage xlink:href="#rect1"/>+/// </filter>+/// <rect id="rect1" x="36" y="36" width="120" height="120" fill="green" filter="url(#filter1)"/>+/// ```+fn fix_recursive_fe_image(doc: &mut Document) {+ let mut ids = Vec::new();+ for fe_node in doc+ .root()+ .descendants()+ .filter(|n| n.tag_name() == Some(EId::FeImage))+ {+ if let Some(link) = fe_node.node_attribute(AId::Href) {+ if let Some(filter_uri) = link.attribute::<&str>(AId::Filter) {+ let filter_id = fe_node.parent().unwrap().element_id();+ for func in svgtypes::FilterValueListParser::from(filter_uri).flatten() {+ if let svgtypes::FilterValue::Url(url) = func {+ if url == filter_id {+ ids.push(link.id);+ }+ }+ }+ }+ }+ }++ for id in ids {+ let idx = doc.get(id).attribute_id(AId::Filter).unwrap();+ doc.attrs[idx].value = roxmltree::StringStorage::Borrowed("none");+ }+}diff --git a/vendor/usvg/src/parser/svgtree/text.rs b/vendor/usvg/src/parser/svgtree/text.rsnew file mode 100644index 00000000..cef703b0--- /dev/null+++ b/vendor/usvg/src/parser/svgtree/text.rs@@ -0,0 +1,362 @@+// Copyright 2021 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++#![allow(clippy::comparison_chain)]++use roxmltree::Error;++use super::{AId, Document, EId, NodeId, NodeKind, SvgNode};++const XLINK_NS: &str = "http://www.w3.org/1999/xlink";++pub(crate) fn parse_svg_text_element<'input>(+ parent: roxmltree::Node<'_, 'input>,+ parent_id: NodeId,+ style_sheet: &simplecss::StyleSheet,+ doc: &mut Document<'input>,+) -> Result<(), Error> {+ debug_assert_eq!(parent.tag_name().name(), "text");++ let space = if doc.get(parent_id).has_attribute(AId::Space) {+ get_xmlspace(doc, parent_id, XmlSpace::Default)+ } else {+ if let Some(node) = doc+ .get(parent_id)+ .ancestors()+ .find(|n| n.has_attribute(AId::Space))+ {+ get_xmlspace(doc, node.id, XmlSpace::Default)+ } else {+ XmlSpace::Default+ }+ };++ parse_svg_text_element_impl(parent, parent_id, style_sheet, space, doc)?;++ trim_text_nodes(parent_id, space, doc);+ Ok(())+}++fn parse_svg_text_element_impl<'input>(+ parent: roxmltree::Node<'_, 'input>,+ parent_id: NodeId,+ style_sheet: &simplecss::StyleSheet,+ space: XmlSpace,+ doc: &mut Document<'input>,+) -> Result<(), Error> {+ for node in parent.children() {+ if node.is_text() {+ let text = trim_text(node.text().unwrap(), space);+ doc.append(parent_id, NodeKind::Text(text));+ continue;+ }++ let mut tag_name = match super::parse::parse_tag_name(node) {+ Some(v) => v,+ None => continue,+ };++ if tag_name == EId::A {+ // Treat links as simple text.+ tag_name = EId::Tspan;+ }++ if !matches!(tag_name, EId::Tspan | EId::Tref | EId::TextPath) {+ continue;+ }++ // `textPath` must be a direct `text` child.+ if tag_name == EId::TextPath && parent.tag_name().name() != "text" {+ continue;+ }++ // We are converting `tref` into `tspan` to simplify later use.+ let mut is_tref = false;+ if tag_name == EId::Tref {+ tag_name = EId::Tspan;+ is_tref = true;+ }++ let node_id =+ super::parse::parse_svg_element(node, parent_id, tag_name, style_sheet, false, doc)?;+ let space = get_xmlspace(doc, node_id, space);++ if is_tref {+ let link_value = node+ .attribute((XLINK_NS, "href"))+ .or_else(|| node.attribute("href"));++ if let Some(href) = link_value {+ if let Some(text) = resolve_tref_text(node.document(), href) {+ let text = trim_text(&text, space);+ doc.append(node_id, NodeKind::Text(text));+ }+ }+ } else {+ parse_svg_text_element_impl(node, node_id, style_sheet, space, doc)?;+ }+ }++ Ok(())+}++fn resolve_tref_text(xml: &roxmltree::Document, href: &str) -> Option<String> {+ let id = svgtypes::IRI::from_str(href).ok()?.0;++ // Find linked element in the original tree.+ let node = xml.descendants().find(|n| n.attribute("id") == Some(id))?;++ // `tref` should be linked to an SVG element.+ super::parse::parse_tag_name(node)?;++ // 'All character data within the referenced element, including character data enclosed+ // within additional markup, will be rendered.'+ //+ // So we don't care about attributes and everything. Just collecting text nodes data.+ //+ // Note: we have to filter nodes by `is_text()` first since `text()` will look up+ // for text nodes in element children therefore we will get duplicates.+ let text: String = node+ .descendants()+ .filter(|n| n.is_text())+ .filter_map(|n| n.text())+ .collect();+ if text.is_empty() { None } else { Some(text) }+}++#[derive(Clone, Copy, PartialEq, Debug)]+enum XmlSpace {+ Default,+ Preserve,+}++fn get_xmlspace(doc: &Document, node_id: NodeId, default: XmlSpace) -> XmlSpace {+ match doc.get(node_id).attribute(AId::Space) {+ Some("preserve") => XmlSpace::Preserve,+ Some(_) => XmlSpace::Default,+ _ => default,+ }+}++trait StrTrim {+ fn remove_first_space(&mut self);+ fn remove_last_space(&mut self);+}++impl StrTrim for String {+ fn remove_first_space(&mut self) {+ debug_assert_eq!(self.chars().next().unwrap(), ' ');+ self.drain(0..1);+ }++ fn remove_last_space(&mut self) {+ debug_assert_eq!(self.chars().next_back().unwrap(), ' ');+ self.pop();+ }+}++/// Prepares text nodes according to the spec: https://www.w3.org/TR/SVG11/text.html#WhiteSpace+///+/// This function handles:+/// - 'xml:space' processing+/// - tabs and newlines removing/replacing+/// - spaces trimming+fn trim_text_nodes(text_elem_id: NodeId, xmlspace: XmlSpace, doc: &mut Document) {+ let mut nodes = Vec::new(); // TODO: allocate only once+ collect_text_nodes(doc.get(text_elem_id), 0, &mut nodes);++ // `trim` method has already collapsed all spaces into a single one,+ // so we have to check only for one leading or trailing space.++ if nodes.len() == 1 {+ // Process element with a single text node child.++ let node_id = nodes[0].0;++ if xmlspace == XmlSpace::Default {+ if let NodeKind::Text(ref mut text) = doc.nodes[node_id.get_usize()].kind {+ match text.len() {+ 0 => {} // An empty string. Do nothing.+ 1 => {+ // If string has only one character and it's a space - clear this string.+ if text.as_bytes()[0] == b' ' {+ text.clear();+ }+ }+ _ => {+ // 'text' has at least 2 bytes, so indexing is safe.+ let c1 = text.as_bytes()[0];+ let c2 = text.as_bytes()[text.len() - 1];++ if c1 == b' ' {+ text.remove_first_space();+ }++ if c2 == b' ' {+ text.remove_last_space();+ }+ }+ }+ }+ } else {+ // Do nothing when xml:space=preserve.+ }+ } else if nodes.len() > 1 {+ // Process element with many text node children.++ // We manage all text nodes as a single text node+ // and trying to remove duplicated spaces across nodes.+ //+ // For example '<text>Text <tspan> text </tspan> text</text>'+ // is the same is '<text>Text <tspan>text</tspan> text</text>'++ let mut i = 0;+ let len = nodes.len() - 1;+ let mut last_non_empty: Option<NodeId> = None;+ while i < len {+ // Process pairs.+ let (mut node1_id, depth1) = nodes[i];+ let (node2_id, depth2) = nodes[i + 1];++ if doc.get(node1_id).text().is_empty() {+ if let Some(n) = last_non_empty {+ node1_id = n;+ }+ }++ // Parent of the text node is always an element node and always exist,+ // so unwrap is safe.+ let xmlspace1 = get_xmlspace(doc, doc.get(node1_id).parent().unwrap().id, xmlspace);+ let xmlspace2 = get_xmlspace(doc, doc.get(node2_id).parent().unwrap().id, xmlspace);++ // >text<..>text<+ // 1 2 3 4+ let (c1, c2, c3, c4) = {+ let text1 = doc.get(node1_id).text();+ let text2 = doc.get(node2_id).text();++ let bytes1 = text1.as_bytes();+ let bytes2 = text2.as_bytes();++ let c1 = bytes1.first().cloned();+ let c2 = bytes1.last().cloned();+ let c3 = bytes2.first().cloned();+ let c4 = bytes2.last().cloned();++ (c1, c2, c3, c4)+ };++ // NOTE: xml:space processing is mostly an undefined behavior,+ // because everyone do it differently.+ // We're mimicking the Chrome behavior.++ // Remove space from the second text node if both nodes has bound spaces.+ // From: '<text>Text <tspan> text</tspan></text>'+ // To: '<text>Text <tspan>text</tspan></text>'+ //+ // See text-tspan-02-b.svg for details.+ if depth1 < depth2 {+ if c3 == Some(b' ') {+ if xmlspace2 == XmlSpace::Default {+ if let NodeKind::Text(ref mut text) = doc.nodes[node2_id.get_usize()].kind {+ text.remove_first_space();+ }+ }+ }+ } else {+ if c2 == Some(b' ') && c2 == c3 {+ if xmlspace1 == XmlSpace::Default && xmlspace2 == XmlSpace::Default {+ if let NodeKind::Text(ref mut text) = doc.nodes[node1_id.get_usize()].kind {+ text.remove_last_space();+ }+ } else {+ if xmlspace1 == XmlSpace::Preserve && xmlspace2 == XmlSpace::Default {+ if let NodeKind::Text(ref mut text) =+ doc.nodes[node2_id.get_usize()].kind+ {+ text.remove_first_space();+ }+ }+ }+ }+ }++ let is_first = i == 0;+ let is_last = i == len - 1;++ if is_first+ && c1 == Some(b' ')+ && xmlspace1 == XmlSpace::Default+ && !doc.get(node1_id).text().is_empty()+ {+ // Remove a leading space from a first text node.+ if let NodeKind::Text(ref mut text) = doc.nodes[node1_id.get_usize()].kind {+ text.remove_first_space();+ }+ } else if is_last+ && c4 == Some(b' ')+ && !doc.get(node2_id).text().is_empty()+ && xmlspace2 == XmlSpace::Default+ {+ // Remove a trailing space from a last text node.+ // Also check that 'text2' is not empty already.+ if let NodeKind::Text(ref mut text) = doc.nodes[node2_id.get_usize()].kind {+ text.remove_last_space();+ }+ }++ if is_last+ && c2 == Some(b' ')+ && !doc.get(node1_id).text().is_empty()+ && doc.get(node2_id).text().is_empty()+ && doc.get(node1_id).text().ends_with(' ')+ {+ if let NodeKind::Text(ref mut text) = doc.nodes[node1_id.get_usize()].kind {+ text.remove_last_space();+ }+ }++ if !doc.get(node1_id).text().trim().is_empty() {+ last_non_empty = Some(node1_id);+ }++ i += 1;+ }+ }++ // TODO: find a way to remove all empty text nodes+}++fn collect_text_nodes(parent: SvgNode, depth: usize, nodes: &mut Vec<(NodeId, usize)>) {+ for child in parent.children() {+ if child.is_text() {+ nodes.push((child.id, depth));+ } else if child.is_element() {+ collect_text_nodes(child, depth + 1, nodes);+ }+ }+}++fn trim_text(text: &str, space: XmlSpace) -> String {+ let mut s = String::with_capacity(text.len());++ let mut prev = '0';+ for c in text.chars() {+ // \r, \n and \t should be converted into spaces.+ let c = match c {+ '\r' | '\n' | '\t' => ' ',+ _ => c,+ };++ // Skip continuous spaces.+ if space == XmlSpace::Default && c == ' ' && c == prev {+ continue;+ }++ prev = c;++ s.push(c);+ }++ s+}diff --git a/vendor/usvg/src/parser/switch.rs b/vendor/usvg/src/parser/switch.rsnew file mode 100644index 00000000..9b0d892c--- /dev/null+++ b/vendor/usvg/src/parser/switch.rs@@ -0,0 +1,125 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use super::svgtree::{AId, SvgNode};+use super::{Options, converter};+use crate::{Group, Node};++// Full list can be found here: https://www.w3.org/TR/SVG11/feature.html+static FEATURES: &[&str] = &[+ "http://www.w3.org/TR/SVG11/feature#SVGDOM-static",+ "http://www.w3.org/TR/SVG11/feature#SVG-static",+ "http://www.w3.org/TR/SVG11/feature#CoreAttribute", // no xml:base and xml:lang+ "http://www.w3.org/TR/SVG11/feature#Structure",+ "http://www.w3.org/TR/SVG11/feature#BasicStructure",+ "http://www.w3.org/TR/SVG11/feature#ContainerAttribute", // `enable-background`+ "http://www.w3.org/TR/SVG11/feature#ConditionalProcessing",+ "http://www.w3.org/TR/SVG11/feature#Image",+ "http://www.w3.org/TR/SVG11/feature#Style",+ // "http://www.w3.org/TR/SVG11/feature#ViewportAttribute", // `clip` and `overflow`, not yet+ "http://www.w3.org/TR/SVG11/feature#Shape",+ "http://www.w3.org/TR/SVG11/feature#Text",+ "http://www.w3.org/TR/SVG11/feature#BasicText",+ "http://www.w3.org/TR/SVG11/feature#PaintAttribute", // no color-interpolation and color-rendering+ "http://www.w3.org/TR/SVG11/feature#BasicPaintAttribute", // no color-interpolation+ "http://www.w3.org/TR/SVG11/feature#OpacityAttribute",+ "http://www.w3.org/TR/SVG11/feature#GraphicsAttribute",+ "http://www.w3.org/TR/SVG11/feature#BasicGraphicsAttribute",+ "http://www.w3.org/TR/SVG11/feature#Marker",+ // "http://www.w3.org/TR/SVG11/feature#ColorProfile", // not yet+ "http://www.w3.org/TR/SVG11/feature#Gradient",+ "http://www.w3.org/TR/SVG11/feature#Pattern",+ "http://www.w3.org/TR/SVG11/feature#Clip",+ "http://www.w3.org/TR/SVG11/feature#BasicClip",+ "http://www.w3.org/TR/SVG11/feature#Mask",+ "http://www.w3.org/TR/SVG11/feature#Filter",+ "http://www.w3.org/TR/SVG11/feature#BasicFilter",+ // only xlink:href+ "http://www.w3.org/TR/SVG11/feature#XlinkAttribute",+ // "http://www.w3.org/TR/SVG11/feature#Font",+ // "http://www.w3.org/TR/SVG11/feature#BasicFont",+];++pub(crate) fn convert(+ node: SvgNode,+ state: &converter::State,+ cache: &mut converter::Cache,+ parent: &mut Group,+) -> Option<()> {+ let child = node+ .children()+ .find(|n| is_condition_passed(*n, state.opt))?;+ if let Some(g) = converter::convert_group(node, state, false, cache, parent, &|cache, g| {+ converter::convert_element(child, state, cache, g);+ }) {+ parent.children.push(Node::Group(Box::new(g)));+ }++ Some(())+}++pub(crate) fn is_condition_passed(node: SvgNode, opt: &Options) -> bool {+ if !node.is_element() {+ return false;+ }++ if node.has_attribute(AId::RequiredExtensions) {+ return false;+ }++ // 'The value is a list of feature strings, with the individual values separated by white space.+ // Determines whether all of the named features are supported by the user agent.+ // Only feature strings defined in the Feature String appendix are allowed.+ // If all of the given features are supported, then the attribute evaluates to true;+ // otherwise, the current element and its children are skipped and thus will not be rendered.'+ if let Some(features) = node.attribute::<&str>(AId::RequiredFeatures) {+ for feature in features.split(' ') {+ if !FEATURES.contains(&feature) {+ return false;+ }+ }+ }++ if !is_valid_sys_lang(node, opt) {+ return false;+ }++ true+}++/// SVG spec 5.8.5+fn is_valid_sys_lang(node: SvgNode, opt: &Options) -> bool {+ // 'The attribute value is a comma-separated list of language names+ // as defined in BCP 47.'+ //+ // But we support only simple cases like `en` or `en-US`.+ // No one really uses this, especially with complex BCP 47 values.+ if let Some(langs) = node.attribute::<&str>(AId::SystemLanguage) {+ let mut has_match = false;+ for lang in langs.split(',') {+ let lang = lang.trim();++ // 'Evaluates to `true` if one of the languages indicated by user preferences exactly+ // equals one of the languages given in the value of this parameter.'+ if opt.languages.iter().any(|v| v == lang) {+ has_match = true;+ break;+ }++ // 'If one of the languages indicated by user preferences exactly equals a prefix+ // of one of the languages given in the value of this parameter such that+ // the first tag character following the prefix is `-`.'+ if let Some(idx) = lang.bytes().position(|c| c == b'-') {+ let lang_prefix = &lang[..idx];+ if opt.languages.iter().any(|v| v == lang_prefix) {+ has_match = true;+ break;+ }+ }+ }++ has_match+ } else {+ true+ }+}diff --git a/vendor/usvg/src/parser/text.rs b/vendor/usvg/src/parser/text.rsnew file mode 100644index 00000000..1cac7a4a--- /dev/null+++ b/vendor/usvg/src/parser/text.rs@@ -0,0 +1,964 @@+// Copyright 2019 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::sync::Arc;++use kurbo::{ParamCurve, ParamCurveArclen};+use svgtypes::{FontFamily, Length, LengthUnit, parse_font_families};++use super::svgtree::{AId, EId, FromValue, SvgNode};+use super::{OptionLog, converter, style};+use crate::*;++impl<'a, 'input: 'a> FromValue<'a, 'input> for TextAnchor {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "start" => Some(TextAnchor::Start),+ "middle" => Some(TextAnchor::Middle),+ "end" => Some(TextAnchor::End),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for AlignmentBaseline {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "auto" => Some(AlignmentBaseline::Auto),+ "baseline" => Some(AlignmentBaseline::Baseline),+ "before-edge" => Some(AlignmentBaseline::BeforeEdge),+ "text-before-edge" => Some(AlignmentBaseline::TextBeforeEdge),+ "middle" => Some(AlignmentBaseline::Middle),+ "central" => Some(AlignmentBaseline::Central),+ "after-edge" => Some(AlignmentBaseline::AfterEdge),+ "text-after-edge" => Some(AlignmentBaseline::TextAfterEdge),+ "ideographic" => Some(AlignmentBaseline::Ideographic),+ "alphabetic" => Some(AlignmentBaseline::Alphabetic),+ "hanging" => Some(AlignmentBaseline::Hanging),+ "mathematical" => Some(AlignmentBaseline::Mathematical),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for DominantBaseline {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "auto" => Some(DominantBaseline::Auto),+ "use-script" => Some(DominantBaseline::UseScript),+ "no-change" => Some(DominantBaseline::NoChange),+ "reset-size" => Some(DominantBaseline::ResetSize),+ "ideographic" => Some(DominantBaseline::Ideographic),+ "alphabetic" => Some(DominantBaseline::Alphabetic),+ "hanging" => Some(DominantBaseline::Hanging),+ "mathematical" => Some(DominantBaseline::Mathematical),+ "central" => Some(DominantBaseline::Central),+ "middle" => Some(DominantBaseline::Middle),+ "text-after-edge" => Some(DominantBaseline::TextAfterEdge),+ "text-before-edge" => Some(DominantBaseline::TextBeforeEdge),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for LengthAdjust {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "spacing" => Some(LengthAdjust::Spacing),+ "spacingAndGlyphs" => Some(LengthAdjust::SpacingAndGlyphs),+ _ => None,+ }+ }+}++impl<'a, 'input: 'a> FromValue<'a, 'input> for FontStyle {+ fn parse(_: SvgNode, _: AId, value: &str) -> Option<Self> {+ match value {+ "normal" => Some(FontStyle::Normal),+ "italic" => Some(FontStyle::Italic),+ "oblique" => Some(FontStyle::Oblique),+ _ => None,+ }+ }+}++/// A text character position.+///+/// _Character_ is a Unicode codepoint.+#[derive(Clone, Copy, Debug)]+struct CharacterPosition {+ /// An absolute X axis position.+ x: Option<f32>,+ /// An absolute Y axis position.+ y: Option<f32>,+ /// A relative X axis offset.+ dx: Option<f32>,+ /// A relative Y axis offset.+ dy: Option<f32>,+}++pub(crate) fn convert(+ text_node: SvgNode,+ state: &converter::State,+ cache: &mut converter::Cache,+ parent: &mut Group,+) {+ let pos_list = resolve_positions_list(text_node, state);+ let rotate_list = resolve_rotate_list(text_node);+ let writing_mode = convert_writing_mode(text_node);++ let chunks = collect_text_chunks(text_node, &pos_list, state, cache);++ let rendering_mode: TextRendering = text_node+ .find_attribute(AId::TextRendering)+ .unwrap_or(state.opt.text_rendering);++ // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.+ let id = if state.parent_markers.is_empty() {+ text_node.element_id().to_string()+ } else {+ String::new()+ };++ let dummy = Rect::from_xywh(0.0, 0.0, 0.0, 0.0).unwrap();++ let mut text = Text {+ id,+ rendering_mode,+ dx: pos_list.iter().map(|v| v.dx.unwrap_or(0.0)).collect(),+ dy: pos_list.iter().map(|v| v.dy.unwrap_or(0.0)).collect(),+ rotate: rotate_list,+ writing_mode,+ chunks,+ abs_transform: parent.abs_transform,+ // All fields below will be reset by `text_to_paths`.+ bounding_box: dummy,+ abs_bounding_box: dummy,+ stroke_bounding_box: dummy,+ abs_stroke_bounding_box: dummy,+ flattened: Box::new(Group::empty()),+ layouted: vec![],+ };++ if text::convert(&mut text, &state.opt.font_resolver, cache).is_none() {+ return;+ }++ parent.children.push(Node::Text(Box::new(text)));+}++struct IterState {+ chars_count: usize,+ chunk_bytes_count: usize,+ split_chunk: bool,+ text_flow: TextFlow,+ chunks: Vec<TextChunk>,+}++fn collect_text_chunks(+ text_node: SvgNode,+ pos_list: &[CharacterPosition],+ state: &converter::State,+ cache: &mut converter::Cache,+) -> Vec<TextChunk> {+ let mut iter_state = IterState {+ chars_count: 0,+ chunk_bytes_count: 0,+ split_chunk: false,+ text_flow: TextFlow::Linear,+ chunks: Vec::new(),+ };++ collect_text_chunks_impl(text_node, pos_list, state, cache, &mut iter_state);++ iter_state.chunks+}++fn collect_text_chunks_impl(+ parent: SvgNode,+ pos_list: &[CharacterPosition],+ state: &converter::State,+ cache: &mut converter::Cache,+ iter_state: &mut IterState,+) {+ for child in parent.children() {+ if child.is_element() {+ if child.tag_name() == Some(EId::TextPath) {+ if parent.tag_name() != Some(EId::Text) {+ // `textPath` can be set only as a direct `text` element child.+ iter_state.chars_count += count_chars(child);+ continue;+ }++ match resolve_text_flow(child, state) {+ Some(v) => {+ iter_state.text_flow = v;+ }+ None => {+ // Skip an invalid text path and all it's children.+ // We have to update the chars count,+ // because `pos_list` was calculated including this text path.+ iter_state.chars_count += count_chars(child);+ continue;+ }+ }++ iter_state.split_chunk = true;+ }++ collect_text_chunks_impl(child, pos_list, state, cache, iter_state);++ iter_state.text_flow = TextFlow::Linear;++ // Next char after `textPath` should be split too.+ if child.tag_name() == Some(EId::TextPath) {+ iter_state.split_chunk = true;+ }++ continue;+ }++ if !parent.is_visible_element(state.opt) {+ iter_state.chars_count += child.text().chars().count();+ continue;+ }++ let anchor = parent.find_attribute(AId::TextAnchor).unwrap_or_default();++ // TODO: what to do when <= 0? UB?+ let font_size = super::units::resolve_font_size(parent, state);+ let font_size = match NonZeroPositiveF32::new(font_size) {+ Some(n) => n,+ None => {+ // Skip this span.+ iter_state.chars_count += child.text().chars().count();+ continue;+ }+ };++ let font = convert_font(parent, state);++ let raw_paint_order: svgtypes::PaintOrder =+ parent.find_attribute(AId::PaintOrder).unwrap_or_default();+ let paint_order = super::converter::svg_paint_order_to_usvg(raw_paint_order);++ let mut dominant_baseline = parent+ .find_attribute(AId::DominantBaseline)+ .unwrap_or_default();++ // `no-change` means "use parent".+ if dominant_baseline == DominantBaseline::NoChange {+ dominant_baseline = parent+ .parent_element()+ .unwrap()+ .find_attribute(AId::DominantBaseline)+ .unwrap_or_default();+ }++ let mut apply_kerning = true;+ #[allow(clippy::if_same_then_else)]+ if parent.resolve_length(AId::Kerning, state, -1.0) == 0.0 {+ apply_kerning = false;+ } else if parent.find_attribute::<&str>(AId::FontKerning) == Some("none") {+ apply_kerning = false;+ }++ let font_optical_sizing = match parent.find_attribute::<&str>(AId::FontOpticalSizing) {+ Some("none") => crate::FontOpticalSizing::None,+ _ => crate::FontOpticalSizing::Auto, // "auto" or missing (browser default)+ };++ let mut text_length =+ parent.try_convert_length(AId::TextLength, Units::UserSpaceOnUse, state);+ // Negative values should be ignored.+ if let Some(n) = text_length {+ if n < 0.0 {+ text_length = None;+ }+ }++ let visibility: Visibility = parent.find_attribute(AId::Visibility).unwrap_or_default();++ let span = TextSpan {+ start: 0,+ end: 0,+ fill: style::resolve_fill(parent, true, state, cache),+ stroke: style::resolve_stroke(parent, true, state, cache),+ paint_order,+ font,+ font_size,+ small_caps: parent.find_attribute::<&str>(AId::FontVariant) == Some("small-caps"),+ apply_kerning,+ font_optical_sizing,+ decoration: resolve_decoration(parent, state, cache),+ visible: visibility == Visibility::Visible,+ dominant_baseline,+ alignment_baseline: parent+ .find_attribute(AId::AlignmentBaseline)+ .unwrap_or_default(),+ baseline_shift: convert_baseline_shift(parent, state),+ letter_spacing: parent.resolve_length(AId::LetterSpacing, state, 0.0),+ word_spacing: parent.resolve_length(AId::WordSpacing, state, 0.0),+ text_length,+ length_adjust: parent.find_attribute(AId::LengthAdjust).unwrap_or_default(),+ };++ let mut is_new_span = true;+ for c in child.text().chars() {+ let char_len = c.len_utf8();++ // Create a new chunk if:+ // - this is the first span (yes, position can be None)+ // - text character has an absolute coordinate assigned to it (via x/y attribute)+ // - `c` is the first char of the `textPath`+ // - `c` is the first char after `textPath`+ let is_new_chunk = pos_list[iter_state.chars_count].x.is_some()+ || pos_list[iter_state.chars_count].y.is_some()+ || iter_state.split_chunk+ || iter_state.chunks.is_empty();++ iter_state.split_chunk = false;++ if is_new_chunk {+ iter_state.chunk_bytes_count = 0;++ let mut span2 = span.clone();+ span2.start = 0;+ span2.end = char_len;++ iter_state.chunks.push(TextChunk {+ x: pos_list[iter_state.chars_count].x,+ y: pos_list[iter_state.chars_count].y,+ anchor,+ spans: vec![span2],+ text_flow: iter_state.text_flow.clone(),+ text: c.to_string(),+ });+ } else if is_new_span {+ // Add this span to the last text chunk.+ let mut span2 = span.clone();+ span2.start = iter_state.chunk_bytes_count;+ span2.end = iter_state.chunk_bytes_count + char_len;++ if let Some(chunk) = iter_state.chunks.last_mut() {+ chunk.text.push(c);+ chunk.spans.push(span2);+ }+ } else {+ // Extend the last span.+ if let Some(chunk) = iter_state.chunks.last_mut() {+ chunk.text.push(c);+ if let Some(span) = chunk.spans.last_mut() {+ debug_assert_ne!(span.end, 0);+ span.end += char_len;+ }+ }+ }++ is_new_span = false;+ iter_state.chars_count += 1;+ iter_state.chunk_bytes_count += char_len;+ }+ }+}++fn resolve_text_flow(node: SvgNode, state: &converter::State) -> Option<TextFlow> {+ let linked_node = node.attribute::<SvgNode>(AId::Href)?;+ let path = super::shapes::convert(linked_node, state)?;++ // The reference path's transform needs to be applied+ let transform = linked_node.resolve_transform(AId::Transform, state);+ let path = if !transform.is_identity() {+ let mut path_copy = path.as_ref().clone();+ path_copy = path_copy.transform(transform)?;+ Arc::new(path_copy)+ } else {+ path+ };++ let start_offset: Length = node.attribute(AId::StartOffset).unwrap_or_default();+ let start_offset = if start_offset.unit == LengthUnit::Percent {+ // 'If a percentage is given, then the `startOffset` represents+ // a percentage distance along the entire path.'+ let path_len = path_length(&path);+ (path_len * (start_offset.number / 100.0)) as f32+ } else {+ node.resolve_length(AId::StartOffset, state, 0.0)+ };++ let id = NonEmptyString::new(linked_node.element_id().to_string())?;+ Some(TextFlow::Path(Arc::new(TextPath {+ id,+ start_offset,+ path,+ })))+}++fn convert_font(node: SvgNode, state: &converter::State) -> Font {+ let style: FontStyle = node.find_attribute(AId::FontStyle).unwrap_or_default();+ let stretch = conv_font_stretch(node);+ let weight = resolve_font_weight(node);+ let mut variations = parse_font_variation_settings(node);++ // Auto-map standard font properties to variation axes if not explicitly set.+ // This allows variable fonts to work with regular font-weight/font-stretch properties.+ let has_wght = variations.iter().any(|v| &v.tag == b"wght");+ let has_wdth = variations.iter().any(|v| &v.tag == b"wdth");+ let has_ital = variations.iter().any(|v| &v.tag == b"ital");+ let has_slnt = variations.iter().any(|v| &v.tag == b"slnt");++ // Map font-weight to wght axis (if not already set)+ if !has_wght {+ variations.push(FontVariation::new(*b"wght", weight as f32));+ }++ // Map font-stretch to wdth axis (if not already set)+ // CSS font-stretch percentages: ultra-condensed=50%, condensed=75%, normal=100%, expanded=125%, ultra-expanded=200%+ if !has_wdth {+ let wdth = match stretch {+ FontStretch::UltraCondensed => 50.0,+ FontStretch::ExtraCondensed => 62.5,+ FontStretch::Condensed => 75.0,+ FontStretch::SemiCondensed => 87.5,+ FontStretch::Normal => 100.0,+ FontStretch::SemiExpanded => 112.5,+ FontStretch::Expanded => 125.0,+ FontStretch::ExtraExpanded => 150.0,+ FontStretch::UltraExpanded => 200.0,+ };+ if wdth != 100.0 {+ variations.push(FontVariation::new(*b"wdth", wdth));+ }+ }++ // Map font-style: italic to ital axis (if not already set)+ if !has_ital && style == FontStyle::Italic {+ variations.push(FontVariation::new(*b"ital", 1.0));+ }++ // Map font-style: oblique to slnt axis (if not already set)+ // Default oblique angle is typically 12-14 degrees+ if !has_slnt && style == FontStyle::Oblique {+ variations.push(FontVariation::new(*b"slnt", -12.0));+ }++ let font_families = if let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::FontFamily))+ {+ n.attribute(AId::FontFamily).unwrap_or("")+ } else {+ ""+ };++ let mut families = parse_font_families(font_families)+ .ok()+ .log_none(|| {+ log::warn!(+ "Failed to parse {} value: '{}'. Falling back to {}.",+ AId::FontFamily,+ font_families,+ state.opt.font_family+ );+ })+ .unwrap_or_default();++ if families.is_empty() {+ families.push(FontFamily::Named(state.opt.font_family.clone()));+ }++ Font {+ families,+ style,+ stretch,+ weight,+ variations,+ }+}++/// Parses the `font-variation-settings` CSS property.+///+/// Syntax: `normal | [ <string> <number> ]#`+/// Example: `"wght" 700, "wdth" 50`+fn parse_font_variation_settings(node: SvgNode) -> Vec<FontVariation> {+ let value = if let Some(n) = node+ .ancestors()+ .find(|n| n.has_attribute(AId::FontVariationSettings))+ {+ let v = n.attribute(AId::FontVariationSettings).unwrap_or("");+ log::debug!("Found font-variation-settings: '{}'", v);+ v+ } else {+ return Vec::new();+ };++ // "normal" means no variations+ if value.eq_ignore_ascii_case("normal") || value.is_empty() {+ return Vec::new();+ }++ let mut variations = Vec::new();++ // Parse comma-separated list of "tag" value pairs+ for part in value.split(',') {+ let part = part.trim();+ if part.is_empty() {+ continue;+ }++ // Find the tag (quoted string) and value+ // Format: "wght" 700 or 'wght' 700+ let mut chars = part.chars().peekable();++ // Skip whitespace+ while chars.peek().map_or(false, |c| c.is_whitespace()) {+ chars.next();+ }++ // Parse quoted tag+ let quote = match chars.next() {+ Some('"') => '"',+ Some('\'') => '\'',+ _ => continue, // Invalid format+ };++ let mut tag_str = String::new();+ for c in chars.by_ref() {+ if c == quote {+ break;+ }+ tag_str.push(c);+ }++ // Tag must be exactly 4 characters+ if tag_str.len() != 4 {+ log::warn!(+ "Invalid font-variation-settings tag: '{}' (must be 4 characters)",+ tag_str+ );+ continue;+ }++ // Skip whitespace before value+ while chars.peek().map_or(false, |c| c.is_whitespace()) {+ chars.next();+ }++ // Parse the numeric value+ let value_str: String = chars.collect();+ let value_str = value_str.trim();++ let value = match value_str.parse::<f32>() {+ Ok(v) => v,+ Err(_) => {+ log::warn!("Invalid font-variation-settings value: '{}'", value_str);+ continue;+ }+ };++ let tag_bytes = tag_str.as_bytes();+ let tag = [tag_bytes[0], tag_bytes[1], tag_bytes[2], tag_bytes[3]];++ variations.push(FontVariation::new(tag, value));+ }++ variations+}++// TODO: properly resolve narrower/wider+fn conv_font_stretch(node: SvgNode) -> FontStretch {+ if let Some(n) = node.ancestors().find(|n| n.has_attribute(AId::FontStretch)) {+ match n.attribute(AId::FontStretch).unwrap_or("") {+ "narrower" | "condensed" => FontStretch::Condensed,+ "ultra-condensed" => FontStretch::UltraCondensed,+ "extra-condensed" => FontStretch::ExtraCondensed,+ "semi-condensed" => FontStretch::SemiCondensed,+ "semi-expanded" => FontStretch::SemiExpanded,+ "wider" | "expanded" => FontStretch::Expanded,+ "extra-expanded" => FontStretch::ExtraExpanded,+ "ultra-expanded" => FontStretch::UltraExpanded,+ _ => FontStretch::Normal,+ }+ } else {+ FontStretch::Normal+ }+}++fn resolve_font_weight(node: SvgNode) -> u16 {+ fn bound(min: usize, val: usize, max: usize) -> usize {+ std::cmp::max(min, std::cmp::min(max, val))+ }++ let nodes: Vec<_> = node.ancestors().collect();+ let mut weight = 400;+ for n in nodes.iter().rev().skip(1) {+ // skip Root+ weight = match n.attribute(AId::FontWeight).unwrap_or("") {+ "normal" => 400,+ "bold" => 700,+ "100" => 100,+ "200" => 200,+ "300" => 300,+ "400" => 400,+ "500" => 500,+ "600" => 600,+ "700" => 700,+ "800" => 800,+ "900" => 900,+ "bolder" => {+ // By the CSS2 spec the default value should be 400+ // so `bolder` will result in 500.+ // But Chrome and Inkscape will give us 700.+ // Have no idea is it a bug or something, but+ // we will follow such behavior for now.+ let step = if weight == 400 { 300 } else { 100 };++ bound(100, weight + step, 900)+ }+ "lighter" => {+ // By the CSS2 spec the default value should be 400+ // so `lighter` will result in 300.+ // But Chrome and Inkscape will give us 200.+ // Have no idea is it a bug or something, but+ // we will follow such behavior for now.+ let step = if weight == 400 { 200 } else { 100 };++ bound(100, weight - step, 900)+ }+ _ => weight,+ };+ }++ weight as u16+}++/// Resolves text's character positions.+///+/// This includes: x, y, dx, dy.+///+/// # The character+///+/// The first problem with this task is that the *character* itself+/// is basically undefined in the SVG spec. Sometimes it's an *XML character*,+/// sometimes a *glyph*, and sometimes just a *character*.+///+/// There is an ongoing [discussion](https://github.com/w3c/svgwg/issues/537)+/// on the SVG working group that addresses this by stating that a character+/// is a Unicode code point. But it's not final.+///+/// Also, according to the SVG 2 spec, *character* is *a Unicode code point*.+///+/// Anyway, we treat a character as a Unicode code point.+///+/// # Algorithm+///+/// To resolve positions, we have to iterate over descendant nodes and+/// if the current node is a `tspan` and has x/y/dx/dy attribute,+/// than the positions from this attribute should be assigned to the characters+/// of this `tspan` and it's descendants.+///+/// Positions list can have more values than characters in the `tspan`,+/// so we have to clamp it, because values should not overlap, e.g.:+///+/// (we ignore whitespaces for example purposes,+/// so the `text` content is `Text` and not `T ex t`)+///+/// ```text+/// <text>+/// a+/// <tspan x="10 20 30">+/// bc+/// </tspan>+/// d+/// </text>+/// ```+///+/// In this example, the `d` position should not be set to `30`.+/// And the result should be: `[None, 10, 20, None]`+///+/// Another example:+///+/// ```text+/// <text>+/// <tspan x="100 110 120 130">+/// a+/// <tspan x="50">+/// bc+/// </tspan>+/// </tspan>+/// d+/// </text>+/// ```+///+/// The result should be: `[100, 50, 120, None]`+fn resolve_positions_list(text_node: SvgNode, state: &converter::State) -> Vec<CharacterPosition> {+ // Allocate a list that has all characters positions set to `None`.+ let total_chars = count_chars(text_node);+ let mut list = vec![+ CharacterPosition {+ x: None,+ y: None,+ dx: None,+ dy: None,+ };+ total_chars+ ];++ let mut offset = 0;+ for child in text_node.descendants() {+ if child.is_element() {+ // We must ignore text positions on `textPath`.+ if !matches!(child.tag_name(), Some(EId::Text) | Some(EId::Tspan)) {+ continue;+ }++ let child_chars = count_chars(child);+ macro_rules! push_list {+ ($aid:expr, $field:ident) => {+ if let Some(num_list) = super::units::convert_list(child, $aid, state) {+ // Note that we are using not the total count,+ // but the amount of characters in the current `tspan` (with children).+ let len = std::cmp::min(num_list.len(), child_chars);+ for i in 0..len {+ list[offset + i].$field = Some(num_list[i]);+ }+ }+ };+ }++ push_list!(AId::X, x);+ push_list!(AId::Y, y);+ push_list!(AId::Dx, dx);+ push_list!(AId::Dy, dy);+ } else if child.is_text() {+ // Advance the offset.+ offset += child.text().chars().count();+ }+ }++ list+}++/// Resolves characters rotation.+///+/// The algorithm is well explained+/// [in the SVG spec](https://www.w3.org/TR/SVG11/text.html#TSpanElement) (scroll down a bit).+///+/// +///+/// Note: this algorithm differs from the position resolving one.+fn resolve_rotate_list(text_node: SvgNode) -> Vec<f32> {+ // Allocate a list that has all characters angles set to `0.0`.+ let mut list = vec![0.0; count_chars(text_node)];+ let mut last = 0.0;+ let mut offset = 0;+ for child in text_node.descendants() {+ if child.is_element() {+ if let Some(rotate) = child.attribute::<Vec<f32>>(AId::Rotate) {+ for i in 0..count_chars(child) {+ if let Some(a) = rotate.get(i).cloned() {+ list[offset + i] = a;+ last = a;+ } else {+ // If the rotate list doesn't specify the rotation for+ // this character - use the last one.+ list[offset + i] = last;+ }+ }+ }+ } else if child.is_text() {+ // Advance the offset.+ offset += child.text().chars().count();+ }+ }++ list+}++/// Resolves node's `text-decoration` property.+fn resolve_decoration(+ tspan: SvgNode,+ state: &converter::State,+ cache: &mut converter::Cache,+) -> TextDecoration {+ // Checks if a decoration is present in a single node.+ fn find_decoration(node: SvgNode, value: &str) -> bool {+ if let Some(str_value) = node.attribute::<&str>(AId::TextDecoration) {+ str_value.split(' ').any(|v| v == value)+ } else {+ false+ }+ }++ // The algorithm is as follows: First, we check whether the given text decoration appears in ANY+ // ancestor, i.e. it can also appear in ancestors outside of the <text> element. If the text+ // decoration is declared somewhere, it means that this tspan will have it. However, we still+ // need to find the corresponding fill/stroke for it. To do this, we iterate through all+ // ancestors (i.e. tspans) until we find the text decoration declared. If not, we will+ // stop at latest at the text node, and use its fill/stroke.+ let mut gen_style = |text_decoration: &str| {+ if !tspan+ .ancestors()+ .any(|n| find_decoration(n, text_decoration))+ {+ return None;+ }++ let mut fill_node = None;+ let mut stroke_node = None;++ for node in tspan.ancestors() {+ if find_decoration(node, text_decoration) || node.tag_name() == Some(EId::Text) {+ fill_node = fill_node.map_or(Some(node), Some);+ stroke_node = stroke_node.map_or(Some(node), Some);+ break;+ }+ }++ Some(TextDecorationStyle {+ fill: fill_node.and_then(|node| style::resolve_fill(node, true, state, cache)),+ stroke: stroke_node.and_then(|node| style::resolve_stroke(node, true, state, cache)),+ })+ };++ TextDecoration {+ underline: gen_style("underline"),+ overline: gen_style("overline"),+ line_through: gen_style("line-through"),+ }+}++fn convert_baseline_shift(node: SvgNode, state: &converter::State) -> Vec<BaselineShift> {+ let mut shift = Vec::new();+ let nodes: Vec<_> = node+ .ancestors()+ .take_while(|n| n.tag_name() != Some(EId::Text))+ .collect();+ for n in nodes {+ if let Some(len) = n.try_attribute::<Length>(AId::BaselineShift) {+ if len.unit == LengthUnit::Percent {+ let n = super::units::resolve_font_size(n, state) * (len.number as f32 / 100.0);+ shift.push(BaselineShift::Number(n));+ } else {+ let n = super::units::convert_length(+ len,+ n,+ AId::BaselineShift,+ Units::ObjectBoundingBox,+ state,+ );+ shift.push(BaselineShift::Number(n));+ }+ } else if let Some(s) = n.attribute(AId::BaselineShift) {+ match s {+ "sub" => shift.push(BaselineShift::Subscript),+ "super" => shift.push(BaselineShift::Superscript),+ _ => shift.push(BaselineShift::Baseline),+ }+ }+ }++ if shift+ .iter()+ .all(|base| matches!(base, BaselineShift::Baseline))+ {+ shift.clear();+ }++ shift+}++fn count_chars(node: SvgNode) -> usize {+ node.descendants()+ .filter(|n| n.is_text())+ .fold(0, |w, n| w + n.text().chars().count())+}++/// Converts the writing mode.+///+/// [SVG 2] references [CSS Writing Modes Level 3] for the definition of the+/// 'writing-mode' property, there are only two writing modes:+/// horizontal left-to-right and vertical right-to-left.+///+/// That specification introduces new values for the property. The SVG 1.1+/// values are obsolete but must still be supported by converting the specified+/// values to computed values as follows:+///+/// - `lr`, `lr-tb`, `rl`, `rl-tb` => `horizontal-tb`+/// - `tb`, `tb-rl` => `vertical-rl`+///+/// The current `vertical-lr` behaves exactly the same as `vertical-rl`.+///+/// Also, looks like no one really supports the `rl` and `rl-tb`, except `Batik`.+/// And I'm not sure if its behaviour is correct.+///+/// So we will ignore it as well, mainly because I have no idea how exactly+/// it should affect the rendering.+///+/// [SVG 2]: https://www.w3.org/TR/SVG2/text.html#WritingModeProperty+/// [CSS Writing Modes Level 3]: https://www.w3.org/TR/css-writing-modes-3/#svg-writing-mode-css+fn convert_writing_mode(text_node: SvgNode) -> WritingMode {+ if let Some(n) = text_node+ .ancestors()+ .find(|n| n.has_attribute(AId::WritingMode))+ {+ match n.attribute(AId::WritingMode).unwrap_or("lr-tb") {+ "tb" | "tb-rl" | "vertical-rl" | "vertical-lr" => WritingMode::TopToBottom,+ _ => WritingMode::LeftToRight,+ }+ } else {+ WritingMode::LeftToRight+ }+}++fn path_length(path: &tiny_skia_path::Path) -> f64 {+ let mut prev_mx = path.points()[0].x;+ let mut prev_my = path.points()[0].y;+ let mut prev_x = prev_mx;+ let mut prev_y = prev_my;++ fn create_curve_from_line(px: f32, py: f32, x: f32, y: f32) -> kurbo::CubicBez {+ let line = kurbo::Line::new(+ kurbo::Point::new(px as f64, py as f64),+ kurbo::Point::new(x as f64, y as f64),+ );+ let p1 = line.eval(0.33);+ let p2 = line.eval(0.66);+ kurbo::CubicBez::new(line.p0, p1, p2, line.p1)+ }++ let mut length = 0.0;+ for seg in path.segments() {+ let curve = match seg {+ tiny_skia_path::PathSegment::MoveTo(p) => {+ prev_mx = p.x;+ prev_my = p.y;+ prev_x = p.x;+ prev_y = p.y;+ continue;+ }+ tiny_skia_path::PathSegment::LineTo(p) => {+ create_curve_from_line(prev_x, prev_y, p.x, p.y)+ }+ tiny_skia_path::PathSegment::QuadTo(p1, p) => kurbo::QuadBez::new(+ kurbo::Point::new(prev_x as f64, prev_y as f64),+ kurbo::Point::new(p1.x as f64, p1.y as f64),+ kurbo::Point::new(p.x as f64, p.y as f64),+ )+ .raise(),+ tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => kurbo::CubicBez::new(+ kurbo::Point::new(prev_x as f64, prev_y as f64),+ kurbo::Point::new(p1.x as f64, p1.y as f64),+ kurbo::Point::new(p2.x as f64, p2.y as f64),+ kurbo::Point::new(p.x as f64, p.y as f64),+ ),+ tiny_skia_path::PathSegment::Close => {+ create_curve_from_line(prev_x, prev_y, prev_mx, prev_my)+ }+ };++ length += curve.arclen(0.5);+ prev_x = curve.p3.x as f32;+ prev_y = curve.p3.y as f32;+ }++ length+}diff --git a/vendor/usvg/src/parser/units.rs b/vendor/usvg/src/parser/units.rsnew file mode 100644index 00000000..ce2c7dd2--- /dev/null+++ b/vendor/usvg/src/parser/units.rs@@ -0,0 +1,145 @@+// Copyright 2019 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use svgtypes::{Length, LengthUnit as Unit};++use super::converter;+use super::svgtree::{AId, SvgNode};+use crate::Units;++#[inline(never)]+pub(crate) fn convert_length(+ length: Length,+ node: SvgNode,+ aid: AId,+ object_units: Units,+ state: &converter::State,+) -> f32 {+ let dpi = state.opt.dpi;+ let n = length.number as f32;+ match length.unit {+ Unit::None | Unit::Px => n,+ Unit::Em => n * resolve_font_size(node, state),+ Unit::Ex => n * resolve_font_size(node, state) / 2.0,+ Unit::In => n * dpi,+ Unit::Cm => n * dpi / 2.54,+ Unit::Mm => n * dpi / 25.4,+ Unit::Pt => n * dpi / 72.0,+ Unit::Pc => n * dpi / 6.0,+ Unit::Percent => {+ if object_units == Units::ObjectBoundingBox {+ n / 100.0+ } else {+ let view_box = state.view_box;++ match aid {+ AId::Cx+ | AId::Dx+ | AId::Fx+ | AId::MarkerWidth+ | AId::RefX+ | AId::Rx+ | AId::Width+ | AId::X+ | AId::X1+ | AId::X2 => convert_percent(length, view_box.width()),+ AId::Cy+ | AId::Dy+ | AId::Fy+ | AId::Height+ | AId::MarkerHeight+ | AId::RefY+ | AId::Ry+ | AId::Y+ | AId::Y1+ | AId::Y2 => convert_percent(length, view_box.height()),+ _ => {+ let mut vb_len = view_box.width().powi(2) + view_box.height().powi(2);+ vb_len = (vb_len / 2.0).sqrt();+ convert_percent(length, vb_len)+ }+ }+ }+ }+ }+}++pub(crate) fn convert_user_length(+ length: Length,+ node: SvgNode,+ aid: AId,+ state: &converter::State,+) -> f32 {+ convert_length(length, node, aid, Units::UserSpaceOnUse, state)+}++#[inline(never)]+pub(crate) fn convert_list(node: SvgNode, aid: AId, state: &converter::State) -> Option<Vec<f32>> {+ if let Some(text) = node.attribute::<&str>(aid) {+ let mut num_list = Vec::new();+ for length in svgtypes::LengthListParser::from(text).flatten() {+ num_list.push(convert_user_length(length, node, aid, state));+ }++ Some(num_list)+ } else {+ None+ }+}++fn convert_percent(length: Length, base: f32) -> f32 {+ base * (length.number as f32) / 100.0+}++#[inline(never)]+pub(crate) fn resolve_font_size(node: SvgNode, state: &converter::State) -> f32 {+ let nodes: Vec<_> = node.ancestors().collect();+ let mut font_size = state.opt.font_size;+ for n in nodes.iter().rev().skip(1) {+ // skip Root+ if let Some(length) = n.try_attribute::<Length>(AId::FontSize) {+ let dpi = state.opt.dpi;+ let n = length.number as f32;+ font_size = match length.unit {+ Unit::None | Unit::Px => n,+ Unit::Em => n * font_size,+ Unit::Ex => n * font_size / 2.0,+ Unit::In => n * dpi,+ Unit::Cm => n * dpi / 2.54,+ Unit::Mm => n * dpi / 25.4,+ Unit::Pt => n * dpi / 72.0,+ Unit::Pc => n * dpi / 6.0,+ Unit::Percent => {+ // If `font-size` has percent units that it's value+ // is relative to the parent node `font-size`.+ length.number as f32 * font_size * 0.01+ }+ }+ } else if let Some(name) = n.attribute(AId::FontSize) {+ font_size = convert_named_font_size(name, font_size);+ }+ }++ font_size+}++fn convert_named_font_size(name: &str, parent_font_size: f32) -> f32 {+ let factor = match name {+ "xx-small" => -3,+ "x-small" => -2,+ "small" => -1,+ "medium" => 0,+ "large" => 1,+ "x-large" => 2,+ "xx-large" => 3,+ "smaller" => -1,+ "larger" => 1,+ _ => {+ log::warn!("Invalid 'font-size' value: '{}'.", name);+ 0+ }+ };++ // 'On a computer screen a scaling factor of 1.2 is suggested between adjacent indexes.'+ parent_font_size * 1.2f32.powi(factor)+}diff --git a/vendor/usvg/src/parser/use_node.rs b/vendor/usvg/src/parser/use_node.rsnew file mode 100644index 00000000..06560d2d--- /dev/null+++ b/vendor/usvg/src/parser/use_node.rs@@ -0,0 +1,371 @@+// Copyright 2019 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::sync::Arc;++use svgtypes::{Length, LengthUnit};++use super::svgtree::{AId, EId, SvgNode};+use super::{converter, style};+use crate::tree::ContextElement;+use crate::{Group, IsValidLength, Node, NonZeroRect, Path, Size, Transform, ViewBox};++pub(crate) fn convert(+ node: SvgNode,+ state: &converter::State,+ cache: &mut converter::Cache,+ parent: &mut Group,+) {+ let child = match node.first_child() {+ Some(v) => v,+ None => return,+ };++ if state.parent_clip_path.is_some() && child.tag_name() == Some(EId::Symbol) {+ // Ignore `symbol` referenced by `use` inside a `clipPath`.+ // It will be ignored later anyway, but this will prevent+ // a redundant `clipPath` creation (which is required for `symbol`).+ return;+ }++ let mut use_state = state.clone();+ use_state.context_element = Some((+ style::resolve_fill(node, true, state, cache).map(|mut f| {+ f.context_element = Some(ContextElement::UseNode);+ f+ }),+ style::resolve_stroke(node, true, state, cache).map(|mut s| {+ s.context_element = Some(ContextElement::UseNode);+ s+ }),+ ));++ // We require an original transformation to setup 'clipPath'.+ let mut orig_ts = node.resolve_transform(AId::Transform, state);+ let mut new_ts = Transform::default();++ {+ let x = node.convert_user_length(AId::X, &use_state, Length::zero());+ let y = node.convert_user_length(AId::Y, &use_state, Length::zero());+ new_ts = new_ts.pre_translate(x, y);+ }++ let linked_to_symbol = child.tag_name() == Some(EId::Symbol);++ if linked_to_symbol {+ // If a `use` element has a width/height attribute and references a symbol+ // then relative units (like percentages) should be resolved relative+ // to the width/height of the `use` element, and not the original SVG.+ // This is why we need to (potentially) adapt the view box here.+ use_state.view_box = {+ let def = Length::new(100.0, LengthUnit::Percent);+ let x = use_state.view_box.x();+ let y = use_state.view_box.y();++ let width = if node.has_attribute(AId::Width) {+ node.convert_user_length(AId::Width, &use_state, def)+ } else {+ use_state.view_box.width()+ };++ let height = if node.has_attribute(AId::Height) {+ node.convert_user_length(AId::Height, &use_state, def)+ } else {+ use_state.view_box.height()+ };++ NonZeroRect::from_xywh(x, y, width, height)+ // Fail silently if the rect is not valid.+ .unwrap_or(use_state.view_box)+ };++ if let Some(ts) = viewbox_transform(node, child, &use_state) {+ new_ts = new_ts.pre_concat(ts);+ }++ if let Some(clip_rect) = get_clip_rect(node, child, &use_state) {+ let mut g = clip_element(node, clip_rect, orig_ts, &use_state, cache);+ g.abs_transform = parent.abs_transform;++ // Make group for `use`.+ if let Some(mut g2) =+ converter::convert_group(node, &use_state, true, cache, &mut g, &|cache, g2| {+ convert_children(child, new_ts, &use_state, cache, false, g2);+ })+ {+ // We must reset transform, because it was already set+ // to the group with clip-path.+ g.is_context_element = true;+ g2.id = String::new(); // Prevent ID duplication.+ g2.transform = Transform::default();+ g.children.push(Node::Group(Box::new(g2)));+ }++ if g.children.is_empty() {+ return;+ }++ g.calculate_bounding_boxes();+ parent.children.push(Node::Group(Box::new(g)));+ return;+ }+ }++ orig_ts = orig_ts.pre_concat(new_ts);++ if linked_to_symbol {+ // Make group for `use`.+ if let Some(mut g) =+ converter::convert_group(node, &use_state, false, cache, parent, &|cache, g| {+ convert_children(child, orig_ts, &use_state, cache, false, g);+ })+ {+ g.is_context_element = true;+ g.transform = Transform::default();+ parent.children.push(Node::Group(Box::new(g)));+ }+ } else {+ let linked_to_svg = child.tag_name() == Some(EId::Svg);+ if linked_to_svg {+ // When a `use` element references a `svg` element,+ // we have to remember `use` element size and use it+ // instead of `svg` element size.++ let def = Length::new(100.0, LengthUnit::Percent);+ // As per usual, the SVG spec doesn't clarify this edge case,+ // but it seems like `use` size has to be reset by each `use`.+ // Meaning if we have two nested `use` elements, where one had set `width` and+ // other set `height`, we have to ignore the first `width`.+ //+ // Example:+ // <use id="use1" xlink:href="#use2" width="100"/>+ // <use id="use2" xlink:href="#svg2" height="100"/>+ // <svg id="svg2" x="40" y="40" width="80" height="80" xmlns="http://www.w3.org/2000/svg"/>+ //+ // In this case `svg2` size is 80x100 and not 100x100.+ use_state.use_size = (None, None);++ // Width and height can be set independently.+ if node.has_attribute(AId::Width) {+ use_state.use_size.0 = Some(node.convert_user_length(AId::Width, &use_state, def));+ }+ if node.has_attribute(AId::Height) {+ use_state.use_size.1 = Some(node.convert_user_length(AId::Height, &use_state, def));+ }++ convert_children(node, orig_ts, &use_state, cache, true, parent);+ } else {+ convert_children(node, orig_ts, &use_state, cache, true, parent);+ }+ }+}++pub(crate) fn convert_svg(+ node: SvgNode,+ state: &converter::State,+ cache: &mut converter::Cache,+ parent: &mut Group,+) {+ // We require original transformation to setup 'clipPath'.+ let mut orig_ts = node.resolve_transform(AId::Transform, state);+ let mut new_ts = Transform::default();++ let x = node.convert_user_length(AId::X, state, Length::zero());+ let y = node.convert_user_length(AId::Y, state, Length::zero());+ new_ts = new_ts.pre_translate(x, y);++ if let Some(ts) = viewbox_transform(node, node, state) {+ new_ts = new_ts.pre_concat(ts);+ }++ // We have to create a new state which would have its viewBox set to the current SVG element.+ // Note that we're not updating State::size - it's a completely different property.+ let mut new_state = state.clone();+ new_state.view_box = {+ if let Some(vb) = node.parse_viewbox() {+ vb+ } else {+ // No `viewBox` attribute? Then use `x`, `y`, `width` and `height` instead.+ let (mut w, mut h) = use_node_size(node, state);++ // If attributes `width` and/or `height` are provided on the `use` element,+ // then these values will override the corresponding attributes+ // on the `svg` in the generated tree.+ w = state.use_size.0.unwrap_or(w);+ h = state.use_size.1.unwrap_or(h);++ NonZeroRect::from_xywh(x, y, w, h).unwrap_or(state.view_box)+ }+ };++ if let Some(clip_rect) = get_clip_rect(node, node, state) {+ let mut g = clip_element(node, clip_rect, orig_ts, state, cache);+ g.abs_transform = parent.abs_transform.pre_concat(orig_ts);+ convert_children(node, new_ts, &new_state, cache, false, &mut g);+ g.calculate_bounding_boxes();+ parent.children.push(Node::Group(Box::new(g)));+ } else {+ orig_ts = orig_ts.pre_concat(new_ts);+ convert_children(node, orig_ts, &new_state, cache, false, parent);+ }+}++fn clip_element(+ node: SvgNode,+ clip_rect: NonZeroRect,+ transform: Transform,+ state: &converter::State,+ cache: &mut converter::Cache,+) -> Group {+ // We can't set `clip-path` on the element itself,+ // because it will be affected by a possible transform.+ // So we have to create an additional group.++ // Emulate a new viewport via clipPath.+ //+ // From:+ // <defs/>+ // <elem/>+ //+ // To:+ // <defs>+ // <clipPath id="clipPath1">+ // <rect/>+ // </clipPath>+ // </defs>+ // <g clip-path="ulr(#clipPath1)">+ // <elem/>+ // </g>++ let mut clip_path = crate::ClipPath::empty(cache.gen_clip_path_id());++ let mut path = Path::new_simple(Arc::new(tiny_skia_path::PathBuilder::from_rect(+ clip_rect.to_rect(),+ )))+ .unwrap();+ path.fill = Some(crate::Fill::default());+ clip_path.root.children.push(Node::Path(Box::new(path)));++ // Nodes generated by markers must not have an ID. Otherwise we would have duplicates.+ let id = if state.parent_markers.is_empty() {+ node.element_id().to_string()+ } else {+ String::new()+ };++ Group {+ id,+ transform,+ clip_path: Some(Arc::new(clip_path)),+ ..Group::empty()+ }+}++fn convert_children(+ node: SvgNode,+ transform: Transform,+ state: &converter::State,+ cache: &mut converter::Cache,+ is_context_element: bool,+ parent: &mut Group,+) {+ // Cache the parent absolute transform.+ let parent_abs_transform = parent.abs_transform;++ let required = !transform.is_identity();++ let Some(g) = converter::convert_group(node, state, required, cache, parent, &|cache, g| {+ // Make sure they are correct before converting children.+ g.transform = transform;+ g.abs_transform = parent_abs_transform.pre_concat(transform);+ g.is_context_element = is_context_element;++ if state.parent_clip_path.is_some() {+ converter::convert_clip_path_elements(node, state, cache, g);+ } else {+ converter::convert_children(node, state, cache, g);+ }+ }) else {+ return;+ };++ parent.children.push(Node::Group(Box::new(g)));+}++fn get_clip_rect(+ use_node: SvgNode,+ symbol_node: SvgNode,+ state: &converter::State,+) -> Option<NonZeroRect> {+ // No need to clip elements with overflow:visible.+ if matches!(+ symbol_node.attribute(AId::Overflow),+ Some("visible") | Some("auto")+ ) {+ return None;+ }++ // A nested `svg` with only the `viewBox` attribute and no "rectangle" (x, y, width, height)+ // should not be clipped.+ if use_node.tag_name() == Some(EId::Svg) {+ // Nested `svg` referenced by `use` still should be clipped, but by `use` bounds.+ if state.use_size.0.is_none() && state.use_size.1.is_none() {+ if !(use_node.has_attribute(AId::Width) && use_node.has_attribute(AId::Height)) {+ return None;+ }+ }+ }++ let (x, y, mut w, mut h) = {+ let x = use_node.convert_user_length(AId::X, state, Length::zero());+ let y = use_node.convert_user_length(AId::Y, state, Length::zero());+ let (w, h) = use_node_size(use_node, state);+ (x, y, w, h)+ };++ if use_node.tag_name() == Some(EId::Svg) {+ // If attributes `width` and/or `height` are provided on the `use` element,+ // then these values will override the corresponding attributes+ // on the `svg` in the generated tree.+ w = state.use_size.0.unwrap_or(w);+ h = state.use_size.1.unwrap_or(h);+ }++ if !w.is_valid_length() || !h.is_valid_length() {+ return None;+ }++ NonZeroRect::from_xywh(x, y, w, h)+}++fn use_node_size(node: SvgNode, state: &converter::State) -> (f32, f32) {+ let def = Length::new(100.0, LengthUnit::Percent);+ let w = node.convert_user_length(AId::Width, state, def);+ let h = node.convert_user_length(AId::Height, state, def);+ (w, h)+}++fn viewbox_transform(+ node: SvgNode,+ linked: SvgNode,+ state: &converter::State,+) -> Option<Transform> {+ let (mut w, mut h) = use_node_size(node, state);++ if node.tag_name() == Some(EId::Svg) {+ // If attributes `width` and/or `height` are provided on the `use` element,+ // then these values will override the corresponding attributes+ // on the `svg` in the generated tree.+ w = state.use_size.0.unwrap_or(w);+ h = state.use_size.1.unwrap_or(h);+ }++ let size = Size::from_wh(w, h)?;+ let rect = linked.parse_viewbox()?;+ let aspect = linked+ .attribute(AId::PreserveAspectRatio)+ .unwrap_or_default();+ let view_box = ViewBox { rect, aspect };++ Some(view_box.to_transform(size))+}diff --git a/vendor/usvg/src/text/colr.rs b/vendor/usvg/src/text/colr.rsnew file mode 100644index 00000000..86533734--- /dev/null+++ b/vendor/usvg/src/text/colr.rs@@ -0,0 +1,578 @@+// Copyright 2024 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use crate::parser::OptionLog;+use skrifa::instance::LocationRef;+use skrifa::prelude::Size;+use skrifa::raw::types::Point;+use skrifa::{+ MetadataProvider,+ color::{Brush, ColorStop, Extend, Transform},+ outline::DrawSettings,+};+use std::fmt::Write as _;+use svgtypes::Color;++use super::transform::{skrifa_to_tsp_transform, tsp_to_skrifa_transform};++struct Builder<'a> {+ path: &'a mut String,+ min_x: f32,+ min_y: f32,+ max_x: f32,+ max_y: f32,+}++impl<'a> Builder<'a> {+ fn new(path: &'a mut String) -> Self {+ Self {+ path,+ min_x: f32::MAX,+ min_y: f32::MAX,+ max_x: f32::MIN,+ max_y: f32::MIN,+ }+ }++ fn add_point(&mut self, x: f32, y: f32) {+ self.min_x = self.min_x.min(x);+ self.min_y = self.min_y.min(y);+ self.max_x = self.max_x.max(x);+ self.max_y = self.max_y.max(y);+ }++ /// Returns a conservative bounding box of the written path.+ /// It includes curve control points, so it can be larger than the exact+ /// bounding box, but never smaller.+ fn bounds(&self) -> Option<tiny_skia_path::Rect> {+ if self.min_x <= self.max_x && self.min_y <= self.max_y {+ tiny_skia_path::Rect::from_ltrb(self.min_x, self.min_y, self.max_x, self.max_y)+ } else {+ None+ }+ }++ fn finish(&mut self) {+ if !self.path.is_empty() {+ self.path.pop(); // remove trailing space+ }+ }+}++impl skrifa::outline::OutlinePen for Builder<'_> {+ fn move_to(&mut self, x: f32, y: f32) {+ self.add_point(x, y);+ write!(self.path, "M {} {} ", x, y).unwrap();+ }++ fn line_to(&mut self, x: f32, y: f32) {+ self.add_point(x, y);+ write!(self.path, "L {} {} ", x, y).unwrap();+ }++ fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {+ self.add_point(cx0, cy0);+ self.add_point(x, y);+ write!(self.path, "Q {} {} {} {} ", cx0, cy0, x, y).unwrap();+ }++ fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {+ self.add_point(cx0, cy0);+ self.add_point(cx1, cy1);+ self.add_point(x, y);+ write!(self.path, "C {} {} {} {} {} {} ", cx0, cy0, cx1, cy1, x, y).unwrap();+ }++ fn close(&mut self) {+ self.path.push_str("Z ");+ }+}++trait XmlWriterExt {+ fn write_color_attribute(&mut self, name: &str, ts: Color);+ fn write_transform_attribute(&mut self, name: &str, ts: Transform);+ fn write_spread_method_attribute(&mut self, method: Extend);+}++impl XmlWriterExt for xmlwriter::XmlWriter {+ fn write_color_attribute(&mut self, name: &str, color: Color) {+ self.write_attribute_fmt(+ name,+ format_args!("rgb({}, {}, {})", color.red, color.green, color.blue),+ );+ }++ fn write_transform_attribute(&mut self, name: &str, ts: Transform) {+ if ts == Transform::default() {+ return;+ }++ self.write_attribute_fmt(+ name,+ format_args!(+ "matrix({} {} {} {} {} {})",+ ts.xx, ts.yx, ts.xy, ts.yy, ts.dx, ts.dy+ ),+ );+ }++ fn write_spread_method_attribute(&mut self, extend: Extend) {+ self.write_attribute(+ "spreadMethod",+ match extend {+ Extend::Pad => "pad",+ Extend::Repeat => "repeat",+ Extend::Reflect => "reflect",+ Extend::Unknown => return,+ },+ );+ }+}++// NOTE: This is only a best-effort translation of COLR into SVG.+pub(crate) struct GlyphPainter<'a> {+ pub(crate) font: &'a skrifa::FontRef<'a>,+ /// The variation location to draw outlines at.+ pub(crate) location: LocationRef<'a>,+ pub(crate) svg: &'a mut xmlwriter::XmlWriter,+ pub(crate) path_buf: &'a mut String,+ pub(crate) gradient_index: usize,+ pub(crate) clip_path_index: usize,+ pub(crate) foreground_color: Color,+ pub(crate) transform: Transform,+ pub(crate) outline_transform: Transform,+ pub(crate) transforms_stack: Vec<Transform>,+ /// The bounding box of every active clip, in the root coordinate space.+ /// `None` means the clip is empty (or its bounds are unknown).+ pub(crate) clip_stack: Vec<Option<tiny_skia_path::Rect>>,+}++impl<'a> GlyphPainter<'a> {+ fn write_gradient_stops(&mut self, stops: &[ColorStop]) {+ for stop in stops {+ let color = self.palette_index_to_color(stop.palette_index, stop.alpha);+ self.svg.start_element("stop");+ self.svg.write_attribute("offset", &stop.offset);+ self.svg.write_color_attribute("stop-color", color);+ let opacity = f32::from(color.alpha) / 255.0;+ self.svg.write_attribute("stop-opacity", &opacity);+ self.svg.end_element();+ }+ }++ fn paint_solid(&mut self, color: Color) {+ self.svg.start_element("path");+ self.svg.write_color_attribute("fill", color);+ let opacity = f32::from(color.alpha) / 255.0;+ self.svg.write_attribute("fill-opacity", &opacity);+ self.svg+ .write_transform_attribute("transform", self.outline_transform);+ self.svg.write_attribute("d", self.path_buf);+ self.svg.end_element();+ }++ fn paint_linear_gradient(+ &mut self,+ p0: Point<f32>,+ p1: Point<f32>,+ color_stops: &[ColorStop],+ extend: Extend,+ ) {+ let gradient_id = format!("lg{}", self.gradient_index);+ self.gradient_index += 1;++ let gradient_transform = paint_transform(self.outline_transform, self.transform);++ self.svg.start_element("linearGradient");+ self.svg.write_attribute("id", &gradient_id);+ self.svg.write_attribute("x1", &p0.x);+ self.svg.write_attribute("y1", &p0.y);+ self.svg.write_attribute("x2", &p1.x);+ self.svg.write_attribute("y2", &p1.y);+ self.svg.write_attribute("gradientUnits", &"userSpaceOnUse");+ self.svg.write_spread_method_attribute(extend);+ self.svg+ .write_transform_attribute("gradientTransform", gradient_transform);+ self.write_gradient_stops(color_stops);+ self.svg.end_element();++ self.svg.start_element("path");+ self.svg+ .write_attribute_fmt("fill", format_args!("url(#{})", gradient_id));+ self.svg+ .write_transform_attribute("transform", self.outline_transform);+ self.svg.write_attribute("d", self.path_buf);+ self.svg.end_element();+ }++ fn paint_radial_gradient(+ &mut self,+ c0: Point<f32>,+ r0: f32,+ c1: Point<f32>,+ r1: f32,+ color_stops: &[ColorStop],+ extend: Extend,+ ) {+ let gradient_id = format!("rg{}", self.gradient_index);+ self.gradient_index += 1;++ let gradient_transform = paint_transform(self.outline_transform, self.transform);++ // TODO: Normalizing the stops into the 0..1 range moves the circles onto the+ // first and last stop, which can make `r0` (and in theory `r1`) negative.+ // SVG cannot express that, so the color line should be cut where the radius+ // reaches zero, with an interpolated stop inserted at the cut and the+ // remaining stops reparameterized into the 0..1 range.+ self.svg.start_element("radialGradient");+ self.svg.write_attribute("id", &gradient_id);+ self.svg.write_attribute("cx", &c1.x);+ self.svg.write_attribute("cy", &c1.y);+ self.svg.write_attribute("r", &r1);+ self.svg.write_attribute("fr", &r0);+ self.svg.write_attribute("fx", &c0.x);+ self.svg.write_attribute("fy", &c0.y);+ self.svg.write_attribute("gradientUnits", &"userSpaceOnUse");+ self.svg.write_spread_method_attribute(extend);+ self.svg+ .write_transform_attribute("gradientTransform", gradient_transform);+ self.write_gradient_stops(color_stops);+ self.svg.end_element();++ self.svg.start_element("path");+ self.svg+ .write_attribute_fmt("fill", format_args!("url(#{})", gradient_id));+ self.svg+ .write_transform_attribute("transform", self.outline_transform);+ self.svg.write_attribute("d", self.path_buf);+ self.svg.end_element();+ }++ fn paint_sweep_gradient(+ &mut self,+ _c0: Point<f32>,+ _start_angle: f32,+ _end_angle: f32,+ _color_stops: &[ColorStop],+ _extend: Extend,+ ) {+ // Sweep gradients are not supported.+ // TODO: surface warning without printing to stdout+ }+}++fn paint_transform(outline_transform: Transform, transform: Transform) -> Transform {+ let outline_transform = skrifa_to_tsp_transform(outline_transform);+ let gradient_transform = skrifa_to_tsp_transform(transform);++ let gradient_transform = outline_transform+ .invert()+ .log_none(|| log::warn!("Failed to calculate transform for gradient in glyph."))+ .unwrap_or_default()+ .pre_concat(gradient_transform);++ tsp_to_skrifa_transform(gradient_transform)+}++/// Returns the bounding box of `rect` transformed by `ts`.+fn map_rect(+ rect: tiny_skia_path::Rect,+ ts: tiny_skia_path::Transform,+) -> Option<tiny_skia_path::Rect> {+ let mut points = [+ tiny_skia_path::Point::from_xy(rect.left(), rect.top()),+ tiny_skia_path::Point::from_xy(rect.right(), rect.top()),+ tiny_skia_path::Point::from_xy(rect.left(), rect.bottom()),+ tiny_skia_path::Point::from_xy(rect.right(), rect.bottom()),+ ];+ ts.map_points(&mut points);+ let min_x = points.iter().map(|p| p.x).fold(f32::MAX, f32::min);+ let min_y = points.iter().map(|p| p.y).fold(f32::MAX, f32::min);+ let max_x = points.iter().map(|p| p.x).fold(f32::MIN, f32::max);+ let max_y = points.iter().map(|p| p.y).fold(f32::MIN, f32::max);+ tiny_skia_path::Rect::from_ltrb(min_x, min_y, max_x, max_y)+}++/// Returns the intersection of two rects, or `None` when they do not overlap.+fn intersect_rects(+ a: tiny_skia_path::Rect,+ b: tiny_skia_path::Rect,+) -> Option<tiny_skia_path::Rect> {+ tiny_skia_path::Rect::from_ltrb(+ a.left().max(b.left()),+ a.top().max(b.top()),+ a.right().min(b.right()),+ a.bottom().min(b.bottom()),+ )+}++impl GlyphPainter<'_> {+ fn clip_with_path(&mut self, path: &str) {+ let clip_id = format!("cp{}", self.clip_path_index);+ self.clip_path_index += 1;++ self.svg.start_element("clipPath");+ self.svg.write_attribute("id", &clip_id);+ self.svg.start_element("path");+ self.svg+ .write_transform_attribute("transform", self.outline_transform);+ self.svg.write_attribute("d", &path);+ self.svg.end_element();+ self.svg.end_element();++ self.svg.start_element("g");+ self.svg+ .write_attribute_fmt("clip-path", format_args!("url(#{})", clip_id));+ }++ /// Outlines a glyph into `path_buf` at the current variation location+ /// (an empty path on failure), records the current transform as the+ /// outline transform and returns the outline's conservative bounding box+ /// in the glyph's local coordinate space.+ fn outline_glyph(&mut self, glyph_id: skrifa::GlyphId) -> Option<tiny_skia_path::Rect> {+ self.path_buf.clear();++ let mut bounds = None;+ let outlined = if let Some(outliner) = self.font.outline_glyphs().get(glyph_id) {+ let mut builder = Builder::new(self.path_buf);+ let size = Size::unscaled();+ let ok = outliner+ .draw(DrawSettings::unhinted(size, self.location), &mut builder)+ .is_ok();+ if ok {+ builder.finish();+ bounds = builder.bounds();+ }+ ok+ } else {+ false+ };+ if !outlined {+ // A partial outline may have been written before a draw error.+ self.path_buf.clear();+ }++ // We have to write outline using the current transform.+ self.outline_transform = self.transform;++ bounds+ }++ /// Paints `path_buf` (positioned by the outline transform) with the given brush.+ fn paint_brush(&mut self, brush: Brush<'_>) {+ match brush {+ Brush::Solid {+ palette_index,+ alpha,+ } => {+ let color = self.palette_index_to_color(palette_index, alpha);+ self.paint_solid(color);+ }+ Brush::LinearGradient {+ p0,+ p1,+ color_stops,+ extend,+ } => self.paint_linear_gradient(p0, p1, color_stops, extend),+ Brush::RadialGradient {+ c0,+ r0,+ c1,+ r1,+ color_stops,+ extend,+ } => self.paint_radial_gradient(c0, r0, c1, r1, color_stops, extend),++ Brush::SweepGradient {+ c0,+ start_angle,+ end_angle,+ color_stops,+ extend,+ } => self.paint_sweep_gradient(c0, start_angle, end_angle, color_stops, extend),+ }+ }++ fn palette_index_to_color(&self, palette_index: u16, alpha: f32) -> Color {+ let lookup = || -> Option<Color> {+ // We always use the first palette. `ColorPalettes` handles+ // per-palette record offsets internally.+ let palettes = self.font.color_palettes();+ let palette = palettes.get(0)?;+ let color = palette.colors().get(palette_index as usize)?;+ Some(Color {+ red: color.red,+ blue: color.blue,+ green: color.green,+ alpha: color.alpha,+ })+ };++ let mut color = if palette_index == u16::MAX {+ self.foreground_color+ } else {+ lookup().unwrap_or(self.foreground_color)+ };++ // Multiply alpha+ color.alpha = ((color.alpha as f32) * alpha) as u8;++ color+ }+}++impl<'a> skrifa::color::ColorPainter for GlyphPainter<'a> {+ fn push_transform(&mut self, transform: Transform) {+ self.transforms_stack.push(self.transform);+ self.transform = self.transform * transform;+ }++ fn pop_transform(&mut self) {+ if let Some(ts) = self.transforms_stack.pop() {+ self.transform = ts;+ }+ }++ fn fill_glyph(+ &mut self,+ glyph_id: skrifa::GlyphId,+ brush_transform: Option<Transform>,+ brush: Brush<'_>,+ ) {+ // Fill the glyph outline directly instead of the default+ // clip-then-fill decomposition. This avoids a redundant clip path+ // per fill and matches the output of the old ttf-parser based painter.+ self.outline_glyph(glyph_id);++ if let Some(brush_transform) = brush_transform {+ self.push_transform(brush_transform);+ self.paint_brush(brush);+ self.pop_transform();+ } else {+ self.paint_brush(brush);+ }+ }++ fn push_clip_glyph(&mut self, glyph_id: skrifa::GlyphId) {+ let bounds = self.outline_glyph(glyph_id);++ // Clip with the outline. This must always open a clip group - even+ // when outlining failed (an empty path clips everything away) - since+ // the corresponding `pop_clip` will unconditionally close it.+ let path = self.path_buf.clone();+ self.clip_with_path(&path);++ let root_bounds =+ bounds.and_then(|b| map_rect(b, skrifa_to_tsp_transform(self.outline_transform)));+ self.clip_stack.push(root_bounds);+ }++ fn push_clip_box(&mut self, clip_box: skrifa::raw::types::BoundingBox<f32>) {+ let x_min = clip_box.x_min;+ let x_max = clip_box.x_max;+ let y_min = clip_box.y_min;+ let y_max = clip_box.y_max;++ let clip_path = format!(+ "M {} {} L {} {} L {} {} L {} {} Z",+ x_min, y_min, x_max, y_min, x_max, y_max, x_min, y_max+ );++ // The clip box is positioned by the current transform.+ self.outline_transform = self.transform;+ self.clip_with_path(&clip_path);++ let bounds = tiny_skia_path::Rect::from_ltrb(x_min, y_min, x_max, y_max)+ .and_then(|b| map_rect(b, skrifa_to_tsp_transform(self.outline_transform)));+ self.clip_stack.push(bounds);+ }++ fn pop_clip(&mut self) {+ self.svg.end_element();+ self.clip_stack.pop();+ }++ fn fill(&mut self, brush: Brush<'_>) {+ // A fill paints the intersection of all currently active clips.+ // Paint a rectangle covering that intersection and let the enclosing+ // clip groups shape it.+ if self.clip_stack.is_empty() {+ log::warn!("Unclipped COLR fills are not supported.");+ return;+ }++ let mut region: Option<tiny_skia_path::Rect> = None;+ for bounds in &self.clip_stack {+ // A clip with no (or unknown) bounds clips everything away.+ let Some(bounds) = bounds else { return };+ region = Some(match region {+ Some(region) => match intersect_rects(region, *bounds) {+ Some(r) => r,+ // An empty intersection - there is nothing to paint.+ None => return,+ },+ None => *bounds,+ });+ }+ let Some(region) = region else { return };++ self.path_buf.clear();+ write!(+ self.path_buf,+ "M {} {} L {} {} L {} {} L {} {} Z",+ region.left(),+ region.top(),+ region.right(),+ region.top(),+ region.right(),+ region.bottom(),+ region.left(),+ region.bottom()+ )+ .unwrap();++ // The covering rectangle is in the root coordinate space.+ self.outline_transform = Transform::default();++ self.paint_brush(brush);+ }++ fn push_layer(&mut self, composite_mode: skrifa::color::CompositeMode) {+ use skrifa::color::CompositeMode;+ // TODO: Need to figure out how to represent the other blend modes in SVG.+ let composite_mode = match composite_mode {+ CompositeMode::SrcOver => "normal",+ CompositeMode::Screen => "screen",+ CompositeMode::Overlay => "overlay",+ CompositeMode::Darken => "darken",+ CompositeMode::Lighten => "lighten",+ CompositeMode::ColorDodge => "color-dodge",+ CompositeMode::ColorBurn => "color-burn",+ CompositeMode::HardLight => "hard-light",+ CompositeMode::SoftLight => "soft-light",+ CompositeMode::Difference => "difference",+ CompositeMode::Exclusion => "exclusion",+ CompositeMode::Multiply => "multiply",+ CompositeMode::HslHue => "hue",+ CompositeMode::HslSaturation => "saturation",+ CompositeMode::HslColor => "color",+ CompositeMode::HslLuminosity => "luminosity",+ _ => {+ // Unsupported blend mode+ // TODO: support other blend modes+ // TODO: surface warning without printing to stdout+ "normal"+ }+ };++ self.svg.start_element("g");+ self.svg.write_attribute_fmt(+ "style",+ format_args!("mix-blend-mode: {}; isolation: isolate", composite_mode),+ );+ }++ fn pop_layer(&mut self) {+ self.svg.end_element();+ }+}diff --git a/vendor/usvg/src/text/flatten.rs b/vendor/usvg/src/text/flatten.rsnew file mode 100644index 00000000..101ca489--- /dev/null+++ b/vendor/usvg/src/text/flatten.rs@@ -0,0 +1,431 @@+// Copyright 2022 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::mem;+use std::sync::Arc;++use crate::GlyphId;+use fontdb::{Database, ID};+use skrifa::MetadataProvider;+use skrifa::Tag;+use skrifa::bitmap::{BitmapData, BitmapFormat};+use skrifa::outline::{DrawSettings, OutlinePen};+use skrifa::prelude::LocationRef;+use skrifa::raw::TableProvider as _;+use skrifa::raw::types::BoundingBox;+use svgtypes::Color;+use tiny_skia_path::{NonZeroRect, Size, Transform};+use xmlwriter::XmlWriter;++use crate::text::OPSZ;+use crate::text::colr::GlyphPainter;+use crate::*;++fn resolve_rendering_mode(text: &Text) -> ShapeRendering {+ match text.rendering_mode {+ TextRendering::OptimizeSpeed => ShapeRendering::CrispEdges,+ TextRendering::OptimizeLegibility => ShapeRendering::GeometricPrecision,+ TextRendering::GeometricPrecision => ShapeRendering::GeometricPrecision,+ }+}++/// Returns the effective variation settings for a glyph: the span's explicit+/// variations plus an automatically computed `opsz` value when+/// `font-optical-sizing: auto` is in effect and the font has an `opsz` axis+/// that wasn't set explicitly. This matches browser behavior+/// (CSS font-optical-sizing: auto).+fn effective_variations(+ cache: &mut Cache,+ span: &layout::Span,+ glyph: &layout::PositionedGlyph,+) -> Vec<FontVariation> {+ let mut variations = span.variations.clone();+ if span.font_optical_sizing == crate::FontOpticalSizing::Auto+ && !variations.iter().any(|v| &v.tag == b"opsz")+ && cache.has_opsz_axis(glyph.font)+ {+ variations.push(FontVariation::new(*b"opsz", glyph.font_size()));+ }+ variations+}++fn push_outline_paths(+ span: &layout::Span,+ builder: &mut tiny_skia_path::PathBuilder,+ new_children: &mut Vec<Node>,+ rendering_mode: ShapeRendering,+ abs_transform: Transform,+) {+ let builder = mem::replace(builder, tiny_skia_path::PathBuilder::new());++ if let Some(path) = builder.finish().and_then(|p| {+ Path::new(+ String::new(),+ span.visible,+ span.fill.clone(),+ span.stroke.clone(),+ span.paint_order,+ rendering_mode,+ Arc::new(p),+ abs_transform,+ )+ }) {+ new_children.push(Node::Path(Box::new(path)));+ }+}++pub(crate) fn flatten(text: &mut Text, cache: &mut Cache) -> Option<(Group, NonZeroRect)> {+ let mut new_children = vec![];++ let abs_transform = text.abs_transform;+ let rendering_mode = resolve_rendering_mode(text);++ for span in &text.layouted {+ if let Some(path) = span.overline.as_ref() {+ let mut path = path.clone();+ path.rendering_mode = rendering_mode;+ new_children.push(Node::Path(Box::new(path)));+ }++ if let Some(path) = span.underline.as_ref() {+ let mut path = path.clone();+ path.rendering_mode = rendering_mode;+ new_children.push(Node::Path(Box::new(path)));+ }++ // Instead of always processing each glyph separately, we always collect+ // as many outline glyphs as possible by pushing them into the span_builder+ // and only if we encounter a different glyph, or we reach the very end of the+ // span to we push the actual outline paths into new_children. This way, we don't need+ // to create a new path for every glyph if we have many consecutive glyphs+ // with just outlines (which is the most common case).+ let mut span_builder = tiny_skia_path::PathBuilder::new();++ for glyph in &span.positioned_glyphs {+ let variations = effective_variations(cache, span, glyph);++ // A (best-effort conversion of a) COLR glyph.+ if let Some(tree) = cache.fontdb_colr(glyph.font, glyph.id, &variations) {+ let mut group = Group {+ transform: glyph.colr_transform(),+ ..Group::empty()+ };+ // TODO: Probably need to update abs_transform of children? Same+ // for SVG and bitmap glyphs.+ group.children.push(Node::Group(Box::new(tree.root)));+ group.calculate_bounding_boxes();++ new_children.push(Node::Group(Box::new(group)));+ }+ // An SVG glyph. Will return the usvg node containing the glyph descriptions.+ else if let Some(node) = cache.fontdb_svg(glyph.font, glyph.id) {+ push_outline_paths(+ span,+ &mut span_builder,+ &mut new_children,+ rendering_mode,+ abs_transform,+ );++ let mut group = Group {+ transform: glyph.svg_transform(),+ ..Group::empty()+ };+ group.children.push(node);+ group.calculate_bounding_boxes();++ new_children.push(Node::Group(Box::new(group)));+ }+ // A bitmap glyph.+ else if let Some(img) = cache.fontdb_raster(glyph.font, glyph.id) {+ push_outline_paths(+ span,+ &mut span_builder,+ &mut new_children,+ rendering_mode,+ abs_transform,+ );++ let transform = if img.is_sbix {+ glyph.sbix_transform(+ img.x as f32,+ img.y as f32,+ img.glyph_bbox.map(|bbox| bbox.x_min).unwrap_or(0) as f32,+ img.glyph_bbox.map(|bbox| bbox.y_min).unwrap_or(0) as f32,+ img.pixels_per_em as f32,+ img.image.size.height(),+ )+ } else {+ glyph.cbdt_transform(img.x as f32, img.y as f32, img.pixels_per_em as f32)+ };++ let mut group = Group {+ transform,+ ..Group::empty()+ };+ group.children.push(Node::Image(Box::new(img.image)));+ group.calculate_bounding_boxes();++ new_children.push(Node::Group(Box::new(group)));+ } else {+ let outline = cache.fontdb_outline(glyph.font, glyph.id, &variations);++ if let Some(outline) = outline.and_then(|p| p.transform(glyph.outline_transform()))+ {+ span_builder.push_path(&outline);+ }+ }+ }++ push_outline_paths(+ span,+ &mut span_builder,+ &mut new_children,+ rendering_mode,+ abs_transform,+ );++ if let Some(path) = span.line_through.as_ref() {+ let mut path = path.clone();+ path.rendering_mode = rendering_mode;+ new_children.push(Node::Path(Box::new(path)));+ }+ }++ let mut group = Group {+ id: text.id.clone(),+ ..Group::empty()+ };++ for child in new_children {+ group.children.push(child);+ }++ group.calculate_bounding_boxes();+ let stroke_bbox = group.stroke_bounding_box().to_non_zero_rect()?;+ Some((group, stroke_bbox))+}++#[derive(Default)]+struct PathBuilder {+ builder: tiny_skia_path::PathBuilder,+}++impl OutlinePen for PathBuilder {+ fn move_to(&mut self, x: f32, y: f32) {+ self.builder.move_to(x, y);+ }++ fn line_to(&mut self, x: f32, y: f32) {+ self.builder.line_to(x, y);+ }++ fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {+ self.builder.quad_to(cx0, cy0, x, y);+ }++ fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {+ self.builder.cubic_to(cx0, cy0, cx1, cy1, x, y);+ }++ fn close(&mut self) {+ self.builder.close();+ }+}++pub(crate) trait DatabaseExt {+ fn outline(+ &self,+ id: ID,+ glyph_id: GlyphId,+ variations: &[crate::FontVariation],+ ) -> Option<tiny_skia_path::Path>;+ fn has_opsz_axis(&self, id: ID) -> bool;+ fn raster(&self, id: ID, glyph_id: GlyphId) -> Option<BitmapImage>;+ fn svg(&self, id: ID, glyph_id: GlyphId) -> Option<Node>;+ fn colr(&self, id: ID, glyph_id: GlyphId, variations: &[crate::FontVariation]) -> Option<Tree>;+}++#[derive(Clone)]+pub(crate) struct BitmapImage {+ image: Image,+ x: i16,+ y: i16,+ pixels_per_em: u16,+ glyph_bbox: Option<BoundingBox<i16>>,+ is_sbix: bool,+}++impl DatabaseExt for Database {+ #[inline(never)]+ fn outline(+ &self,+ id: ID,+ glyph_id: GlyphId,+ variations: &[crate::FontVariation],+ ) -> Option<tiny_skia_path::Path> {+ self.with_face_data(id, |data, face_index| -> Option<tiny_skia_path::Path> {+ let font = skrifa::FontRef::from_index(data, face_index).ok()?;+ let outline = font.outline_glyphs().get(glyph_id.into())?;++ let mut builder = PathBuilder::default();++ let size = skrifa::prelude::Size::unscaled();+ // An empty variation list resolves to the default value of every+ // variation axis, which is what we want for non-variable fonts and+ // for variable fonts used without variations.+ let location = font.axes().location(+ variations+ .iter()+ .map(|v| (Tag::from_be_bytes(v.tag), v.value)),+ );+ outline+ .draw(DrawSettings::unhinted(size, &location), &mut builder)+ .ok()?;++ builder.builder.finish()+ })?+ }++ fn has_opsz_axis(&self, id: ID) -> bool {+ self.with_face_data(id, |data, face_index| -> Option<bool> {+ let font = skrifa::FontRef::from_index(data, face_index).ok()?;+ Some(font.axes().get_by_tag(OPSZ).is_some())+ })+ .flatten()+ .unwrap_or(false)+ }++ fn raster(&self, id: ID, glyph_id: GlyphId) -> Option<BitmapImage> {+ self.with_face_data(id, |data, face_index| -> Option<BitmapImage> {+ let font = skrifa::FontRef::from_index(data, face_index).ok()?;+ let bitmap_strikes = font.bitmap_strikes();++ // We set size to unscaled to get the largest image available+ let size = skrifa::prelude::Size::unscaled();+ let location = LocationRef::default();+ let image = bitmap_strikes.glyph_for_size(size, glyph_id.into())?;++ match image.data {+ BitmapData::Png(data) => {+ let metrics = font.glyph_metrics(size, location);+ let bounding_box = metrics.bounds(glyph_id.into()).map(|bbox| BoundingBox {+ x_min: bbox.x_min as i16,+ y_min: bbox.y_min as i16,+ x_max: bbox.x_max as i16,+ y_max: bbox.y_max as i16,+ });++ let bitmap_image = BitmapImage {+ image: Image {+ id: String::new(),+ visible: true,+ size: Size::from_wh(image.width as f32, image.height as f32)?,+ rendering_mode: ImageRendering::OptimizeQuality,+ kind: ImageKind::PNG(Arc::new(data.to_vec())),+ abs_transform: Transform::default(),+ abs_bounding_box: NonZeroRect::from_xywh(+ 0.0,+ 0.0,+ image.width as f32,+ image.height as f32,+ )?,+ },+ x: image.inner_bearing_x as i16,+ y: image.inner_bearing_y as i16,+ pixels_per_em: image.ppem_x as u16,+ glyph_bbox: bounding_box,+ is_sbix: bitmap_strikes.format() == Some(BitmapFormat::Sbix),+ };++ Some(bitmap_image)+ }+ // TODO: implement other bitmap formats+ BitmapData::Bgra(_) | BitmapData::Mask(_) => None,+ }+ })?+ }++ fn svg(&self, id: ID, glyph_id: GlyphId) -> Option<Node> {+ // SEE: https://docs.rs/read-fonts/latest/read_fonts/tables/svg/type.Svg.html++ // TODO: Technically not 100% accurate because the SVG format in a OTF font+ // is actually a subset/superset of a normal SVG, but it seems to work fine+ // for Twitter Color Emoji, so might as well use what we already have.++ // TODO: Glyph records can contain the data for multiple glyphs. We should+ // add a cache so we don't need to reparse the data every time.+ self.with_face_data(id, |data, face_index| -> Option<Node> {+ let font = skrifa::FontRef::from_index(data, face_index).ok()?;+ let svg_table = font.svg().ok()?;+ let image_data = svg_table.glyph_data(glyph_id.into()).ok()??;+ let tree = Tree::from_data(image_data, &Options::default()).ok()?;++ // Twitter Color Emoji seems to always have one SVG record per glyph,+ // while Noto Color Emoji sometimes contains multiple ones. It's kind of hacky,+ // but the best we have for now.+ let document_list = svg_table.svg_document_list().ok()?;+ let doc_record = document_list.document_records().iter().find(|r| {+ (r.start_glyph_id.get().to_u32()..=r.end_glyph_id.get().to_u32())+ .contains(&glyph_id.0)+ })?;+ let node = if doc_record.start_glyph_id == doc_record.end_glyph_id {+ Node::Group(Box::new(tree.root))+ } else {+ tree.node_by_id(&format!("glyph{}", glyph_id.0))+ .log_none(|| {+ log::warn!("Failed to find SVG glyph node for glyph {}", glyph_id.0);+ })+ .cloned()?+ };++ Some(node)+ })?+ }++ fn colr(&self, id: ID, glyph_id: GlyphId, variations: &[crate::FontVariation]) -> Option<Tree> {+ self.with_face_data(id, |data, face_index| -> Option<Tree> {+ let font = skrifa::FontRef::from_index(data, face_index).ok()?;++ let location = font.axes().location(+ variations+ .iter()+ .map(|v| (Tag::from_be_bytes(v.tag), v.value)),+ );++ let mut svg = XmlWriter::new(xmlwriter::Options::default());++ svg.start_element("svg");+ svg.write_attribute("xmlns", "http://www.w3.org/2000/svg");+ svg.write_attribute("xmlns:xlink", "http://www.w3.org/1999/xlink");++ let mut path_buf = String::with_capacity(256);+ let gradient_index = 1;+ let clip_path_index = 1;++ svg.start_element("g");++ let mut glyph_painter = GlyphPainter {+ font: &font,+ location: LocationRef::from(&location),+ svg: &mut svg,+ path_buf: &mut path_buf,+ gradient_index,+ clip_path_index,+ foreground_color: Color::new_rgba(0, 0, 0, 255),+ transform: skrifa::color::Transform::default(),+ outline_transform: skrifa::color::Transform::default(),+ transforms_stack: vec![skrifa::color::Transform::default()],+ clip_stack: Vec::new(),+ };++ font.color_glyphs()+ .get(glyph_id.into())?+ .paint(&location, &mut glyph_painter)+ .ok()?;+ svg.end_element();++ Tree::from_data(svg.end_document().as_bytes(), &Options::default()).ok()+ })?+ }+}diff --git a/vendor/usvg/src/text/layout.rs b/vendor/usvg/src/text/layout.rsnew file mode 100644index 00000000..b82a2add--- /dev/null+++ b/vendor/usvg/src/text/layout.rs@@ -0,0 +1,1842 @@+// Copyright 2022 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::collections::{HashMap, HashSet};+use std::num::NonZeroU16;+use std::sync::Arc;++use fontdb::{Database, ID};+use harfrust::ShapeOptions;+use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};+use skrifa::MetadataProvider;+use skrifa::Tag;+use skrifa::prelude::Size;+use skrifa::raw::TableProvider;+use strict_num::NonZeroPositiveF32;+use tiny_skia_path::{NonZeroRect, Transform};+use unicode_script::UnicodeScript;++use crate::tree::{BBox, IsValidLength};+use crate::{+ AlignmentBaseline, ApproxZeroUlps, BaselineShift, DominantBaseline, Fill, FillRule, Font,+ FontResolver, GlyphId, LengthAdjust, PaintOrder, Path, ShapeRendering, Stroke, Text,+ TextAnchor, TextChunk, TextDecorationStyle, TextFlow, TextPath, TextSpan, WritingMode,+};++/// A glyph that has already been positioned correctly.+///+/// Note that the transform already takes the font size into consideration, so applying the+/// transform to the outline of the glyphs is all that is necessary to display it correctly.+#[derive(Clone, Debug)]+pub struct PositionedGlyph {+ /// Returns the transform of the glyph itself within the cluster. For example,+ /// for zalgo text, it contains the transform to position the glyphs above/below+ /// the main glyph.+ glyph_ts: Transform,+ /// Returns the transform of the whole cluster that the glyph is part of.+ cluster_ts: Transform,+ /// Returns the transform of the span that the glyph is a part of.+ span_ts: Transform,+ /// The units per em of the font the glyph belongs to.+ units_per_em: u16,+ /// The font size the glyph should be scaled to.+ font_size: f32,+ /// The ID of the glyph.+ pub id: GlyphId,+ /// The text from the original string that corresponds to that glyph.+ pub text: String,+ /// The ID of the font the glyph should be taken from. Can be used with the+ /// [font database of the tree](crate::Tree::fontdb) this glyph is part of.+ pub font: ID,+}++impl PositionedGlyph {+ /// Returns the font size for this glyph.+ pub fn font_size(&self) -> f32 {+ self.font_size+ }++ /// Returns the transform of glyph.+ pub fn transform(&self) -> Transform {+ let sx = self.font_size / self.units_per_em as f32;++ self.span_ts+ .pre_concat(self.cluster_ts)+ .pre_concat(Transform::from_scale(sx, sx))+ .pre_concat(self.glyph_ts)+ }++ /// Returns the transform of glyph, assuming that an outline+ /// glyph is being used (i.e. from the `glyf` or `CFF/CFF2` table).+ pub fn outline_transform(&self) -> Transform {+ // Outlines are mirrored by default.+ self.transform()+ .pre_concat(Transform::from_scale(1.0, -1.0))+ }++ /// Returns the transform for the glyph, assuming that a CBTD-based raster glyph+ /// is being used.+ pub fn cbdt_transform(&self, x: f32, y: f32, pixels_per_em: f32) -> Transform {+ self.transform()+ .pre_concat(Transform::from_scale(+ self.units_per_em as f32 / pixels_per_em,+ self.units_per_em as f32 / pixels_per_em,+ ))+ // Right now, the top-left corner of the image would be placed in+ // on the "text cursor", but we want the bottom-left corner to be there,+ // so we need to shift it up and also apply the x/y offset.+ .pre_translate(x, -y)+ }++ /// Returns the transform for the glyph, assuming that a sbix-based raster glyph+ /// is being used.+ pub fn sbix_transform(+ &self,+ x: f32,+ y: f32,+ x_min: f32,+ y_min: f32,+ pixels_per_em: f32,+ height: f32,+ ) -> Transform {+ // In contrast to CBDT, we also need to look at the outline bbox of the glyph and add a shift if necessary.+ let bbox_x_shift = -x_min;++ let bbox_y_shift = if y_min.approx_zero_ulps(4) {+ // For unknown reasons, using Apple Color Emoji will lead to a vertical shift on MacOS, but this shift+ // doesn't seem to be coming from the font and most likely is somehow hardcoded. On Windows,+ // this shift will not be applied. However, if this shift is not applied the emojis are a bit+ // too high up when being together with other text, so we try to imitate this.+ // See also https://github.com/harfbuzz/harfbuzz/issues/2679#issuecomment-1345595425+ // So whenever the y-shift is 0, we approximate this vertical shift that seems to be produced by it.+ // This value seems to be pretty close to what is happening on MacOS.+ // We can still remove this if it turns out to be a problem, but Apple Color Emoji is pretty+ // much the only `sbix` font out there and they all seem to have a y-shift of 0, so it+ // makes sense to keep it.+ 0.128 * self.units_per_em as f32+ } else {+ -y_min+ };++ self.transform()+ .pre_concat(Transform::from_translate(bbox_x_shift, bbox_y_shift))+ .pre_concat(Transform::from_scale(+ self.units_per_em as f32 / pixels_per_em,+ self.units_per_em as f32 / pixels_per_em,+ ))+ // Right now, the top-left corner of the image would be placed in+ // on the "text cursor", but we want the bottom-left corner to be there,+ // so we need to shift it up and also apply the x/y offset.+ .pre_translate(x, -height - y)+ }++ /// Returns the transform for the glyph, assuming that an SVG glyph is+ /// being used.+ pub fn svg_transform(&self) -> Transform {+ self.transform()+ }++ /// Returns the transform for the glyph, assuming that a COLR glyph is+ /// being used.+ pub fn colr_transform(&self) -> Transform {+ self.outline_transform()+ }+}++/// A span contains a number of layouted glyphs that share the same fill, stroke, paint order and+/// visibility.+#[derive(Clone, Debug)]+pub struct Span {+ /// The fill of the span.+ pub fill: Option<Fill>,+ /// The stroke of the span.+ pub stroke: Option<Stroke>,+ /// The paint order of the span.+ pub paint_order: PaintOrder,+ /// The font size of the span.+ pub font_size: NonZeroPositiveF32,+ /// Font variation settings for variable fonts.+ pub variations: Vec<crate::FontVariation>,+ /// Font optical sizing mode.+ pub font_optical_sizing: crate::FontOpticalSizing,+ /// The visibility of the span.+ pub visible: bool,+ /// The glyphs that make up the span.+ pub positioned_glyphs: Vec<PositionedGlyph>,+ /// An underline text decoration of the span.+ /// Needs to be rendered before all glyphs.+ pub underline: Option<Path>,+ /// An overline text decoration of the span.+ /// Needs to be rendered before all glyphs.+ pub overline: Option<Path>,+ /// A line-through text decoration of the span.+ /// Needs to be rendered after all glyphs.+ pub line_through: Option<Path>,+}++#[derive(Clone, Debug)]+struct GlyphCluster {+ byte_idx: ByteIndex,+ codepoint: char,+ width: f32,+ advance: f32,+ ascent: f32,+ descent: f32,+ has_relative_shift: bool,+ glyphs: Vec<PositionedGlyph>,+ transform: Transform,+ path_transform: Transform,+ visible: bool,+}++impl GlyphCluster {+ pub(crate) fn height(&self) -> f32 {+ self.ascent - self.descent+ }++ pub(crate) fn transform(&self) -> Transform {+ self.path_transform.post_concat(self.transform)+ }+}++pub(crate) fn layout_text(+ text_node: &Text,+ resolver: &FontResolver,+ fontdb: &mut Arc<fontdb::Database>,+) -> Option<(Vec<Span>, NonZeroRect)> {+ let mut fonts_cache: FontsCache = HashMap::new();++ for chunk in &text_node.chunks {+ for span in &chunk.spans {+ if !fonts_cache.contains_key(&span.font) {+ if let Some(font) = (resolver.select_font)(&span.font, fontdb)+ .and_then(|id| fontdb.load_font(id, &span.font.variations))+ {+ fonts_cache.insert(span.font.clone(), Arc::new(font));+ }+ }+ }+ }++ let mut spans = vec![];+ let mut char_offset = 0;+ let mut last_x = 0.0;+ let mut last_y = 0.0;+ let mut bbox = BBox::default();+ for chunk in &text_node.chunks {+ let (x, y) = match chunk.text_flow {+ TextFlow::Linear => (chunk.x.unwrap_or(last_x), chunk.y.unwrap_or(last_y)),+ TextFlow::Path(_) => (0.0, 0.0),+ };++ let mut clusters = process_chunk(chunk, &fonts_cache, resolver, fontdb);+ if clusters.is_empty() {+ char_offset += chunk.text.chars().count();+ continue;+ }++ apply_writing_mode(text_node.writing_mode, &mut clusters);+ apply_letter_spacing(chunk, &mut clusters);+ apply_word_spacing(chunk, &mut clusters);++ apply_length_adjust(chunk, &mut clusters);+ let mut curr_pos = resolve_clusters_positions(+ text_node,+ chunk,+ char_offset,+ text_node.writing_mode,+ &fonts_cache,+ &mut clusters,+ );++ let mut text_ts = Transform::default();+ if text_node.writing_mode == WritingMode::TopToBottom {+ if let TextFlow::Linear = chunk.text_flow {+ text_ts = text_ts.pre_rotate_at(90.0, x, y);+ }+ }++ for span in &chunk.spans {+ let font = match fonts_cache.get(&span.font) {+ Some(v) => v,+ None => continue,+ };++ let decoration_spans = collect_decoration_spans(span, &clusters);++ let mut span_ts = text_ts;+ span_ts = span_ts.pre_translate(x, y);+ if let TextFlow::Linear = chunk.text_flow {+ let shift = resolve_baseline(span, font, text_node.writing_mode);++ // In case of a horizontal flow, shift transform and not clusters,+ // because clusters can be rotated and an additional shift will lead+ // to invalid results.+ span_ts = span_ts.pre_translate(0.0, shift);+ }++ let mut underline = None;+ let mut overline = None;+ let mut line_through = None;++ if let Some(decoration) = span.decoration.underline.clone() {+ // TODO: No idea what offset should be used for top-to-bottom layout.+ // There is+ // https://www.w3.org/TR/css-text-decor-3/#text-underline-position-property+ // but it doesn't go into details.+ let offset = match text_node.writing_mode {+ WritingMode::LeftToRight => -font.underline_position(span.font_size.get()),+ WritingMode::TopToBottom => font.height(span.font_size.get()) / 2.0,+ };++ if let Some(path) =+ convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)+ {+ bbox = bbox.expand(path.data.bounds());+ underline = Some(path);+ }+ }++ if let Some(decoration) = span.decoration.overline.clone() {+ let offset = match text_node.writing_mode {+ WritingMode::LeftToRight => -font.ascent(span.font_size.get()),+ WritingMode::TopToBottom => -font.height(span.font_size.get()) / 2.0,+ };++ if let Some(path) =+ convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)+ {+ bbox = bbox.expand(path.data.bounds());+ overline = Some(path);+ }+ }++ if let Some(decoration) = span.decoration.line_through.clone() {+ let offset = match text_node.writing_mode {+ WritingMode::LeftToRight => -font.line_through_position(span.font_size.get()),+ WritingMode::TopToBottom => 0.0,+ };++ if let Some(path) =+ convert_decoration(offset, span, font, decoration, &decoration_spans, span_ts)+ {+ bbox = bbox.expand(path.data.bounds());+ line_through = Some(path);+ }+ }++ let mut fill = span.fill.clone();+ if let Some(ref mut fill) = fill {+ // The `fill-rule` should be ignored.+ // https://www.w3.org/TR/SVG2/text.html#TextRenderingOrder+ //+ // 'Since the fill-rule property does not apply to SVG text elements,+ // the specific order of the subpaths within the equivalent path does not matter.'+ fill.rule = FillRule::NonZero;+ }++ if let Some((span_fragments, span_bbox)) = convert_span(span, &clusters, span_ts) {+ bbox = bbox.expand(span_bbox);++ let positioned_glyphs = span_fragments+ .into_iter()+ .flat_map(|mut gc| {+ let cluster_ts = gc.transform();+ gc.glyphs.iter_mut().for_each(|pg| {+ pg.cluster_ts = cluster_ts;+ pg.span_ts = span_ts;+ });+ gc.glyphs+ })+ .collect();++ spans.push(Span {+ fill,+ stroke: span.stroke.clone(),+ paint_order: span.paint_order,+ font_size: span.font_size,+ variations: span.font.variations.clone(),+ font_optical_sizing: span.font_optical_sizing,+ visible: span.visible,+ positioned_glyphs,+ underline,+ overline,+ line_through,+ });+ }+ }++ char_offset += chunk.text.chars().count();++ if text_node.writing_mode == WritingMode::TopToBottom {+ if let TextFlow::Linear = chunk.text_flow {+ std::mem::swap(&mut curr_pos.0, &mut curr_pos.1);+ }+ }++ last_x = x + curr_pos.0;+ last_y = y + curr_pos.1;+ }++ let bbox = bbox.to_non_zero_rect()?;++ Some((spans, bbox))+}++fn convert_span(+ span: &TextSpan,+ clusters: &[GlyphCluster],+ text_ts: Transform,+) -> Option<(Vec<GlyphCluster>, NonZeroRect)> {+ let mut span_clusters = vec![];+ let mut bboxes_builder = tiny_skia_path::PathBuilder::new();++ for cluster in clusters {+ if !cluster.visible {+ continue;+ }++ if span_contains(span, cluster.byte_idx) {+ span_clusters.push(cluster.clone());+ }++ let mut advance = cluster.advance;+ if advance <= 0.0 {+ advance = 1.0;+ }++ // We have to calculate text bbox using font metrics and not glyph shape.+ if let Some(r) = NonZeroRect::from_xywh(0.0, -cluster.ascent, advance, cluster.height()) {+ if let Some(r) = r.transform(cluster.transform()) {+ bboxes_builder.push_rect(r.to_rect());+ }+ }+ }++ let mut bboxes = bboxes_builder.finish()?;+ bboxes = bboxes.transform(text_ts)?;+ let bbox = bboxes.compute_tight_bounds()?.to_non_zero_rect()?;++ Some((span_clusters, bbox))+}++fn collect_decoration_spans(span: &TextSpan, clusters: &[GlyphCluster]) -> Vec<DecorationSpan> {+ let mut spans = Vec::new();++ let mut started = false;+ let mut width = 0.0;+ let mut transform = Transform::default();++ for cluster in clusters {+ if span_contains(span, cluster.byte_idx) {+ if started && cluster.has_relative_shift {+ started = false;+ spans.push(DecorationSpan { width, transform });+ }++ if !started {+ width = cluster.advance;+ started = true;+ transform = cluster.transform;+ } else {+ width += cluster.advance;+ }+ } else if started {+ spans.push(DecorationSpan { width, transform });+ started = false;+ }+ }++ if started {+ spans.push(DecorationSpan { width, transform });+ }++ spans+}++pub(crate) fn convert_decoration(+ dy: f32,+ span: &TextSpan,+ font: &ResolvedFont,+ mut decoration: TextDecorationStyle,+ decoration_spans: &[DecorationSpan],+ transform: Transform,+) -> Option<Path> {+ debug_assert!(!decoration_spans.is_empty());++ let thickness = font.underline_thickness(span.font_size.get());++ let mut builder = tiny_skia_path::PathBuilder::new();+ for dec_span in decoration_spans {+ let rect = match NonZeroRect::from_xywh(0.0, -thickness / 2.0, dec_span.width, thickness) {+ Some(v) => v,+ None => {+ log::warn!("a decoration span has a malformed bbox");+ continue;+ }+ };++ let ts = dec_span.transform.pre_translate(0.0, dy);++ let mut path = tiny_skia_path::PathBuilder::from_rect(rect.to_rect());+ path = match path.transform(ts) {+ Some(v) => v,+ None => continue,+ };++ builder.push_path(&path);+ }++ let mut path_data = builder.finish()?;+ path_data = path_data.transform(transform)?;++ Path::new(+ String::new(),+ span.visible,+ decoration.fill.take(),+ decoration.stroke.take(),+ PaintOrder::default(),+ ShapeRendering::default(),+ Arc::new(path_data),+ Transform::default(),+ )+}++/// A text decoration span.+///+/// Basically a horizontal line, that will be used for underline, overline and line-through.+/// It doesn't have a height, since it depends on the Font metrics.+#[derive(Clone, Copy)]+pub(crate) struct DecorationSpan {+ pub(crate) width: f32,+ pub(crate) transform: Transform,+}++/// Resolves clusters positions.+///+/// Mainly sets the `transform` property.+///+/// Returns the last text position. The next text chunk should start from that position.+fn resolve_clusters_positions(+ text: &Text,+ chunk: &TextChunk,+ char_offset: usize,+ writing_mode: WritingMode,+ fonts_cache: &FontsCache,+ clusters: &mut [GlyphCluster],+) -> (f32, f32) {+ match chunk.text_flow {+ TextFlow::Linear => {+ resolve_clusters_positions_horizontal(text, chunk, char_offset, writing_mode, clusters)+ }+ TextFlow::Path(ref path) => resolve_clusters_positions_path(+ text,+ chunk,+ char_offset,+ path,+ writing_mode,+ fonts_cache,+ clusters,+ ),+ }+}++fn clusters_length(clusters: &[GlyphCluster]) -> f32 {+ clusters.iter().fold(0.0, |w, cluster| w + cluster.advance)+}++fn resolve_clusters_positions_horizontal(+ text: &Text,+ chunk: &TextChunk,+ offset: usize,+ writing_mode: WritingMode,+ clusters: &mut [GlyphCluster],+) -> (f32, f32) {+ let mut x = process_anchor(chunk.anchor, clusters_length(clusters));+ let mut y = 0.0;++ for cluster in clusters {+ let cp = offset + cluster.byte_idx.code_point_at(&chunk.text);+ if let (Some(dx), Some(dy)) = (text.dx.get(cp), text.dy.get(cp)) {+ if writing_mode == WritingMode::LeftToRight {+ x += dx;+ y += dy;+ } else {+ y -= dx;+ x += dy;+ }+ cluster.has_relative_shift = !dx.approx_zero_ulps(4) || !dy.approx_zero_ulps(4);+ }++ cluster.transform = cluster.transform.pre_translate(x, y);++ if let Some(angle) = text.rotate.get(cp).cloned() {+ if !angle.approx_zero_ulps(4) {+ cluster.transform = cluster.transform.pre_rotate(angle);+ cluster.has_relative_shift = true;+ }+ }++ x += cluster.advance;+ }++ (x, y)+}++// Baseline resolving in SVG is a mess.+// Not only it's poorly documented, but as soon as you start mixing+// `dominant-baseline` and `alignment-baseline` each application/browser will produce+// different results.+//+// For now, resvg simply tries to match Chrome's output and not the mythical SVG spec output.+//+// See `alignment_baseline_shift` method comment for more details.+pub(crate) fn resolve_baseline(+ span: &TextSpan,+ font: &ResolvedFont,+ writing_mode: WritingMode,+) -> f32 {+ let mut shift = -resolve_baseline_shift(&span.baseline_shift, font, span.font_size.get());++ // TODO: support vertical layout as well+ if writing_mode == WritingMode::LeftToRight {+ if span.alignment_baseline == AlignmentBaseline::Auto+ || span.alignment_baseline == AlignmentBaseline::Baseline+ {+ shift += font.dominant_baseline_shift(span.dominant_baseline, span.font_size.get());+ } else {+ shift += font.alignment_baseline_shift(span.alignment_baseline, span.font_size.get());+ }+ }++ shift+}++fn resolve_baseline_shift(baselines: &[BaselineShift], font: &ResolvedFont, font_size: f32) -> f32 {+ let mut shift = 0.0;+ for baseline in baselines.iter().rev() {+ match baseline {+ BaselineShift::Baseline => {}+ BaselineShift::Subscript => shift -= font.subscript_offset(font_size),+ BaselineShift::Superscript => shift += font.superscript_offset(font_size),+ BaselineShift::Number(n) => shift += n,+ }+ }++ shift+}++fn resolve_clusters_positions_path(+ text: &Text,+ chunk: &TextChunk,+ char_offset: usize,+ path: &TextPath,+ writing_mode: WritingMode,+ fonts_cache: &FontsCache,+ clusters: &mut [GlyphCluster],+) -> (f32, f32) {+ let mut last_x = 0.0;+ let mut last_y = 0.0;++ let mut dy = 0.0;++ // In the text path mode, chunk's x/y coordinates provide an additional offset along the path.+ // The X coordinate is used in a horizontal mode, and Y in vertical.+ let chunk_offset = match writing_mode {+ WritingMode::LeftToRight => chunk.x.unwrap_or(0.0),+ WritingMode::TopToBottom => chunk.y.unwrap_or(0.0),+ };++ let start_offset =+ chunk_offset + path.start_offset + process_anchor(chunk.anchor, clusters_length(clusters));++ let normals = collect_normals(text, chunk, clusters, &path.path, char_offset, start_offset);+ for (cluster, normal) in clusters.iter_mut().zip(normals) {+ let (x, y, angle) = match normal {+ Some(normal) => (normal.x, normal.y, normal.angle),+ None => {+ // Hide clusters that are outside the text path.+ cluster.visible = false;+ continue;+ }+ };++ // We have to break a decoration line for each cluster during text-on-path.+ cluster.has_relative_shift = true;++ let orig_ts = cluster.transform;++ // Clusters should be rotated by the x-midpoint x baseline position.+ let half_width = cluster.width / 2.0;+ cluster.transform = Transform::default();+ cluster.transform = cluster.transform.pre_translate(x - half_width, y);+ cluster.transform = cluster.transform.pre_rotate_at(angle, half_width, 0.0);++ let cp = char_offset + cluster.byte_idx.code_point_at(&chunk.text);+ dy += text.dy.get(cp).cloned().unwrap_or(0.0);++ let baseline_shift = chunk_span_at(chunk, cluster.byte_idx)+ .map(|span| {+ let font = match fonts_cache.get(&span.font) {+ Some(v) => v,+ None => return 0.0,+ };+ -resolve_baseline(span, font, writing_mode)+ })+ .unwrap_or(0.0);++ // Shift only by `dy` since we already applied `dx`+ // during offset along the path calculation.+ if !dy.approx_zero_ulps(4) || !baseline_shift.approx_zero_ulps(4) {+ let shift = kurbo::Vec2::new(0.0, (dy - baseline_shift) as f64);+ cluster.transform = cluster+ .transform+ .pre_translate(shift.x as f32, shift.y as f32);+ }++ if let Some(angle) = text.rotate.get(cp).cloned() {+ if !angle.approx_zero_ulps(4) {+ cluster.transform = cluster.transform.pre_rotate(angle);+ }+ }++ // The possible `lengthAdjust` transform should be applied after text-on-path positioning.+ cluster.transform = cluster.transform.pre_concat(orig_ts);++ last_x = x + cluster.advance;+ last_y = y;+ }++ (last_x, last_y)+}++pub(crate) fn process_anchor(a: TextAnchor, text_width: f32) -> f32 {+ match a {+ TextAnchor::Start => 0.0, // Nothing.+ TextAnchor::Middle => -text_width / 2.0,+ TextAnchor::End => -text_width,+ }+}++pub(crate) struct PathNormal {+ pub(crate) x: f32,+ pub(crate) y: f32,+ pub(crate) angle: f32,+}++fn collect_normals(+ text: &Text,+ chunk: &TextChunk,+ clusters: &[GlyphCluster],+ path: &tiny_skia_path::Path,+ char_offset: usize,+ offset: f32,+) -> Vec<Option<PathNormal>> {+ let mut offsets = Vec::with_capacity(clusters.len());+ let mut normals = Vec::with_capacity(clusters.len());+ {+ let mut advance = offset;+ for cluster in clusters {+ // Clusters should be rotated by the x-midpoint x baseline position.+ let half_width = cluster.width / 2.0;++ // Include relative position.+ let cp = char_offset + cluster.byte_idx.code_point_at(&chunk.text);+ advance += text.dx.get(cp).cloned().unwrap_or(0.0);++ let offset = advance + half_width;++ // Clusters outside the path have no normals.+ if offset < 0.0 {+ normals.push(None);+ }++ offsets.push(offset as f64);+ advance += cluster.advance;+ }+ }++ let mut prev_mx = path.points()[0].x;+ let mut prev_my = path.points()[0].y;+ let mut prev_x = prev_mx;+ let mut prev_y = prev_my;++ fn create_curve_from_line(px: f32, py: f32, x: f32, y: f32) -> kurbo::CubicBez {+ let line = kurbo::Line::new(+ kurbo::Point::new(px as f64, py as f64),+ kurbo::Point::new(x as f64, y as f64),+ );+ let p1 = line.eval(0.33);+ let p2 = line.eval(0.66);+ kurbo::CubicBez {+ p0: line.p0,+ p1,+ p2,+ p3: line.p1,+ }+ }++ let mut length: f64 = 0.0;+ for seg in path.segments() {+ let curve = match seg {+ tiny_skia_path::PathSegment::MoveTo(p) => {+ prev_mx = p.x;+ prev_my = p.y;+ prev_x = p.x;+ prev_y = p.y;+ continue;+ }+ tiny_skia_path::PathSegment::LineTo(p) => {+ create_curve_from_line(prev_x, prev_y, p.x, p.y)+ }+ tiny_skia_path::PathSegment::QuadTo(p1, p) => kurbo::QuadBez {+ p0: kurbo::Point::new(prev_x as f64, prev_y as f64),+ p1: kurbo::Point::new(p1.x as f64, p1.y as f64),+ p2: kurbo::Point::new(p.x as f64, p.y as f64),+ }+ .raise(),+ tiny_skia_path::PathSegment::CubicTo(p1, p2, p) => kurbo::CubicBez {+ p0: kurbo::Point::new(prev_x as f64, prev_y as f64),+ p1: kurbo::Point::new(p1.x as f64, p1.y as f64),+ p2: kurbo::Point::new(p2.x as f64, p2.y as f64),+ p3: kurbo::Point::new(p.x as f64, p.y as f64),+ },+ tiny_skia_path::PathSegment::Close => {+ create_curve_from_line(prev_x, prev_y, prev_mx, prev_my)+ }+ };++ let arclen_accuracy = {+ let base_arclen_accuracy = 0.5;+ // Accuracy depends on a current scale.+ // When we have a tiny path scaled by a large value,+ // we have to increase out accuracy accordingly.+ let (sx, sy) = text.abs_transform.get_scale();+ // 1.0 acts as a threshold to prevent division by 0 and/or low accuracy.+ base_arclen_accuracy / (sx * sy).sqrt().max(1.0)+ };++ let curve_len = curve.arclen(arclen_accuracy as f64);++ for offset in &offsets[normals.len()..] {+ if *offset >= length && *offset <= length + curve_len {+ let mut offset = curve.inv_arclen(offset - length, arclen_accuracy as f64);+ // some rounding error may occur, so we give offset a little tolerance+ debug_assert!((-1.0e-3..=1.0 + 1.0e-3).contains(&offset));+ offset = offset.clamp(0.0, 1.0);++ let pos = curve.eval(offset);+ let d = curve.deriv().eval(offset);+ let d = kurbo::Vec2::new(-d.y, d.x); // tangent+ let angle = d.atan2().to_degrees() - 90.0;++ normals.push(Some(PathNormal {+ x: pos.x as f32,+ y: pos.y as f32,+ angle: angle as f32,+ }));++ if normals.len() == offsets.len() {+ break;+ }+ }+ }++ length += curve_len;+ prev_x = curve.p3.x as f32;+ prev_y = curve.p3.y as f32;+ }++ // If path ended and we still have unresolved normals - set them to `None`.+ for _ in 0..(offsets.len() - normals.len()) {+ normals.push(None);+ }++ normals+}++/// Converts a text chunk into a list of outlined clusters.+///+/// This function will do the BIDI reordering, text shaping and glyphs outlining,+/// but not the text layouting. So all clusters are in the 0x0 position.+fn process_chunk(+ chunk: &TextChunk,+ fonts_cache: &FontsCache,+ resolver: &FontResolver,+ fontdb: &mut Arc<fontdb::Database>,+) -> Vec<GlyphCluster> {+ // The way this function works is a bit tricky.+ //+ // The first problem is BIDI reordering.+ // We cannot shape text span-by-span, because glyph clusters are not guarantee to be continuous.+ //+ // For example:+ // <text>Hel<tspan fill="url(#lg1)">lo של</tspan>ום.</text>+ //+ // Would be shaped as:+ // H e l l o ש ל ו ם . (characters)+ // 0 1 2 3 4 5 12 10 8 6 14 (cluster indices in UTF-8)+ // --- --- (green span)+ //+ // As you can see, our continuous `lo של` span was split into two separated one.+ // So our 3 spans: black - green - black, become 5 spans: black - green - black - green - black.+ // If we shape `Hel`, then `lo של` an then `ום` separately - we would get an incorrect output.+ // To properly handle this we simply shape the whole chunk.+ //+ // But this introduces another issue - what to do when we have multiple fonts?+ // The easy solution would be to simply shape text with each font,+ // where the first font output is used as a base one and all others overwrite it.+ // This way in case of:+ // <text font-family="Arial">Hello <tspan font-family="Helvetica">world</tspan></text>+ // we would replace Arial glyphs for `world` with Helvetica one. Pretty simple.+ //+ // Well, it would work most of the time, but not always.+ // This is because different fonts can produce different amount of glyphs for the same text.+ // The most common example are ligatures. Some fonts can shape `fi` as two glyphs `f` and `i`,+ // but some can use `fi` (U+FB01) instead.+ // Meaning that during merging we have to overwrite not individual glyphs, but clusters.++ // Glyph splitting assigns distinct glyphs to the same index in the original text, we need to+ // store previously used indices to make sure we do not re-use the same index while overwriting+ // span glyphs.+ let mut positions = HashSet::new();++ let mut glyphs = Vec::new();+ for span in &chunk.spans {+ let font = match fonts_cache.get(&span.font) {+ Some(v) => v.clone(),+ None => continue,+ };++ let tmp_glyphs = shape_text(+ &chunk.text,+ font,+ span.small_caps,+ span.apply_kerning,+ &span.font.variations,+ span.font_size.get(),+ span.font_optical_sizing,+ resolver,+ fontdb,+ );++ // Do nothing with the first run.+ if glyphs.is_empty() {+ glyphs = tmp_glyphs;+ continue;+ }++ positions.clear();++ // Overwrite span's glyphs.+ let mut iter = tmp_glyphs.into_iter();+ while let Some(new_glyph) = iter.next() {+ if !span_contains(span, new_glyph.byte_idx) {+ continue;+ }++ let Some(idx) = glyphs+ .iter()+ .position(|g| g.byte_idx == new_glyph.byte_idx)+ .filter(|pos| !positions.contains(pos))+ else {+ continue;+ };++ positions.insert(idx);++ let prev_cluster_len = glyphs[idx].cluster_len;+ if prev_cluster_len < new_glyph.cluster_len {+ // If the new font represents the same cluster with fewer glyphs+ // then remove remaining glyphs.+ for _ in 1..new_glyph.cluster_len {+ glyphs.remove(idx + 1);+ }+ } else if prev_cluster_len > new_glyph.cluster_len {+ // If the new font represents the same cluster with more glyphs+ // then insert them after the current one.+ for j in 1..prev_cluster_len {+ if let Some(g) = iter.next() {+ glyphs.insert(idx + j, g);+ }+ }+ }++ glyphs[idx] = new_glyph;+ }+ }++ // Convert glyphs to clusters.+ let mut clusters = Vec::new();+ for (range, byte_idx) in GlyphClusters::new(&glyphs) {+ if let Some(span) = chunk_span_at(chunk, byte_idx) {+ clusters.push(form_glyph_clusters(+ &glyphs[range],+ &chunk.text,+ span.font_size.get(),+ ));+ }+ }++ clusters+}++fn apply_length_adjust(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {+ let is_horizontal = matches!(chunk.text_flow, TextFlow::Linear);++ for span in &chunk.spans {+ let target_width = match span.text_length {+ Some(v) => v,+ None => continue,+ };++ let mut width = 0.0;+ let mut cluster_indexes = Vec::new();+ for i in span.start..span.end {+ if let Some(index) = clusters.iter().position(|c| c.byte_idx.value() == i) {+ cluster_indexes.push(index);+ }+ }+ // Complex scripts can have multi-codepoint clusters therefore we have to remove duplicates.+ cluster_indexes.sort();+ cluster_indexes.dedup();++ for i in &cluster_indexes {+ // Use the original cluster `width` and not `advance`.+ // This method essentially discards any `word-spacing` and `letter-spacing`.+ width += clusters[*i].width;+ }++ if cluster_indexes.is_empty() {+ continue;+ }++ if span.length_adjust == LengthAdjust::Spacing {+ let factor = if cluster_indexes.len() > 1 {+ (target_width - width) / (cluster_indexes.len() - 1) as f32+ } else {+ 0.0+ };++ for i in cluster_indexes {+ clusters[i].advance = clusters[i].width + factor;+ }+ } else {+ let factor = target_width / width;+ // Prevent multiplying by zero.+ if factor < 0.001 {+ continue;+ }++ for i in cluster_indexes {+ clusters[i].transform = clusters[i].transform.pre_scale(factor, 1.0);++ // Technically just a hack to support the current text-on-path algorithm.+ if !is_horizontal {+ clusters[i].advance *= factor;+ clusters[i].width *= factor;+ }+ }+ }+ }+}++/// Rotates clusters according to+/// [Unicode Vertical_Orientation Property](https://www.unicode.org/reports/tr50/tr50-19.html).+fn apply_writing_mode(writing_mode: WritingMode, clusters: &mut [GlyphCluster]) {+ if writing_mode != WritingMode::TopToBottom {+ return;+ }++ for cluster in clusters {+ let orientation = unicode_vo::char_orientation(cluster.codepoint);+ if orientation == unicode_vo::Orientation::Upright {+ let mut ts = Transform::default();+ // Position glyph in the center of vertical axis.+ ts = ts.pre_translate(0.0, (cluster.ascent + cluster.descent) / 2.0);+ // Rotate by 90 degrees in the center.+ ts = ts.pre_rotate_at(+ -90.0,+ cluster.width / 2.0,+ -(cluster.ascent + cluster.descent) / 2.0,+ );++ cluster.path_transform = ts;++ // Move "baseline" to the middle and make height equal to width.+ cluster.ascent = cluster.width / 2.0;+ cluster.descent = -cluster.width / 2.0;+ } else {+ // Could not find a spec that explains this,+ // but this is how other applications are shifting the "rotated" characters+ // in the top-to-bottom mode.+ cluster.transform = cluster+ .transform+ .pre_translate(0.0, (cluster.ascent + cluster.descent) / 2.0);+ }+ }+}++/// Applies the `letter-spacing` property to a text chunk clusters.+///+/// [In the CSS spec](https://www.w3.org/TR/css-text-3/#letter-spacing-property).+fn apply_letter_spacing(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {+ // At least one span should have a non-zero spacing.+ if !chunk+ .spans+ .iter()+ .any(|span| !span.letter_spacing.approx_zero_ulps(4))+ {+ return;+ }++ for cluster in clusters.iter_mut() {+ // Spacing must be applied only to characters that belongs to the script+ // that supports spacing.+ // We are checking only the first code point, since it should be enough.+ // https://www.w3.org/TR/css-text-3/#cursive-tracking+ let script = cluster.codepoint.script();+ if script_supports_letter_spacing(script) {+ if let Some(span) = chunk_span_at(chunk, cluster.byte_idx) {+ // raea: the last cluster is spaced too, as Chrome spaces it: its bbox and a middle or end anchor+ // include the spacing after the last letter (docs/layout-reads.feature LR10). usvg left it out, so+ // svg text with letter-spacing was drawn half a spacing off centre and measured a spacing too wide.+ cluster.advance += span.letter_spacing;++ // If the cluster advance became negative - clear it.+ // This is an UB so we can do whatever we want, and we mimic Chrome's behavior.+ if !cluster.advance.is_valid_length() {+ cluster.width = 0.0;+ cluster.advance = 0.0;+ cluster.glyphs = vec![];+ }+ }+ }+ }+}++/// Applies the `word-spacing` property to a text chunk clusters.+///+/// [In the CSS spec](https://www.w3.org/TR/css-text-3/#propdef-word-spacing).+fn apply_word_spacing(chunk: &TextChunk, clusters: &mut [GlyphCluster]) {+ // At least one span should have a non-zero spacing.+ if !chunk+ .spans+ .iter()+ .any(|span| !span.word_spacing.approx_zero_ulps(4))+ {+ return;+ }++ for cluster in clusters {+ if is_word_separator_characters(cluster.codepoint) {+ if let Some(span) = chunk_span_at(chunk, cluster.byte_idx) {+ // Technically, word spacing 'should be applied half on each+ // side of the character', but it doesn't affect us in any way,+ // so we are ignoring this.+ cluster.advance += span.word_spacing;++ // After word spacing, `advance` can be negative.+ }+ }+ }+}++fn form_glyph_clusters(glyphs: &[Glyph], text: &str, font_size: f32) -> GlyphCluster {+ debug_assert!(!glyphs.is_empty());++ let mut x = 0.0;+ let mut width = 0.0;+ let mut advance = 0.0;++ let mut positioned_glyphs = vec![];++ for glyph in glyphs {+ let sx = glyph.font.scale(font_size);++ // Apply offset.+ //+ // The first glyph in the cluster will have an offset from 0x0,+ // but the later one will have an offset from the "current position".+ // So we have to keep an advance.+ // TODO: should be done only inside a single text span+ let ts = Transform::from_translate(x + glyph.dx as f32, -glyph.dy as f32);++ positioned_glyphs.push(PositionedGlyph {+ glyph_ts: ts,+ // Will be set later.+ cluster_ts: Transform::default(),+ // Will be set later.+ span_ts: Transform::default(),+ units_per_em: glyph.font.units_per_em.get(),+ font_size,+ font: glyph.font.id,+ text: glyph.text.clone(),+ id: glyph.id,+ });++ x += glyph.width as f32;++ let glyph_width = glyph.width as f32 * sx;+ advance += glyph_width;+ if glyph_width > width {+ width = glyph_width;+ }+ }++ let byte_idx = glyphs[0].byte_idx;+ let font = glyphs[0].font.clone();+ GlyphCluster {+ byte_idx,+ codepoint: byte_idx.char_from(text),+ width,+ advance,+ ascent: font.ascent(font_size),+ descent: font.descent(font_size),+ has_relative_shift: false,+ transform: Transform::default(),+ path_transform: Transform::default(),+ glyphs: positioned_glyphs,+ visible: true,+ }+}++pub(crate) trait DatabaseExt {+ fn load_font(&self, id: ID, variations: &[crate::FontVariation]) -> Option<ResolvedFont>;+ fn has_char(&self, id: ID, c: char) -> bool;+}++impl DatabaseExt for Database {+ #[inline(never)]+ fn load_font(&self, id: ID, variations: &[crate::FontVariation]) -> Option<ResolvedFont> {+ self.with_face_data(id, |data, face_index| -> Option<ResolvedFont> {+ let font = skrifa::FontRef::from_index(data, face_index).ok()?;++ // For variable fonts, metrics depend on the position in the design space,+ // so resolve the requested variations to a normalized location first.+ // Metrics are always in font units, so the size stays unscaled.+ let location = font.axes().location(+ variations+ .iter()+ .map(|v| (Tag::from_be_bytes(v.tag), v.value)),+ );+ let coords = location.coords();+ let metrics = font.metrics(Size::unscaled(), &location);++ // Reject fonts with an out-of-range unitsPerEm, like `ttf-parser` did.+ if !(16..=16384).contains(&metrics.units_per_em) {+ return None;+ }+ let units_per_em = NonZeroU16::new(metrics.units_per_em)?;++ let ascent = metrics.ascent;+ let descent = metrics.descent;++ let x_height = metrics+ .x_height+ .filter(|x| *x > 0.0)+ .and_then(|x| u16::try_from(x.round() as i32).ok())+ .and_then(NonZeroU16::new);+ let x_height = match x_height {+ Some(height) => height,+ None => {+ // If not set - fallback to height * 45%.+ // 45% is what Firefox uses.+ u16::try_from(((ascent - descent) * 0.45).round() as i32)+ .ok()+ .and_then(NonZeroU16::new)?+ }+ };++ let line_through = metrics.strikeout;+ let line_through_position = match line_through {+ Some(metrics) => metrics.offset.round() as i16,+ None => x_height.get() as i16 / 2,+ };++ let (underline_position, underline_thickness) = match metrics.underline {+ Some(metrics) => {+ let thickness = u16::try_from(metrics.thickness.round() as i32)+ .ok()+ .and_then(NonZeroU16::new)+ // `skrifa` guarantees that units_per_em is > 0+ .unwrap_or_else(|| NonZeroU16::new(units_per_em.get() / 12).unwrap());++ (metrics.offset.round() as i16, thickness)+ }+ None => (+ -(units_per_em.get() as i16) / 9,+ NonZeroU16::new(units_per_em.get() / 12).unwrap(),+ ),+ };++ // 0.2 and 0.4 are generic offsets used by some applications (Inkscape/librsvg).+ let mut subscript_offset = (units_per_em.get() as f32 / 0.2).round() as i16;+ let mut superscript_offset = (units_per_em.get() as f32 / 0.4).round() as i16;++ // TODO: Consider upstreaming into skrifa+ if let Ok(os2) = font.os2() {+ subscript_offset = os2.y_subscript_y_offset();+ superscript_offset = os2.y_superscript_y_offset();+ }+ if let (Ok(mvar), true) = (font.mvar(), !coords.is_empty()) {+ use skrifa::raw::tables::mvar::tags::*;+ let metric_delta =+ |tag| mvar.metric_delta(tag, coords).unwrap_or_default().to_f32();++ subscript_offset += metric_delta(SBYO).round() as i16;+ superscript_offset += metric_delta(SPYO).round() as i16;+ }++ Some(ResolvedFont {+ id,+ units_per_em,+ ascent: ascent.round() as i16,+ descent: descent.round() as i16,+ x_height,+ underline_position,+ underline_thickness,+ line_through_position,+ subscript_offset,+ superscript_offset,+ })+ })?+ }++ #[inline(never)]+ fn has_char(&self, id: ID, c: char) -> bool {+ let res = self.with_face_data(id, |font_data, face_index| -> Option<bool> {+ let font = skrifa::FontRef::from_index(font_data, face_index).ok()?;+ let char_map = skrifa::charmap::Charmap::new(&font);+ char_map.map(c)?;+ Some(true)+ });++ res == Some(Some(true))+ }+}++/// Text shaping with font fallback.+pub(crate) fn shape_text(+ text: &str,+ font: Arc<ResolvedFont>,+ small_caps: bool,+ apply_kerning: bool,+ variations: &[crate::FontVariation],+ font_size: f32,+ font_optical_sizing: crate::FontOpticalSizing,+ resolver: &FontResolver,+ fontdb: &mut Arc<fontdb::Database>,+) -> Vec<Glyph> {+ let mut glyphs = shape_text_with_font(+ text,+ font.clone(),+ small_caps,+ apply_kerning,+ variations,+ font_size,+ font_optical_sizing,+ fontdb,+ )+ .unwrap_or_default();++ // Remember all fonts used for shaping.+ let mut used_fonts = vec![font.id];++ // Loop until all glyphs become resolved or until no more fonts are left.+ 'outer: loop {+ let mut missing = None;+ for glyph in &glyphs {+ if glyph.is_missing() {+ missing = Some(glyph.byte_idx.char_from(text));+ break;+ }+ }++ if let Some(c) = missing {+ let fallback_font = match (resolver.select_fallback)(c, &used_fonts, fontdb)+ .and_then(|id| fontdb.load_font(id, variations))+ {+ Some(v) => Arc::new(v),+ None => break 'outer,+ };++ // Shape again, using a new font.+ let fallback_glyphs = shape_text_with_font(+ text,+ fallback_font.clone(),+ small_caps,+ apply_kerning,+ variations,+ font_size,+ font_optical_sizing,+ fontdb,+ )+ .unwrap_or_default();++ let all_matched = fallback_glyphs.iter().all(|g| !g.is_missing());+ if all_matched {+ // Replace all glyphs when all of them were matched.+ glyphs = fallback_glyphs;+ break 'outer;+ }++ // We assume, that shaping with an any font will produce the same amount of glyphs.+ // This is incorrect, but good enough for now.+ if glyphs.len() != fallback_glyphs.len() {+ break 'outer;+ }++ // TODO: Replace clusters and not glyphs. This should be more accurate.++ // Copy new glyphs.+ for i in 0..glyphs.len() {+ if glyphs[i].is_missing() && !fallback_glyphs[i].is_missing() {+ glyphs[i] = fallback_glyphs[i].clone();+ }+ }++ // Remember this font.+ used_fonts.push(fallback_font.id);+ } else {+ break 'outer;+ }+ }++ // Warn about missing glyphs.+ for glyph in &glyphs {+ if glyph.is_missing() {+ let c = glyph.byte_idx.char_from(text);+ // TODO: print a full grapheme+ log::warn!(+ "No fonts with a {}/U+{:X} character were found.",+ c,+ c as u32+ );+ }+ }++ glyphs+}++/// Converts a text into a list of glyph IDs.+///+/// This function will do the BIDI reordering and text shaping.+fn shape_text_with_font(+ text: &str,+ font: Arc<ResolvedFont>,+ small_caps: bool,+ apply_kerning: bool,+ variations: &[crate::FontVariation],+ font_size: f32,+ font_optical_sizing: crate::FontOpticalSizing,+ fontdb: &fontdb::Database,+) -> Option<Vec<Glyph>> {+ fontdb.with_face_data(font.id, |font_data, face_index| -> Option<Vec<Glyph>> {+ use harfrust::{Feature, ShaperData, ShaperInstance, Tag, UnicodeBuffer, Variation};++ use crate::text::OPSZ;++ let hr_font = harfrust::FontRef::from_index(font_data, face_index).ok()?;++ // Build the list of variations to apply+ let mut variations: Vec<Variation> = variations+ .iter()+ .map(|v| Variation {+ tag: Tag::from_be_bytes(v.tag),+ value: v.value,+ })+ .collect();++ // Automatic optical sizing: if font-optical-sizing is auto and the font has+ // an 'opsz' axis that isn't explicitly set, auto-set it to match font size.+ // This matches browser behavior (CSS font-optical-sizing: auto).+ if font_optical_sizing == crate::FontOpticalSizing::Auto {+ let has_explicit_opsz = variations.iter().any(|v| v.tag == *b"opsz");+ if !has_explicit_opsz && hr_font.axes().get_by_tag(OPSZ).is_some() {+ variations.push(Variation {+ tag: OPSZ,+ value: font_size,+ });+ }+ }++ let bidi_info = unicode_bidi::BidiInfo::new(text, Some(unicode_bidi::Level::ltr()));+ let paragraph = &bidi_info.paragraphs[0];+ let line = paragraph.range.clone();++ let mut glyphs = Vec::new();++ // A shaper instance is only needed to apply variations.+ let instance_data = (!variations.is_empty())+ .then(|| ShaperInstance::from_variations(&hr_font, &variations));+ let shaper_data = ShaperData::new(&hr_font);+ let shaper = shaper_data+ .shaper(&hr_font)+ .instance(instance_data.as_ref())+ .build();++ let mut features = Vec::new();+ if small_caps {+ features.push(Feature::new(Tag::new(b"smcp"), 1, ..));+ }+ if !apply_kerning {+ features.push(Feature::new(Tag::new(b"kern"), 0, ..));+ }++ let (levels, runs) = bidi_info.visual_runs(paragraph, line);+ for run in runs.iter() {+ let sub_text = &text[run.clone()];+ if sub_text.is_empty() {+ continue;+ }++ let ltr = levels[run.start].is_ltr();+ let direction = if ltr {+ harfrust::Direction::LeftToRight+ } else {+ harfrust::Direction::RightToLeft+ };++ let mut buffer = UnicodeBuffer::new();+ buffer.push_str(sub_text);+ buffer.set_direction(direction);++ // TODO: explicitly set language?+ buffer.guess_segment_properties();++ let output = shaper.shape(buffer, ShapeOptions::new().features(&features));++ let positions = output.glyph_positions();+ let infos = output.glyph_infos();++ for i in 0..output.len() {+ let pos = positions[i];+ let info = infos[i];+ let idx = run.start + info.cluster as usize;++ let start = info.cluster as usize;++ let end = if ltr {+ i.checked_add(1)+ } else {+ i.checked_sub(1)+ }+ .and_then(|last| infos.get(last))+ .map_or(sub_text.len(), |info| info.cluster as usize);++ glyphs.push(Glyph {+ byte_idx: ByteIndex::new(idx),+ cluster_len: end.checked_sub(start).unwrap_or(0), // TODO: can fail?+ text: sub_text[start..end].to_string(),+ id: GlyphId(info.glyph_id),+ dx: pos.x_offset,+ dy: pos.y_offset,+ width: pos.x_advance,+ font: font.clone(),+ });+ }+ }++ Some(glyphs)+ })?+}++/// An iterator over glyph clusters.+///+/// Input: 0 2 2 2 3 4 4 5 5+/// Result: 0 1 4 5 7+pub(crate) struct GlyphClusters<'a> {+ data: &'a [Glyph],+ idx: usize,+}++impl<'a> GlyphClusters<'a> {+ pub(crate) fn new(data: &'a [Glyph]) -> Self {+ GlyphClusters { data, idx: 0 }+ }+}++impl Iterator for GlyphClusters<'_> {+ type Item = (std::ops::Range<usize>, ByteIndex);++ fn next(&mut self) -> Option<Self::Item> {+ if self.idx == self.data.len() {+ return None;+ }++ let start = self.idx;+ let cluster = self.data[self.idx].byte_idx;+ for g in &self.data[self.idx..] {+ if g.byte_idx != cluster {+ break;+ }++ self.idx += 1;+ }++ Some((start..self.idx, cluster))+ }+}++/// Checks that selected script supports letter spacing.+///+/// [In the CSS spec](https://www.w3.org/TR/css-text-3/#cursive-tracking).+///+/// The list itself is from: https://github.com/harfbuzz/harfbuzz/issues/64+pub(crate) fn script_supports_letter_spacing(script: unicode_script::Script) -> bool {+ use unicode_script::Script;++ !matches!(+ script,+ Script::Arabic+ | Script::Syriac+ | Script::Nko+ | Script::Manichaean+ | Script::Psalter_Pahlavi+ | Script::Mandaic+ | Script::Mongolian+ | Script::Phags_Pa+ | Script::Devanagari+ | Script::Bengali+ | Script::Gurmukhi+ | Script::Modi+ | Script::Sharada+ | Script::Syloti_Nagri+ | Script::Tirhuta+ | Script::Ogham+ )+}++/// A glyph.+///+/// Basically, a glyph ID and it's metrics.+#[derive(Clone)]+pub(crate) struct Glyph {+ /// The glyph ID in the font.+ pub(crate) id: GlyphId,++ /// Position in bytes in the original string.+ ///+ /// We use it to match a glyph with a character in the text chunk and therefore with the style.+ pub(crate) byte_idx: ByteIndex,++ // The length of the cluster in bytes.+ pub(crate) cluster_len: usize,++ /// The text from the original string that corresponds to that glyph.+ pub(crate) text: String,++ /// The glyph offset in font units.+ pub(crate) dx: i32,++ /// The glyph offset in font units.+ pub(crate) dy: i32,++ /// The glyph width / X-advance in font units.+ pub(crate) width: i32,++ /// Reference to the source font.+ ///+ /// Each glyph can have it's own source font.+ pub(crate) font: Arc<ResolvedFont>,+}++impl Glyph {+ fn is_missing(&self) -> bool {+ self.id.0 == 0+ }+}++#[derive(Clone, Copy, Debug)]+pub(crate) struct ResolvedFont {+ pub(crate) id: ID,++ units_per_em: NonZeroU16,++ // All values below are in font units.+ ascent: i16,+ descent: i16,+ x_height: NonZeroU16,++ underline_position: i16,+ underline_thickness: NonZeroU16,++ // line-through thickness should be the the same as underline thickness+ // according to the TrueType spec:+ // https://docs.microsoft.com/en-us/typography/opentype/spec/os2#ystrikeoutsize+ line_through_position: i16,++ subscript_offset: i16,+ superscript_offset: i16,+}++pub(crate) fn chunk_span_at(chunk: &TextChunk, byte_offset: ByteIndex) -> Option<&TextSpan> {+ chunk+ .spans+ .iter()+ .find(|&span| span_contains(span, byte_offset))+}++pub(crate) fn span_contains(span: &TextSpan, byte_offset: ByteIndex) -> bool {+ byte_offset.value() >= span.start && byte_offset.value() < span.end+}++/// Checks that the selected character is a word separator.+///+/// According to: https://www.w3.org/TR/css-text-3/#word-separator+pub(crate) fn is_word_separator_characters(c: char) -> bool {+ matches!(+ c as u32,+ 0x0020 | 0x00A0 | 0x1361 | 0x010100 | 0x010101 | 0x01039F | 0x01091F+ )+}++impl ResolvedFont {+ #[inline]+ pub(crate) fn scale(&self, font_size: f32) -> f32 {+ font_size / self.units_per_em.get() as f32+ }++ #[inline]+ pub(crate) fn ascent(&self, font_size: f32) -> f32 {+ self.ascent as f32 * self.scale(font_size)+ }++ #[inline]+ pub(crate) fn descent(&self, font_size: f32) -> f32 {+ self.descent as f32 * self.scale(font_size)+ }++ #[inline]+ pub(crate) fn height(&self, font_size: f32) -> f32 {+ self.ascent(font_size) - self.descent(font_size)+ }++ #[inline]+ pub(crate) fn x_height(&self, font_size: f32) -> f32 {+ self.x_height.get() as f32 * self.scale(font_size)+ }++ #[inline]+ pub(crate) fn underline_position(&self, font_size: f32) -> f32 {+ self.underline_position as f32 * self.scale(font_size)+ }++ #[inline]+ fn underline_thickness(&self, font_size: f32) -> f32 {+ self.underline_thickness.get() as f32 * self.scale(font_size)+ }++ #[inline]+ pub(crate) fn line_through_position(&self, font_size: f32) -> f32 {+ self.line_through_position as f32 * self.scale(font_size)+ }++ #[inline]+ fn subscript_offset(&self, font_size: f32) -> f32 {+ self.subscript_offset as f32 * self.scale(font_size)+ }++ #[inline]+ fn superscript_offset(&self, font_size: f32) -> f32 {+ self.superscript_offset as f32 * self.scale(font_size)+ }++ fn dominant_baseline_shift(&self, baseline: DominantBaseline, font_size: f32) -> f32 {+ let alignment = match baseline {+ DominantBaseline::Auto => AlignmentBaseline::Auto,+ DominantBaseline::UseScript => AlignmentBaseline::Auto, // unsupported+ DominantBaseline::NoChange => AlignmentBaseline::Auto, // already resolved+ DominantBaseline::ResetSize => AlignmentBaseline::Auto, // unsupported+ DominantBaseline::Ideographic => AlignmentBaseline::Ideographic,+ DominantBaseline::Alphabetic => AlignmentBaseline::Alphabetic,+ DominantBaseline::Hanging => AlignmentBaseline::Hanging,+ DominantBaseline::Mathematical => AlignmentBaseline::Mathematical,+ DominantBaseline::Central => AlignmentBaseline::Central,+ DominantBaseline::Middle => AlignmentBaseline::Middle,+ DominantBaseline::TextAfterEdge => AlignmentBaseline::TextAfterEdge,+ DominantBaseline::TextBeforeEdge => AlignmentBaseline::TextBeforeEdge,+ };++ self.alignment_baseline_shift(alignment, font_size)+ }++ // The `alignment-baseline` property is a mess.+ //+ // The SVG 1.1 spec (https://www.w3.org/TR/SVG11/text.html#BaselineAlignmentProperties)+ // goes on and on about what this property suppose to do, but doesn't actually explain+ // how it should be implemented. It's just a very verbose overview.+ //+ // As of Nov 2022, only Chrome and Safari support `alignment-baseline`. Firefox isn't.+ // Same goes for basically every SVG library in existence.+ // Meaning we have no idea how exactly it should be implemented.+ //+ // And even Chrome and Safari cannot agree on how to handle `baseline`, `after-edge`,+ // `text-after-edge` and `ideographic` variants. Producing vastly different output.+ //+ // As per spec, a proper implementation should get baseline values from the font itself,+ // using `BASE` and `bsln` TrueType tables. If those tables are not present,+ // we have to synthesize them (https://drafts.csswg.org/css-inline/#baseline-synthesis-fonts).+ // And in the worst case scenario simply fallback to hardcoded values.+ //+ // Also, most fonts do not provide `BASE` and `bsln` tables to begin with.+ //+ // Again, as of Nov 2022, Chrome does only the latter:+ // https://github.com/chromium/chromium/blob/main/third_party/blink/renderer/platform/fonts/font_metrics.cc#L153+ //+ // Since baseline TrueType tables parsing and baseline synthesis are pretty hard,+ // we do what Chrome does - use hardcoded values. And it seems like Safari does the same.+ //+ //+ // But that's not all! SVG 2 and CSS Inline Layout 3 did a baseline handling overhaul,+ // and it's far more complex now. Not sure if anyone actually supports it.+ fn alignment_baseline_shift(&self, alignment: AlignmentBaseline, font_size: f32) -> f32 {+ match alignment {+ AlignmentBaseline::Auto => 0.0,+ AlignmentBaseline::Baseline => 0.0,+ AlignmentBaseline::BeforeEdge | AlignmentBaseline::TextBeforeEdge => {+ self.ascent(font_size)+ }+ AlignmentBaseline::Middle => self.x_height(font_size) * 0.5,+ AlignmentBaseline::Central => self.ascent(font_size) - self.height(font_size) * 0.5,+ AlignmentBaseline::AfterEdge | AlignmentBaseline::TextAfterEdge => {+ self.descent(font_size)+ }+ AlignmentBaseline::Ideographic => self.descent(font_size),+ AlignmentBaseline::Alphabetic => 0.0,+ AlignmentBaseline::Hanging => self.ascent(font_size) * 0.8,+ AlignmentBaseline::Mathematical => self.ascent(font_size) * 0.5,+ }+ }+}++pub(crate) type FontsCache = HashMap<Font, Arc<ResolvedFont>>;++/// A read-only text index in bytes.+///+/// Guarantee to be on a char boundary and in text bounds.+#[derive(Clone, Copy, PartialEq, Debug)]+pub(crate) struct ByteIndex(usize);++impl ByteIndex {+ fn new(i: usize) -> Self {+ ByteIndex(i)+ }++ pub(crate) fn value(&self) -> usize {+ self.0+ }++ /// Converts byte position into a code point position.+ pub(crate) fn code_point_at(&self, text: &str) -> usize {+ text.char_indices()+ .take_while(|(i, _)| *i != self.0)+ .count()+ }++ /// Converts byte position into a character.+ pub(crate) fn char_from(&self, text: &str) -> char {+ text[self.0..].chars().next().unwrap()+ }+}diff --git a/vendor/usvg/src/text/mod.rs b/vendor/usvg/src/text/mod.rsnew file mode 100644index 00000000..cdeaa7a8--- /dev/null+++ b/vendor/usvg/src/text/mod.rs@@ -0,0 +1,230 @@+// Copyright 2024 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::sync::Arc;++use fontdb::{Database, ID};+use svgtypes::FontFamily;++use self::layout::DatabaseExt;+use crate::{Cache, Font, FontStretch, FontStyle, Text};++pub(crate) mod flatten;+mod transform;++mod colr;+/// Provides access to the layout of a text node.+pub mod layout;++/// The optical sizing variation axis tag.+pub(crate) const OPSZ: skrifa::Tag = skrifa::Tag::from_be_bytes(*b"opsz");++/// The ID of a glyph within a font+#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]+pub struct GlyphId(pub u32);++impl From<GlyphId> for skrifa::raw::types::GlyphId {+ fn from(value: GlyphId) -> Self {+ Self::new(value.0)+ }+}++/// A shorthand for [FontResolver]'s font selection function.+///+/// This function receives a font specification (families + a style, weight,+/// stretch triple) and a font database and should return the ID of the font+/// that shall be used (if any).+///+/// In the basic case, the function will search the existing fonts in the+/// database to find a good match, e.g. via+/// [`Database::query`](fontdb::Database::query). This is what the [default+/// implementation](FontResolver::default_font_selector) does.+///+/// Users with more complex requirements can mutate the database to load+/// additional fonts dynamically. To perform mutation, it is recommended to call+/// `Arc::make_mut` on the provided database. (This call is not done outside of+/// the callback to not needless clone an underlying shared database if no+/// mutation will be performed.) It is important that the database is only+/// mutated additively. Removing fonts or replacing the entire database will+/// break things.+pub type FontSelectionFn<'a> =+ Box<dyn Fn(&Font, &mut Arc<Database>) -> Option<ID> + Send + Sync + 'a>;++/// A shorthand for [FontResolver]'s fallback selection function.+///+/// This function receives a specific character, a list of already used fonts,+/// and a font database. It should return the ID of a font that+/// - is not any of the already used fonts+/// - is as close as possible to the first already used font (if any)+/// - supports the given character+///+/// The function can search the existing database, but can also load additional+/// fonts dynamically. See the documentation of [`FontSelectionFn`] for more+/// details.+pub type FallbackSelectionFn<'a> =+ Box<dyn Fn(char, &[ID], &mut Arc<Database>) -> Option<ID> + Send + Sync + 'a>;++/// A font resolver for `<text>` elements.+///+/// This type can be useful if you want to have an alternative font handling to+/// the default one. By default, only fonts specified upfront in+/// [`Options::fontdb`](crate::Options::fontdb) will be used. This type allows+/// you to load additional fonts on-demand and customize the font selection+/// process.+pub struct FontResolver<'a> {+ /// Resolver function that will be used when selecting a specific font+ /// for a generic [`Font`] specification.+ pub select_font: FontSelectionFn<'a>,++ /// Resolver function that will be used when selecting a fallback font for a+ /// character.+ pub select_fallback: FallbackSelectionFn<'a>,+}++impl Default for FontResolver<'_> {+ fn default() -> Self {+ FontResolver {+ select_font: FontResolver::default_font_selector(),+ select_fallback: FontResolver::default_fallback_selector(),+ }+ }+}++impl FontResolver<'_> {+ /// Creates a default font selection resolver.+ ///+ /// The default implementation forwards to+ /// [`query`](fontdb::Database::query) on the font database specified in the+ /// [`Options`](crate::Options).+ pub fn default_font_selector() -> FontSelectionFn<'static> {+ Box::new(move |font, fontdb| {+ let mut name_list = Vec::new();+ for family in &font.families {+ name_list.push(match family {+ FontFamily::Serif => fontdb::Family::Serif,+ FontFamily::SansSerif => fontdb::Family::SansSerif,+ FontFamily::Cursive => fontdb::Family::Cursive,+ FontFamily::Fantasy => fontdb::Family::Fantasy,+ FontFamily::Monospace => fontdb::Family::Monospace,+ FontFamily::Named(s) => fontdb::Family::Name(s),+ });+ }++ // Use the default font as fallback.+ name_list.push(fontdb::Family::Serif);++ let stretch = match font.stretch {+ FontStretch::UltraCondensed => fontdb::Stretch::UltraCondensed,+ FontStretch::ExtraCondensed => fontdb::Stretch::ExtraCondensed,+ FontStretch::Condensed => fontdb::Stretch::Condensed,+ FontStretch::SemiCondensed => fontdb::Stretch::SemiCondensed,+ FontStretch::Normal => fontdb::Stretch::Normal,+ FontStretch::SemiExpanded => fontdb::Stretch::SemiExpanded,+ FontStretch::Expanded => fontdb::Stretch::Expanded,+ FontStretch::ExtraExpanded => fontdb::Stretch::ExtraExpanded,+ FontStretch::UltraExpanded => fontdb::Stretch::UltraExpanded,+ };++ let style = match font.style {+ FontStyle::Normal => fontdb::Style::Normal,+ FontStyle::Italic => fontdb::Style::Italic,+ FontStyle::Oblique => fontdb::Style::Oblique,+ };++ let query = fontdb::Query {+ families: &name_list,+ weight: fontdb::Weight(font.weight),+ stretch,+ style,+ };++ let id = fontdb.query(&query);+ if id.is_none() {+ log::warn!(+ "No match for '{}' font-family.",+ font.families+ .iter()+ .map(|f| f.to_string())+ .collect::<Vec<_>>()+ .join(", ")+ );+ }++ id+ })+ }++ /// Creates a default font fallback selection resolver.+ ///+ /// The default implementation searches through the entire `fontdb`+ /// to find a font that has the correct style and supports the character.+ pub fn default_fallback_selector() -> FallbackSelectionFn<'static> {+ Box::new(|c, exclude_fonts, fontdb| {+ let base_font_id = exclude_fonts[0];++ // Iterate over fonts and check if any of them support the specified char.+ for face in fontdb.faces() {+ // Ignore fonts, that were used for shaping already.+ if exclude_fonts.contains(&face.id) {+ continue;+ }++ // Check that the new face has the same style.+ let base_face = fontdb.face(base_font_id)?;+ if base_face.style != face.style+ && base_face.weight != face.weight+ && base_face.stretch != face.stretch+ {+ continue;+ }++ if !fontdb.has_char(face.id, c) {+ continue;+ }++ let base_family = base_face+ .families+ .iter()+ .find(|f| f.1 == fontdb::Language::English_UnitedStates)+ .unwrap_or(&base_face.families[0]);++ let new_family = face+ .families+ .iter()+ .find(|f| f.1 == fontdb::Language::English_UnitedStates)+ .unwrap_or(&base_face.families[0]);++ log::warn!("Fallback from {} to {}.", base_family.0, new_family.0);+ return Some(face.id);+ }++ None+ })+ }+}++impl std::fmt::Debug for FontResolver<'_> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("FontResolver { .. }")+ }+}++/// Convert a text into its paths. This is done in two steps:+/// 1. We convert the text into glyphs and position them according to the rules specified+/// in the SVG specification. While doing so, we also calculate the text bbox (which+/// is not based on the outlines of a glyph, but instead the glyph metrics as well+/// as decoration spans).+/// 2. We convert all of the positioned glyphs into outlines.+pub(crate) fn convert(text: &mut Text, resolver: &FontResolver, cache: &mut Cache) -> Option<()> {+ let (text_fragments, bbox) = layout::layout_text(text, resolver, &mut cache.fontdb)?;+ text.layouted = text_fragments;+ text.bounding_box = bbox.to_rect();+ text.abs_bounding_box = bbox.transform(text.abs_transform)?.to_rect();++ let (group, stroke_bbox) = flatten::flatten(text, cache)?;+ text.flattened = Box::new(group);+ text.stroke_bounding_box = stroke_bbox.to_rect();+ text.abs_stroke_bounding_box = stroke_bbox.transform(text.abs_transform)?.to_rect();++ Some(())+}diff --git a/vendor/usvg/src/text/transform.rs b/vendor/usvg/src/text/transform.rsnew file mode 100644index 00000000..0a12bac0--- /dev/null+++ b/vendor/usvg/src/text/transform.rs@@ -0,0 +1,17 @@+// Copyright 2025 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++pub(crate) fn skrifa_to_tsp_transform(t: skrifa::color::Transform) -> tiny_skia_path::Transform {+ tiny_skia_path::Transform::from_row(t.xx, t.yx, t.xy, t.yy, t.dx, t.dy)+}++pub(crate) fn tsp_to_skrifa_transform(t: tiny_skia_path::Transform) -> skrifa::color::Transform {+ skrifa::color::Transform {+ xx: t.sx,+ yx: t.ky,+ xy: t.kx,+ yy: t.sy,+ dx: t.tx,+ dy: t.ty,+ }+}diff --git a/vendor/usvg/src/tree/filter.rs b/vendor/usvg/src/tree/filter.rsnew file mode 100644index 00000000..896e118e--- /dev/null+++ b/vendor/usvg/src/tree/filter.rs@@ -0,0 +1,1061 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++//! SVG filter types.++use strict_num::PositiveF32;++use crate::{BlendMode, Color, Group, NonEmptyString, NonZeroF32, NonZeroRect, Opacity};++/// A filter element.+///+/// `filter` element in the SVG.+#[derive(Debug)]+pub struct Filter {+ pub(crate) id: NonEmptyString,+ pub(crate) rect: NonZeroRect,+ pub(crate) primitives: Vec<Primitive>,+}++impl Filter {+ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Used only during SVG writing. `resvg` doesn't rely on this property.+ pub fn id(&self) -> &str {+ self.id.get()+ }++ /// Filter region.+ ///+ /// `x`, `y`, `width` and `height` in the SVG.+ pub fn rect(&self) -> NonZeroRect {+ self.rect+ }++ /// A list of filter primitives.+ pub fn primitives(&self) -> &[Primitive] {+ &self.primitives+ }+}++/// A filter primitive element.+#[derive(Clone, Debug)]+pub struct Primitive {+ pub(crate) rect: NonZeroRect,+ pub(crate) color_interpolation: ColorInterpolation,+ pub(crate) result: String,+ pub(crate) kind: Kind,+}++impl Primitive {+ /// Filter subregion.+ ///+ /// `x`, `y`, `width` and `height` in the SVG.+ pub fn rect(&self) -> NonZeroRect {+ self.rect+ }++ /// Color interpolation mode.+ ///+ /// `color-interpolation-filters` in the SVG.+ pub fn color_interpolation(&self) -> ColorInterpolation {+ self.color_interpolation+ }++ /// Assigned name for this filter primitive.+ ///+ /// `result` in the SVG.+ pub fn result(&self) -> &str {+ &self.result+ }++ /// Filter primitive kind.+ pub fn kind(&self) -> &Kind {+ &self.kind+ }+}++/// A filter kind.+#[allow(missing_docs)]+#[derive(Clone, Debug)]+pub enum Kind {+ Blend(Blend),+ ColorMatrix(ColorMatrix),+ ComponentTransfer(ComponentTransfer),+ Composite(Composite),+ ConvolveMatrix(ConvolveMatrix),+ DiffuseLighting(DiffuseLighting),+ DisplacementMap(DisplacementMap),+ DropShadow(DropShadow),+ Flood(Flood),+ GaussianBlur(GaussianBlur),+ Image(Image),+ Merge(Merge),+ Morphology(Morphology),+ Offset(Offset),+ SpecularLighting(SpecularLighting),+ Tile(Tile),+ Turbulence(Turbulence),+}++impl Kind {+ /// Checks that `FilterKind` has a specific input.+ pub fn has_input(&self, input: &Input) -> bool {+ match self {+ Kind::Blend(fe) => fe.input1 == *input || fe.input2 == *input,+ Kind::ColorMatrix(fe) => fe.input == *input,+ Kind::ComponentTransfer(fe) => fe.input == *input,+ Kind::Composite(fe) => fe.input1 == *input || fe.input2 == *input,+ Kind::ConvolveMatrix(fe) => fe.input == *input,+ Kind::DiffuseLighting(fe) => fe.input == *input,+ Kind::DisplacementMap(fe) => fe.input1 == *input || fe.input2 == *input,+ Kind::DropShadow(fe) => fe.input == *input,+ Kind::Flood(_) => false,+ Kind::GaussianBlur(fe) => fe.input == *input,+ Kind::Image(_) => false,+ Kind::Merge(fe) => fe.inputs.iter().any(|i| i == input),+ Kind::Morphology(fe) => fe.input == *input,+ Kind::Offset(fe) => fe.input == *input,+ Kind::SpecularLighting(fe) => fe.input == *input,+ Kind::Tile(fe) => fe.input == *input,+ Kind::Turbulence(_) => false,+ }+ }+}++/// Identifies input for a filter primitive.+#[allow(missing_docs)]+#[derive(Clone, PartialEq, Debug)]+pub enum Input {+ SourceGraphic,+ SourceAlpha,+ Reference(String),+}++/// A color interpolation mode.+///+/// The default is `ColorInterpolation::LinearRGB`.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug, Default)]+pub enum ColorInterpolation {+ SRGB,+ #[default]+ LinearRGB,+}++/// A blend filter primitive.+///+/// `feBlend` element in the SVG.+#[derive(Clone, Debug)]+pub struct Blend {+ pub(crate) input1: Input,+ pub(crate) input2: Input,+ pub(crate) mode: BlendMode,+}++impl Blend {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input1(&self) -> &Input {+ &self.input1+ }++ /// Identifies input for the given filter primitive.+ ///+ /// `in2` in the SVG.+ pub fn input2(&self) -> &Input {+ &self.input2+ }++ /// A blending mode.+ ///+ /// `mode` in the SVG.+ pub fn mode(&self) -> BlendMode {+ self.mode+ }+}++/// A color matrix filter primitive.+///+/// `feColorMatrix` element in the SVG.+#[derive(Clone, Debug)]+pub struct ColorMatrix {+ pub(crate) input: Input,+ pub(crate) kind: ColorMatrixKind,+}++impl ColorMatrix {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// A matrix kind.+ ///+ /// `type` in the SVG.+ pub fn kind(&self) -> &ColorMatrixKind {+ &self.kind+ }+}++/// A color matrix filter primitive kind.+#[derive(Clone, Debug)]+#[allow(missing_docs)]+pub enum ColorMatrixKind {+ Matrix(Vec<f32>), // Guarantee to have 20 numbers.+ Saturate(PositiveF32),+ HueRotate(f32),+ LuminanceToAlpha,+}++impl Default for ColorMatrixKind {+ fn default() -> Self {+ ColorMatrixKind::Matrix(vec![+ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,+ 0.0, 1.0, 0.0,+ ])+ }+}++/// A component-wise remapping filter primitive.+///+/// `feComponentTransfer` element in the SVG.+#[derive(Clone, Debug)]+pub struct ComponentTransfer {+ pub(crate) input: Input,+ pub(crate) func_r: TransferFunction,+ pub(crate) func_g: TransferFunction,+ pub(crate) func_b: TransferFunction,+ pub(crate) func_a: TransferFunction,+}++impl ComponentTransfer {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// `feFuncR` in the SVG.+ pub fn func_r(&self) -> &TransferFunction {+ &self.func_r+ }++ /// `feFuncG` in the SVG.+ pub fn func_g(&self) -> &TransferFunction {+ &self.func_g+ }++ /// `feFuncB` in the SVG.+ pub fn func_b(&self) -> &TransferFunction {+ &self.func_b+ }++ /// `feFuncA` in the SVG.+ pub fn func_a(&self) -> &TransferFunction {+ &self.func_a+ }+}++/// A transfer function used by `FeComponentTransfer`.+///+/// <https://www.w3.org/TR/SVG11/filters.html#transferFuncElements>+#[derive(Clone, Debug)]+pub enum TransferFunction {+ /// Keeps a component as is.+ Identity,++ /// Applies a linear interpolation to a component.+ ///+ /// The number list can be empty.+ Table(Vec<f32>),++ /// Applies a step function to a component.+ ///+ /// The number list can be empty.+ Discrete(Vec<f32>),++ /// Applies a linear shift to a component.+ #[allow(missing_docs)]+ Linear { slope: f32, intercept: f32 },++ /// Applies an exponential shift to a component.+ #[allow(missing_docs)]+ Gamma {+ amplitude: f32,+ exponent: f32,+ offset: f32,+ },+}++/// A composite filter primitive.+///+/// `feComposite` element in the SVG.+#[derive(Clone, Debug)]+pub struct Composite {+ pub(crate) input1: Input,+ pub(crate) input2: Input,+ pub(crate) operator: CompositeOperator,+}++impl Composite {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input1(&self) -> &Input {+ &self.input1+ }++ /// Identifies input for the given filter primitive.+ ///+ /// `in2` in the SVG.+ pub fn input2(&self) -> &Input {+ &self.input2+ }++ /// A compositing operation.+ ///+ /// `operator` in the SVG.+ pub fn operator(&self) -> CompositeOperator {+ self.operator+ }+}++/// An images compositing operation.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum CompositeOperator {+ Over,+ In,+ Out,+ Atop,+ Xor,+ Arithmetic { k1: f32, k2: f32, k3: f32, k4: f32 },+}++/// A matrix convolution filter primitive.+///+/// `feConvolveMatrix` element in the SVG.+#[derive(Clone, Debug)]+pub struct ConvolveMatrix {+ pub(crate) input: Input,+ pub(crate) matrix: ConvolveMatrixData,+ pub(crate) divisor: NonZeroF32,+ pub(crate) bias: f32,+ pub(crate) edge_mode: EdgeMode,+ pub(crate) preserve_alpha: bool,+}++impl ConvolveMatrix {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// A convolve matrix.+ pub fn matrix(&self) -> &ConvolveMatrixData {+ &self.matrix+ }++ /// A matrix divisor.+ ///+ /// `divisor` in the SVG.+ pub fn divisor(&self) -> NonZeroF32 {+ self.divisor+ }++ /// A kernel matrix bias.+ ///+ /// `bias` in the SVG.+ pub fn bias(&self) -> f32 {+ self.bias+ }++ /// An edges processing mode.+ ///+ /// `edgeMode` in the SVG.+ pub fn edge_mode(&self) -> EdgeMode {+ self.edge_mode+ }++ /// An alpha preserving flag.+ ///+ /// `preserveAlpha` in the SVG.+ pub fn preserve_alpha(&self) -> bool {+ self.preserve_alpha+ }+}++/// A convolve matrix representation.+///+/// Used primarily by [`ConvolveMatrix`].+#[derive(Clone, Debug)]+pub struct ConvolveMatrixData {+ pub(crate) target_x: u32,+ pub(crate) target_y: u32,+ pub(crate) columns: u32,+ pub(crate) rows: u32,+ pub(crate) data: Vec<f32>,+}++impl ConvolveMatrixData {+ /// Returns a matrix's X target.+ ///+ /// `targetX` in the SVG.+ pub fn target_x(&self) -> u32 {+ self.target_x+ }++ /// Returns a matrix's Y target.+ ///+ /// `targetY` in the SVG.+ pub fn target_y(&self) -> u32 {+ self.target_y+ }++ /// Returns a number of columns in the matrix.+ ///+ /// Part of the `order` attribute in the SVG.+ pub fn columns(&self) -> u32 {+ self.columns+ }++ /// Returns a number of rows in the matrix.+ ///+ /// Part of the `order` attribute in the SVG.+ pub fn rows(&self) -> u32 {+ self.rows+ }++ /// The actual matrix.+ pub fn data(&self) -> &[f32] {+ &self.data+ }+}++impl ConvolveMatrixData {+ /// Creates a new `ConvolveMatrixData`.+ ///+ /// Returns `None` when:+ ///+ /// - `columns` * `rows` != `data.len()`+ /// - `target_x` >= `columns`+ /// - `target_y` >= `rows`+ pub(crate) fn new(+ target_x: u32,+ target_y: u32,+ columns: u32,+ rows: u32,+ data: Vec<f32>,+ ) -> Option<Self> {+ if (columns * rows) as usize != data.len() || target_x >= columns || target_y >= rows {+ return None;+ }++ Some(ConvolveMatrixData {+ target_x,+ target_y,+ columns,+ rows,+ data,+ })+ }++ /// Returns a matrix value at the specified position.+ ///+ /// # Panics+ ///+ /// - When position is out of bounds.+ pub fn get(&self, x: u32, y: u32) -> f32 {+ self.data[(y * self.columns + x) as usize]+ }+}++/// An edges processing mode.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum EdgeMode {+ None,+ Duplicate,+ Wrap,+}++/// A displacement map filter primitive.+///+/// `feDisplacementMap` element in the SVG.+#[derive(Clone, Debug)]+pub struct DisplacementMap {+ pub(crate) input1: Input,+ pub(crate) input2: Input,+ pub(crate) scale: f32,+ pub(crate) x_channel_selector: ColorChannel,+ pub(crate) y_channel_selector: ColorChannel,+}++impl DisplacementMap {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input1(&self) -> &Input {+ &self.input1+ }++ /// Identifies input for the given filter primitive.+ ///+ /// `in2` in the SVG.+ pub fn input2(&self) -> &Input {+ &self.input2+ }++ /// Scale factor.+ ///+ /// `scale` in the SVG.+ pub fn scale(&self) -> f32 {+ self.scale+ }++ /// Indicates a source color channel along the X-axis.+ ///+ /// `xChannelSelector` in the SVG.+ pub fn x_channel_selector(&self) -> ColorChannel {+ self.x_channel_selector+ }++ /// Indicates a source color channel along the Y-axis.+ ///+ /// `yChannelSelector` in the SVG.+ pub fn y_channel_selector(&self) -> ColorChannel {+ self.y_channel_selector+ }+}++/// A color channel.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum ColorChannel {+ R,+ G,+ B,+ A,+}++/// A drop shadow filter primitive.+///+/// This is essentially `feGaussianBlur`, `feOffset` and `feFlood` joined together.+///+/// `feDropShadow` element in the SVG.+#[derive(Clone, Debug)]+pub struct DropShadow {+ pub(crate) input: Input,+ pub(crate) dx: f32,+ pub(crate) dy: f32,+ pub(crate) std_dev_x: PositiveF32,+ pub(crate) std_dev_y: PositiveF32,+ pub(crate) color: Color,+ pub(crate) opacity: Opacity,+}++impl DropShadow {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// The amount to offset the input graphic along the X-axis.+ pub fn dx(&self) -> f32 {+ self.dx+ }++ /// The amount to offset the input graphic along the Y-axis.+ pub fn dy(&self) -> f32 {+ self.dy+ }++ /// A standard deviation along the X-axis.+ ///+ /// `stdDeviation` in the SVG.+ pub fn std_dev_x(&self) -> PositiveF32 {+ self.std_dev_x+ }++ /// A standard deviation along the Y-axis.+ ///+ /// `stdDeviation` in the SVG.+ pub fn std_dev_y(&self) -> PositiveF32 {+ self.std_dev_y+ }++ /// A flood color.+ ///+ /// `flood-color` in the SVG.+ pub fn color(&self) -> Color {+ self.color+ }++ /// A flood opacity.+ ///+ /// `flood-opacity` in the SVG.+ pub fn opacity(&self) -> Opacity {+ self.opacity+ }+}++/// A flood filter primitive.+///+/// `feFlood` element in the SVG.+#[derive(Clone, Copy, Debug)]+pub struct Flood {+ pub(crate) color: Color,+ pub(crate) opacity: Opacity,+}++impl Flood {+ /// A flood color.+ ///+ /// `flood-color` in the SVG.+ pub fn color(&self) -> Color {+ self.color+ }++ /// A flood opacity.+ ///+ /// `flood-opacity` in the SVG.+ pub fn opacity(&self) -> Opacity {+ self.opacity+ }+}++/// A Gaussian blur filter primitive.+///+/// `feGaussianBlur` element in the SVG.+#[derive(Clone, Debug)]+pub struct GaussianBlur {+ pub(crate) input: Input,+ pub(crate) std_dev_x: PositiveF32,+ pub(crate) std_dev_y: PositiveF32,+}++impl GaussianBlur {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// A standard deviation along the X-axis.+ ///+ /// `stdDeviation` in the SVG.+ pub fn std_dev_x(&self) -> PositiveF32 {+ self.std_dev_x+ }++ /// A standard deviation along the Y-axis.+ ///+ /// `stdDeviation` in the SVG.+ pub fn std_dev_y(&self) -> PositiveF32 {+ self.std_dev_y+ }+}++/// An image filter primitive.+///+/// `feImage` element in the SVG.+#[derive(Clone, Debug)]+pub struct Image {+ pub(crate) root: Group,+}++impl Image {+ /// `feImage` children.+ pub fn root(&self) -> &Group {+ &self.root+ }+}++/// A diffuse lighting filter primitive.+///+/// `feDiffuseLighting` element in the SVG.+#[derive(Clone, Debug)]+pub struct DiffuseLighting {+ pub(crate) input: Input,+ pub(crate) surface_scale: f32,+ pub(crate) diffuse_constant: f32,+ pub(crate) lighting_color: Color,+ pub(crate) light_source: LightSource,+}++impl DiffuseLighting {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// A surface scale.+ ///+ /// `surfaceScale` in the SVG.+ pub fn surface_scale(&self) -> f32 {+ self.surface_scale+ }++ /// A diffuse constant.+ ///+ /// `diffuseConstant` in the SVG.+ pub fn diffuse_constant(&self) -> f32 {+ self.diffuse_constant+ }++ /// A lighting color.+ ///+ /// `lighting-color` in the SVG.+ pub fn lighting_color(&self) -> Color {+ self.lighting_color+ }++ /// A light source.+ pub fn light_source(&self) -> LightSource {+ self.light_source+ }+}++/// A specular lighting filter primitive.+///+/// `feSpecularLighting` element in the SVG.+#[derive(Clone, Debug)]+pub struct SpecularLighting {+ pub(crate) input: Input,+ pub(crate) surface_scale: f32,+ pub(crate) specular_constant: f32,+ pub(crate) specular_exponent: f32,+ pub(crate) lighting_color: Color,+ pub(crate) light_source: LightSource,+}++impl SpecularLighting {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// A surface scale.+ ///+ /// `surfaceScale` in the SVG.+ pub fn surface_scale(&self) -> f32 {+ self.surface_scale+ }++ /// A specular constant.+ ///+ /// `specularConstant` in the SVG.+ pub fn specular_constant(&self) -> f32 {+ self.specular_constant+ }++ /// A specular exponent.+ ///+ /// Should be in 1..128 range.+ ///+ /// `specularExponent` in the SVG.+ pub fn specular_exponent(&self) -> f32 {+ self.specular_exponent+ }++ /// A lighting color.+ ///+ /// `lighting-color` in the SVG.+ pub fn lighting_color(&self) -> Color {+ self.lighting_color+ }++ /// A light source.+ pub fn light_source(&self) -> LightSource {+ self.light_source+ }+}++/// A light source kind.+#[allow(missing_docs)]+#[derive(Clone, Copy, Debug)]+pub enum LightSource {+ DistantLight(DistantLight),+ PointLight(PointLight),+ SpotLight(SpotLight),+}++/// A distant light source.+///+/// `feDistantLight` element in the SVG.+#[derive(Clone, Copy, Debug)]+pub struct DistantLight {+ /// Direction angle for the light source on the XY plane (clockwise),+ /// in degrees from the x axis.+ ///+ /// `azimuth` in the SVG.+ pub azimuth: f32,++ /// Direction angle for the light source from the XY plane towards the z axis, in degrees.+ ///+ /// `elevation` in the SVG.+ pub elevation: f32,+}++/// A point light source.+///+/// `fePointLight` element in the SVG.+#[derive(Clone, Copy, Debug)]+pub struct PointLight {+ /// X location for the light source.+ ///+ /// `x` in the SVG.+ pub x: f32,++ /// Y location for the light source.+ ///+ /// `y` in the SVG.+ pub y: f32,++ /// Z location for the light source.+ ///+ /// `z` in the SVG.+ pub z: f32,+}++/// A spot light source.+///+/// `feSpotLight` element in the SVG.+#[derive(Clone, Copy, Debug)]+pub struct SpotLight {+ /// X location for the light source.+ ///+ /// `x` in the SVG.+ pub x: f32,++ /// Y location for the light source.+ ///+ /// `y` in the SVG.+ pub y: f32,++ /// Z location for the light source.+ ///+ /// `z` in the SVG.+ pub z: f32,++ /// X point at which the light source is pointing.+ ///+ /// `pointsAtX` in the SVG.+ pub points_at_x: f32,++ /// Y point at which the light source is pointing.+ ///+ /// `pointsAtY` in the SVG.+ pub points_at_y: f32,++ /// Z point at which the light source is pointing.+ ///+ /// `pointsAtZ` in the SVG.+ pub points_at_z: f32,++ /// Exponent value controlling the focus for the light source.+ ///+ /// `specularExponent` in the SVG.+ pub specular_exponent: PositiveF32,++ /// A limiting cone which restricts the region where the light is projected.+ ///+ /// `limitingConeAngle` in the SVG.+ pub limiting_cone_angle: Option<f32>,+}++/// A merge filter primitive.+///+/// `feMerge` element in the SVG.+#[derive(Clone, Debug)]+pub struct Merge {+ pub(crate) inputs: Vec<Input>,+}++impl Merge {+ /// List of input layers that should be merged.+ ///+ /// List of `feMergeNode`'s in the SVG.+ pub fn inputs(&self) -> &[Input] {+ &self.inputs+ }+}++/// A morphology filter primitive.+///+/// `feMorphology` element in the SVG.+#[derive(Clone, Debug)]+pub struct Morphology {+ pub(crate) input: Input,+ pub(crate) operator: MorphologyOperator,+ pub(crate) radius_x: PositiveF32,+ pub(crate) radius_y: PositiveF32,+}++impl Morphology {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// A filter operator.+ ///+ /// `operator` in the SVG.+ pub fn operator(&self) -> MorphologyOperator {+ self.operator+ }++ /// A filter radius along the X-axis.+ ///+ /// A value of zero disables the effect of the given filter primitive.+ ///+ /// `radius` in the SVG.+ pub fn radius_x(&self) -> PositiveF32 {+ self.radius_x+ }++ /// A filter radius along the Y-axis.+ ///+ /// A value of zero disables the effect of the given filter primitive.+ ///+ /// `radius` in the SVG.+ pub fn radius_y(&self) -> PositiveF32 {+ self.radius_y+ }+}++/// A morphology operation.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum MorphologyOperator {+ Erode,+ Dilate,+}++/// An offset filter primitive.+///+/// `feOffset` element in the SVG.+#[derive(Clone, Debug)]+pub struct Offset {+ pub(crate) input: Input,+ pub(crate) dx: f32,+ pub(crate) dy: f32,+}++impl Offset {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }++ /// The amount to offset the input graphic along the X-axis.+ pub fn dx(&self) -> f32 {+ self.dx+ }++ /// The amount to offset the input graphic along the Y-axis.+ pub fn dy(&self) -> f32 {+ self.dy+ }+}++/// A tile filter primitive.+///+/// `feTile` element in the SVG.+#[derive(Clone, Debug)]+pub struct Tile {+ pub(crate) input: Input,+}++impl Tile {+ /// Identifies input for the given filter primitive.+ ///+ /// `in` in the SVG.+ pub fn input(&self) -> &Input {+ &self.input+ }+}++/// A turbulence generation filter primitive.+///+/// `feTurbulence` element in the SVG.+#[derive(Clone, Copy, Debug)]+pub struct Turbulence {+ pub(crate) base_frequency_x: PositiveF32,+ pub(crate) base_frequency_y: PositiveF32,+ pub(crate) num_octaves: u32,+ pub(crate) seed: i32,+ pub(crate) stitch_tiles: bool,+ pub(crate) kind: TurbulenceKind,+}++impl Turbulence {+ /// Identifies the base frequency for the noise function.+ ///+ /// `baseFrequency` in the SVG.+ pub fn base_frequency_x(&self) -> PositiveF32 {+ self.base_frequency_x+ }++ /// Identifies the base frequency for the noise function.+ ///+ /// `baseFrequency` in the SVG.+ pub fn base_frequency_y(&self) -> PositiveF32 {+ self.base_frequency_y+ }++ /// Identifies the number of octaves for the noise function.+ ///+ /// `numOctaves` in the SVG.+ pub fn num_octaves(&self) -> u32 {+ self.num_octaves+ }++ /// The starting number for the pseudo random number generator.+ ///+ /// `seed` in the SVG.+ pub fn seed(&self) -> i32 {+ self.seed+ }++ /// Smooth transitions at the border of tiles.+ ///+ /// `stitchTiles` in the SVG.+ pub fn stitch_tiles(&self) -> bool {+ self.stitch_tiles+ }++ /// Indicates whether the filter primitive should perform a noise or turbulence function.+ ///+ /// `type` in the SVG.+ pub fn kind(&self) -> TurbulenceKind {+ self.kind+ }+}++/// A turbulence kind for the `feTurbulence` filter.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum TurbulenceKind {+ FractalNoise,+ Turbulence,+}diff --git a/vendor/usvg/src/tree/geom.rs b/vendor/usvg/src/tree/geom.rsnew file mode 100644index 00000000..c2913703--- /dev/null+++ b/vendor/usvg/src/tree/geom.rs@@ -0,0 +1,185 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use strict_num::ApproxEqUlps;+use svgtypes::{Align, AspectRatio};+pub use tiny_skia_path::{NonZeroRect, Rect, Size, Transform};++/// Approximate zero equality comparisons.+pub trait ApproxZeroUlps: ApproxEqUlps {+ /// Checks if the number is approximately zero.+ fn approx_zero_ulps(&self, ulps: <Self::Flt as strict_num::Ulps>::U) -> bool;+}++impl ApproxZeroUlps for f32 {+ fn approx_zero_ulps(&self, ulps: i32) -> bool {+ self.approx_eq_ulps(&0.0, ulps)+ }+}++impl ApproxZeroUlps for f64 {+ fn approx_zero_ulps(&self, ulps: i64) -> bool {+ self.approx_eq_ulps(&0.0, ulps)+ }+}++/// Checks that the current number is > 0.+pub(crate) trait IsValidLength {+ /// Checks that the current number is > 0.+ fn is_valid_length(&self) -> bool;+}++impl IsValidLength for f32 {+ #[inline]+ fn is_valid_length(&self) -> bool {+ *self > 0.0 && self.is_finite()+ }+}++impl IsValidLength for f64 {+ #[inline]+ fn is_valid_length(&self) -> bool {+ *self > 0.0 && self.is_finite()+ }+}++/// View box.+#[derive(Clone, Copy, Debug)]+pub(crate) struct ViewBox {+ /// Value of the `viewBox` attribute.+ pub rect: NonZeroRect,++ /// Value of the `preserveAspectRatio` attribute.+ pub aspect: AspectRatio,+}++impl ViewBox {+ /// Converts `viewBox` into `Transform`.+ pub fn to_transform(&self, img_size: Size) -> Transform {+ let vr = self.rect;++ let sx = img_size.width() / vr.width();+ let sy = img_size.height() / vr.height();++ let (sx, sy) = if self.aspect.align == Align::None {+ (sx, sy)+ } else {+ let s = if self.aspect.slice {+ if sx < sy { sy } else { sx }+ } else {+ if sx > sy { sy } else { sx }+ };++ (s, s)+ };++ let x = -vr.x() * sx;+ let y = -vr.y() * sy;+ let w = img_size.width() - vr.width() * sx;+ let h = img_size.height() - vr.height() * sy;++ let (tx, ty) = aligned_pos(self.aspect.align, x, y, w, h);+ Transform::from_row(sx, 0.0, 0.0, sy, tx, ty)+ }+}++/// A bounding box calculator.+#[derive(Clone, Copy, Debug)]+pub(crate) struct BBox {+ left: f32,+ top: f32,+ right: f32,+ bottom: f32,+}++impl From<Rect> for BBox {+ fn from(r: Rect) -> Self {+ Self {+ left: r.left(),+ top: r.top(),+ right: r.right(),+ bottom: r.bottom(),+ }+ }+}++impl From<NonZeroRect> for BBox {+ fn from(r: NonZeroRect) -> Self {+ Self {+ left: r.left(),+ top: r.top(),+ right: r.right(),+ bottom: r.bottom(),+ }+ }+}++impl Default for BBox {+ fn default() -> Self {+ Self {+ left: f32::MAX,+ top: f32::MAX,+ right: f32::MIN,+ bottom: f32::MIN,+ }+ }+}++impl BBox {+ /// Checks if the bounding box is default, i.e. invalid.+ pub fn is_default(&self) -> bool {+ self.left == f32::MAX+ && self.top == f32::MAX+ && self.right == f32::MIN+ && self.bottom == f32::MIN+ }++ /// Expand the bounding box to the specified bounds.+ #[must_use]+ pub fn expand(&self, r: impl Into<Self>) -> Self {+ self.expand_impl(r.into())+ }++ fn expand_impl(&self, r: Self) -> Self {+ Self {+ left: self.left.min(r.left),+ top: self.top.min(r.top),+ right: self.right.max(r.right),+ bottom: self.bottom.max(r.bottom),+ }+ }++ /// Converts a bounding box into [`Rect`].+ pub fn to_rect(&self) -> Option<Rect> {+ if !self.is_default() {+ Rect::from_ltrb(self.left, self.top, self.right, self.bottom)+ } else {+ None+ }+ }++ /// Converts a bounding box into [`NonZeroRect`].+ pub fn to_non_zero_rect(&self) -> Option<NonZeroRect> {+ if !self.is_default() {+ NonZeroRect::from_ltrb(self.left, self.top, self.right, self.bottom)+ } else {+ None+ }+ }+}++/// Returns object aligned position.+pub(crate) fn aligned_pos(align: Align, x: f32, y: f32, w: f32, h: f32) -> (f32, f32) {+ match align {+ Align::None => (x, y),+ Align::XMinYMin => (x, y),+ Align::XMidYMin => (x + w / 2.0, y),+ Align::XMaxYMin => (x + w, y),+ Align::XMinYMid => (x, y + h / 2.0),+ Align::XMidYMid => (x + w / 2.0, y + h / 2.0),+ Align::XMaxYMid => (x + w, y + h / 2.0),+ Align::XMinYMax => (x, y + h),+ Align::XMidYMax => (x + w / 2.0, y + h),+ Align::XMaxYMax => (x + w, y + h),+ }+}diff --git a/vendor/usvg/src/tree/mod.rs b/vendor/usvg/src/tree/mod.rsnew file mode 100644index 00000000..6b204f52--- /dev/null+++ b/vendor/usvg/src/tree/mod.rs@@ -0,0 +1,1930 @@+// Copyright 2019 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++pub mod filter;+mod geom;+mod text;++use std::fmt::Display;+use std::sync::Arc;++pub use strict_num::{self, ApproxEqUlps, NonZeroPositiveF32, NormalizedF32, PositiveF32};++pub use tiny_skia_path;++pub use self::geom::*;+pub use self::text::*;++use crate::OptionLog;++/// An alias to `NormalizedF32`.+pub type Opacity = NormalizedF32;++// Must not be clone-able to preserve ID uniqueness.+#[derive(Debug)]+pub(crate) struct NonEmptyString(String);++impl NonEmptyString {+ pub(crate) fn new(string: String) -> Option<Self> {+ if string.trim().is_empty() {+ return None;+ }++ Some(NonEmptyString(string))+ }++ pub(crate) fn get(&self) -> &str {+ &self.0+ }++ pub(crate) fn take(self) -> String {+ self.0+ }+}++/// A non-zero `f32`.+///+/// Just like `f32` but immutable and guarantee to never be zero.+#[derive(Clone, Copy, Debug)]+pub struct NonZeroF32(f32);++impl NonZeroF32 {+ /// Creates a new `NonZeroF32` value.+ #[inline]+ pub fn new(n: f32) -> Option<Self> {+ if n.approx_eq_ulps(&0.0, 4) {+ None+ } else {+ Some(NonZeroF32(n))+ }+ }++ /// Returns an underlying value.+ #[inline]+ pub fn get(&self) -> f32 {+ self.0+ }+}++#[derive(Clone, Copy, PartialEq, Debug)]+pub(crate) enum Units {+ UserSpaceOnUse,+ ObjectBoundingBox,+}++// `Units` cannot have a default value, because it changes depending on an element.++impl std::fmt::Display for Units {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Units::UserSpaceOnUse => write!(f, "userSpaceOnUse"),+ Units::ObjectBoundingBox => write!(f, "objectBoundingBox"),+ }+ }+}++/// A visibility property.+///+/// `visibility` attribute in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub(crate) enum Visibility {+ Visible,+ Hidden,+ Collapse,+}++impl Default for Visibility {+ fn default() -> Self {+ Self::Visible+ }+}++/// A shape rendering method.+///+/// `shape-rendering` attribute in the SVG.+#[derive(Clone, Copy, PartialEq, Debug)]+#[allow(missing_docs)]+pub enum ShapeRendering {+ OptimizeSpeed,+ CrispEdges,+ GeometricPrecision,+}++impl ShapeRendering {+ /// Checks if anti-aliasing should be enabled.+ pub fn use_shape_antialiasing(self) -> bool {+ match self {+ ShapeRendering::OptimizeSpeed => false,+ ShapeRendering::CrispEdges => false,+ ShapeRendering::GeometricPrecision => true,+ }+ }+}++impl Default for ShapeRendering {+ fn default() -> Self {+ Self::GeometricPrecision+ }+}++impl std::str::FromStr for ShapeRendering {+ type Err = &'static str;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "optimizeSpeed" => Ok(ShapeRendering::OptimizeSpeed),+ "crispEdges" => Ok(ShapeRendering::CrispEdges),+ "geometricPrecision" => Ok(ShapeRendering::GeometricPrecision),+ _ => Err("invalid"),+ }+ }+}++/// A text rendering method.+///+/// `text-rendering` attribute in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum TextRendering {+ OptimizeSpeed,+ OptimizeLegibility,+ GeometricPrecision,+}++impl Default for TextRendering {+ fn default() -> Self {+ Self::OptimizeLegibility+ }+}++impl std::str::FromStr for TextRendering {+ type Err = &'static str;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "optimizeSpeed" => Ok(TextRendering::OptimizeSpeed),+ "optimizeLegibility" => Ok(TextRendering::OptimizeLegibility),+ "geometricPrecision" => Ok(TextRendering::GeometricPrecision),+ _ => Err("invalid"),+ }+ }+}++/// An image rendering method.+///+/// `image-rendering` attribute in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum ImageRendering {+ OptimizeQuality,+ OptimizeSpeed,+ // The following can only appear as presentation attributes.+ Smooth,+ HighQuality,+ CrispEdges,+ Pixelated,+}++impl Default for ImageRendering {+ fn default() -> Self {+ Self::OptimizeQuality+ }+}++impl std::str::FromStr for ImageRendering {+ type Err = &'static str;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s {+ "optimizeQuality" => Ok(ImageRendering::OptimizeQuality),+ "optimizeSpeed" => Ok(ImageRendering::OptimizeSpeed),+ "smooth" => Ok(ImageRendering::Smooth),+ "high-quality" => Ok(ImageRendering::HighQuality),+ "crisp-edges" => Ok(ImageRendering::CrispEdges),+ "pixelated" => Ok(ImageRendering::Pixelated),+ _ => Err("invalid"),+ }+ }+}++/// A blending mode property.+///+/// `mix-blend-mode` attribute in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum BlendMode {+ Normal,+ Multiply,+ Screen,+ Overlay,+ Darken,+ Lighten,+ ColorDodge,+ ColorBurn,+ HardLight,+ SoftLight,+ Difference,+ Exclusion,+ Hue,+ Saturation,+ Color,+ Luminosity,+}++impl Default for BlendMode {+ fn default() -> Self {+ Self::Normal+ }+}++impl Display for BlendMode {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let blend_mode = match self {+ BlendMode::Normal => "normal",+ BlendMode::Multiply => "multiply",+ BlendMode::Screen => "screen",+ BlendMode::Overlay => "overlay",+ BlendMode::Darken => "darken",+ BlendMode::Lighten => "lighten",+ BlendMode::ColorDodge => "color-dodge",+ BlendMode::ColorBurn => "color-burn",+ BlendMode::HardLight => "hard-light",+ BlendMode::SoftLight => "soft-light",+ BlendMode::Difference => "difference",+ BlendMode::Exclusion => "exclusion",+ BlendMode::Hue => "hue",+ BlendMode::Saturation => "saturation",+ BlendMode::Color => "color",+ BlendMode::Luminosity => "luminosity",+ };+ write!(f, "{blend_mode}")+ }+}++/// A spread method.+///+/// `spreadMethod` attribute in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum SpreadMethod {+ Pad,+ Reflect,+ Repeat,+}++impl Default for SpreadMethod {+ fn default() -> Self {+ Self::Pad+ }+}++/// A generic gradient.+#[derive(Debug)]+pub struct BaseGradient {+ pub(crate) id: NonEmptyString,+ pub(crate) units: Units, // used only during parsing+ pub(crate) transform: Transform,+ pub(crate) spread_method: SpreadMethod,+ pub(crate) stops: Vec<Stop>,+}++impl BaseGradient {+ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Used only during SVG writing. `resvg` doesn't rely on this property.+ pub fn id(&self) -> &str {+ self.id.get()+ }++ /// Gradient transform.+ ///+ /// `gradientTransform` in SVG.+ pub fn transform(&self) -> Transform {+ self.transform+ }++ /// Gradient spreading method.+ ///+ /// `spreadMethod` in SVG.+ pub fn spread_method(&self) -> SpreadMethod {+ self.spread_method+ }++ /// A list of `stop` elements.+ pub fn stops(&self) -> &[Stop] {+ &self.stops+ }+}++/// A linear gradient.+///+/// `linearGradient` element in SVG.+#[derive(Debug)]+pub struct LinearGradient {+ pub(crate) base: BaseGradient,+ pub(crate) x1: f32,+ pub(crate) y1: f32,+ pub(crate) x2: f32,+ pub(crate) y2: f32,+}++impl LinearGradient {+ /// `x1` coordinate.+ pub fn x1(&self) -> f32 {+ self.x1+ }++ /// `y1` coordinate.+ pub fn y1(&self) -> f32 {+ self.y1+ }++ /// `x2` coordinate.+ pub fn x2(&self) -> f32 {+ self.x2+ }++ /// `y2` coordinate.+ pub fn y2(&self) -> f32 {+ self.y2+ }+}++impl std::ops::Deref for LinearGradient {+ type Target = BaseGradient;++ fn deref(&self) -> &Self::Target {+ &self.base+ }+}++/// A radial gradient.+///+/// `radialGradient` element in SVG.+#[derive(Debug)]+pub struct RadialGradient {+ pub(crate) base: BaseGradient,+ pub(crate) cx: f32,+ pub(crate) cy: f32,+ pub(crate) r: PositiveF32,+ pub(crate) fx: f32,+ pub(crate) fy: f32,+ pub(crate) fr: PositiveF32,+}++impl RadialGradient {+ /// `cx` coordinate.+ pub fn cx(&self) -> f32 {+ self.cx+ }++ /// `cy` coordinate.+ pub fn cy(&self) -> f32 {+ self.cy+ }++ /// Gradient radius.+ pub fn r(&self) -> PositiveF32 {+ self.r+ }++ /// `fx` coordinate.+ pub fn fx(&self) -> f32 {+ self.fx+ }++ /// `fy` coordinate.+ pub fn fy(&self) -> f32 {+ self.fy+ }++ /// Focal radius.+ pub fn fr(&self) -> PositiveF32 {+ self.fr+ }+}++impl std::ops::Deref for RadialGradient {+ type Target = BaseGradient;++ fn deref(&self) -> &Self::Target {+ &self.base+ }+}++/// An alias to `NormalizedF32`.+pub type StopOffset = NormalizedF32;++/// Gradient's stop element.+///+/// `stop` element in SVG.+#[derive(Clone, Copy, Debug)]+pub struct Stop {+ pub(crate) offset: StopOffset,+ pub(crate) color: Color,+ pub(crate) opacity: Opacity,+}++impl Stop {+ /// Gradient stop offset.+ ///+ /// `offset` in SVG.+ pub fn offset(&self) -> StopOffset {+ self.offset+ }++ /// Gradient stop color.+ ///+ /// `stop-color` in SVG.+ pub fn color(&self) -> Color {+ self.color+ }++ /// Gradient stop opacity.+ ///+ /// `stop-opacity` in SVG.+ pub fn opacity(&self) -> Opacity {+ self.opacity+ }+}++/// A pattern element.+///+/// `pattern` element in SVG.+#[derive(Debug)]+pub struct Pattern {+ pub(crate) id: NonEmptyString,+ pub(crate) units: Units, // used only during parsing+ pub(crate) content_units: Units, // used only during parsing+ pub(crate) transform: Transform,+ pub(crate) rect: NonZeroRect,+ pub(crate) view_box: Option<ViewBox>,+ pub(crate) root: Group,+}++impl Pattern {+ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Used only during SVG writing. `resvg` doesn't rely on this property.+ pub fn id(&self) -> &str {+ self.id.get()+ }++ /// Pattern transform.+ ///+ /// `patternTransform` in SVG.+ pub fn transform(&self) -> Transform {+ self.transform+ }++ /// Pattern rectangle.+ ///+ /// `x`, `y`, `width` and `height` in SVG.+ pub fn rect(&self) -> NonZeroRect {+ self.rect+ }++ /// Pattern children.+ pub fn root(&self) -> &Group {+ &self.root+ }+}++/// An alias to `NonZeroPositiveF32`.+pub type StrokeWidth = NonZeroPositiveF32;++/// A `stroke-miterlimit` value.+///+/// Just like `f32` but immutable and guarantee to be >=1.0.+#[derive(Clone, Copy, Debug)]+pub struct StrokeMiterlimit(f32);++impl StrokeMiterlimit {+ /// Creates a new `StrokeMiterlimit` value.+ #[inline]+ pub fn new(n: f32) -> Self {+ debug_assert!(n.is_finite());+ debug_assert!(n >= 1.0);++ let n = if !(n >= 1.0) { 1.0 } else { n };++ StrokeMiterlimit(n)+ }++ /// Returns an underlying value.+ #[inline]+ pub fn get(&self) -> f32 {+ self.0+ }+}++impl Default for StrokeMiterlimit {+ #[inline]+ fn default() -> Self {+ StrokeMiterlimit::new(4.0)+ }+}++impl From<f32> for StrokeMiterlimit {+ #[inline]+ fn from(n: f32) -> Self {+ Self::new(n)+ }+}++impl PartialEq for StrokeMiterlimit {+ #[inline]+ fn eq(&self, other: &Self) -> bool {+ self.0.approx_eq_ulps(&other.0, 4)+ }+}++/// A line cap.+///+/// `stroke-linecap` attribute in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum LineCap {+ Butt,+ Round,+ Square,+}++impl Default for LineCap {+ fn default() -> Self {+ Self::Butt+ }+}++/// A line join.+///+/// `stroke-linejoin` attribute in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum LineJoin {+ Miter,+ MiterClip,+ Round,+ Bevel,+}++impl Default for LineJoin {+ fn default() -> Self {+ Self::Miter+ }+}++/// A stroke style.+#[derive(Clone, Debug)]+pub struct Stroke {+ pub(crate) paint: Paint,+ pub(crate) dasharray: Option<Vec<f32>>,+ pub(crate) dashoffset: f32,+ pub(crate) miterlimit: StrokeMiterlimit,+ pub(crate) opacity: Opacity,+ pub(crate) width: StrokeWidth,+ pub(crate) linecap: LineCap,+ pub(crate) linejoin: LineJoin,+ // Whether the current stroke needs to be resolved relative+ // to a context element.+ pub(crate) context_element: Option<ContextElement>,+}++impl Stroke {+ /// Stroke paint.+ pub fn paint(&self) -> &Paint {+ &self.paint+ }++ /// Stroke dash array.+ pub fn dasharray(&self) -> Option<&[f32]> {+ self.dasharray.as_deref()+ }++ /// Stroke dash offset.+ pub fn dashoffset(&self) -> f32 {+ self.dashoffset+ }++ /// Stroke miter limit.+ pub fn miterlimit(&self) -> StrokeMiterlimit {+ self.miterlimit+ }++ /// Stroke opacity.+ pub fn opacity(&self) -> Opacity {+ self.opacity+ }++ /// Stroke width.+ pub fn width(&self) -> StrokeWidth {+ self.width+ }++ /// Stroke linecap.+ pub fn linecap(&self) -> LineCap {+ self.linecap+ }++ /// Stroke linejoin.+ pub fn linejoin(&self) -> LineJoin {+ self.linejoin+ }++ /// Converts into a `tiny_skia_path::Stroke` type.+ pub fn to_tiny_skia(&self) -> tiny_skia_path::Stroke {+ let mut stroke = tiny_skia_path::Stroke {+ width: self.width.get(),+ miter_limit: self.miterlimit.get(),+ line_cap: match self.linecap {+ LineCap::Butt => tiny_skia_path::LineCap::Butt,+ LineCap::Round => tiny_skia_path::LineCap::Round,+ LineCap::Square => tiny_skia_path::LineCap::Square,+ },+ line_join: match self.linejoin {+ LineJoin::Miter => tiny_skia_path::LineJoin::Miter,+ LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip,+ LineJoin::Round => tiny_skia_path::LineJoin::Round,+ LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel,+ },+ // According to the spec, dash should not be accounted during+ // bbox calculation.+ dash: None,+ };++ if let Some(ref list) = self.dasharray {+ stroke.dash = tiny_skia_path::StrokeDash::new(list.clone(), self.dashoffset);+ }++ stroke+ }+}++/// A fill rule.+///+/// `fill-rule` attribute in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum FillRule {+ NonZero,+ EvenOdd,+}++impl Default for FillRule {+ fn default() -> Self {+ Self::NonZero+ }+}++#[derive(Clone, Copy, Debug)]+pub(crate) enum ContextElement {+ /// The current context element is a use node. Since we can get+ /// the bounding box of a use node only once we have converted+ /// all elements, we need to fix the transform and units of+ /// the stroke/fill after converting the whole tree.+ UseNode,+ /// The current context element is a path node (i.e. only applicable+ /// if we draw the marker of a path). Since we already know the bounding+ /// box of the path when rendering the markers, we can convert them directly,+ /// so we do it while parsing.+ PathNode(Transform, Option<NonZeroRect>),+}++/// A fill style.+#[derive(Clone, Debug)]+pub struct Fill {+ pub(crate) paint: Paint,+ pub(crate) opacity: Opacity,+ pub(crate) rule: FillRule,+ // Whether the current fill needs to be resolved relative+ // to a context element.+ pub(crate) context_element: Option<ContextElement>,+}++impl Fill {+ /// Fill paint.+ pub fn paint(&self) -> &Paint {+ &self.paint+ }++ /// Fill opacity.+ pub fn opacity(&self) -> Opacity {+ self.opacity+ }++ /// Fill rule.+ pub fn rule(&self) -> FillRule {+ self.rule+ }+}++impl Default for Fill {+ fn default() -> Self {+ Fill {+ paint: Paint::Color(Color::black()),+ opacity: Opacity::ONE,+ rule: FillRule::default(),+ context_element: None,+ }+ }+}++/// A 8-bit RGB color.+#[derive(Clone, Copy, PartialEq, Debug)]+#[allow(missing_docs)]+pub struct Color {+ pub red: u8,+ pub green: u8,+ pub blue: u8,+}++impl Color {+ /// Constructs a new `Color` from RGB values.+ #[inline]+ pub fn new_rgb(red: u8, green: u8, blue: u8) -> Color {+ Color { red, green, blue }+ }++ /// Constructs a new `Color` set to black.+ #[inline]+ pub fn black() -> Color {+ Color::new_rgb(0, 0, 0)+ }++ /// Constructs a new `Color` set to white.+ #[inline]+ pub fn white() -> Color {+ Color::new_rgb(255, 255, 255)+ }+}++/// A paint style.+///+/// `paint` value type in the SVG.+#[allow(missing_docs)]+#[derive(Clone, Debug)]+pub enum Paint {+ Color(Color),+ LinearGradient(Arc<LinearGradient>),+ RadialGradient(Arc<RadialGradient>),+ Pattern(Arc<Pattern>),+}++impl PartialEq for Paint {+ #[inline]+ fn eq(&self, other: &Self) -> bool {+ match (self, other) {+ (Self::Color(lc), Self::Color(rc)) => lc == rc,+ (Self::LinearGradient(lg1), Self::LinearGradient(lg2)) => Arc::ptr_eq(lg1, lg2),+ (Self::RadialGradient(rg1), Self::RadialGradient(rg2)) => Arc::ptr_eq(rg1, rg2),+ (Self::Pattern(p1), Self::Pattern(p2)) => Arc::ptr_eq(p1, p2),+ _ => false,+ }+ }+}++/// A clip-path element.+///+/// `clipPath` element in SVG.+#[derive(Debug)]+pub struct ClipPath {+ pub(crate) id: NonEmptyString,+ pub(crate) transform: Transform,+ pub(crate) clip_path: Option<Arc<ClipPath>>,+ pub(crate) root: Group,+}++impl ClipPath {+ pub(crate) fn empty(id: NonEmptyString) -> Self {+ ClipPath {+ id,+ transform: Transform::default(),+ clip_path: None,+ root: Group::empty(),+ }+ }++ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Used only during SVG writing. `resvg` doesn't rely on this property.+ pub fn id(&self) -> &str {+ self.id.get()+ }++ /// Clip path transform.+ ///+ /// `transform` in SVG.+ pub fn transform(&self) -> Transform {+ self.transform+ }++ /// Additional clip path.+ ///+ /// `clip-path` in SVG.+ pub fn clip_path(&self) -> Option<&ClipPath> {+ self.clip_path.as_deref()+ }++ /// Clip path children.+ pub fn root(&self) -> &Group {+ &self.root+ }+}++/// A mask type.+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum MaskType {+ /// Indicates that the luminance values of the mask should be used.+ Luminance,+ /// Indicates that the alpha values of the mask should be used.+ Alpha,+}++impl Default for MaskType {+ fn default() -> Self {+ Self::Luminance+ }+}++/// A mask element.+///+/// `mask` element in SVG.+#[derive(Debug)]+pub struct Mask {+ pub(crate) id: NonEmptyString,+ pub(crate) rect: NonZeroRect,+ pub(crate) kind: MaskType,+ pub(crate) mask: Option<Arc<Mask>>,+ pub(crate) root: Group,+}++impl Mask {+ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Used only during SVG writing. `resvg` doesn't rely on this property.+ pub fn id(&self) -> &str {+ self.id.get()+ }++ /// Mask rectangle.+ ///+ /// `x`, `y`, `width` and `height` in SVG.+ pub fn rect(&self) -> NonZeroRect {+ self.rect+ }++ /// Mask type.+ ///+ /// `mask-type` in SVG.+ pub fn kind(&self) -> MaskType {+ self.kind+ }++ /// Additional mask.+ ///+ /// `mask` in SVG.+ pub fn mask(&self) -> Option<&Mask> {+ self.mask.as_deref()+ }++ /// Mask children.+ ///+ /// A mask can have no children, in which case the whole element should be masked out.+ pub fn root(&self) -> &Group {+ &self.root+ }+}++/// Node's kind.+#[allow(missing_docs)]+#[derive(Clone, Debug)]+pub enum Node {+ Group(Box<Group>),+ Path(Box<Path>),+ Image(Box<Image>),+ Text(Box<Text>),+}++impl Node {+ /// Returns node's ID.+ pub fn id(&self) -> &str {+ match self {+ Node::Group(e) => e.id.as_str(),+ Node::Path(e) => e.id.as_str(),+ Node::Image(e) => e.id.as_str(),+ Node::Text(e) => e.id.as_str(),+ }+ }++ /// Returns node's absolute transform.+ ///+ /// This method is cheap since absolute transforms are already resolved.+ pub fn abs_transform(&self) -> Transform {+ match self {+ Node::Group(group) => group.abs_transform(),+ Node::Path(path) => path.abs_transform(),+ Node::Image(image) => image.abs_transform(),+ Node::Text(text) => text.abs_transform(),+ }+ }++ /// Returns node's bounding box in object coordinates, if any.+ pub fn bounding_box(&self) -> Rect {+ match self {+ Node::Group(group) => group.bounding_box(),+ Node::Path(path) => path.bounding_box(),+ Node::Image(image) => image.bounding_box(),+ Node::Text(text) => text.bounding_box(),+ }+ }++ /// Returns node's bounding box in canvas coordinates, if any.+ pub fn abs_bounding_box(&self) -> Rect {+ match self {+ Node::Group(group) => group.abs_bounding_box(),+ Node::Path(path) => path.abs_bounding_box(),+ Node::Image(image) => image.abs_bounding_box(),+ Node::Text(text) => text.abs_bounding_box(),+ }+ }++ /// Returns node's bounding box, including stroke, in object coordinates, if any.+ pub fn stroke_bounding_box(&self) -> Rect {+ match self {+ Node::Group(group) => group.stroke_bounding_box(),+ Node::Path(path) => path.stroke_bounding_box(),+ // Image cannot be stroked.+ Node::Image(image) => image.bounding_box(),+ Node::Text(text) => text.stroke_bounding_box(),+ }+ }++ /// Returns node's bounding box, including stroke, in canvas coordinates, if any.+ pub fn abs_stroke_bounding_box(&self) -> Rect {+ match self {+ Node::Group(group) => group.abs_stroke_bounding_box(),+ Node::Path(path) => path.abs_stroke_bounding_box(),+ // Image cannot be stroked.+ Node::Image(image) => image.abs_bounding_box(),+ Node::Text(text) => text.abs_stroke_bounding_box(),+ }+ }++ /// Element's "layer" bounding box in canvas units, if any.+ ///+ /// For most nodes this is just `abs_bounding_box`,+ /// but for groups this is `abs_layer_bounding_box`.+ ///+ /// See [`Group::layer_bounding_box`] for details.+ pub fn abs_layer_bounding_box(&self) -> Option<NonZeroRect> {+ match self {+ Node::Group(group) => Some(group.abs_layer_bounding_box()),+ // Hor/ver path without stroke can return None. This is expected.+ Node::Path(path) => path.abs_bounding_box().to_non_zero_rect(),+ Node::Image(image) => image.abs_bounding_box().to_non_zero_rect(),+ Node::Text(text) => text.abs_bounding_box().to_non_zero_rect(),+ }+ }++ /// Calls a closure for each subroot this `Node` has.+ ///+ /// The [`Tree::root`](Tree::root) field contain only render-able SVG elements.+ /// But some elements, specifically clip paths, masks, patterns and feImage+ /// can store their own SVG subtrees.+ /// And while one can access them manually, it's pretty verbose.+ /// This methods allows looping over _all_ SVG elements present in the `Tree`.+ ///+ /// # Example+ ///+ /// ```no_run+ /// fn all_nodes(parent: &usvg::Group) {+ /// for node in parent.children() {+ /// // do stuff...+ ///+ /// if let usvg::Node::Group(g) = node {+ /// all_nodes(g);+ /// }+ ///+ /// // handle subroots as well+ /// node.subroots(|subroot| all_nodes(subroot));+ /// }+ /// }+ /// ```+ pub fn subroots<F: FnMut(&Group)>(&self, mut f: F) {+ match self {+ Node::Group(group) => group.subroots(&mut f),+ Node::Path(path) => path.subroots(&mut f),+ Node::Image(image) => image.subroots(&mut f),+ Node::Text(text) => text.subroots(&mut f),+ }+ }+}++/// A group container.+///+/// The preprocessor will remove all groups that don't impact rendering.+/// Those that left is just an indicator that a new canvas should be created.+///+/// `g` element in SVG.+#[derive(Clone, Debug)]+pub struct Group {+ pub(crate) id: String,+ pub(crate) transform: Transform,+ pub(crate) abs_transform: Transform,+ pub(crate) opacity: Opacity,+ pub(crate) blend_mode: BlendMode,+ pub(crate) isolate: bool,+ pub(crate) clip_path: Option<Arc<ClipPath>>,+ /// Whether the group is a context element (i.e. a use node)+ pub(crate) is_context_element: bool,+ pub(crate) mask: Option<Arc<Mask>>,+ pub(crate) filters: Vec<Arc<filter::Filter>>,+ pub(crate) bounding_box: Rect,+ pub(crate) abs_bounding_box: Rect,+ pub(crate) stroke_bounding_box: Rect,+ pub(crate) abs_stroke_bounding_box: Rect,+ pub(crate) layer_bounding_box: NonZeroRect,+ pub(crate) abs_layer_bounding_box: NonZeroRect,+ pub(crate) children: Vec<Node>,+}++impl Group {+ pub(crate) fn empty() -> Self {+ let dummy = Rect::from_xywh(0.0, 0.0, 0.0, 0.0).unwrap();+ Group {+ id: String::new(),+ transform: Transform::default(),+ abs_transform: Transform::default(),+ opacity: Opacity::ONE,+ blend_mode: BlendMode::Normal,+ isolate: false,+ clip_path: None,+ mask: None,+ filters: Vec::new(),+ is_context_element: false,+ bounding_box: dummy,+ abs_bounding_box: dummy,+ stroke_bounding_box: dummy,+ abs_stroke_bounding_box: dummy,+ layer_bounding_box: NonZeroRect::from_xywh(0.0, 0.0, 1.0, 1.0).unwrap(),+ abs_layer_bounding_box: NonZeroRect::from_xywh(0.0, 0.0, 1.0, 1.0).unwrap(),+ children: Vec::new(),+ }+ }++ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Isn't automatically generated.+ /// Can be empty.+ pub fn id(&self) -> &str {+ &self.id+ }++ /// Element's transform.+ ///+ /// This is a relative transform. The one that is set via the `transform` attribute in SVG.+ pub fn transform(&self) -> Transform {+ self.transform+ }++ /// Element's absolute transform.+ ///+ /// Contains all ancestors transforms including group's transform.+ ///+ /// Note that subroots, like clipPaths, masks and patterns, have their own root transform,+ /// which isn't affected by the node that references this subroot.+ pub fn abs_transform(&self) -> Transform {+ self.abs_transform+ }++ /// Group opacity.+ ///+ /// After the group is rendered we should combine+ /// it with a parent group using the specified opacity.+ pub fn opacity(&self) -> Opacity {+ self.opacity+ }++ /// Group blend mode.+ ///+ /// `mix-blend-mode` in SVG.+ pub fn blend_mode(&self) -> BlendMode {+ self.blend_mode+ }++ /// Group isolation.+ ///+ /// `isolation` in SVG.+ pub fn isolate(&self) -> bool {+ self.isolate+ }++ /// Element's clip path.+ pub fn clip_path(&self) -> Option<&ClipPath> {+ self.clip_path.as_deref()+ }++ /// Element's mask.+ pub fn mask(&self) -> Option<&Mask> {+ self.mask.as_deref()+ }++ /// Element's filters.+ pub fn filters(&self) -> &[Arc<filter::Filter>] {+ &self.filters+ }++ /// Element's object bounding box.+ ///+ /// `objectBoundingBox` in SVG terms. Meaning it doesn't affected by parent transforms.+ ///+ /// Can be set to `None` in case of an empty group.+ pub fn bounding_box(&self) -> Rect {+ self.bounding_box+ }++ /// Element's bounding box in canvas coordinates.+ ///+ /// `userSpaceOnUse` in SVG terms.+ pub fn abs_bounding_box(&self) -> Rect {+ self.abs_bounding_box+ }++ /// Element's object bounding box including stroke.+ ///+ /// Similar to `bounding_box`, but includes stroke.+ pub fn stroke_bounding_box(&self) -> Rect {+ self.stroke_bounding_box+ }++ /// Element's bounding box including stroke in user coordinates.+ ///+ /// Similar to `abs_bounding_box`, but includes stroke.+ pub fn abs_stroke_bounding_box(&self) -> Rect {+ self.abs_stroke_bounding_box+ }++ /// Element's "layer" bounding box in object units.+ ///+ /// Conceptually, this is `stroke_bounding_box` expanded and/or clipped+ /// by `filters_bounding_box`, but also including all the children.+ /// This is the bounding box `resvg` will later use to allocate layers/pixmaps+ /// during isolated groups rendering.+ ///+ /// Only groups have it, because only groups can have filters.+ /// For other nodes layer bounding box is the same as stroke bounding box.+ ///+ /// Unlike other bounding boxes, cannot have zero size.+ ///+ /// Returns 0x0x1x1 for empty groups.+ pub fn layer_bounding_box(&self) -> NonZeroRect {+ self.layer_bounding_box+ }++ /// Element's "layer" bounding box in canvas units.+ pub fn abs_layer_bounding_box(&self) -> NonZeroRect {+ self.abs_layer_bounding_box+ }++ /// Group's children.+ pub fn children(&self) -> &[Node] {+ &self.children+ }++ /// Checks if this group should be isolated during rendering.+ pub fn should_isolate(&self) -> bool {+ self.isolate+ || self.opacity != Opacity::ONE+ || self.clip_path.is_some()+ || self.mask.is_some()+ || !self.filters.is_empty()+ || self.blend_mode != BlendMode::Normal // TODO: probably not needed?+ }++ /// Returns `true` if the group has any children.+ pub fn has_children(&self) -> bool {+ !self.children.is_empty()+ }++ /// Calculates a node's filter bounding box.+ ///+ /// Filters with `objectBoundingBox` and missing or zero `bounding_box` would be ignored.+ ///+ /// Note that a filter region can act like a clipping rectangle,+ /// therefore this function can produce a bounding box smaller than `bounding_box`.+ ///+ /// Returns `None` when then group has no filters.+ ///+ /// This function is very fast, that's why we do not store this bbox as a `Group` field.+ pub fn filters_bounding_box(&self) -> Option<NonZeroRect> {+ let mut full_region = BBox::default();+ for filter in &self.filters {+ full_region = full_region.expand(filter.rect);+ }++ full_region.to_non_zero_rect()+ }++ fn subroots(&self, f: &mut dyn FnMut(&Group)) {+ if let Some(ref clip) = self.clip_path {+ f(&clip.root);++ if let Some(ref sub_clip) = clip.clip_path {+ f(&sub_clip.root);+ }+ }++ if let Some(ref mask) = self.mask {+ f(&mask.root);++ if let Some(ref sub_mask) = mask.mask {+ f(&sub_mask.root);+ }+ }++ for filter in &self.filters {+ for primitive in &filter.primitives {+ if let filter::Kind::Image(ref image) = primitive.kind {+ f(image.root());+ }+ }+ }+ }+}++/// Representation of the [`paint-order`] property.+///+/// `usvg` will handle `markers` automatically,+/// therefore we provide only `fill` and `stroke` variants.+///+/// [`paint-order`]: https://www.w3.org/TR/SVG2/painting.html#PaintOrder+#[derive(Clone, Copy, PartialEq, Debug)]+#[allow(missing_docs)]+pub enum PaintOrder {+ FillAndStroke,+ StrokeAndFill,+}++impl Default for PaintOrder {+ fn default() -> Self {+ Self::FillAndStroke+ }+}++/// A path element.+#[derive(Clone, Debug)]+pub struct Path {+ pub(crate) id: String,+ pub(crate) visible: bool,+ pub(crate) fill: Option<Fill>,+ pub(crate) stroke: Option<Stroke>,+ pub(crate) paint_order: PaintOrder,+ pub(crate) rendering_mode: ShapeRendering,+ pub(crate) data: Arc<tiny_skia_path::Path>,+ pub(crate) abs_transform: Transform,+ pub(crate) bounding_box: Rect,+ pub(crate) abs_bounding_box: Rect,+ pub(crate) stroke_bounding_box: Rect,+ pub(crate) abs_stroke_bounding_box: Rect,+}++impl Path {+ pub(crate) fn new_simple(data: Arc<tiny_skia_path::Path>) -> Option<Self> {+ Self::new(+ String::new(),+ true,+ None,+ None,+ PaintOrder::default(),+ ShapeRendering::default(),+ data,+ Transform::default(),+ )+ }++ pub(crate) fn new(+ id: String,+ visible: bool,+ fill: Option<Fill>,+ stroke: Option<Stroke>,+ paint_order: PaintOrder,+ rendering_mode: ShapeRendering,+ data: Arc<tiny_skia_path::Path>,+ abs_transform: Transform,+ ) -> Option<Self> {+ let bounding_box = data.compute_tight_bounds()?;+ let stroke_bounding_box =+ Path::calculate_stroke_bbox(stroke.as_ref(), &data).unwrap_or(bounding_box);++ let abs_bounding_box: Rect;+ let abs_stroke_bounding_box: Rect;+ if abs_transform.has_skew() {+ // TODO: avoid re-alloc+ let path2 = data.as_ref().clone();+ let path2 = path2.transform(abs_transform)?;+ abs_bounding_box = path2.compute_tight_bounds()?;+ abs_stroke_bounding_box =+ Path::calculate_stroke_bbox(stroke.as_ref(), &path2).unwrap_or(abs_bounding_box);+ } else {+ // A transform without a skew can be performed just on a bbox.+ abs_bounding_box = bounding_box.transform(abs_transform)?;+ abs_stroke_bounding_box = stroke_bounding_box.transform(abs_transform)?;+ }++ Some(Path {+ id,+ visible,+ fill,+ stroke,+ paint_order,+ rendering_mode,+ data,+ abs_transform,+ bounding_box,+ abs_bounding_box,+ stroke_bounding_box,+ abs_stroke_bounding_box,+ })+ }++ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Isn't automatically generated.+ /// Can be empty.+ pub fn id(&self) -> &str {+ &self.id+ }++ /// Element visibility.+ pub fn is_visible(&self) -> bool {+ self.visible+ }++ /// Fill style.+ pub fn fill(&self) -> Option<&Fill> {+ self.fill.as_ref()+ }++ /// Stroke style.+ pub fn stroke(&self) -> Option<&Stroke> {+ self.stroke.as_ref()+ }++ /// Fill and stroke paint order.+ ///+ /// Since markers will be replaced with regular nodes automatically,+ /// `usvg` doesn't provide the `markers` order type. It's was already done.+ ///+ /// `paint-order` in SVG.+ pub fn paint_order(&self) -> PaintOrder {+ self.paint_order+ }++ /// Rendering mode.+ ///+ /// `shape-rendering` in SVG.+ pub fn rendering_mode(&self) -> ShapeRendering {+ self.rendering_mode+ }++ // TODO: find a better name+ /// Segments list.+ ///+ /// All segments are in absolute coordinates.+ pub fn data(&self) -> &tiny_skia_path::Path {+ self.data.as_ref()+ }++ /// Element's absolute transform.+ ///+ /// Contains all ancestors transforms including elements's transform.+ ///+ /// Note that this is not the relative transform present in SVG.+ /// The SVG one would be set only on groups.+ pub fn abs_transform(&self) -> Transform {+ self.abs_transform+ }++ /// Element's object bounding box.+ ///+ /// `objectBoundingBox` in SVG terms. Meaning it doesn't affected by parent transforms.+ pub fn bounding_box(&self) -> Rect {+ self.bounding_box+ }++ /// Element's bounding box in canvas coordinates.+ ///+ /// `userSpaceOnUse` in SVG terms.+ pub fn abs_bounding_box(&self) -> Rect {+ self.abs_bounding_box+ }++ /// Element's object bounding box including stroke.+ ///+ /// Will have the same value as `bounding_box` when path has no stroke.+ pub fn stroke_bounding_box(&self) -> Rect {+ self.stroke_bounding_box+ }++ /// Element's bounding box including stroke in canvas coordinates.+ ///+ /// Will have the same value as `abs_bounding_box` when path has no stroke.+ pub fn abs_stroke_bounding_box(&self) -> Rect {+ self.abs_stroke_bounding_box+ }++ fn calculate_stroke_bbox(stroke: Option<&Stroke>, path: &tiny_skia_path::Path) -> Option<Rect> {+ let mut stroke = stroke?.to_tiny_skia();+ // According to the spec, dash should not be accounted during bbox calculation.+ stroke.dash = None;++ // TODO: avoid for round and bevel caps++ // Expensive, but there is not much we can do about it.+ if let Some(stroked_path) = path.stroke(&stroke, 1.0) {+ return stroked_path.compute_tight_bounds();+ }++ None+ }++ fn subroots(&self, f: &mut dyn FnMut(&Group)) {+ if let Some(Paint::Pattern(patt)) = self.fill.as_ref().map(|f| &f.paint) {+ f(patt.root());+ }+ if let Some(Paint::Pattern(patt)) = self.stroke.as_ref().map(|f| &f.paint) {+ f(patt.root());+ }+ }+}++/// An embedded image kind.+#[derive(Clone)]+pub enum ImageKind {+ /// A reference to raw JPEG data. Should be decoded by the caller.+ JPEG(Arc<Vec<u8>>),+ /// A reference to raw PNG data. Should be decoded by the caller.+ PNG(Arc<Vec<u8>>),+ /// A reference to raw GIF data. Should be decoded by the caller.+ GIF(Arc<Vec<u8>>),+ /// A reference to raw WebP data. Should be decoded by the caller.+ WEBP(Arc<Vec<u8>>),+ /// A preprocessed SVG tree. Can be rendered as is.+ SVG(Tree),+}++impl ImageKind {+ pub(crate) fn actual_size(&self) -> Option<Size> {+ match self {+ ImageKind::JPEG(data)+ | ImageKind::PNG(data)+ | ImageKind::GIF(data)+ | ImageKind::WEBP(data) => imagesize::blob_size(data)+ .ok()+ .and_then(|size| Size::from_wh(size.width as f32, size.height as f32))+ .log_none(|| log::warn!("Image has an invalid size. Skipped.")),+ ImageKind::SVG(svg) => Some(svg.size),+ }+ }+}++impl std::fmt::Debug for ImageKind {+ fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ match self {+ ImageKind::JPEG(_) => f.write_str("ImageKind::JPEG(..)"),+ ImageKind::PNG(_) => f.write_str("ImageKind::PNG(..)"),+ ImageKind::GIF(_) => f.write_str("ImageKind::GIF(..)"),+ ImageKind::WEBP(_) => f.write_str("ImageKind::WEBP(..)"),+ ImageKind::SVG(_) => f.write_str("ImageKind::SVG(..)"),+ }+ }+}++/// A raster image element.+///+/// `image` element in SVG.+#[derive(Clone, Debug)]+pub struct Image {+ pub(crate) id: String,+ pub(crate) visible: bool,+ pub(crate) size: Size,+ pub(crate) rendering_mode: ImageRendering,+ pub(crate) kind: ImageKind,+ pub(crate) abs_transform: Transform,+ pub(crate) abs_bounding_box: NonZeroRect,+}++impl Image {+ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Isn't automatically generated.+ /// Can be empty.+ pub fn id(&self) -> &str {+ &self.id+ }++ /// Element visibility.+ pub fn is_visible(&self) -> bool {+ self.visible+ }++ /// The actual image size.+ ///+ /// This is not `width` and `height` attributes,+ /// but rather the actual PNG/JPEG/GIF/SVG image size.+ pub fn size(&self) -> Size {+ self.size+ }++ /// Rendering mode.+ ///+ /// `image-rendering` in SVG.+ pub fn rendering_mode(&self) -> ImageRendering {+ self.rendering_mode+ }++ /// Image data.+ pub fn kind(&self) -> &ImageKind {+ &self.kind+ }++ /// Element's absolute transform.+ ///+ /// Contains all ancestors transforms including elements's transform.+ ///+ /// Note that this is not the relative transform present in SVG.+ /// The SVG one would be set only on groups.+ pub fn abs_transform(&self) -> Transform {+ self.abs_transform+ }++ /// Element's object bounding box.+ ///+ /// `objectBoundingBox` in SVG terms. Meaning it doesn't affected by parent transforms.+ pub fn bounding_box(&self) -> Rect {+ self.size.to_rect(0.0, 0.0).unwrap()+ }++ /// Element's bounding box in canvas coordinates.+ ///+ /// `userSpaceOnUse` in SVG terms.+ pub fn abs_bounding_box(&self) -> Rect {+ self.abs_bounding_box.to_rect()+ }++ fn subroots(&self, f: &mut dyn FnMut(&Group)) {+ if let ImageKind::SVG(ref tree) = self.kind {+ f(&tree.root);+ }+ }+}++/// A nodes tree container.+#[allow(missing_debug_implementations)]+#[derive(Clone, Debug)]+pub struct Tree {+ pub(crate) size: Size,+ pub(crate) root: Group,+ pub(crate) linear_gradients: Vec<Arc<LinearGradient>>,+ pub(crate) radial_gradients: Vec<Arc<RadialGradient>>,+ pub(crate) patterns: Vec<Arc<Pattern>>,+ pub(crate) clip_paths: Vec<Arc<ClipPath>>,+ pub(crate) masks: Vec<Arc<Mask>>,+ pub(crate) filters: Vec<Arc<filter::Filter>>,+ #[cfg(feature = "text")]+ pub(crate) fontdb: Arc<fontdb::Database>,+}++impl Tree {+ /// Image size.+ ///+ /// Size of an image that should be created to fit the SVG.+ ///+ /// `width` and `height` in SVG.+ ///+ /// Note that this does not necessarily represent the bounding box of the+ /// rendered contents. Use+ /// [`self.root().abs_layer_bounding_box()`](Group::abs_layer_bounding_box)+ /// to retrieve it instead.+ pub fn size(&self) -> Size {+ self.size+ }++ /// The root element of the SVG tree.+ pub fn root(&self) -> &Group {+ &self.root+ }++ /// Returns a renderable node by ID.+ ///+ /// If an empty ID is provided, than this method will always return `None`.+ pub fn node_by_id(&self, id: &str) -> Option<&Node> {+ if id.is_empty() {+ return None;+ }++ node_by_id(&self.root, id)+ }++ /// Checks if the current tree has any text nodes.+ pub fn has_text_nodes(&self) -> bool {+ has_text_nodes(&self.root)+ }++ /// Checks if the current tree has any `defs` nodes.+ pub fn has_defs_nodes(&self) -> bool {+ !self.linear_gradients().is_empty()+ || !self.radial_gradients().is_empty()+ || !self.patterns().is_empty()+ || !self.filters().is_empty()+ || !self.clip_paths().is_empty()+ || !self.masks().is_empty()+ }++ /// Returns a list of all unique [`LinearGradient`]s in the tree.+ pub fn linear_gradients(&self) -> &[Arc<LinearGradient>] {+ &self.linear_gradients+ }++ /// Returns a list of all unique [`RadialGradient`]s in the tree.+ pub fn radial_gradients(&self) -> &[Arc<RadialGradient>] {+ &self.radial_gradients+ }++ /// Returns a list of all unique [`Pattern`]s in the tree.+ pub fn patterns(&self) -> &[Arc<Pattern>] {+ &self.patterns+ }++ /// Returns a list of all unique [`ClipPath`]s in the tree.+ pub fn clip_paths(&self) -> &[Arc<ClipPath>] {+ &self.clip_paths+ }++ /// Returns a list of all unique [`Mask`]s in the tree.+ pub fn masks(&self) -> &[Arc<Mask>] {+ &self.masks+ }++ /// Returns a list of all unique [`Filter`](filter::Filter)s in the tree.+ pub fn filters(&self) -> &[Arc<filter::Filter>] {+ &self.filters+ }++ /// Returns the font database that applies to all text nodes in the tree.+ #[cfg(feature = "text")]+ pub fn fontdb(&self) -> &Arc<fontdb::Database> {+ &self.fontdb+ }++ pub(crate) fn collect_paint_servers(&mut self) {+ loop_over_paint_servers(&self.root, &mut |paint| match paint {+ Paint::Color(_) => {}+ Paint::LinearGradient(lg) => {+ if !self+ .linear_gradients+ .iter()+ .any(|other| Arc::ptr_eq(lg, other))+ {+ self.linear_gradients.push(lg.clone());+ }+ }+ Paint::RadialGradient(rg) => {+ if !self+ .radial_gradients+ .iter()+ .any(|other| Arc::ptr_eq(rg, other))+ {+ self.radial_gradients.push(rg.clone());+ }+ }+ Paint::Pattern(patt) => {+ if !self.patterns.iter().any(|other| Arc::ptr_eq(patt, other)) {+ self.patterns.push(patt.clone());+ }+ }+ });+ }+}++fn node_by_id<'a>(parent: &'a Group, id: &str) -> Option<&'a Node> {+ for child in &parent.children {+ if child.id() == id {+ return Some(child);+ }++ if let Node::Group(g) = child {+ if let Some(n) = node_by_id(g, id) {+ return Some(n);+ }+ }+ }++ None+}++fn has_text_nodes(root: &Group) -> bool {+ for node in &root.children {+ if let Node::Text(_) = node {+ return true;+ }++ let mut has_text = false;++ if let Node::Image(image) = node {+ if let ImageKind::SVG(tree) = &image.kind {+ if has_text_nodes(&tree.root) {+ has_text = true;+ }+ }+ }++ node.subroots(|subroot| has_text |= has_text_nodes(subroot));++ if has_text {+ return true;+ }+ }++ false+}++fn loop_over_paint_servers(parent: &Group, f: &mut dyn FnMut(&Paint)) {+ fn push(paint: Option<&Paint>, f: &mut dyn FnMut(&Paint)) {+ if let Some(paint) = paint {+ f(paint);+ }+ }++ for node in &parent.children {+ match node {+ Node::Group(group) => loop_over_paint_servers(group, f),+ Node::Path(path) => {+ push(path.fill.as_ref().map(|f| &f.paint), f);+ push(path.stroke.as_ref().map(|f| &f.paint), f);+ }+ Node::Image(_) => {}+ // Flattened text would be used instead.+ Node::Text(_) => {}+ }++ node.subroots(|subroot| loop_over_paint_servers(subroot, f));+ }+}++impl Group {+ pub(crate) fn collect_clip_paths(&self, clip_paths: &mut Vec<Arc<ClipPath>>) {+ for node in self.children() {+ if let Node::Group(g) = node {+ if let Some(clip) = &g.clip_path {+ if !clip_paths.iter().any(|other| Arc::ptr_eq(clip, other)) {+ clip_paths.push(clip.clone());+ }++ if let Some(sub_clip) = &clip.clip_path {+ if !clip_paths.iter().any(|other| Arc::ptr_eq(sub_clip, other)) {+ clip_paths.push(sub_clip.clone());+ }+ }+ }+ }++ node.subroots(|subroot| subroot.collect_clip_paths(clip_paths));++ if let Node::Group(g) = node {+ g.collect_clip_paths(clip_paths);+ }+ }+ }++ pub(crate) fn collect_masks(&self, masks: &mut Vec<Arc<Mask>>) {+ for node in self.children() {+ if let Node::Group(g) = node {+ if let Some(mask) = &g.mask {+ if !masks.iter().any(|other| Arc::ptr_eq(mask, other)) {+ masks.push(mask.clone());+ }++ if let Some(sub_mask) = &mask.mask {+ if !masks.iter().any(|other| Arc::ptr_eq(sub_mask, other)) {+ masks.push(sub_mask.clone());+ }+ }+ }+ }++ node.subroots(|subroot| subroot.collect_masks(masks));++ if let Node::Group(g) = node {+ g.collect_masks(masks);+ }+ }+ }++ pub(crate) fn collect_filters(&self, filters: &mut Vec<Arc<filter::Filter>>) {+ for node in self.children() {+ if let Node::Group(g) = node {+ for filter in g.filters() {+ if !filters.iter().any(|other| Arc::ptr_eq(filter, other)) {+ filters.push(filter.clone());+ }+ }+ }++ node.subroots(|subroot| subroot.collect_filters(filters));++ if let Node::Group(g) = node {+ g.collect_filters(filters);+ }+ }+ }++ pub(crate) fn calculate_object_bbox(&mut self) -> Option<NonZeroRect> {+ let mut bbox = BBox::default();+ for child in &self.children {+ let mut c_bbox = child.bounding_box();+ if let Node::Group(group) = child {+ if let Some(r) = c_bbox.transform(group.transform) {+ c_bbox = r;+ }+ }++ bbox = bbox.expand(c_bbox);+ }++ bbox.to_non_zero_rect()+ }++ pub(crate) fn calculate_bounding_boxes(&mut self) -> Option<()> {+ let mut bbox = BBox::default();+ let mut abs_bbox = BBox::default();+ let mut stroke_bbox = BBox::default();+ let mut abs_stroke_bbox = BBox::default();+ let mut layer_bbox = BBox::default();+ for child in &self.children {+ {+ let mut c_bbox = child.bounding_box();+ if let Node::Group(group) = child {+ if let Some(r) = c_bbox.transform(group.transform) {+ c_bbox = r;+ }+ }++ bbox = bbox.expand(c_bbox);+ }++ abs_bbox = abs_bbox.expand(child.abs_bounding_box());++ {+ let mut c_bbox = child.stroke_bounding_box();+ if let Node::Group(group) = child {+ if let Some(r) = c_bbox.transform(group.transform) {+ c_bbox = r;+ }+ }++ stroke_bbox = stroke_bbox.expand(c_bbox);+ }++ abs_stroke_bbox = abs_stroke_bbox.expand(child.abs_stroke_bounding_box());++ if let Node::Group(group) = child {+ let r = group.layer_bounding_box;+ if let Some(r) = r.transform(group.transform) {+ layer_bbox = layer_bbox.expand(r);+ }+ } else {+ // Not a group - no need to transform.+ layer_bbox = layer_bbox.expand(child.stroke_bounding_box());+ }+ }++ // `bbox` can be None for empty groups, but we still have to+ // calculate `layer_bounding_box after` it.+ if let Some(bbox) = bbox.to_rect() {+ self.bounding_box = bbox;+ self.abs_bounding_box = abs_bbox.to_rect()?;+ self.stroke_bounding_box = stroke_bbox.to_rect()?;+ self.abs_stroke_bounding_box = abs_stroke_bbox.to_rect()?;+ }++ // Filter bbox has a higher priority than layers bbox.+ if let Some(filter_bbox) = self.filters_bounding_box() {+ self.layer_bounding_box = filter_bbox;+ } else {+ self.layer_bounding_box = layer_bbox.to_non_zero_rect()?;+ }++ self.abs_layer_bounding_box = self.layer_bounding_box.transform(self.abs_transform)?;++ Some(())+ }+}diff --git a/vendor/usvg/src/tree/text.rs b/vendor/usvg/src/tree/text.rsnew file mode 100644index 00000000..c1739b90--- /dev/null+++ b/vendor/usvg/src/tree/text.rs@@ -0,0 +1,721 @@+// Copyright 2018 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::sync::Arc;++use strict_num::NonZeroPositiveF32;+pub use svgtypes::FontFamily;++#[cfg(feature = "text")]+use crate::layout::Span;+use crate::{Fill, Group, NonEmptyString, PaintOrder, Rect, Stroke, TextRendering, Transform};++/// A font stretch property.+#[allow(missing_docs)]+#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]+pub enum FontStretch {+ UltraCondensed,+ ExtraCondensed,+ Condensed,+ SemiCondensed,+ Normal,+ SemiExpanded,+ Expanded,+ ExtraExpanded,+ UltraExpanded,+}++impl Default for FontStretch {+ #[inline]+ fn default() -> Self {+ Self::Normal+ }+}++#[cfg(feature = "text")]+impl From<fontdb::Stretch> for FontStretch {+ fn from(stretch: fontdb::Stretch) -> Self {+ match stretch {+ fontdb::Stretch::UltraCondensed => FontStretch::UltraCondensed,+ fontdb::Stretch::ExtraCondensed => FontStretch::ExtraCondensed,+ fontdb::Stretch::Condensed => FontStretch::Condensed,+ fontdb::Stretch::SemiCondensed => FontStretch::SemiCondensed,+ fontdb::Stretch::Normal => FontStretch::Normal,+ fontdb::Stretch::SemiExpanded => FontStretch::SemiExpanded,+ fontdb::Stretch::Expanded => FontStretch::Expanded,+ fontdb::Stretch::ExtraExpanded => FontStretch::ExtraExpanded,+ fontdb::Stretch::UltraExpanded => FontStretch::UltraExpanded,+ }+ }+}++#[cfg(feature = "text")]+impl From<FontStretch> for fontdb::Stretch {+ fn from(stretch: FontStretch) -> Self {+ match stretch {+ FontStretch::UltraCondensed => fontdb::Stretch::UltraCondensed,+ FontStretch::ExtraCondensed => fontdb::Stretch::ExtraCondensed,+ FontStretch::Condensed => fontdb::Stretch::Condensed,+ FontStretch::SemiCondensed => fontdb::Stretch::SemiCondensed,+ FontStretch::Normal => fontdb::Stretch::Normal,+ FontStretch::SemiExpanded => fontdb::Stretch::SemiExpanded,+ FontStretch::Expanded => fontdb::Stretch::Expanded,+ FontStretch::ExtraExpanded => fontdb::Stretch::ExtraExpanded,+ FontStretch::UltraExpanded => fontdb::Stretch::UltraExpanded,+ }+ }+}++/// A font variation axis setting.+///+/// Used for variable fonts to specify axis values like weight, width, etc.+#[derive(Clone, Copy, Debug)]+pub struct FontVariation {+ /// The 4-byte axis tag (e.g., b"wght" for weight).+ pub tag: [u8; 4],+ /// The axis value.+ pub value: f32,+}++impl FontVariation {+ /// Creates a new font variation.+ pub fn new(tag: [u8; 4], value: f32) -> Self {+ Self { tag, value }+ }+}++impl PartialEq for FontVariation {+ fn eq(&self, other: &Self) -> bool {+ self.tag == other.tag && self.value.to_bits() == other.value.to_bits()+ }+}++impl Eq for FontVariation {}++impl std::hash::Hash for FontVariation {+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {+ self.tag.hash(state);+ self.value.to_bits().hash(state);+ }+}++/// A font style property.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]+pub enum FontStyle {+ /// A face that is neither italic not obliqued.+ Normal,+ /// A form that is generally cursive in nature.+ Italic,+ /// A typically-sloped version of the regular face.+ Oblique,+}++impl Default for FontStyle {+ #[inline]+ fn default() -> FontStyle {+ Self::Normal+ }+}++#[cfg(feature = "text")]+impl From<fontdb::Style> for FontStyle {+ fn from(style: fontdb::Style) -> Self {+ match style {+ fontdb::Style::Normal => FontStyle::Normal,+ fontdb::Style::Italic => FontStyle::Italic,+ fontdb::Style::Oblique => FontStyle::Oblique,+ }+ }+}++#[cfg(feature = "text")]+impl From<FontStyle> for fontdb::Style {+ fn from(style: FontStyle) -> Self {+ match style {+ FontStyle::Normal => fontdb::Style::Normal,+ FontStyle::Italic => fontdb::Style::Italic,+ FontStyle::Oblique => fontdb::Style::Oblique,+ }+ }+}++/// Text font properties.+#[derive(Clone, Eq, PartialEq, Hash, Debug)]+pub struct Font {+ pub(crate) families: Vec<FontFamily>,+ pub(crate) style: FontStyle,+ pub(crate) stretch: FontStretch,+ pub(crate) weight: u16,+ pub(crate) variations: Vec<FontVariation>,+}++impl Font {+ /// A list of family names.+ ///+ /// Never empty. Uses `usvg::Options::font_family` as fallback.+ pub fn families(&self) -> &[FontFamily] {+ &self.families+ }++ /// A font style.+ pub fn style(&self) -> FontStyle {+ self.style+ }++ /// A font stretch.+ pub fn stretch(&self) -> FontStretch {+ self.stretch+ }++ /// A font width.+ pub fn weight(&self) -> u16 {+ self.weight+ }++ /// Font variation settings for variable fonts.+ pub fn variations(&self) -> &[FontVariation] {+ &self.variations+ }+}++/// A dominant baseline property.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum DominantBaseline {+ Auto,+ UseScript,+ NoChange,+ ResetSize,+ Ideographic,+ Alphabetic,+ Hanging,+ Mathematical,+ Central,+ Middle,+ TextAfterEdge,+ TextBeforeEdge,+}++impl Default for DominantBaseline {+ fn default() -> Self {+ Self::Auto+ }+}++/// An alignment baseline property.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum AlignmentBaseline {+ Auto,+ Baseline,+ BeforeEdge,+ TextBeforeEdge,+ Middle,+ Central,+ AfterEdge,+ TextAfterEdge,+ Ideographic,+ Alphabetic,+ Hanging,+ Mathematical,+}++impl Default for AlignmentBaseline {+ fn default() -> Self {+ Self::Auto+ }+}++/// A baseline shift property.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum BaselineShift {+ Baseline,+ Subscript,+ Superscript,+ Number(f32),+}++impl Default for BaselineShift {+ #[inline]+ fn default() -> BaselineShift {+ BaselineShift::Baseline+ }+}++/// A length adjust property.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum LengthAdjust {+ Spacing,+ SpacingAndGlyphs,+}++impl Default for LengthAdjust {+ fn default() -> Self {+ Self::Spacing+ }+}++/// A font optical sizing property.+///+/// Controls automatic adjustment of the `opsz` axis in variable fonts+/// based on font size. Matches CSS `font-optical-sizing`.+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum FontOpticalSizing {+ /// Automatically set `opsz` to match font size (browser default).+ Auto,+ /// Do not automatically adjust `opsz`.+ None,+}++impl Default for FontOpticalSizing {+ fn default() -> Self {+ Self::Auto+ }+}++/// A text span decoration style.+///+/// In SVG, text decoration and text it's applied to can have different styles.+/// So you can have black text and green underline.+///+/// Also, in SVG you can specify text decoration stroking.+#[derive(Clone, Debug)]+pub struct TextDecorationStyle {+ pub(crate) fill: Option<Fill>,+ pub(crate) stroke: Option<Stroke>,+}++impl TextDecorationStyle {+ /// A fill style.+ pub fn fill(&self) -> Option<&Fill> {+ self.fill.as_ref()+ }++ /// A stroke style.+ pub fn stroke(&self) -> Option<&Stroke> {+ self.stroke.as_ref()+ }+}++/// A text span decoration.+#[derive(Clone, Debug)]+pub struct TextDecoration {+ pub(crate) underline: Option<TextDecorationStyle>,+ pub(crate) overline: Option<TextDecorationStyle>,+ pub(crate) line_through: Option<TextDecorationStyle>,+}++impl TextDecoration {+ /// An optional underline and its style.+ pub fn underline(&self) -> Option<&TextDecorationStyle> {+ self.underline.as_ref()+ }++ /// An optional overline and its style.+ pub fn overline(&self) -> Option<&TextDecorationStyle> {+ self.overline.as_ref()+ }++ /// An optional line-through and its style.+ pub fn line_through(&self) -> Option<&TextDecorationStyle> {+ self.line_through.as_ref()+ }+}++/// A text style span.+///+/// Spans do not overlap inside a text chunk.+#[derive(Clone, Debug)]+pub struct TextSpan {+ pub(crate) start: usize,+ pub(crate) end: usize,+ pub(crate) fill: Option<Fill>,+ pub(crate) stroke: Option<Stroke>,+ pub(crate) paint_order: PaintOrder,+ pub(crate) font: Font,+ pub(crate) font_size: NonZeroPositiveF32,+ pub(crate) small_caps: bool,+ pub(crate) apply_kerning: bool,+ pub(crate) font_optical_sizing: FontOpticalSizing,+ pub(crate) decoration: TextDecoration,+ pub(crate) dominant_baseline: DominantBaseline,+ pub(crate) alignment_baseline: AlignmentBaseline,+ pub(crate) baseline_shift: Vec<BaselineShift>,+ pub(crate) visible: bool,+ pub(crate) letter_spacing: f32,+ pub(crate) word_spacing: f32,+ pub(crate) text_length: Option<f32>,+ pub(crate) length_adjust: LengthAdjust,+}++impl TextSpan {+ /// A span start in bytes.+ ///+ /// Offset is relative to the parent text chunk and not the parent text element.+ pub fn start(&self) -> usize {+ self.start+ }++ /// A span end in bytes.+ ///+ /// Offset is relative to the parent text chunk and not the parent text element.+ pub fn end(&self) -> usize {+ self.end+ }++ /// A fill style.+ pub fn fill(&self) -> Option<&Fill> {+ self.fill.as_ref()+ }++ /// A stroke style.+ pub fn stroke(&self) -> Option<&Stroke> {+ self.stroke.as_ref()+ }++ /// A paint order style.+ pub fn paint_order(&self) -> PaintOrder {+ self.paint_order+ }++ /// A font.+ pub fn font(&self) -> &Font {+ &self.font+ }++ /// A font size.+ pub fn font_size(&self) -> NonZeroPositiveF32 {+ self.font_size+ }++ /// Indicates that small caps should be used.+ ///+ /// Set by `font-variant="small-caps"`+ pub fn small_caps(&self) -> bool {+ self.small_caps+ }++ /// Indicates that a kerning should be applied.+ ///+ /// Supports both `kerning` and `font-kerning` properties.+ pub fn apply_kerning(&self) -> bool {+ self.apply_kerning+ }++ /// Font optical sizing mode.+ ///+ /// When `Auto` (default), the `opsz` axis will be automatically set+ /// to match the font size for variable fonts that support it.+ /// This matches the CSS `font-optical-sizing: auto` behavior.+ pub fn font_optical_sizing(&self) -> FontOpticalSizing {+ self.font_optical_sizing+ }++ /// A span decorations.+ pub fn decoration(&self) -> &TextDecoration {+ &self.decoration+ }++ /// A span dominant baseline.+ pub fn dominant_baseline(&self) -> DominantBaseline {+ self.dominant_baseline+ }++ /// A span alignment baseline.+ pub fn alignment_baseline(&self) -> AlignmentBaseline {+ self.alignment_baseline+ }++ /// A list of all baseline shift that should be applied to this span.+ ///+ /// Ordered from `text` element down to the actual `span` element.+ pub fn baseline_shift(&self) -> &[BaselineShift] {+ &self.baseline_shift+ }++ /// A visibility property.+ pub fn is_visible(&self) -> bool {+ self.visible+ }++ /// A letter spacing property.+ pub fn letter_spacing(&self) -> f32 {+ self.letter_spacing+ }++ /// A word spacing property.+ pub fn word_spacing(&self) -> f32 {+ self.word_spacing+ }++ /// A text length property.+ pub fn text_length(&self) -> Option<f32> {+ self.text_length+ }++ /// A length adjust property.+ pub fn length_adjust(&self) -> LengthAdjust {+ self.length_adjust+ }+}++/// A text chunk anchor property.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum TextAnchor {+ Start,+ Middle,+ End,+}++impl Default for TextAnchor {+ fn default() -> Self {+ Self::Start+ }+}++/// A path used by text-on-path.+#[derive(Debug)]+pub struct TextPath {+ pub(crate) id: NonEmptyString,+ pub(crate) start_offset: f32,+ pub(crate) path: Arc<tiny_skia_path::Path>,+}++impl TextPath {+ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ pub fn id(&self) -> &str {+ self.id.get()+ }++ /// A text offset in SVG coordinates.+ ///+ /// Percentage values already resolved.+ pub fn start_offset(&self) -> f32 {+ self.start_offset+ }++ /// A path.+ pub fn path(&self) -> &tiny_skia_path::Path {+ &self.path+ }+}++/// A text chunk flow property.+#[derive(Clone, Debug)]+pub enum TextFlow {+ /// A linear layout.+ ///+ /// Includes left-to-right, right-to-left and top-to-bottom.+ Linear,+ /// A text-on-path layout.+ Path(Arc<TextPath>),+}++/// A text chunk.+///+/// Text alignment and BIDI reordering can only be done inside a text chunk.+#[derive(Clone, Debug)]+pub struct TextChunk {+ pub(crate) x: Option<f32>,+ pub(crate) y: Option<f32>,+ pub(crate) anchor: TextAnchor,+ pub(crate) spans: Vec<TextSpan>,+ pub(crate) text_flow: TextFlow,+ pub(crate) text: String,+}++impl TextChunk {+ /// An absolute X axis offset.+ pub fn x(&self) -> Option<f32> {+ self.x+ }++ /// An absolute Y axis offset.+ pub fn y(&self) -> Option<f32> {+ self.y+ }++ /// A text anchor.+ pub fn anchor(&self) -> TextAnchor {+ self.anchor+ }++ /// A list of text chunk style spans.+ pub fn spans(&self) -> &[TextSpan] {+ &self.spans+ }++ /// A text chunk flow.+ pub fn text_flow(&self) -> TextFlow {+ self.text_flow.clone()+ }++ /// A text chunk actual text.+ pub fn text(&self) -> &str {+ &self.text+ }+}++/// A writing mode.+#[allow(missing_docs)]+#[derive(Clone, Copy, PartialEq, Debug)]+pub enum WritingMode {+ LeftToRight,+ TopToBottom,+}++/// A text element.+///+/// `text` element in SVG.+#[derive(Clone, Debug)]+pub struct Text {+ pub(crate) id: String,+ pub(crate) rendering_mode: TextRendering,+ pub(crate) dx: Vec<f32>,+ pub(crate) dy: Vec<f32>,+ pub(crate) rotate: Vec<f32>,+ pub(crate) writing_mode: WritingMode,+ pub(crate) chunks: Vec<TextChunk>,+ pub(crate) abs_transform: Transform,+ pub(crate) bounding_box: Rect,+ pub(crate) abs_bounding_box: Rect,+ pub(crate) stroke_bounding_box: Rect,+ pub(crate) abs_stroke_bounding_box: Rect,+ pub(crate) flattened: Box<Group>,+ #[cfg(feature = "text")]+ pub(crate) layouted: Vec<Span>,+}++impl Text {+ /// Element's ID.+ ///+ /// Taken from the SVG itself.+ /// Isn't automatically generated.+ /// Can be empty.+ pub fn id(&self) -> &str {+ &self.id+ }++ /// Rendering mode.+ ///+ /// `text-rendering` in SVG.+ pub fn rendering_mode(&self) -> TextRendering {+ self.rendering_mode+ }++ /// A relative X axis offsets.+ ///+ /// One offset for each Unicode codepoint. Aka `char` in Rust.+ pub fn dx(&self) -> &[f32] {+ &self.dx+ }++ /// A relative Y axis offsets.+ ///+ /// One offset for each Unicode codepoint. Aka `char` in Rust.+ pub fn dy(&self) -> &[f32] {+ &self.dy+ }++ /// A list of rotation angles.+ ///+ /// One angle for each Unicode codepoint. Aka `char` in Rust.+ pub fn rotate(&self) -> &[f32] {+ &self.rotate+ }++ /// A writing mode.+ pub fn writing_mode(&self) -> WritingMode {+ self.writing_mode+ }++ /// A list of text chunks.+ pub fn chunks(&self) -> &[TextChunk] {+ &self.chunks+ }++ /// Element's absolute transform.+ ///+ /// Contains all ancestors transforms including elements's transform.+ ///+ /// Note that this is not the relative transform present in SVG.+ /// The SVG one would be set only on groups.+ pub fn abs_transform(&self) -> Transform {+ self.abs_transform+ }++ /// Element's text bounding box.+ ///+ /// Text bounding box is special in SVG and doesn't represent+ /// tight bounds of the element's content.+ /// You can find more about it+ /// [here](https://razrfalcon.github.io/notes-on-svg-parsing/text/bbox.html).+ ///+ /// `objectBoundingBox` in SVG terms. Meaning it isn't affected by parent transforms.+ ///+ /// Returns `None` when the `text` build feature was disabled.+ /// This is because we have to perform a text layout before calculating a bounding box.+ pub fn bounding_box(&self) -> Rect {+ self.bounding_box+ }++ /// Element's text bounding box in canvas coordinates.+ ///+ /// `userSpaceOnUse` in SVG terms.+ pub fn abs_bounding_box(&self) -> Rect {+ self.abs_bounding_box+ }++ /// Element's object bounding box including stroke.+ ///+ /// Similar to `bounding_box`, but includes stroke.+ ///+ /// Will have the same value as `bounding_box` when path has no stroke.+ pub fn stroke_bounding_box(&self) -> Rect {+ self.stroke_bounding_box+ }++ /// Element's bounding box including stroke in canvas coordinates.+ pub fn abs_stroke_bounding_box(&self) -> Rect {+ self.abs_stroke_bounding_box+ }++ /// Text converted into paths, ready to render.+ ///+ /// Note that this is only a+ /// "best-effort" attempt: The text will be converted into group/paths/image+ /// primitives, so that they can be rendered with the existing infrastructure.+ /// This process is in general lossless and should lead to correct output, with+ /// two notable exceptions:+ /// 1. For glyphs based on the `SVG` table, only glyphs that are pure SVG 1.1/2.0+ /// are supported. Glyphs that make use of features in the OpenType specification+ /// that are not part of the original SVG specification are not supported.+ /// 2. For glyphs based on the `COLR` table, there are a certain number of features+ /// that are not (correctly) supported, such as conical+ /// gradients, certain gradient transforms and some blend modes. But this shouldn't+ /// cause any issues in 95% of the cases, as most of those are edge cases.+ /// If the two above are not acceptable, then you will need to implement your own+ /// glyph rendering logic based on the layouted glyphs (see the `layouted` method).+ pub fn flattened(&self) -> &Group {+ &self.flattened+ }++ /// The positioned glyphs and decoration spans of the text.+ ///+ /// This should only be used if you need more low-level access+ /// to the glyphs that make up the text. If you just need the+ /// outlines of the text, you should use `flattened` instead.+ #[cfg(feature = "text")]+ pub fn layouted(&self) -> &[Span] {+ &self.layouted+ }++ pub(crate) fn subroots(&self, f: &mut dyn FnMut(&Group)) {+ f(&self.flattened);+ }+}diff --git a/vendor/usvg/src/writer.rs b/vendor/usvg/src/writer.rsnew file mode 100644index 00000000..e5dc9ddc--- /dev/null+++ b/vendor/usvg/src/writer.rs@@ -0,0 +1,1584 @@+// Copyright 2023 the Resvg Authors+// SPDX-License-Identifier: Apache-2.0 OR MIT++use std::fmt::Display;+use std::io::Write;++use svgtypes::{FontFamily, parse_font_families};+use xmlwriter::XmlWriter;++use crate::parser::{AId, EId};+use crate::*;++impl Tree {+ /// Writes `usvg::Tree` back to SVG.+ pub fn to_string(&self, opt: &WriteOptions) -> String {+ convert(self, opt)+ }+}++/// Checks that type has a default value.+trait IsDefault: Default {+ /// Checks that type has a default value.+ fn is_default(&self) -> bool;+}++impl<T: Default + PartialEq + Copy> IsDefault for T {+ #[inline]+ fn is_default(&self) -> bool {+ *self == Self::default()+ }+}++/// XML writing options.+#[derive(Clone, Debug)]+pub struct WriteOptions {+ /// Used to add a custom prefix to each element ID during writing.+ pub id_prefix: Option<String>,++ /// Do not convert text into paths.+ ///+ /// Default: false+ pub preserve_text: bool,++ /// Set the coordinates numeric precision.+ ///+ /// Smaller precision can lead to a malformed output in some cases.+ ///+ /// Default: 8+ pub coordinates_precision: u8,++ /// Set the transform values numeric precision.+ ///+ /// Smaller precision can lead to a malformed output in some cases.+ ///+ /// Default: 8+ pub transforms_precision: u8,++ /// Use single quote marks instead of double quote.+ ///+ /// # Examples+ ///+ /// Before:+ ///+ /// ```text+ /// <rect fill="red"/>+ /// ```+ ///+ /// After:+ ///+ /// ```text+ /// <rect fill='red'/>+ /// ```+ ///+ /// Default: disabled+ pub use_single_quote: bool,++ /// Set XML nodes indention.+ ///+ /// # Examples+ ///+ /// `Indent::None`+ /// Before:+ ///+ /// ```text+ /// <svg>+ /// <rect fill="red"/>+ /// </svg>+ /// ```+ ///+ /// After:+ ///+ /// ```text+ /// <svg><rect fill="red"/></svg>+ /// ```+ ///+ /// Default: 4 spaces+ pub indent: Indent,++ /// Set XML attributes indention.+ ///+ /// # Examples+ ///+ /// `Indent::Spaces(2)`+ ///+ /// Before:+ ///+ /// ```text+ /// <svg>+ /// <rect fill="red" stroke="black"/>+ /// </svg>+ /// ```+ ///+ /// After:+ ///+ /// ```text+ /// <svg>+ /// <rect+ /// fill="red"+ /// stroke="black"/>+ /// </svg>+ /// ```+ ///+ /// Default: `None`+ pub attributes_indent: Indent,+}++impl Default for WriteOptions {+ fn default() -> Self {+ Self {+ id_prefix: Default::default(),+ preserve_text: false,+ coordinates_precision: 8,+ transforms_precision: 8,+ use_single_quote: false,+ indent: Indent::Spaces(4),+ attributes_indent: Indent::None,+ }+ }+}++pub(crate) fn convert(tree: &Tree, opt: &WriteOptions) -> String {+ let mut xml = XmlWriter::new(xmlwriter::Options {+ use_single_quote: opt.use_single_quote,+ indent: opt.indent,+ attributes_indent: opt.attributes_indent,+ });++ xml.start_svg_element(EId::Svg);+ xml.write_svg_attribute(AId::Width, &tree.size.width());+ xml.write_svg_attribute(AId::Height, &tree.size.height());+ xml.write_attribute("xmlns", "http://www.w3.org/2000/svg");+ if has_xlink(&tree.root) {+ xml.write_attribute("xmlns:xlink", "http://www.w3.org/1999/xlink");+ }++ let has_text_paths = has_text_paths(&tree.root);+ if tree.has_defs_nodes() || has_text_paths {+ write_defs(tree, opt, &mut xml, has_text_paths);+ }++ write_elements(&tree.root, false, opt, &mut xml);++ xml.end_document()+}++fn write_filters(tree: &Tree, opt: &WriteOptions, xml: &mut XmlWriter) {+ let mut written_fe_image_nodes: Vec<String> = Vec::new();+ for filter in tree.filters() {+ for fe in &filter.primitives {+ if let filter::Kind::Image(ref img) = fe.kind {+ if let Some(child) = img.root().children.first() {+ if !written_fe_image_nodes.iter().any(|id| id == child.id()) {+ write_element(child, false, opt, xml);+ written_fe_image_nodes.push(child.id().to_string());+ }+ }+ }+ }++ xml.start_svg_element(EId::Filter);+ xml.write_id_attribute(filter.id(), opt);+ xml.write_rect_attrs(filter.rect);+ xml.write_units(+ AId::FilterUnits,+ Units::UserSpaceOnUse,+ Units::ObjectBoundingBox,+ );++ for fe in &filter.primitives {+ match fe.kind {+ filter::Kind::DropShadow(ref shadow) => {+ xml.start_svg_element(EId::FeDropShadow);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &shadow.input);+ xml.write_attribute_fmt(+ AId::StdDeviation.to_str(),+ format_args!("{} {}", shadow.std_dev_x.get(), shadow.std_dev_y.get()),+ );+ xml.write_svg_attribute(AId::Dx, &shadow.dx);+ xml.write_svg_attribute(AId::Dy, &shadow.dy);+ xml.write_color(AId::FloodColor, shadow.color);+ xml.write_svg_attribute(AId::FloodOpacity, &shadow.opacity.get());+ xml.write_svg_attribute(AId::Result, &fe.result);+ xml.end_element();+ }+ filter::Kind::GaussianBlur(ref blur) => {+ xml.start_svg_element(EId::FeGaussianBlur);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &blur.input);+ xml.write_attribute_fmt(+ AId::StdDeviation.to_str(),+ format_args!("{} {}", blur.std_dev_x.get(), blur.std_dev_y.get()),+ );+ xml.write_svg_attribute(AId::Result, &fe.result);+ xml.end_element();+ }+ filter::Kind::Offset(ref offset) => {+ xml.start_svg_element(EId::FeOffset);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &offset.input);+ xml.write_svg_attribute(AId::Dx, &offset.dx);+ xml.write_svg_attribute(AId::Dy, &offset.dy);+ xml.write_svg_attribute(AId::Result, &fe.result);+ xml.end_element();+ }+ filter::Kind::Blend(ref blend) => {+ xml.start_svg_element(EId::FeBlend);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &blend.input1);+ xml.write_filter_input(AId::In2, &blend.input2);+ xml.write_svg_attribute(AId::Mode, &blend.mode.to_string());+ xml.write_svg_attribute(AId::Result, &fe.result);+ xml.end_element();+ }+ filter::Kind::Flood(ref flood) => {+ xml.start_svg_element(EId::FeFlood);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_color(AId::FloodColor, flood.color);+ xml.write_svg_attribute(AId::FloodOpacity, &flood.opacity.get());+ xml.write_svg_attribute(AId::Result, &fe.result);+ xml.end_element();+ }+ filter::Kind::Composite(ref composite) => {+ xml.start_svg_element(EId::FeComposite);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &composite.input1);+ xml.write_filter_input(AId::In2, &composite.input2);+ xml.write_svg_attribute(+ AId::Operator,+ match composite.operator {+ filter::CompositeOperator::Over => "over",+ filter::CompositeOperator::In => "in",+ filter::CompositeOperator::Out => "out",+ filter::CompositeOperator::Atop => "atop",+ filter::CompositeOperator::Xor => "xor",+ filter::CompositeOperator::Arithmetic { .. } => "arithmetic",+ },+ );++ if let filter::CompositeOperator::Arithmetic { k1, k2, k3, k4 } =+ composite.operator+ {+ xml.write_svg_attribute(AId::K1, &k1);+ xml.write_svg_attribute(AId::K2, &k2);+ xml.write_svg_attribute(AId::K3, &k3);+ xml.write_svg_attribute(AId::K4, &k4);+ }++ xml.write_svg_attribute(AId::Result, &fe.result);+ xml.end_element();+ }+ filter::Kind::Merge(ref merge) => {+ xml.start_svg_element(EId::FeMerge);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_svg_attribute(AId::Result, &fe.result);+ for input in &merge.inputs {+ xml.start_svg_element(EId::FeMergeNode);+ xml.write_filter_input(AId::In, input);+ xml.end_element();+ }++ xml.end_element();+ }+ filter::Kind::Tile(ref tile) => {+ xml.start_svg_element(EId::FeTile);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &tile.input);+ xml.write_svg_attribute(AId::Result, &fe.result);+ xml.end_element();+ }+ filter::Kind::Image(ref img) => {+ xml.start_svg_element(EId::FeImage);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ if let Some(child) = img.root.children.first() {+ let prefix = opt.id_prefix.as_deref().unwrap_or_default();+ xml.write_attribute_fmt(+ "xlink:href",+ format_args!("#{}{}", prefix, child.id()),+ );+ }++ xml.write_svg_attribute(AId::Result, &fe.result);+ xml.end_element();+ }+ filter::Kind::ComponentTransfer(ref transfer) => {+ xml.start_svg_element(EId::FeComponentTransfer);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &transfer.input);+ xml.write_svg_attribute(AId::Result, &fe.result);++ xml.write_filter_transfer_function(EId::FeFuncR, &transfer.func_r);+ xml.write_filter_transfer_function(EId::FeFuncG, &transfer.func_g);+ xml.write_filter_transfer_function(EId::FeFuncB, &transfer.func_b);+ xml.write_filter_transfer_function(EId::FeFuncA, &transfer.func_a);++ xml.end_element();+ }+ filter::Kind::ColorMatrix(ref matrix) => {+ xml.start_svg_element(EId::FeColorMatrix);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &matrix.input);+ xml.write_svg_attribute(AId::Result, &fe.result);++ match matrix.kind {+ filter::ColorMatrixKind::Matrix(ref values) => {+ xml.write_svg_attribute(AId::Type, "matrix");+ xml.write_numbers(AId::Values, values);+ }+ filter::ColorMatrixKind::Saturate(value) => {+ xml.write_svg_attribute(AId::Type, "saturate");+ xml.write_svg_attribute(AId::Values, &value.get());+ }+ filter::ColorMatrixKind::HueRotate(angle) => {+ xml.write_svg_attribute(AId::Type, "hueRotate");+ xml.write_svg_attribute(AId::Values, &angle);+ }+ filter::ColorMatrixKind::LuminanceToAlpha => {+ xml.write_svg_attribute(AId::Type, "luminanceToAlpha");+ }+ }++ xml.end_element();+ }+ filter::Kind::ConvolveMatrix(ref matrix) => {+ xml.start_svg_element(EId::FeConvolveMatrix);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &matrix.input);+ xml.write_svg_attribute(AId::Result, &fe.result);++ xml.write_attribute_fmt(+ AId::Order.to_str(),+ format_args!("{} {}", matrix.matrix.columns, matrix.matrix.rows),+ );+ xml.write_numbers(AId::KernelMatrix, &matrix.matrix.data);+ xml.write_svg_attribute(AId::Divisor, &matrix.divisor.get());+ xml.write_svg_attribute(AId::Bias, &matrix.bias);+ xml.write_svg_attribute(AId::TargetX, &matrix.matrix.target_x);+ xml.write_svg_attribute(AId::TargetY, &matrix.matrix.target_y);+ xml.write_svg_attribute(+ AId::EdgeMode,+ match matrix.edge_mode {+ filter::EdgeMode::None => "none",+ filter::EdgeMode::Duplicate => "duplicate",+ filter::EdgeMode::Wrap => "wrap",+ },+ );+ xml.write_svg_attribute(+ AId::PreserveAlpha,+ if matrix.preserve_alpha {+ "true"+ } else {+ "false"+ },+ );++ xml.end_element();+ }+ filter::Kind::Morphology(ref morphology) => {+ xml.start_svg_element(EId::FeMorphology);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &morphology.input);+ xml.write_svg_attribute(AId::Result, &fe.result);++ xml.write_svg_attribute(+ AId::Operator,+ match morphology.operator {+ filter::MorphologyOperator::Erode => "erode",+ filter::MorphologyOperator::Dilate => "dilate",+ },+ );+ xml.write_attribute_fmt(+ AId::Radius.to_str(),+ format_args!(+ "{} {}",+ morphology.radius_x.get(),+ morphology.radius_y.get()+ ),+ );++ xml.end_element();+ }+ filter::Kind::DisplacementMap(ref map) => {+ xml.start_svg_element(EId::FeDisplacementMap);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_filter_input(AId::In, &map.input1);+ xml.write_filter_input(AId::In2, &map.input2);+ xml.write_svg_attribute(AId::Result, &fe.result);++ xml.write_svg_attribute(AId::Scale, &map.scale);++ let mut write_channel = |c, aid| {+ xml.write_svg_attribute(+ aid,+ match c {+ filter::ColorChannel::R => "R",+ filter::ColorChannel::G => "G",+ filter::ColorChannel::B => "B",+ filter::ColorChannel::A => "A",+ },+ );+ };+ write_channel(map.x_channel_selector, AId::XChannelSelector);+ write_channel(map.y_channel_selector, AId::YChannelSelector);++ xml.end_element();+ }+ filter::Kind::Turbulence(ref turbulence) => {+ xml.start_svg_element(EId::FeTurbulence);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_svg_attribute(AId::Result, &fe.result);++ xml.write_attribute_fmt(+ AId::BaseFrequency.to_str(),+ format_args!(+ "{} {}",+ turbulence.base_frequency_x.get(),+ turbulence.base_frequency_y.get()+ ),+ );+ xml.write_svg_attribute(AId::NumOctaves, &turbulence.num_octaves);+ xml.write_svg_attribute(AId::Seed, &turbulence.seed);+ xml.write_svg_attribute(+ AId::StitchTiles,+ match turbulence.stitch_tiles {+ true => "stitch",+ false => "noStitch",+ },+ );+ xml.write_svg_attribute(+ AId::Type,+ match turbulence.kind {+ filter::TurbulenceKind::FractalNoise => "fractalNoise",+ filter::TurbulenceKind::Turbulence => "turbulence",+ },+ );++ xml.end_element();+ }+ filter::Kind::DiffuseLighting(ref light) => {+ xml.start_svg_element(EId::FeDiffuseLighting);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_svg_attribute(AId::Result, &fe.result);++ xml.write_svg_attribute(AId::SurfaceScale, &light.surface_scale);+ xml.write_svg_attribute(AId::DiffuseConstant, &light.diffuse_constant);+ xml.write_color(AId::LightingColor, light.lighting_color);+ write_light_source(&light.light_source, xml);++ xml.end_element();+ }+ filter::Kind::SpecularLighting(ref light) => {+ xml.start_svg_element(EId::FeSpecularLighting);+ xml.write_filter_primitive_attrs(filter.rect(), fe);+ xml.write_svg_attribute(AId::Result, &fe.result);++ xml.write_svg_attribute(AId::SurfaceScale, &light.surface_scale);+ xml.write_svg_attribute(AId::SpecularConstant, &light.specular_constant);+ xml.write_svg_attribute(AId::SpecularExponent, &light.specular_exponent);+ xml.write_color(AId::LightingColor, light.lighting_color);+ write_light_source(&light.light_source, xml);++ xml.end_element();+ }+ };+ }++ xml.end_element();+ }+}++fn write_defs(tree: &Tree, opt: &WriteOptions, xml: &mut XmlWriter, write_text_paths: bool) {+ xml.start_svg_element(EId::Defs);+ for lg in tree.linear_gradients() {+ xml.start_svg_element(EId::LinearGradient);+ xml.write_id_attribute(lg.id(), opt);+ xml.write_svg_attribute(AId::X1, &lg.x1);+ xml.write_svg_attribute(AId::Y1, &lg.y1);+ xml.write_svg_attribute(AId::X2, &lg.x2);+ xml.write_svg_attribute(AId::Y2, &lg.y2);+ write_base_grad(&lg.base, opt, xml);+ xml.end_element();+ }++ for rg in tree.radial_gradients() {+ xml.start_svg_element(EId::RadialGradient);+ xml.write_id_attribute(rg.id(), opt);+ xml.write_svg_attribute(AId::Cx, &rg.cx);+ xml.write_svg_attribute(AId::Cy, &rg.cy);+ xml.write_svg_attribute(AId::R, &rg.r.get());+ xml.write_svg_attribute(AId::Fx, &rg.fx);+ xml.write_svg_attribute(AId::Fy, &rg.fy);+ write_base_grad(&rg.base, opt, xml);+ xml.end_element();+ }++ for pattern in tree.patterns() {+ xml.start_svg_element(EId::Pattern);+ xml.write_id_attribute(pattern.id(), opt);+ xml.write_rect_attrs(pattern.rect);+ xml.write_units(AId::PatternUnits, pattern.units, Units::ObjectBoundingBox);+ xml.write_units(+ AId::PatternContentUnits,+ pattern.content_units,+ Units::UserSpaceOnUse,+ );+ xml.write_transform(AId::PatternTransform, pattern.transform, opt);++ write_elements(&pattern.root, false, opt, xml);++ xml.end_element();+ }++ if write_text_paths {+ write_text_path_paths(&tree.root, opt, xml);+ }++ write_filters(tree, opt, xml);++ for clip in tree.clip_paths() {+ xml.start_svg_element(EId::ClipPath);+ xml.write_id_attribute(clip.id(), opt);+ xml.write_transform(AId::Transform, clip.transform, opt);++ if let Some(ref clip) = clip.clip_path {+ xml.write_func_iri(AId::ClipPath, clip.id(), opt);+ }++ write_elements(&clip.root, true, opt, xml);++ xml.end_element();+ }++ for mask in tree.masks() {+ xml.start_svg_element(EId::Mask);+ xml.write_id_attribute(mask.id(), opt);+ if mask.kind == MaskType::Alpha {+ xml.write_svg_attribute(AId::MaskType, "alpha");+ }+ xml.write_units(+ AId::MaskUnits,+ Units::UserSpaceOnUse,+ Units::ObjectBoundingBox,+ );+ xml.write_rect_attrs(mask.rect);++ if let Some(ref mask) = mask.mask {+ xml.write_func_iri(AId::Mask, mask.id(), opt);+ }++ write_elements(&mask.root, false, opt, xml);++ xml.end_element();+ }+ xml.end_element(); // end EId::Defs+}++fn has_text_paths(parent: &Group) -> bool {+ for node in &parent.children {+ if let Node::Group(group) = node {+ if has_text_paths(group) {+ return true;+ }+ } else if let Node::Text(text) = node {+ for chunk in &text.chunks {+ if let TextFlow::Path(text_path) = &chunk.text_flow {+ let path = Path::new(+ text_path.id().to_string(),+ true,+ None,+ None,+ PaintOrder::default(),+ ShapeRendering::default(),+ text_path.path.clone(),+ Transform::default(),+ );+ if path.is_some() {+ return true;+ }+ }+ }+ }+ let mut need_path = false;+ node.subroots(|subroot| {+ if !need_path && has_text_paths(subroot) {+ need_path = true;+ }+ });+ if need_path {+ return true;+ }+ }+ false+}++/// Write the `path` elements for text paths.+fn write_text_path_paths(parent: &Group, opt: &WriteOptions, xml: &mut XmlWriter) {+ for node in &parent.children {+ if let Node::Group(group) = node {+ write_text_path_paths(group, opt, xml);+ } else if let Node::Text(text) = node {+ for chunk in &text.chunks {+ if let TextFlow::Path(text_path) = &chunk.text_flow {+ let path = Path::new(+ text_path.id().to_string(),+ true,+ None,+ None,+ PaintOrder::default(),+ ShapeRendering::default(),+ text_path.path.clone(),+ Transform::default(),+ );+ if let Some(path) = &path {+ write_path(path, false, Transform::default(), None, opt, xml);+ }+ }+ }+ }++ node.subroots(|subroot| write_text_path_paths(subroot, opt, xml));+ }+}++fn write_elements(parent: &Group, is_clip_path: bool, opt: &WriteOptions, xml: &mut XmlWriter) {+ for n in &parent.children {+ write_element(n, is_clip_path, opt, xml);+ }+}++fn write_element(node: &Node, is_clip_path: bool, opt: &WriteOptions, xml: &mut XmlWriter) {+ match node {+ Node::Path(p) => {+ write_path(p, is_clip_path, Transform::default(), None, opt, xml);+ }+ Node::Image(img) => {+ xml.start_svg_element(EId::Image);+ if !img.id.is_empty() {+ xml.write_id_attribute(&img.id, opt);+ }++ xml.write_svg_attribute(AId::Width, &img.size().width());+ xml.write_svg_attribute(AId::Height, &img.size().height());++ xml.write_visibility(img.visible);++ match img.rendering_mode {+ ImageRendering::OptimizeQuality => {}+ ImageRendering::OptimizeSpeed => {+ xml.write_svg_attribute(AId::ImageRendering, "optimizeSpeed");+ }+ ImageRendering::Smooth => {+ xml.write_attribute(AId::Style.to_str(), "image-rendering:smooth");+ }+ ImageRendering::HighQuality => {+ xml.write_attribute(AId::Style.to_str(), "image-rendering:high-quality");+ }+ ImageRendering::CrispEdges => {+ xml.write_attribute(AId::Style.to_str(), "image-rendering:crisp-edges");+ }+ ImageRendering::Pixelated => {+ xml.write_attribute(AId::Style.to_str(), "image-rendering:pixelated");+ }+ }++ xml.write_image_data(&img.kind);++ xml.end_element();+ }+ Node::Group(g) => {+ write_group_element(g, is_clip_path, opt, xml);+ }+ Node::Text(text) => {+ if opt.preserve_text {+ xml.start_svg_element(EId::Text);++ if !text.id.is_empty() {+ xml.write_id_attribute(&text.id, opt);+ }++ xml.write_attribute("xml:space", "preserve");++ match text.writing_mode {+ WritingMode::LeftToRight => {}+ WritingMode::TopToBottom => xml.write_svg_attribute(AId::WritingMode, "tb"),+ }++ match text.rendering_mode {+ TextRendering::OptimizeSpeed => {+ xml.write_svg_attribute(AId::TextRendering, "optimizeSpeed");+ }+ TextRendering::GeometricPrecision => {+ xml.write_svg_attribute(AId::TextRendering, "geometricPrecision");+ }+ TextRendering::OptimizeLegibility => {}+ }++ if text.rotate.iter().any(|r| *r != 0.0) {+ xml.write_numbers(AId::Rotate, &text.rotate);+ }++ if text.dx.iter().any(|dx| *dx != 0.0) {+ xml.write_numbers(AId::Dx, &text.dx);+ }++ if text.dy.iter().any(|dy| *dy != 0.0) {+ xml.write_numbers(AId::Dy, &text.dy);+ }++ xml.set_preserve_whitespaces(true);++ for chunk in &text.chunks {+ if let TextFlow::Path(text_path) = &chunk.text_flow {+ xml.start_svg_element(EId::TextPath);++ let prefix = opt.id_prefix.as_deref().unwrap_or_default();+ xml.write_attribute_fmt(+ "xlink:href",+ format_args!("#{}{}", prefix, text_path.id()),+ );++ if text_path.start_offset != 0.0 {+ xml.write_svg_attribute(AId::StartOffset, &text_path.start_offset);+ }+ }++ xml.start_svg_element(EId::Tspan);++ if let Some(x) = chunk.x {+ xml.write_svg_attribute(AId::X, &x);+ }++ if let Some(y) = chunk.y {+ xml.write_svg_attribute(AId::Y, &y);+ }++ match chunk.anchor {+ TextAnchor::Start => {}+ TextAnchor::Middle => xml.write_svg_attribute(AId::TextAnchor, "middle"),+ TextAnchor::End => xml.write_svg_attribute(AId::TextAnchor, "end"),+ }++ for span in &chunk.spans {+ let decorations: Vec<_> = [+ ("underline", &span.decoration.underline),+ ("line-through", &span.decoration.line_through),+ ("overline", &span.decoration.overline),+ ]+ .iter()+ .filter_map(|&(key, option_value)| {+ option_value.as_ref().map(|value| (key, value))+ })+ .collect();++ // Decorations need to be dumped BEFORE we write the actual span data+ // (so that for example stroke color of span doesn't affect the text+ // itself while baseline shifts need to be written after (since they are+ // affected by the font size)+ for (deco_name, deco) in &decorations {+ xml.start_svg_element(EId::Tspan);+ xml.write_svg_attribute(AId::TextDecoration, deco_name);+ write_fill(&deco.fill, false, opt, xml);+ write_stroke(&deco.stroke, opt, xml);+ }++ write_span(is_clip_path, opt, xml, chunk, span);++ // End for each tspan we needed to create for decorations+ for _ in &decorations {+ xml.end_element();+ }+ }+ xml.end_element();++ // End textPath element+ if matches!(&chunk.text_flow, TextFlow::Path(_)) {+ xml.end_element();+ }+ }++ xml.end_element();+ xml.set_preserve_whitespaces(false);+ } else {+ write_group_element(text.flattened(), is_clip_path, opt, xml);+ }+ }+ }+}++fn write_group_element(g: &Group, is_clip_path: bool, opt: &WriteOptions, xml: &mut XmlWriter) {+ if is_clip_path {+ // The `clipPath` element in SVG doesn't allow groups, only shapes and text.+ // The problem is that in `usvg` we can set a `clip-path` only on groups.+ // So in cases when a `clipPath` child has a `clip-path` as well,+ // it would be inside a group. And we have to skip this group during writing.+ //+ // Basically, the following SVG:+ //+ // <clipPath id="clip">+ // <path clip-path="url(#clip-nested)"/>+ // </clipPath>+ //+ // will be represented in usvg as:+ //+ // <clipPath id="clip">+ // <g clip-path="url(#clip-nested)">+ // <path/>+ // </g>+ // </clipPath>+ //+ //+ // Same with text. Text elements will be converted into groups,+ // but only the group's children should be written.+ for child in &g.children {+ match child {+ Node::Group(child_group) => {+ write_group_element(child_group, is_clip_path, opt, xml);+ }+ Node::Path(child_path) => {+ let clip_id = g.clip_path.as_ref().map(|cp| cp.id().to_string());+ write_path(+ child_path,+ is_clip_path,+ g.transform,+ clip_id.as_deref(),+ opt,+ xml,+ );+ }+ _ => {}+ }+ }+ return;+ }++ xml.start_svg_element(EId::G);+ if !g.id.is_empty() {+ xml.write_id_attribute(&g.id, opt);+ };++ if let Some(ref clip) = g.clip_path {+ xml.write_func_iri(AId::ClipPath, clip.id(), opt);+ }++ if let Some(ref mask) = g.mask {+ xml.write_func_iri(AId::Mask, mask.id(), opt);+ }++ if !g.filters.is_empty() {+ let prefix = opt.id_prefix.as_deref().unwrap_or_default();+ let ids: Vec<_> = g+ .filters+ .iter()+ .map(|filter| format!("url(#{}{})", prefix, filter.id()))+ .collect();+ xml.write_svg_attribute(AId::Filter, &ids.join(" "));+ }++ if g.opacity != Opacity::ONE {+ xml.write_svg_attribute(AId::Opacity, &g.opacity.get());+ }++ xml.write_transform(AId::Transform, g.transform, opt);++ if g.blend_mode != BlendMode::Normal || g.isolate {+ // For reasons unknown, `mix-blend-mode` and `isolation` must be written+ // as `style` attribute.+ let isolation = if g.isolate { "isolate" } else { "auto" };+ xml.write_attribute_fmt(+ AId::Style.to_str(),+ format_args!("mix-blend-mode:{};isolation:{}", g.blend_mode, isolation),+ );+ }++ write_elements(g, false, opt, xml);++ xml.end_element();+}++trait XmlWriterExt {+ fn start_svg_element(&mut self, id: EId);+ fn write_svg_attribute<V: Display + ?Sized>(&mut self, id: AId, value: &V);+ fn write_id_attribute(&mut self, id: &str, opt: &WriteOptions);+ fn write_color(&mut self, id: AId, color: Color);+ fn write_units(&mut self, id: AId, units: Units, def: Units);+ fn write_transform(&mut self, id: AId, units: Transform, opt: &WriteOptions);+ fn write_visibility(&mut self, value: bool);+ fn write_func_iri(&mut self, aid: AId, id: &str, opt: &WriteOptions);+ fn write_rect_attrs(&mut self, r: NonZeroRect);+ fn write_numbers(&mut self, aid: AId, list: &[f32]);+ fn write_image_data(&mut self, kind: &ImageKind);+ fn write_filter_input(&mut self, id: AId, input: &filter::Input);+ fn write_filter_primitive_attrs(&mut self, parent_rect: NonZeroRect, fe: &filter::Primitive);+ fn write_filter_transfer_function(&mut self, eid: EId, fe: &filter::TransferFunction);+}++impl XmlWriterExt for XmlWriter {+ #[inline(never)]+ fn start_svg_element(&mut self, id: EId) {+ self.start_element(id.to_str());+ }++ #[inline(never)]+ fn write_svg_attribute<V: Display + ?Sized>(&mut self, id: AId, value: &V) {+ self.write_attribute(id.to_str(), value);+ }++ #[inline(never)]+ fn write_id_attribute(&mut self, id: &str, opt: &WriteOptions) {+ debug_assert!(!id.is_empty());++ if let Some(ref prefix) = opt.id_prefix {+ let full_id = format!("{}{}", prefix, id);+ self.write_attribute("id", &full_id);+ } else {+ self.write_attribute("id", id);+ }+ }++ #[inline(never)]+ fn write_color(&mut self, id: AId, c: Color) {+ static CHARS: &[u8] = b"0123456789abcdef";++ #[inline]+ fn int2hex(n: u8) -> (u8, u8) {+ (CHARS[(n >> 4) as usize], CHARS[(n & 0xf) as usize])+ }++ let (r1, r2) = int2hex(c.red);+ let (g1, g2) = int2hex(c.green);+ let (b1, b2) = int2hex(c.blue);++ self.write_attribute_raw(id.to_str(), |buf| {+ buf.extend_from_slice(&[b'#', r1, r2, g1, g2, b1, b2]);+ });+ }++ fn write_units(&mut self, id: AId, units: Units, def: Units) {+ if units != def {+ self.write_attribute(id.to_str(), &units);+ }+ }++ fn write_transform(&mut self, id: AId, ts: Transform, opt: &WriteOptions) {+ if !ts.is_default() {+ self.write_attribute_raw(id.to_str(), |buf| {+ buf.extend_from_slice(b"matrix(");+ write_num(ts.sx, buf, opt.transforms_precision);+ buf.push(b' ');+ write_num(ts.ky, buf, opt.transforms_precision);+ buf.push(b' ');+ write_num(ts.kx, buf, opt.transforms_precision);+ buf.push(b' ');+ write_num(ts.sy, buf, opt.transforms_precision);+ buf.push(b' ');+ write_num(ts.tx, buf, opt.transforms_precision);+ buf.push(b' ');+ write_num(ts.ty, buf, opt.transforms_precision);+ buf.extend_from_slice(b")");+ });+ }+ }++ fn write_visibility(&mut self, value: bool) {+ if !value {+ self.write_attribute(AId::Visibility.to_str(), "hidden");+ }+ }++ fn write_func_iri(&mut self, aid: AId, id: &str, opt: &WriteOptions) {+ debug_assert!(!id.is_empty());+ let prefix = opt.id_prefix.as_deref().unwrap_or_default();+ self.write_attribute_fmt(aid.to_str(), format_args!("url(#{}{})", prefix, id));+ }++ fn write_rect_attrs(&mut self, r: NonZeroRect) {+ self.write_svg_attribute(AId::X, &r.x());+ self.write_svg_attribute(AId::Y, &r.y());+ self.write_svg_attribute(AId::Width, &r.width());+ self.write_svg_attribute(AId::Height, &r.height());+ }++ fn write_numbers(&mut self, aid: AId, list: &[f32]) {+ self.write_attribute_raw(aid.to_str(), |buf| {+ for n in list {+ buf.write_fmt(format_args!("{} ", n)).unwrap();+ }++ if !list.is_empty() {+ buf.pop();+ }+ });+ }++ fn write_filter_input(&mut self, id: AId, input: &filter::Input) {+ self.write_attribute(+ id.to_str(),+ match input {+ filter::Input::SourceGraphic => "SourceGraphic",+ filter::Input::SourceAlpha => "SourceAlpha",+ filter::Input::Reference(s) => s,+ },+ );+ }++ fn write_filter_primitive_attrs(&mut self, parent_rect: NonZeroRect, fe: &filter::Primitive) {+ if parent_rect.x() != fe.rect().x() {+ self.write_svg_attribute(AId::X, &fe.rect().x());+ }+ if parent_rect.y() != fe.rect().y() {+ self.write_svg_attribute(AId::Y, &fe.rect().y());+ }+ if parent_rect.width() != fe.rect().width() {+ self.write_svg_attribute(AId::Width, &fe.rect().width());+ }+ if parent_rect.height() != fe.rect().height() {+ self.write_svg_attribute(AId::Height, &fe.rect().height());+ }++ self.write_attribute(+ AId::ColorInterpolationFilters.to_str(),+ match fe.color_interpolation {+ filter::ColorInterpolation::SRGB => "sRGB",+ filter::ColorInterpolation::LinearRGB => "linearRGB",+ },+ );+ }++ fn write_filter_transfer_function(&mut self, eid: EId, fe: &filter::TransferFunction) {+ self.start_svg_element(eid);++ match fe {+ filter::TransferFunction::Identity => {+ self.write_svg_attribute(AId::Type, "identity");+ }+ filter::TransferFunction::Table(values) => {+ self.write_svg_attribute(AId::Type, "table");+ self.write_numbers(AId::TableValues, values);+ }+ filter::TransferFunction::Discrete(values) => {+ self.write_svg_attribute(AId::Type, "discrete");+ self.write_numbers(AId::TableValues, values);+ }+ filter::TransferFunction::Linear { slope, intercept } => {+ self.write_svg_attribute(AId::Type, "linear");+ self.write_svg_attribute(AId::Slope, &slope);+ self.write_svg_attribute(AId::Intercept, &intercept);+ }+ filter::TransferFunction::Gamma {+ amplitude,+ exponent,+ offset,+ } => {+ self.write_svg_attribute(AId::Type, "gamma");+ self.write_svg_attribute(AId::Amplitude, &litude);+ self.write_svg_attribute(AId::Exponent, &exponent);+ self.write_svg_attribute(AId::Offset, &offset);+ }+ }++ self.end_element();+ }++ fn write_image_data(&mut self, kind: &ImageKind) {+ let svg_string;+ let (mime, data) = match kind {+ ImageKind::JPEG(data) => ("jpeg", data.as_slice()),+ ImageKind::PNG(data) => ("png", data.as_slice()),+ ImageKind::GIF(data) => ("gif", data.as_slice()),+ ImageKind::WEBP(data) => ("webp", data.as_slice()),+ ImageKind::SVG(tree) => {+ svg_string = tree.to_string(&WriteOptions::default());+ ("svg+xml", svg_string.as_bytes())+ }+ };++ self.write_attribute_raw("xlink:href", |buf| {+ buf.extend_from_slice(b"data:image/");+ buf.extend_from_slice(mime.as_bytes());+ buf.extend_from_slice(b";base64, ");++ let mut enc =+ base64::write::EncoderWriter::new(buf, &base64::engine::general_purpose::STANDARD);+ enc.write_all(data).unwrap();+ enc.finish().unwrap();+ });+ }+}++fn has_xlink(parent: &Group) -> bool {+ for node in &parent.children {+ match node {+ Node::Group(g) => {+ for filter in &g.filters {+ if filter+ .primitives+ .iter()+ .any(|p| matches!(p.kind, filter::Kind::Image(_)))+ {+ return true;+ }+ }++ if let Some(mask) = &g.mask {+ if has_xlink(mask.root()) {+ return true;+ }++ if let Some(sub_mask) = &mask.mask {+ if has_xlink(&sub_mask.root) {+ return true;+ }+ }+ }++ if has_xlink(g) {+ return true;+ }+ }+ Node::Image(_) => {+ return true;+ }+ Node::Text(text) => {+ if text+ .chunks+ .iter()+ .any(|t| matches!(t.text_flow, TextFlow::Path(_)))+ {+ return true;+ }+ }+ _ => {}+ }++ let mut present = false;+ node.subroots(|root| present |= has_xlink(root));+ if present {+ return true;+ }+ }++ false+}++fn write_base_grad(g: &BaseGradient, opt: &WriteOptions, xml: &mut XmlWriter) {+ xml.write_units(AId::GradientUnits, g.units, Units::ObjectBoundingBox);+ xml.write_transform(AId::GradientTransform, g.transform, opt);++ match g.spread_method {+ SpreadMethod::Pad => {}+ SpreadMethod::Reflect => xml.write_svg_attribute(AId::SpreadMethod, "reflect"),+ SpreadMethod::Repeat => xml.write_svg_attribute(AId::SpreadMethod, "repeat"),+ }++ for s in &g.stops {+ xml.start_svg_element(EId::Stop);+ xml.write_svg_attribute(AId::Offset, &s.offset.get());+ xml.write_color(AId::StopColor, s.color);+ if s.opacity != Opacity::ONE {+ xml.write_svg_attribute(AId::StopOpacity, &s.opacity.get());+ }++ xml.end_element();+ }+}++fn write_path(+ path: &Path,+ is_clip_path: bool,+ path_transform: Transform,+ clip_path: Option<&str>,+ opt: &WriteOptions,+ xml: &mut XmlWriter,+) {+ xml.start_svg_element(EId::Path);+ if !path.id.is_empty() {+ xml.write_id_attribute(&path.id, opt);+ }++ write_fill(&path.fill, is_clip_path, opt, xml);+ write_stroke(&path.stroke, opt, xml);++ xml.write_visibility(path.visible);++ if path.paint_order == PaintOrder::StrokeAndFill {+ xml.write_svg_attribute(AId::PaintOrder, "stroke");+ }++ match path.rendering_mode {+ ShapeRendering::OptimizeSpeed => {+ xml.write_svg_attribute(AId::ShapeRendering, "optimizeSpeed");+ }+ ShapeRendering::CrispEdges => xml.write_svg_attribute(AId::ShapeRendering, "crispEdges"),+ ShapeRendering::GeometricPrecision => {}+ }++ if let Some(id) = clip_path {+ xml.write_func_iri(AId::ClipPath, id, opt);+ }++ xml.write_transform(AId::Transform, path_transform, opt);++ xml.write_attribute_raw("d", |buf| {+ use tiny_skia_path::PathSegment;++ for seg in path.data.segments() {+ match seg {+ PathSegment::MoveTo(p) => {+ buf.extend_from_slice(b"M ");+ write_num(p.x, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p.y, buf, opt.coordinates_precision);+ buf.push(b' ');+ }+ PathSegment::LineTo(p) => {+ buf.extend_from_slice(b"L ");+ write_num(p.x, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p.y, buf, opt.coordinates_precision);+ buf.push(b' ');+ }+ PathSegment::QuadTo(p1, p) => {+ buf.extend_from_slice(b"Q ");+ write_num(p1.x, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p1.y, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p.x, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p.y, buf, opt.coordinates_precision);+ buf.push(b' ');+ }+ PathSegment::CubicTo(p1, p2, p) => {+ buf.extend_from_slice(b"C ");+ write_num(p1.x, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p1.y, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p2.x, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p2.y, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p.x, buf, opt.coordinates_precision);+ buf.push(b' ');+ write_num(p.y, buf, opt.coordinates_precision);+ buf.push(b' ');+ }+ PathSegment::Close => {+ buf.extend_from_slice(b"Z ");+ }+ }+ }++ buf.pop();+ });++ xml.end_element();+}++fn write_fill(fill: &Option<Fill>, is_clip_path: bool, opt: &WriteOptions, xml: &mut XmlWriter) {+ if let Some(fill) = fill {+ write_paint(AId::Fill, &fill.paint, opt, xml);++ if fill.opacity != Opacity::ONE {+ xml.write_svg_attribute(AId::FillOpacity, &fill.opacity.get());+ }++ if !fill.rule.is_default() {+ let name = if is_clip_path {+ AId::ClipRule+ } else {+ AId::FillRule+ };++ xml.write_svg_attribute(name, "evenodd");+ }+ } else {+ xml.write_svg_attribute(AId::Fill, "none");+ }+}++fn write_stroke(stroke: &Option<Stroke>, opt: &WriteOptions, xml: &mut XmlWriter) {+ if let Some(stroke) = stroke {+ write_paint(AId::Stroke, &stroke.paint, opt, xml);++ if stroke.opacity != Opacity::ONE {+ xml.write_svg_attribute(AId::StrokeOpacity, &stroke.opacity.get());+ }++ if !stroke.dashoffset.approx_zero_ulps(4) {+ xml.write_svg_attribute(AId::StrokeDashoffset, &stroke.dashoffset);+ }++ if !stroke.miterlimit.is_default() {+ xml.write_svg_attribute(AId::StrokeMiterlimit, &stroke.miterlimit.get());+ }++ if stroke.width.get() != 1.0 {+ xml.write_svg_attribute(AId::StrokeWidth, &stroke.width.get());+ }++ match stroke.linecap {+ LineCap::Butt => {}+ LineCap::Round => xml.write_svg_attribute(AId::StrokeLinecap, "round"),+ LineCap::Square => xml.write_svg_attribute(AId::StrokeLinecap, "square"),+ }++ match stroke.linejoin {+ LineJoin::Miter => {}+ LineJoin::MiterClip => xml.write_svg_attribute(AId::StrokeLinejoin, "miter-clip"),+ LineJoin::Round => xml.write_svg_attribute(AId::StrokeLinejoin, "round"),+ LineJoin::Bevel => xml.write_svg_attribute(AId::StrokeLinejoin, "bevel"),+ }++ if let Some(ref array) = stroke.dasharray {+ xml.write_numbers(AId::StrokeDasharray, array);+ }+ } else {+ // Always set `stroke` to `none` to override the parent value.+ // In 99.9% of the cases it's redundant, but a group with `filter` with `StrokePaint`+ // will set `stroke`, which will interfere with children nodes.+ xml.write_svg_attribute(AId::Stroke, "none");+ }+}++fn write_paint(aid: AId, paint: &Paint, opt: &WriteOptions, xml: &mut XmlWriter) {+ match paint {+ Paint::Color(c) => xml.write_color(aid, *c),+ Paint::LinearGradient(lg) => {+ xml.write_func_iri(aid, lg.id(), opt);+ }+ Paint::RadialGradient(rg) => {+ xml.write_func_iri(aid, rg.id(), opt);+ }+ Paint::Pattern(patt) => {+ xml.write_func_iri(aid, patt.id(), opt);+ }+ }+}++fn write_light_source(light: &filter::LightSource, xml: &mut XmlWriter) {+ match light {+ filter::LightSource::DistantLight(light) => {+ xml.start_svg_element(EId::FeDistantLight);+ xml.write_svg_attribute(AId::Azimuth, &light.azimuth);+ xml.write_svg_attribute(AId::Elevation, &light.elevation);+ }+ filter::LightSource::PointLight(light) => {+ xml.start_svg_element(EId::FePointLight);+ xml.write_svg_attribute(AId::X, &light.x);+ xml.write_svg_attribute(AId::Y, &light.y);+ xml.write_svg_attribute(AId::Z, &light.z);+ }+ filter::LightSource::SpotLight(light) => {+ xml.start_svg_element(EId::FeSpotLight);+ xml.write_svg_attribute(AId::X, &light.x);+ xml.write_svg_attribute(AId::Y, &light.y);+ xml.write_svg_attribute(AId::Z, &light.z);+ xml.write_svg_attribute(AId::PointsAtX, &light.points_at_x);+ xml.write_svg_attribute(AId::PointsAtY, &light.points_at_y);+ xml.write_svg_attribute(AId::PointsAtZ, &light.points_at_z);+ xml.write_svg_attribute(AId::SpecularExponent, &light.specular_exponent);+ if let Some(n) = light.limiting_cone_angle {+ xml.write_svg_attribute(AId::LimitingConeAngle, &n);+ }+ }+ }++ xml.end_element();+}++static POW_VEC: &[f32] = &[+ 1.0,+ 10.0,+ 100.0,+ 1_000.0,+ 10_000.0,+ 100_000.0,+ 1_000_000.0,+ 10_000_000.0,+ 100_000_000.0,+ 1_000_000_000.0,+ 10_000_000_000.0,+ 100_000_000_000.0,+ 1_000_000_000_000.0,+];++fn write_num(num: f32, buf: &mut Vec<u8>, precision: u8) {+ // If number is an integer, it's faster to write it as i32.+ if num.fract().approx_zero_ulps(4) {+ write!(buf, "{}", num as i32).unwrap();+ return;+ }++ // Round numbers up to the specified precision to prevent writing+ // ugly numbers like 29.999999999999996.+ // It's not 100% correct, but differences are insignificant.+ //+ // Note that at least in Rust 1.64 the number formatting in debug and release modes+ // can be slightly different. So having a lower precision makes+ // our output and tests reproducible.+ let v = (num * POW_VEC[precision as usize]).round() / POW_VEC[precision as usize];++ write!(buf, "{}", v).unwrap();+}++/// Write all of the tspan attributes except for decorations.+fn write_span(+ is_clip_path: bool,+ opt: &WriteOptions,+ xml: &mut XmlWriter,+ chunk: &TextChunk,+ span: &TextSpan,+) {+ xml.start_svg_element(EId::Tspan);++ let font_family_to_str = |font_family: &FontFamily| match font_family {+ FontFamily::Monospace => "monospace".to_string(),+ FontFamily::Serif => "serif".to_string(),+ FontFamily::SansSerif => "sans-serif".to_string(),+ FontFamily::Cursive => "cursive".to_string(),+ FontFamily::Fantasy => "fantasy".to_string(),+ FontFamily::Named(s) => {+ // Only quote if absolutely necessary+ match parse_font_families(s) {+ Ok(_) => s.clone(),+ Err(_) => {+ if opt.use_single_quote {+ format!("\"{}\"", s)+ } else {+ format!("'{}'", s)+ }+ }+ }+ }+ };++ if !span.font.families.is_empty() {+ let families = span+ .font+ .families+ .iter()+ .map(font_family_to_str)+ .collect::<Vec<_>>()+ .join(", ");+ xml.write_svg_attribute(AId::FontFamily, &families);+ }++ match span.font.style {+ FontStyle::Normal => {}+ FontStyle::Italic => xml.write_svg_attribute(AId::FontStyle, "italic"),+ FontStyle::Oblique => xml.write_svg_attribute(AId::FontStyle, "oblique"),+ }++ if span.font.weight != 400 {+ xml.write_svg_attribute(AId::FontWeight, &span.font.weight);+ }++ if span.font.stretch != FontStretch::Normal {+ let name = match span.font.stretch {+ FontStretch::Condensed => "condensed",+ FontStretch::ExtraCondensed => "extra-condensed",+ FontStretch::UltraCondensed => "ultra-condensed",+ FontStretch::SemiCondensed => "semi-condensed",+ FontStretch::Expanded => "expanded",+ FontStretch::SemiExpanded => "semi-expanded",+ FontStretch::ExtraExpanded => "extra-expanded",+ FontStretch::UltraExpanded => "ultra-expanded",+ FontStretch::Normal => unreachable!(),+ };+ xml.write_svg_attribute(AId::FontStretch, name);+ }++ xml.write_svg_attribute(AId::FontSize, &span.font_size);++ xml.write_visibility(span.visible);++ if span.letter_spacing != 0.0 {+ xml.write_svg_attribute(AId::LetterSpacing, &span.letter_spacing);+ }++ if span.word_spacing != 0.0 {+ xml.write_svg_attribute(AId::WordSpacing, &span.word_spacing);+ }++ if let Some(text_length) = span.text_length {+ xml.write_svg_attribute(AId::TextLength, &text_length);+ }++ if span.length_adjust == LengthAdjust::SpacingAndGlyphs {+ xml.write_svg_attribute(AId::LengthAdjust, "spacingAndGlyphs");+ }++ if span.small_caps {+ xml.write_svg_attribute(AId::FontVariant, "small-caps");+ }++ if span.paint_order == PaintOrder::StrokeAndFill {+ xml.write_svg_attribute(AId::PaintOrder, "stroke fill");+ }++ if !span.apply_kerning {+ xml.write_attribute("style", "font-kerning:none");+ }++ if span.dominant_baseline != DominantBaseline::Auto {+ let name = match span.dominant_baseline {+ DominantBaseline::UseScript => "use-script",+ DominantBaseline::NoChange => "no-change",+ DominantBaseline::ResetSize => "reset-size",+ DominantBaseline::TextBeforeEdge => "text-before-edge",+ DominantBaseline::Middle => "middle",+ DominantBaseline::Central => "central",+ DominantBaseline::TextAfterEdge => "text-after-edge",+ DominantBaseline::Ideographic => "ideographic",+ DominantBaseline::Alphabetic => "alphabetic",+ DominantBaseline::Hanging => "hanging",+ DominantBaseline::Mathematical => "mathematical",+ DominantBaseline::Auto => unreachable!(),+ };+ xml.write_svg_attribute(AId::DominantBaseline, name);+ }++ if span.alignment_baseline != AlignmentBaseline::Auto {+ let name = match span.alignment_baseline {+ AlignmentBaseline::Baseline => "baseline",+ AlignmentBaseline::BeforeEdge => "before-edge",+ AlignmentBaseline::TextBeforeEdge => "text-before-edge",+ AlignmentBaseline::Middle => "middle",+ AlignmentBaseline::Central => "central",+ AlignmentBaseline::AfterEdge => "after-edge",+ AlignmentBaseline::TextAfterEdge => "text-after-edge",+ AlignmentBaseline::Ideographic => "ideographic",+ AlignmentBaseline::Alphabetic => "alphabetic",+ AlignmentBaseline::Hanging => "hanging",+ AlignmentBaseline::Mathematical => "mathematical",+ AlignmentBaseline::Auto => unreachable!(),+ };+ xml.write_svg_attribute(AId::AlignmentBaseline, name);+ }++ write_fill(&span.fill, is_clip_path, opt, xml);+ write_stroke(&span.stroke, opt, xml);++ for baseline_shift in &span.baseline_shift {+ xml.start_svg_element(EId::Tspan);+ match baseline_shift {+ BaselineShift::Baseline => {}+ BaselineShift::Number(num) => xml.write_svg_attribute(AId::BaselineShift, num),+ BaselineShift::Subscript => xml.write_svg_attribute(AId::BaselineShift, "sub"),+ BaselineShift::Superscript => xml.write_svg_attribute(AId::BaselineShift, "super"),+ }+ }++ let cur_text = &chunk.text[span.start..span.end];++ xml.write_text(&cur_text.replace('&', "&"));++ // End for each tspan we needed to create for baseline_shift+ for _ in &span.baseline_shift {+ xml.end_element();+ }++ xml.end_element();+}diff --git a/vendor/vendor.toml b/vendor/vendor.tomlindex 53b34c43..1a38ed58 100644--- a/vendor/vendor.toml+++ b/vendor/vendor.toml@@ -171,3 +171,10 @@ upstream = "git:github.com/djeedai/bevy_hanabi@77630ff1eed8b104f34e91d23e9440428kind = "patch"reason = "frame-pure particles (raea #52): a new particle seeded by its spawn index, not the dead slot it recycles (vfx_init.wesl), and blended effects sorted by view depth from the main camera, far first as Bevy sorts its transparent phase, through the ribbons' sort pass (mod.rs, sort.rs, vfx_sort_fill.wesl); examples and GPU tests dropped"exit = "a hanabi with a deterministic mode (both changes offered upstream); then back to the git dependency and drop the copy"++[usvg]+path = "vendor/usvg"+upstream = "crates.io:0.48.1"+kind = "patch"+reason = "letter-spacing after a text chunk's last letter too, as Chrome spaces it (an anchored svg text was drawn half a spacing off and measured a spacing wide)"+exit = "a usvg release that spaces the last cluster, or none: usvg drops it on purpose"