From 8b25bf8acea3d3ec2ef781c340e817cbc0ab01d2 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 01:39:32 -0300 Subject: [PATCH 01/12] feat(render): embed real fonts in a layout's vector PDF (#1815, part 1) A layout's PDF now sets its text in the faces it is drawn in, each embedded as a subset of its glyphs (Type 0 over CIDFontType2 or CIDFontType0, Identity-H, ToUnicode), so vector editors open it as editable text. A face whose licence forbids embedding or subsetting, one drawn at another instance than its variable file's default, or one whose file can't be subset is set in Type 3 outlines as before, and the export names it with why. `"pdf": {"text": "outlines"}` on layout.export keeps today's output. New dependencies: subsetter 0.2 (MIT OR Apache-2.0, without its variable-fonts feature) and ttf-parser 0.25 as a direct dependency (already in the tree through ab_glyph). Part of #1815. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 11 + Cargo.toml | 6 + THIRD-PARTY-LICENSES.txt | 539 +++++++++++++++++- apps/rustgis-python/THIRD-PARTY-LICENSES.txt | 558 ++++++++++++++++++- crates/engine/src/cmd/layout.rs | 73 ++- crates/engine/src/tests.rs | 52 +- crates/render/Cargo.toml | 2 + crates/render/src/pdf.rs | 96 +++- crates/render/src/pdf/content.rs | 4 +- crates/render/src/pdf/embed.rs | 315 +++++++++++ crates/render/src/pdf/fonts.rs | 152 ++++- crates/ui-egui/src/lib.rs | 10 +- docs/user-guide/layouts.md | 7 + 13 files changed, 1773 insertions(+), 52 deletions(-) create mode 100644 crates/render/src/pdf/embed.rs diff --git a/Cargo.lock b/Cargo.lock index 127ec015f7..a03ce87922 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4912,8 +4912,10 @@ dependencies = [ "rustgis-map", "rustgis-tiles", "serde_json", + "subsetter", "tempfile", "tiny-skia 0.12.0", + "ttf-parser", "unicode-segmentation", "web-time", ] @@ -5607,6 +5609,15 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "subsetter" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6" +dependencies = [ + "rustc-hash 2.1.3", +] + [[package]] name = "subtle" version = "2.6.1" diff --git a/Cargo.toml b/Cargo.toml index d93fa91f35..4117964718 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,12 @@ crs-definitions = { version = "0.6", default-features = false, features = ["proj base64 = "0.23" # Deflate for PDF image streams. miniz_oxide = "0.9" +# Vector PDF text in the faces it is set in: each face embedded as a subset of its glyphs +# (opengeos/RustGIS#1815). Without its variable-font instancing, which brings skrifa and write-fonts. +subsetter = { version = "0.2", default-features = false } +# A face's embedding permissions, names and metrics for its PDF font (already in the tree through +# ab_glyph). +ttf-parser = { version = "0.25", default-features = false, features = ["std"] } roxmltree = "0.21" # CityGML: where each city object lies in a document, found without building its tree (already in # the tree through calamine). diff --git a/THIRD-PARTY-LICENSES.txt b/THIRD-PARTY-LICENSES.txt index 11137710ec..9d604906c9 100644 --- a/THIRD-PARTY-LICENSES.txt +++ b/THIRD-PARTY-LICENSES.txt @@ -42,7 +42,7 @@ rustls, rustls-native-certs, rustls-pemfile, rustls-platform-verifier, rustversi scopeguard, secrecy, secret-service, security-framework, security-framework-sys, self_cell, semver, send_wrapper, seq-macro, serde, serde_core, serde_derive, serde_json, serde_repr, sha1, sha2, shlex, sif-itree, signal-hook-registry, simdutf8, siphasher, smallvec, smol_str, socket2, spade, spirv, -spki, stable_deref_trait, static_assertions, syn, sys-locale, tar, tempfile, thiserror, +spki, stable_deref_trait, static_assertions, subsetter, syn, sys-locale, tar, tempfile, thiserror, thiserror-impl, tiberius-macros, time, time-core, tinyvec, tokio-postgres, ttf-parser, type-map, typed-path, unicode-bidi, unicode-ident, unicode-normalization, unicode-properties, unicode-segmentation, unicode-width, ureq, ureq-proto, url, utf8-zero, utf8_iter, uuid, vcpkg, @@ -11362,6 +11362,543 @@ This product includes software from the compact-thrift project (Apache 2.0) * Copyright Jörn Horstmann * https://github.com/jhorstmann/compact-thrift +==================================================================================================== +NOTICE of subsetter +==================================================================================================== + +# Code + +ttf-parser +Code from ttf-parser was used/adapted for the following parts: +- Reader, Writer, LazyArray16 and LazyArray16Iter +- `name` table parsing. +- `hmtx` table parsing. +- Most of the `cff` parsing logic as well auxiliary structs and functions +such as `calc_subroutine_bias`, `SIDMetadata`, `CIDMetadata` `RealNumber`, +`Index`, `IndexSize`, `OffsetSize`, `FDSelect`, `ArgumentStack`, `Top Dict` and `FONT Dict`, +`DictionaryParser`. + +The MIT license applies: + +Copyright (c) 2018 Yevhenii Reizner + +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. + +============================================================================== + +fonttools +Code from fonttools was used/adapted for the following parts: +- The `Decompiler` for charstrings. + +The MIT license applies: +MIT License + +Copyright (c) 2017 Just van Rossum + +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. + +# Fonts + +The SIL OPEN FONT LICENSE Version 1.1 applies to the following fonts: +- fonts/ClickerScript-Regular.ttf +- fonts/MPLUS1p-Regular.ttf +- fonts/Cantarell-VF.otf +- fonts/NotoSans-Regular.ttf +- fonts/NotoSans-Regular_var.ttf +- fonts/NotoSansCJKsc-Bold-subset1.otf +- fonts/NotoSansCJKsc-Regular.otf +- fonts/Syne-Regular_subset.oft (Copyright 2017 The Syne Project Authors (https://gitlab.com/bonjour-monde/fonderie/syne-typeface)) + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +============================================================================== + +The Bitstream Vera Fonts license applies to the following fonts: +- fonts/DejaVuSansMono.ttf + +Bitstream Vera Fonts Copyright +——————————————— + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is +a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of the fonts accompanying this license (“Fonts”) and associated +documentation files (the “Font Software”), to reproduce and distribute the +Font Software, including without limitation the rights to use, copy, merge, +publish, distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to the +following conditions: + +The above copyright and trademark notices and this permission notice shall +be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular +the designs of glyphs or characters in the Fonts may be modified and +additional glyphs or characters may be added to the Fonts, only if the fonts +are renamed to names not containing either the words “Bitstream” or the word +“Vera”. + +This License becomes null and void to the extent applicable to Fonts or Font +Software that has been modified and is distributed under the “Bitstream +Vera” names. + +The Font Software may be sold as part of a larger software package but no +copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME +FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING +ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE +FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome +Foundation, and Bitstream Inc., shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this Font Software +without prior written authorization from the Gnome Foundation or Bitstream +Inc., respectively. For further information, contact: fonts at gnome dot +org. + +Arev Fonts Copyright +——————————————— + +Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the fonts accompanying this license (“Fonts”) and +associated documentation files (the “Font Software”), to reproduce +and distribute the modifications to the Bitstream Vera Font Software, +including without limitation the rights to use, copy, merge, publish, +distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to +the following conditions: + +The above copyright and trademark notices and this permission notice +shall be included in all copies of one or more of the Font Software +typefaces. + +The Font Software may be modified, altered, or added to, and in +particular the designs of glyphs or characters in the Fonts may be +modified and additional glyphs or characters may be added to the +Fonts, only if the fonts are renamed to names not containing either +the words “Tavmjong Bah” or the word “Arev”. + +This License becomes null and void to the extent applicable to Fonts +or Font Software that has been modified and is distributed under the +“Tavmjong Bah Arev” names. + +The Font Software may be sold as part of a larger software package but +no copy of one or more of the Font Software typefaces may be sold by +itself. + +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL +TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the name of Tavmjong Bah shall not +be used in advertising or otherwise to promote the sale, use or other +dealings in this Font Software without prior written authorization +from Tavmjong Bah. For further information, contact: tavmjong @ free +. fr. + +============================================================================== + +The GUST font license applies to the following fonts: +- fonts/LatinModernRoman-Regular.otf +- fonts/EndcharInSubroutine_1.otf (derived from LatinModernRoman-Regular.otf) +- fonts/NewCMMath-Regular.otf + +% This is version 1.0, dated 22 June 2009, of the GUST Font License. +% (GUST is the Polish TeX Users Group, http://www.gust.org.pl) +% +% For the most recent version of this license see +% http://www.gust.org.pl/fonts/licenses/GUST-FONT-LICENSE.txt +% or +% http://tug.org/fonts/licenses/GUST-FONT-LICENSE.txt +% +% This work may be distributed and/or modified under the conditions +% of the LaTeX Project Public License, either version 1.3c of this +% license or (at your option) any later version. +% +% Please also observe the following clause: +% 1) it is requested, but not legally required, that derived works be +% distributed only after changing the names of the fonts comprising this +% work and given in an accompanying "manifest", and that the +% files comprising the Work, as listed in the manifest, also be given +% new names. Any exceptions to this request are also given in the +% manifest. +% +% We recommend the manifest be given in a separate file named +% MANIFEST-.txt, where is some unique identification +% of the font family. If a separate "readme" file accompanies the Work, +% we recommend a name of the form README-.txt. +% +% The latest version of the LaTeX Project Public License is in +% http://www.latex-project.org/lppl.txt and version 1.3c or later +% is part of all distributions of LaTeX version 2006/05/20 or later. + +============================================================================== + +The Apache 2.0 license applies to the following fonts: +- fonts/Roboto-Regular.ttf + + + 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 CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +============================================================================== + +The MIT license applies to the following fonts: +- fonts/TestTTC.ttc + +MIT License + +Copyright (c) 2017 Just van Rossum + +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. + ==================================================================================================== Colour maps. Scientific colour maps sampled at evenly spaced stops (scientific.rs): Viridis, Plasma, Inferno and Magma by Stéfan van der Walt and Nathaniel Smith (CC0-1.0), and Cividis by Jamie R. diff --git a/apps/rustgis-python/THIRD-PARTY-LICENSES.txt b/apps/rustgis-python/THIRD-PARTY-LICENSES.txt index b97ebd0155..ccd3e9ad4e 100644 --- a/apps/rustgis-python/THIRD-PARTY-LICENSES.txt +++ b/apps/rustgis-python/THIRD-PARTY-LICENSES.txt @@ -28,16 +28,17 @@ ordered-stream, owned_ttf_parser, parking, parking_lot, parking_lot_core, percen pin-project-lite, piper, pkg-config, png, polling, postgres, postgres-protocol, postgres-types, proc-macro2, proj4rs, proj4rs-geodesic, pyo3, pyo3-build-config, pyo3-ffi, pyo3-macros, pyo3-macros-backend, quote, rand, rayon, rayon-core, regex, regex-automata, regex-syntax, ring, -robust, roxmltree, rstar, rustc_version, rustix, rustls, rustls-native-certs, rustls-pemfile, -rustls-platform-verifier, rustversion, ryu, scopeguard, secrecy, secret-service, security-framework, -security-framework-sys, semver, seq-macro, serde, serde_core, serde_derive, serde_json, serde_repr, -sha1, sha2, shlex, sif-itree, signal-hook-registry, simdutf8, siphasher, smallvec, socket2, spade, -spki, stable_deref_trait, syn, sys-locale, tar, tempfile, thiserror, thiserror-impl, -tiberius-macros, time, time-core, tinyvec, tokio-postgres, ttf-parser, typed-path, unicode-bidi, -unicode-ident, unicode-normalization, unicode-properties, unicode-segmentation, ureq, ureq-proto, -url, utf8-zero, utf8_iter, uuid, vcpkg, version_check, wasm-bindgen, wasm-bindgen-macro, -wasm-bindgen-macro-support, wasm-bindgen-shared, wasmi, wasmi_collections, wasmi_core, wasmi_ir, -wasmparser, web-sys, weezl, whoami, winauth, wkt, x509-cert, xattr, zeroize, zune-core, zune-jpeg +robust, roxmltree, rstar, rustc-hash, rustc_version, rustix, rustls, rustls-native-certs, +rustls-pemfile, rustls-platform-verifier, rustversion, ryu, scopeguard, secrecy, secret-service, +security-framework, security-framework-sys, semver, seq-macro, serde, serde_core, serde_derive, +serde_json, serde_repr, sha1, sha2, shlex, sif-itree, signal-hook-registry, simdutf8, siphasher, +smallvec, socket2, spade, spki, stable_deref_trait, subsetter, syn, sys-locale, tar, tempfile, +thiserror, thiserror-impl, tiberius-macros, time, time-core, tinyvec, tokio-postgres, ttf-parser, +typed-path, unicode-bidi, unicode-ident, unicode-normalization, unicode-properties, +unicode-segmentation, ureq, ureq-proto, url, utf8-zero, utf8_iter, uuid, vcpkg, version_check, +wasm-bindgen, wasm-bindgen-macro, wasm-bindgen-macro-support, wasm-bindgen-shared, wasmi, +wasmi_collections, wasmi_core, wasmi_ir, wasmparser, web-sys, weezl, whoami, winauth, wkt, +x509-cert, xattr, zeroize, zune-core, zune-jpeg ==================================================================================================== Apache License @@ -9355,6 +9356,543 @@ This product includes software from the compact-thrift project (Apache 2.0) * Copyright Jörn Horstmann * https://github.com/jhorstmann/compact-thrift +==================================================================================================== +NOTICE of subsetter +==================================================================================================== + +# Code + +ttf-parser +Code from ttf-parser was used/adapted for the following parts: +- Reader, Writer, LazyArray16 and LazyArray16Iter +- `name` table parsing. +- `hmtx` table parsing. +- Most of the `cff` parsing logic as well auxiliary structs and functions +such as `calc_subroutine_bias`, `SIDMetadata`, `CIDMetadata` `RealNumber`, +`Index`, `IndexSize`, `OffsetSize`, `FDSelect`, `ArgumentStack`, `Top Dict` and `FONT Dict`, +`DictionaryParser`. + +The MIT license applies: + +Copyright (c) 2018 Yevhenii Reizner + +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. + +============================================================================== + +fonttools +Code from fonttools was used/adapted for the following parts: +- The `Decompiler` for charstrings. + +The MIT license applies: +MIT License + +Copyright (c) 2017 Just van Rossum + +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. + +# Fonts + +The SIL OPEN FONT LICENSE Version 1.1 applies to the following fonts: +- fonts/ClickerScript-Regular.ttf +- fonts/MPLUS1p-Regular.ttf +- fonts/Cantarell-VF.otf +- fonts/NotoSans-Regular.ttf +- fonts/NotoSans-Regular_var.ttf +- fonts/NotoSansCJKsc-Bold-subset1.otf +- fonts/NotoSansCJKsc-Regular.otf +- fonts/Syne-Regular_subset.oft (Copyright 2017 The Syne Project Authors (https://gitlab.com/bonjour-monde/fonderie/syne-typeface)) + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +============================================================================== + +The Bitstream Vera Fonts license applies to the following fonts: +- fonts/DejaVuSansMono.ttf + +Bitstream Vera Fonts Copyright +——————————————— + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is +a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of the fonts accompanying this license (“Fonts”) and associated +documentation files (the “Font Software”), to reproduce and distribute the +Font Software, including without limitation the rights to use, copy, merge, +publish, distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to the +following conditions: + +The above copyright and trademark notices and this permission notice shall +be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular +the designs of glyphs or characters in the Fonts may be modified and +additional glyphs or characters may be added to the Fonts, only if the fonts +are renamed to names not containing either the words “Bitstream” or the word +“Vera”. + +This License becomes null and void to the extent applicable to Fonts or Font +Software that has been modified and is distributed under the “Bitstream +Vera” names. + +The Font Software may be sold as part of a larger software package but no +copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, +TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME +FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING +ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE +FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome +Foundation, and Bitstream Inc., shall not be used in advertising or +otherwise to promote the sale, use or other dealings in this Font Software +without prior written authorization from the Gnome Foundation or Bitstream +Inc., respectively. For further information, contact: fonts at gnome dot +org. + +Arev Fonts Copyright +——————————————— + +Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the fonts accompanying this license (“Fonts”) and +associated documentation files (the “Font Software”), to reproduce +and distribute the modifications to the Bitstream Vera Font Software, +including without limitation the rights to use, copy, merge, publish, +distribute, and/or sell copies of the Font Software, and to permit +persons to whom the Font Software is furnished to do so, subject to +the following conditions: + +The above copyright and trademark notices and this permission notice +shall be included in all copies of one or more of the Font Software +typefaces. + +The Font Software may be modified, altered, or added to, and in +particular the designs of glyphs or characters in the Fonts may be +modified and additional glyphs or characters may be added to the +Fonts, only if the fonts are renamed to names not containing either +the words “Tavmjong Bah” or the word “Arev”. + +This License becomes null and void to the extent applicable to Fonts +or Font Software that has been modified and is distributed under the +“Tavmjong Bah Arev” names. + +The Font Software may be sold as part of a larger software package but +no copy of one or more of the Font Software typefaces may be sold by +itself. + +THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL +TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the name of Tavmjong Bah shall not +be used in advertising or otherwise to promote the sale, use or other +dealings in this Font Software without prior written authorization +from Tavmjong Bah. For further information, contact: tavmjong @ free +. fr. + +============================================================================== + +The GUST font license applies to the following fonts: +- fonts/LatinModernRoman-Regular.otf +- fonts/EndcharInSubroutine_1.otf (derived from LatinModernRoman-Regular.otf) +- fonts/NewCMMath-Regular.otf + +% This is version 1.0, dated 22 June 2009, of the GUST Font License. +% (GUST is the Polish TeX Users Group, http://www.gust.org.pl) +% +% For the most recent version of this license see +% http://www.gust.org.pl/fonts/licenses/GUST-FONT-LICENSE.txt +% or +% http://tug.org/fonts/licenses/GUST-FONT-LICENSE.txt +% +% This work may be distributed and/or modified under the conditions +% of the LaTeX Project Public License, either version 1.3c of this +% license or (at your option) any later version. +% +% Please also observe the following clause: +% 1) it is requested, but not legally required, that derived works be +% distributed only after changing the names of the fonts comprising this +% work and given in an accompanying "manifest", and that the +% files comprising the Work, as listed in the manifest, also be given +% new names. Any exceptions to this request are also given in the +% manifest. +% +% We recommend the manifest be given in a separate file named +% MANIFEST-.txt, where is some unique identification +% of the font family. If a separate "readme" file accompanies the Work, +% we recommend a name of the form README-.txt. +% +% The latest version of the LaTeX Project Public License is in +% http://www.latex-project.org/lppl.txt and version 1.3c or later +% is part of all distributions of LaTeX version 2006/05/20 or later. + +============================================================================== + +The Apache 2.0 license applies to the following fonts: +- fonts/Roboto-Regular.ttf + + + 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 CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +============================================================================== + +The MIT license applies to the following fonts: +- fonts/TestTTC.ttc + +MIT License + +Copyright (c) 2017 Just van Rossum + +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. + ==================================================================================================== Colour maps. Scientific colour maps sampled at evenly spaced stops (scientific.rs): Viridis, Plasma, Inferno and Magma by Stéfan van der Walt and Nathaniel Smith (CC0-1.0), and Cividis by Jamie R. diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 2ca805d4fc..650bd3d84a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -129,7 +129,7 @@ pub fn commands() -> Vec { .params(r#"{"layout"?}"#), C::new("layout.export", "Export Layout", "Publish › Output", |s, p| super::exports::write_here(s, p, "layout.export")).inputs(layout_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() - .params(r#"{"layout"?, "path": "*.png|*.pdf|*.svg" (PNG/SVG: current page; SVG: each element a group of its own; text and shapes as SVG, map frames and surrounds as vectors, rasters and tiles in them as pictures at dpi), "dpi"?: 72..600, "allPages"?: bool (PDF only; default true: every map series page, up to 500; false: the current page), "georeference"?: bool (PDF only; default true: map frames carry their coordinates, a GeoPDF; false: none)}"#), + .params(r#"{"layout"?, "path": "*.png|*.pdf|*.svg" (PNG/SVG: current page; SVG: each element a group of its own; text and shapes as SVG, map frames and surrounds as vectors, rasters and tiles in them as pictures at dpi), "dpi"?: 72..600, "allPages"?: bool (PDF only; default true: every map series page, up to 500; false: the current page), "georeference"?: bool (PDF only; default true: map frames carry their coordinates, a GeoPDF; false: none), "pdf"?: {"text"?: "fonts" (default: text in its faces, embedded as subsets, editable in a vector editor; a face that can't be is set in outlines, and said)|"outlines" (glyphs as outlines, as print shops ask)}}"#), C::new("layout.save", "Save Layout File", "Publish › Save As", |s, p| { let path = ps(p, "path").ok_or("path is required")?; let l = active(s, p)?.clone(); @@ -4188,15 +4188,24 @@ fn named_fonts_unread(layout: &Layout) -> Option<&'static str> { /// Layout `li` as a PDF (kept as vectors; every map series page when `all`; its map frames /// georeferenced) or a PNG of the current page, at `dpi`. pub fn layout_bytes(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool) -> Result, String> { - layout_bytes_with(s, li, pdf, dpi, all, true) + layout_bytes_with(s, li, pdf, dpi, all, true, rustgis_render::pdf::Text::Fonts) } -/// [`layout_bytes`], a PDF's map frames georeferenced only when `georeference` (#1191). -/// Returns an actionable error if a linked archive changes while the pages are drawn. -pub fn layout_bytes_with(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool, georeference: bool) -> Result, String> { +/// [`layout_bytes`], a PDF's map frames georeferenced only when `georeference` (#1191), its text +/// written as `text` says (#1815). Returns an actionable error if a linked archive changes while +/// the pages are drawn. +pub fn layout_bytes_with( + s: &mut Session, + li: usize, + pdf: bool, + dpi: f64, + all: bool, + georeference: bool, + text: rustgis_render::pdf::Text, +) -> Result, String> { let layout = s.project.layouts.get(li).ok_or("no layout")?; let revisions = rustgis_render::layout::archive_revisions(layout, &s.project.maps); - let result = layout_bytes_inner(s, li, pdf, dpi, all, georeference); + let result = layout_bytes_inner(s, li, pdf, dpi, all, georeference, text); let layout = s.project.layouts.get(li).ok_or("no layout")?; revisions.finish_revision( rustgis_render::layout::archive_revisions(layout, &s.project.maps), @@ -4205,7 +4214,15 @@ pub fn layout_bytes_with(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: b )? } -fn layout_bytes_inner(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool, georeference: bool) -> Result, String> { +fn layout_bytes_inner( + s: &mut Session, + li: usize, + pdf: bool, + dpi: f64, + all: bool, + georeference: bool, + text: rustgis_render::pdf::Text, +) -> Result, String> { let saved = s.project.layouts.get(li).ok_or("no layout")?.clone(); if let Some(note) = named_fonts_unread(&saved) { s.warn(note); @@ -4309,7 +4326,30 @@ fn layout_bytes_inner(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool let (pages, png) = result?; pictured_notices(s, &frames_pictured, &pages_pictured); georeference_notices(s, &left_out, &by_corners, pages.len()); - if pdf { Ok(rustgis_render::pdf::write(&pages, &saved.name)) } else { png.ok_or_else(|| "nothing to draw".to_string()) } + if !pdf { + return png.ok_or_else(|| "nothing to draw".to_string()); + } + let (bytes, outlined) = rustgis_render::pdf::write_with(&pages, &saved.name, text); + outlined_notice(s, &outlined); + Ok(bytes) +} + +/// Says which faces a PDF set in outlines though its text was to be in fonts (#1815), with why: +/// their text is drawings, not text, in a vector editor. One notice, the faces counted. +fn outlined_notice(s: &mut Session, outlined: &[rustgis_render::pdf::Outlined]) { + let n = outlined.len(); + if n == 0 { + return; + } + let mut each: Vec = outlined.iter().take(10).map(|o| format!("{} ({})", o.face, o.why)).collect(); + if n > 10 { + each.push(format!("and {} more", n - 10)); + } + s.warn(format!( + "The PDF sets the text of {n} face{} as outlines, not as text a vector editor can edit: {}", + if n == 1 { "" } else { "s" }, + each.join(", ") + )); } /// Says which map frames a PDF doesn't georeference, with why, and which it georeferences by their @@ -4425,6 +4465,20 @@ pub(crate) fn pictured_notices(s: &mut Session, frames: &[(u32, String)], pages: } } +/// How `layout.export`'s `"pdf": {"text": …}` asks a PDF's text to be written (#1815): in its +/// fonts unless it says `"outlines"`. +fn pdf_text(p: &Value) -> Result { + use rustgis_render::pdf::Text; + let Some(pdf) = p.get("pdf").filter(|v| !v.is_null()) else { return Ok(Text::Fonts) }; + let Some(pdf) = pdf.as_object() else { return Err(r#"pdf is an object: {"text": "fonts"|"outlines"}"#.into()) }; + match pdf.get("text").and_then(Value::as_str) { + None if pdf.get("text").is_none_or(Value::is_null) => Ok(Text::Fonts), + Some("fonts") => Ok(Text::Fonts), + Some("outlines") => Ok(Text::Outlines), + _ => Err(r#"pdf.text is "fonts" or "outlines""#.into()), + } +} + /// `layout.export`: a layout to a PNG, PDF or SVG. It draws a copy of the project, so the project /// can change meanwhile (a map series steps through its pages on the copy); a cancelled export /// stops at the next page, or its map's wait for tiles, and writes nothing. @@ -4437,6 +4491,7 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Result = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + (String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into_owned(), said) + }) + }; + let (pdf, said) = export(&mut s, json!({})).unwrap(); + assert!(pdf.contains("/Subtype /Type0") && pdf.contains("/Encoding /Identity-H"), "{said:?}"); + assert!(pdf.contains("/Subtype /CIDFontType2") || pdf.contains("/Subtype /CIDFontType0")); + assert!(!pdf.contains("/Subtype /Type3"), "every face embedded: {said:?}"); + assert!(!said.iter().any(|t| t.contains("as outlines")), "{said:?}"); + // The text read back: the title's and the labels' characters are in the fonts' maps. + let raw = std::fs::read(&path).unwrap(); + let maps: String = raw + .windows(8) + .enumerate() + .filter(|(_, w)| w == b"\nstream\n") + .filter_map(|(i, _)| miniz_oxide::inflate::decompress_to_vec_zlib(&raw[i + 8..]).ok()) + .map(|d| String::from_utf8_lossy(&d).into_owned()) + .filter(|d| d.contains("<0000> ")) + .collect(); + for ch in ['O', 'ç', 'ã'] { + assert!(maps.contains(&format!("> <{:04X}>", ch as u32)), "{ch}"); + } + let (outlines, said) = export(&mut s, json!({"pdf": {"text": "outlines"}})).unwrap(); + assert!(outlines.contains("/Subtype /Type3") && !outlines.contains("/Type0"), "{said:?}"); + assert_eq!(export(&mut s, json!({"pdf": {"text": "fonts"}})).unwrap().0.len(), pdf.len()); + for bad in [json!({"pdf": {"text": "curves"}}), json!({"pdf": "outlines"}), json!({"pdf": {"text": 1}})] { + let err = export(&mut s, bad.clone()).unwrap_err(); + assert!(err.contains("\"fonts\" or \"outlines\"") || err.contains("fonts\"|\"outlines"), "{bad}: {err}"); + } + let _ = std::fs::remove_file(&path); +} + /// A layout's PDF georeferences its map frames (#1191): each as an ISO 32000 viewport with its /// corners and its map's coordinate system, so that the frame's corners, taken back to the map, /// make the frame's rectangle. A tilted frame is left out, and said. diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 7ad7a3ee3e..a12360dcf8 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -24,6 +24,8 @@ base64 = { workspace = true } web-time = { workspace = true } serde_json = { workspace = true } miniz_oxide = { workspace = true } +subsetter = { workspace = true } +ttf-parser = { workspace = true } rustgis-tiles = { workspace = true } [dev-dependencies] diff --git a/crates/render/src/pdf.rs b/crates/render/src/pdf.rs index c96d80c172..283ad60672 100644 --- a/crates/render/src/pdf.rs +++ b/crates/render/src/pdf.rs @@ -1,14 +1,15 @@ //! A PDF writer. A page is either one picture (a rendered page, at the page's size) or a //! [`Drawing`] kept as vectors: its paths, text and pictures become the page's content, its text -//! set in fonts whose glyphs are their outlines (Type 3), searchable and copyable through each -//! font's map back to Unicode. A page's map frames can be georeferenced ([`Viewport`]), which -//! makes the document a GeoPDF. +//! set in its faces embedded as subsets, or in fonts whose glyphs are their outlines (Type 3) +//! ([`Text`]); searchable and copyable either way, through each font's map back to Unicode. A +//! page's map frames can be georeferenced ([`Viewport`]), which makes the document a GeoPDF. use tiny_skia::Pixmap; use crate::vector::{Drawing, Item, deflate_rows}; mod content; +mod embed; mod fonts; /// One PDF page and its size in millimetres. Pictures are compressed as they are made, so a long @@ -224,15 +225,67 @@ impl Doc { } } -/// Writes the pages as a PDF document. +/// How a document's vector text is written (#1815). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Text { + /// In the faces it is set in, embedded as subsets, so that a vector editor reads it as text; + /// a face that can't be is set in outlines, and said ([`Outlined`]). + Fonts, + /// In fonts whose glyphs are their outlines (Type 3): searchable and copyable, but drawings + /// in a vector editor, as a print shop asking for outlined type wants. + Outlines, +} + +/// A face whose text was set in outlines though [`Text::Fonts`] was asked for, and why. +#[derive(Clone, Debug, PartialEq)] +pub struct Outlined { + pub face: String, + pub why: String, +} + +/// Writes the pages as a PDF document, its text in outlines ([`Text::Outlines`]). pub fn write(pages: &[Page], title: &str) -> Vec { + write_with(pages, title, Text::Outlines).0 +} + +/// Writes the pages as a PDF document, its text as `text` says, and the faces set in outlines +/// though fonts were asked for. +pub fn write_with(pages: &[Page], title: &str, text: Text) -> (Vec, Vec) { + // Every face's glyphs, gathered before any is written: a face is embedded or not as a whole, + // and its glyphs' codes are the subset's. + let mut used: Vec<(&'static ab_glyph::FontRef<'static>, Vec)> = Vec::new(); + if text == Text::Fonts { + let mut seen = (std::collections::HashMap::new(), std::collections::HashSet::new()); + for p in pages { + if let Content::Vector { items, .. } = &p.content { + gather(items, &mut used, &mut seen); + } + } + } + let (mut real, mut outlined, mut room) = (Vec::new(), Vec::new(), embed::MAX_EMBEDDED); + for (font, glyphs) in used { + match embed::embed(font, &glyphs, room) { + Ok(e) => { + room = room.saturating_sub(e.file.len()); + real.push((font, e)); + } + Err(why) => outlined.push(Outlined { face: embed::face_name(font), why: why.to_string() }), + } + } // Georeferenced frames make the document PDF 1.7 with Adobe's extension level 3, where - // geospatial measures are defined (since taken into ISO 32000-2); what else it holds is 1.4. + // geospatial measures are defined (since taken into ISO 32000-2); an embedded CFF face makes + // it 1.6, where OpenType font files are; what else it holds is 1.4. let geo = pages.iter().any(|p| !p.viewports.is_empty()); - let mut doc = if geo { Doc::of_version("1.7") } else { Doc::new() }; + let mut doc = if geo { + Doc::of_version("1.7") + } else if real.iter().any(|(_, e)| e.cff) { + Doc::of_version("1.6") + } else { + Doc::new() + }; let (catalog, tree, info) = (doc.reserve(), doc.reserve(), doc.reserve()); let ids: Vec = pages.iter().map(|_| doc.reserve()).collect(); - let mut fonts = fonts::Fonts::default(); + let mut fonts = fonts::Fonts::with_real(&mut doc, real); for (p, &page) in pages.iter().zip(&ids) { let (pw, ph) = (p.width_mm * 72.0 / 25.4, p.height_mm * 72.0 / 25.4); let (contents, resources) = match &p.content { @@ -273,7 +326,34 @@ pub fn write(pages: &[Page], title: &str) -> Vec { let kids: Vec = ids.iter().map(|i| format!("{i} 0 R")).collect(); doc.put(tree, format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), pages.len()).as_bytes()); doc.put(info, format!("<< /Title {} /Producer (RustGIS) >>", text_string(title)).as_bytes()); - doc.finish(catalog, info) + (doc.finish(catalog, info), outlined) +} + +/// Faces' places in the list of glyphs used, by their address, and the glyphs already listed. +type Seen = (std::collections::HashMap, std::collections::HashSet<(usize, u16)>); + +/// Adds the glyphs `items` set to `used`, face by face, each once. +fn gather(items: &[Item], used: &mut Vec<(&'static ab_glyph::FontRef<'static>, Vec)>, seen: &mut Seen) { + for item in items { + match item { + Item::Glyphs(run) => { + let key = std::ptr::from_ref(run.font) as usize; + let at = *seen.0.entry(key).or_insert_with(|| { + used.push((run.font, Vec::new())); + used.len() - 1 + }); + for g in &run.glyphs { + if seen.1.insert((key, g.id.0)) + && let Some((_, glyphs)) = used.get_mut(at) + { + glyphs.push(g.id); + } + } + } + Item::Group(g) => gather(&g.items, used, seen), + Item::Fill { .. } | Item::Stroke { .. } | Item::Image(_) => {} + } + } } /// A PDF literal string of any length (a WKT): ASCII in parentheses, its backslashes and diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index 920681ccd7..e6d96d336f 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -236,7 +236,7 @@ impl Writer<'_> { end(out, st, saved); } - /// Sets a run of glyphs in the document's Type 3 fonts, each at its pen position. + /// Sets a run of glyphs in the document's fonts, each at its pen position. fn glyphs(&mut self, out: &mut Vec, st: &mut State, run: &GlyphRun) { let mut placed = Vec::with_capacity(run.glyphs.len()); for g in &run.glyphs { @@ -273,7 +273,7 @@ impl Writer<'_> { if shift.abs() >= 0.05 { num(out, shift, 1); } - let _ = write!(out, "<{:02X}>", p.code); + let _ = if p.wide { write!(out, "<{:04X}>", p.code) } else { write!(out, "<{:02X}>", p.code) }; pen = x + p.advance * size; } out.extend_from_slice(b"] TJ\nET\n"); diff --git a/crates/render/src/pdf/embed.rs b/crates/render/src/pdf/embed.rs new file mode 100644 index 0000000000..411693c070 --- /dev/null +++ b/crates/render/src/pdf/embed.rs @@ -0,0 +1,315 @@ +//! A face embedded in a PDF as itself (#1815): a subset of its file holding the glyphs the +//! document sets, written as a composite font (Type 0 over a CID font, Identity-H), so that a +//! vector editor reads its text as text. A face is embedded only when its file draws exactly what +//! the export draws (the face at its file's default instance) and its licence allows it; anything +//! else is set in Type 3 outlines, with the reason. + +use ab_glyph::{Font, FontRef, GlyphId, OutlineCurve}; + +/// The largest subset of one face embedded, and of all of a document's faces together: past +/// them a face's text is set in outlines. +const MAX_SUBSET: usize = 8 << 20; +pub(super) const MAX_EMBEDDED: usize = 32 << 20; +/// The most faces of a collection (`.ttc`) looked through for the one drawn. +const MAX_COLLECTION: u32 = 64; + +/// A face's subset, ready to be written. +pub(super) struct Embedded { + /// The subset font file, and whether its outlines are CFF (else TrueType). + pub file: Vec, + pub cff: bool, + /// Its name, with the subset's tag (`ABCDEF+Name`). + pub name: String, + /// The subset's glyph (the CID the content sets) of each glyph of the face. + pub remapper: subsetter::GlyphRemapper, + /// Its descriptor's metrics, in thousandths of the em: box, ascent, descent, cap height, + /// italic angle in degrees. + pub bbox: [f32; 4], + pub ascent: f32, + pub descent: f32, + pub cap_height: f32, + pub italic_angle: f32, +} + +/// Why a face's text is set in outlines rather than in the face itself. +#[derive(Clone, Debug, PartialEq)] +pub(super) enum Refused { + /// Its licence forbids embedding (`fsType` 2), subsetting (0x100), or allows bitmaps only (0x200). + Licence(&'static str), + /// It is drawn at a variable font's instance other than its file's default. + Instance, + /// Its file doesn't hold the face as it is drawn. + NotInFile, + /// Its file can't be read or subset. + Unreadable(String), + /// Its subset would pass [`MAX_SUBSET`], or the document's faces [`MAX_EMBEDDED`]: the limit + /// passed, in bytes. + TooLarge(usize), +} + +impl std::fmt::Display for Refused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Refused::Licence(what) => write!(f, "its licence {what}"), + Refused::Instance => f.write_str("it is drawn at another weight or width than its file's default"), + Refused::NotInFile => f.write_str("its file doesn't hold it as drawn"), + Refused::Unreadable(e) => write!(f, "its file could not be subset: {e}"), + Refused::TooLarge(limit) if *limit == MAX_SUBSET => write!(f, "its subset passes {} MB", MAX_SUBSET >> 20), + Refused::TooLarge(_) => write!(f, "the document's embedded faces would pass {} MB", MAX_EMBEDDED >> 20), + } + } +} + +/// A name for the face in a notice: its full name, else its family, else its PostScript name. +pub(super) fn face_name(font: &FontRef<'_>) -> String { + let data = font.font_data(); + let face = (0..collection_len(data)).find_map(|i| ttf_parser::Face::parse(data, i).ok().filter(|f| same_face(font, f))); + face.and_then(|f| { + [ttf_parser::name_id::FULL_NAME, ttf_parser::name_id::FAMILY, ttf_parser::name_id::POST_SCRIPT_NAME] + .into_iter() + .find_map(|id| f.names().into_iter().filter(|n| n.name_id == id).find_map(|n| n.to_string())) + }) + .map(|n| n.chars().filter(|c| !c.is_control()).take(80).collect()) + .unwrap_or_else(|| "an unnamed face".into()) +} + +/// How many faces `data` holds: one for a single font file. +fn collection_len(data: &[u8]) -> u32 { + ttf_parser::fonts_in_collection(data).unwrap_or(1).clamp(1, MAX_COLLECTION) +} + +/// Whether `face` parsed from the file is the one `font` was read as: the same number of glyphs +/// and units per em (a quick check before comparing outlines). +fn same_face(font: &FontRef<'_>, face: &ttf_parser::Face) -> bool { + usize::from(face.number_of_glyphs()) == font.glyph_count() && font.units_per_em() == Some(f32::from(face.units_per_em())) +} + +/// The face `font` as a subset holding `glyphs`, or why it can't be. Never panics, whatever the +/// file holds: a subsetter that fails, or would, leaves the face to outlines. `room` is what the +/// document can still embed. +pub(super) fn embed(font: &FontRef<'_>, glyphs: &[GlyphId], room: usize) -> Result { + let data = font.font_data(); + // The face of the file that draws these glyphs as `font` does (a collection's faces can share + // glyphs; any that draws them alike will do), at the file's own default instance. + let index = (0..collection_len(data)).find(|&i| { + FontRef::try_from_slice_and_index(data, i).is_ok_and(|fresh| { + fresh.glyph_count() == font.glyph_count() + && fresh.units_per_em() == font.units_per_em() + && glyphs.iter().all(|&g| draws_alike(font, &fresh, g)) + }) + }); + let Some(index) = index else { + return Err(if ab_glyph::VariableFont::variations(font).is_empty() { Refused::NotInFile } else { Refused::Instance }); + }; + let face = ttf_parser::Face::parse(data, index).map_err(|e| Refused::Unreadable(e.to_string()))?; + if let Some(os2) = face.tables().os2 { + if os2.permissions() == Some(ttf_parser::Permissions::Restricted) { + return Err(Refused::Licence("forbids embedding")); + } + if !os2.is_subsetting_allowed() { + return Err(Refused::Licence("forbids subsetting")); + } + if !os2.is_outline_embedding_allowed() { + return Err(Refused::Licence("allows embedding bitmaps only")); + } + } + let mut remapper = subsetter::GlyphRemapper::new(); + for g in glyphs { + remapper.remap(g.0); + } + let subset = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| subsetter::subset(data, index, &remapper))); + let file = match subset { + Ok(Ok(file)) => file, + Ok(Err(e)) => return Err(Refused::Unreadable(e.to_string())), + Err(_) => return Err(Refused::Unreadable("the subsetter failed".into())), + }; + if file.len() > MAX_SUBSET { + return Err(Refused::TooLarge(MAX_SUBSET)); + } + if file.len() > room { + return Err(Refused::TooLarge(MAX_EMBEDDED)); + } + let k = 1000.0 / f32::from(face.units_per_em().max(1)); + let b = face.global_bounding_box(); + let name = face + .names() + .into_iter() + .filter(|n| n.name_id == ttf_parser::name_id::POST_SCRIPT_NAME) + .find_map(|n| n.to_string()) + .unwrap_or_default(); + let name: String = name.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')).take(56).collect(); + let name = if name.is_empty() { "Face".to_string() } else { name }; + Ok(Embedded { + cff: face.tables().cff.is_some(), + name: format!("{}+{name}", tag(&name, glyphs)), + remapper, + bbox: [f32::from(b.x_min) * k, f32::from(b.y_min) * k, f32::from(b.x_max) * k, f32::from(b.y_max) * k], + ascent: f32::from(face.ascender()) * k, + descent: f32::from(face.descender()) * k, + cap_height: f32::from(face.capital_height().unwrap_or(face.ascender())) * k, + italic_angle: face.italic_angle(), + file, + }) +} + +/// Whether glyph `g` has the same advance and outline in both faces. +fn draws_alike(a: &impl Font, b: &impl Font, g: GlyphId) -> bool { + if a.h_advance_unscaled(g).to_bits() != b.h_advance_unscaled(g).to_bits() { + return false; + } + match (a.outline(g), b.outline(g)) { + (None, None) => true, + (Some(x), Some(y)) => { + x.curves.len() == y.curves.len() && x.curves.iter().zip(&y.curves).all(|(p, q)| curve_points(p) == curve_points(q)) + } + _ => false, + } +} + +/// A curve's kind and points, to compare. +fn curve_points(c: &OutlineCurve) -> (u8, [(f32, f32); 4]) { + let p = |q: &ab_glyph::Point| (q.x, q.y); + match c { + OutlineCurve::Line(a, b) => (0, [p(a), p(b), (0.0, 0.0), (0.0, 0.0)]), + OutlineCurve::Quad(a, b, c) => (1, [p(a), p(b), p(c), (0.0, 0.0)]), + OutlineCurve::Cubic(a, b, c, d) => (2, [p(a), p(b), p(c), p(d)]), + } +} + +/// A subset's six-letter tag, from its face's name and glyphs: the same subset, the same tag. +fn tag(name: &str, glyphs: &[GlyphId]) -> String { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in name.bytes().chain(glyphs.iter().flat_map(|g| g.0.to_le_bytes())) { + h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); + } + (0..6).map(|i| char::from(b'A' + ((h >> (i * 5)) % 26) as u8)).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pdf::tests::objects; + use crate::pdf::{Page, Text, write, write_with}; + use crate::vector::{Drawing, Glyph, GlyphRun}; + use tiny_skia::{Color, Transform}; + + /// A face of the test's own (egui's bundled Ubuntu Light, which allows embedding), its bytes + /// changed by `patch` first, parsed and kept. + fn face(patch: impl FnOnce(&mut Vec)) -> &'static FontRef<'static> { + let mut bytes = epaint_default_fonts::UBUNTU_LIGHT.to_vec(); + patch(&mut bytes); + let bytes: &'static [u8] = Box::leak(bytes.into_boxed_slice()); + Box::leak(Box::new(FontRef::try_from_slice(bytes).unwrap())) + } + + /// Where the table `tag` starts in a single font file. + fn table(bytes: &[u8], tag: &[u8; 4]) -> usize { + let n = usize::from(u16::from_be_bytes([bytes[4], bytes[5]])); + let rec = (0..n).map(|i| 12 + 16 * i).find(|&r| &bytes[r..r + 4] == tag).unwrap(); + u32::from_be_bytes(bytes[rec + 8..rec + 12].try_into().unwrap()) as usize + } + + /// A page with `text` set in `font` twice: on the page (a layout text) and in a group (a + /// map's label), the second slanted as a synthetic italic is. + fn page(font: &'static FontRef<'static>, text: &str) -> Page { + let run = |kx: f32| GlyphRun { + font, + size: 20.0, + color: Color::BLACK, + transform: Transform::from_row(1.0, 0.0, kx, 1.0, 10.0, 40.0), + glyphs: text.chars().zip(0..).map(|(ch, i)| Glyph { id: font.glyph_id(ch), x: 11.0 * i as f32, ch }).collect(), + }; + let mut d = Drawing::new(200.0, 100.0); + d.glyphs(run(0.0)); + let mut label = Drawing::new(200.0, 100.0); + label.glyphs(run(-0.2)); + d.place(label, Transform::from_translate(0.0, 40.0), 1.0, rustgis_map::effects::Blend::Normal, None); + Page::drawing(d, 100.0, 50.0) + } + + /// Text in fonts is its face embedded as a subset (#1815), a Type 0 font over a TrueType CID + /// font, the label and the slanted copy set in it too, and its text still read back. + #[test] + fn text_in_fonts_is_its_face_embedded() { + let font = face(|_| ()); + let (pdf, outlined) = write_with(&[page(font, "Ação")], "Fonts", Text::Fonts); + assert!(outlined.is_empty(), "{outlined:?}"); + let objs = objects(&pdf); + let dicts: Vec<&str> = objs.iter().map(|o| o.0.as_str()).collect(); + assert!(dicts.iter().any(|d| d.contains("/Subtype /Type0") && d.contains("/Encoding /Identity-H")), "{dicts:?}"); + assert!(dicts.iter().any(|d| d.contains("/Subtype /CIDFontType2") && d.contains("/CIDToGIDMap /Identity"))); + assert!(!dicts.iter().any(|d| d.contains("/Type3")), "no glyph is set in outlines"); + let file = objs.iter().find(|o| o.0.contains("/Length1")).unwrap(); + assert!(file.1.len() < epaint_default_fonts::UBUNTU_LIGHT.len() / 4, "a subset: {} bytes", file.1.len()); + assert!(FontRef::try_from_slice(&file.1).is_ok(), "the subset is a font"); + // Each character back from its CID, and the content setting two-byte codes. + let cmap = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|s| s.contains("<0000> ")).unwrap(); + for ch in ['A', 'ç', 'ã', 'o'] { + assert!(cmap.contains(&format!("> <{:04X}>", ch as u32)), "{ch} in {cmap}"); + } + let content = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|s| s.contains(" TJ")).unwrap(); + assert!(content.contains("[<0001>") && content.contains("<0004>] TJ"), "codes are CIDs: {content}"); + // Outlines, as before, whatever the face allows. + let (outlines, none) = write_with(&[page(font, "Ação")], "Fonts", Text::Outlines); + assert!(none.is_empty() && outlines == write(&[page(font, "Ação")], "Fonts")); + let text = String::from_utf8_lossy(&outlines); + assert!(text.contains("/Subtype /Type3") && !text.contains("/Type0")); + } + + /// A face whose licence forbids embedding (fsType 2) is set in outlines, and said. + #[test] + fn a_face_that_forbids_embedding_is_set_in_outlines() { + let font = face(|b| { + let os2 = table(b, b"OS/2"); + b[os2 + 8..os2 + 10].copy_from_slice(&2u16.to_be_bytes()); + }); + let (pdf, outlined) = write_with(&[page(font, "Rio")], "Restricted", Text::Fonts); + let text = String::from_utf8_lossy(&pdf); + assert!(text.contains("/Subtype /Type3") && !text.contains("/Type0")); + assert_eq!(outlined.len(), 1, "{outlined:?}"); + assert_eq!(outlined[0].face, "Ubuntu Light"); + assert_eq!(outlined[0].why, "its licence forbids embedding"); + } + + /// A face drawn at another instance than its file's default isn't the file's face: embedding + /// the file would draw it otherwise. A static face (Ubuntu Light) has none, so it is embedded; + /// a face its file doesn't hold as drawn is refused. + #[test] + fn only_the_face_as_drawn_is_embedded() { + let font = face(|_| ()); + let glyphs: Vec = "Rio".chars().map(|c| font.glyph_id(c)).collect(); + assert!(embed(font, &glyphs, MAX_EMBEDDED).is_ok()); + // Another file's face, read from this one's bytes, draws its glyphs otherwise. + let hack = FontRef::try_from_slice(epaint_default_fonts::HACK_REGULAR).unwrap(); + assert!(!draws_alike(font, &hack, glyphs[0])); + let full = embed(font, &glyphs, 10).err(); + assert_eq!(full, Some(Refused::TooLarge(MAX_EMBEDDED)), "past the room left"); + assert_eq!(full.unwrap().to_string(), "the document's embedded faces would pass 32 MB"); + } + + /// A font file cut short or scrambled anywhere never panics: its face is embedded, or set in + /// outlines with the reason. + #[test] + fn a_hostile_font_file_never_panics() { + let clean = epaint_default_fonts::UBUNTU_LIGHT; + let glyf = table(clean, b"glyf"); + let mut tried = 0; + for step in 0..64usize { + let mut bytes = clean.to_vec(); + // Scramble a stretch of the glyph outlines, the table directory or the metrics. + let at = [glyf + step * 97, 12 + step * 3, table(clean, b"hmtx") + step * 13][step % 3]; + for b in bytes.iter_mut().skip(at).take(16) { + *b = b.wrapping_mul(31).wrapping_add(step as u8); + } + if step % 4 == 0 { + bytes.truncate(clean.len() * (step + 1) / 70); + } + let Ok(font) = FontRef::try_from_slice(&bytes) else { continue }; + tried += 1; + let glyphs: Vec = (0..40).map(GlyphId).collect(); + let _ = embed(&font, &glyphs, MAX_EMBEDDED); + let _ = face_name(&font); + } + assert!(tried > 10, "{tried} scrambled files parsed"); + } +} diff --git a/crates/render/src/pdf/fonts.rs b/crates/render/src/pdf/fonts.rs index 8058e64eef..439e2ec01b 100644 --- a/crates/render/src/pdf/fonts.rs +++ b/crates/render/src/pdf/fonts.rs @@ -1,6 +1,7 @@ -//! The document's fonts: for each face text is set in, Type 3 fonts whose glyphs are the face's -//! outlines, in font units, 256 glyphs to a font (a Type 3 font's codes are single bytes), each -//! with the map from its codes back to the characters they stand for. +//! The document's fonts: each face text is set in, embedded as itself where it can be (a subset +//! of its file, as a Type 0 font: [`super::embed`]), else as Type 3 fonts whose glyphs are the +//! face's outlines, in font units, 256 glyphs to a font (a Type 3 font's codes are single bytes); +//! each font with the map from its codes back to the characters they stand for. use std::collections::HashMap; use std::fmt::Write as _; @@ -9,12 +10,26 @@ use ab_glyph::{Font, FontRef, GlyphId, OutlineCurve}; use super::Doc; use super::content::num; +use super::embed::Embedded; #[derive(Default)] pub(super) struct Fonts { faces: Vec, /// Faces by the address of their `FontRef` (fonts are parsed once and kept). by_font: HashMap, + /// The faces embedded as themselves, in the order given (so a document is written the same + /// way each time), and their places there by the same address. + real: Vec, + real_by_font: HashMap, +} + +/// A face embedded as itself: its Type 0 font's object number, its subset, and the glyphs set +/// in it by their CIDs. +struct Real { + id: usize, + font: &'static FontRef<'static>, + embedded: Embedded, + glyphs: std::collections::BTreeMap, } struct Face { @@ -31,32 +46,60 @@ struct Chunk { glyphs: Vec<(GlyphId, char)>, } -/// Where a glyph is: its font's object number, its code there and its advance in ems. +/// Where a glyph is: its font's object number, its code there (two bytes, a CID, when `wide`) +/// and its advance in ems. pub(super) struct Placed { pub font: usize, - pub code: u8, + pub code: u16, + pub wide: bool, pub advance: f32, } +/// A face's advance for `id` in ems, 0 where it isn't a number. +fn advance_em(font: &FontRef<'static>, upm: f32, id: GlyphId) -> f32 { + let advance = font.h_advance_unscaled(id) / upm; + if advance.is_finite() { advance } else { 0.0 } +} + +/// A face's units per em, read as the usual 1000 where it has none usable. +fn upm_of(font: &FontRef<'static>) -> f32 { + font.units_per_em().filter(|u| u.is_finite() && *u > 0.0).unwrap_or(1000.0) +} + impl Fonts { + /// Fonts that set the faces of `real` as themselves, each given its font's number now. + pub fn with_real(doc: &mut Doc, real: Vec<(&'static FontRef<'static>, Embedded)>) -> Fonts { + let real_by_font = real.iter().enumerate().map(|(i, (font, _))| (std::ptr::from_ref(*font) as usize, i)).collect(); + let real = + real.into_iter().map(|(font, embedded)| Real { id: doc.reserve(), font, embedded, glyphs: Default::default() }).collect(); + Fonts { real, real_by_font, ..Fonts::default() } + } + /// `id` of `font` (standing for `ch`), given a code in one of its Type 3 fonts the first time; /// `None` only past what a font can hold. pub fn place(&mut self, doc: &mut Doc, font: &'static FontRef<'static>, id: GlyphId, ch: char) -> Option { let key = std::ptr::from_ref(font) as usize; + // An embedded face's glyph is its CID in the subset (every glyph the document sets was + // given one before the content was written). + if let Some(r) = self.real_by_font.get(&key).and_then(|&i| self.real.get_mut(i)) + && let Some(cid) = r.embedded.remapper.get(id.0) + { + r.glyphs.entry(cid).or_insert(ch); + return Some(Placed { font: r.id, code: cid, wide: true, advance: advance_em(font, upm_of(font), id) }); + } let fi = match self.by_font.get(&key) { Some(&i) => i, None => { // A face with no usable units per em is read as the usual 1000, as the pixels read // it at one unit a pixel's em: its text is kept, not left out. - let upm = font.units_per_em().filter(|u| u.is_finite() && *u > 0.0).unwrap_or(1000.0); + let upm = upm_of(font); self.faces.push(Face { font, upm, chunks: Vec::new(), codes: HashMap::new() }); self.by_font.insert(key, self.faces.len() - 1); self.faces.len() - 1 } }; let face = self.faces.get_mut(fi)?; - let advance = font.h_advance_unscaled(id) / face.upm; - let advance = if advance.is_finite() { advance } else { 0.0 }; + let advance = advance_em(font, face.upm, id); let (ci, code) = match face.codes.get(&id.0) { Some(&c) => c, None => { @@ -71,11 +114,14 @@ impl Fonts { (ci, code) } }; - Some(Placed { font: face.chunks.get(ci)?.id, code, advance }) + Some(Placed { font: face.chunks.get(ci)?.id, code: u16::from(code), wide: false, advance }) } /// Writes every font given a glyph. pub fn write(self, doc: &mut Doc) { + for r in &self.real { + write_real(doc, r); + } for face in &self.faces { for chunk in &face.chunks { write_chunk(doc, face, chunk); @@ -110,7 +156,8 @@ fn write_chunk(doc: &mut Doc, face: &Face, chunk: &Chunk) { bbox = [0.0; 4]; } let to_unicode = doc.reserve(); - doc.stream(to_unicode, "", to_unicode_cmap(&chunk.glyphs).as_bytes(), false); + let codes: Vec<(u16, char)> = chunk.glyphs.iter().zip(0u16..).map(|((_, ch), code)| (code, *ch)).collect(); + doc.stream(to_unicode, "", to_unicode_cmap(&codes, false).as_bytes(), false); let mut matrix = Vec::new(); for v in [1.0 / face.upm, 0.0, 0.0, 1.0 / face.upm, 0.0, 0.0] { num(&mut matrix, v, 9); @@ -133,6 +180,71 @@ fn write_chunk(doc: &mut Doc, face: &Face, chunk: &Chunk) { ); } +/// An embedded face's fonts: the Type 0 font over its CID font, the CID font's descriptor and +/// file, its glyphs' widths and the map from its CIDs back to their characters. +fn write_real(doc: &mut Doc, r: &Real) { + let e = &r.embedded; + let (cid_font, descriptor, file, to_unicode) = (doc.reserve(), doc.reserve(), doc.reserve(), doc.reserve()); + let upm = upm_of(r.font); + let gids: Vec = e.remapper.remapped_gids().collect(); + let mut widths = String::new(); + for &cid in r.glyphs.keys() { + let gid = gids.get(usize::from(cid)).copied().unwrap_or(0); + let mut w = Vec::new(); + num(&mut w, advance_em(r.font, upm, GlyphId(gid)) * 1000.0, 2); + let _ = write!(widths, "{cid} [{}] ", String::from_utf8_lossy(&w)); + } + let n = |v: f32| { + let mut b = Vec::new(); + num(&mut b, if v.is_finite() { v } else { 0.0 }, 1); + String::from_utf8_lossy(&b).into_owned() + }; + // The file: TrueType outlines (FontFile2), or CFF ones in an OpenType wrapper (FontFile3). + let (subtype, file_key, file_dict, gid_map) = if e.cff { + ("CIDFontType0", "FontFile3", "/Subtype /OpenType".to_string(), "") + } else { + ("CIDFontType2", "FontFile2", format!("/Length1 {}", e.file.len()), " /CIDToGIDMap /Identity") + }; + doc.stream(file, &file_dict, &e.file, false); + // Symbolic (its glyphs are reached by CID, not a standard encoding), and italic where it leans. + let flags = 4 + if e.italic_angle.abs() > 0.01 { 64 } else { 0 }; + let [x0, y0, x1, y1] = e.bbox; + doc.put( + descriptor, + format!( + "<< /Type /FontDescriptor /FontName /{} /Flags {flags} /FontBBox [{} {} {} {}] /ItalicAngle {} /Ascent {} /Descent {} /CapHeight {} /StemV 80 /{file_key} {file} 0 R >>", + e.name, + n(x0), + n(y0), + n(x1), + n(y1), + n(e.italic_angle), + n(e.ascent), + n(e.descent), + n(e.cap_height) + ) + .as_bytes(), + ); + doc.put( + cid_font, + format!( + "<< /Type /Font /Subtype /{subtype} /BaseFont /{} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor} 0 R /DW 0 /W [{widths}]{gid_map} >>", + e.name + ) + .as_bytes(), + ); + let codes: Vec<(u16, char)> = r.glyphs.iter().map(|(c, ch)| (*c, *ch)).collect(); + doc.stream(to_unicode, "", to_unicode_cmap(&codes, true).as_bytes(), false); + doc.put( + r.id, + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{} /Encoding /Identity-H /DescendantFonts [{cid_font} 0 R] /ToUnicode {to_unicode} 0 R >>", + e.name + ) + .as_bytes(), + ); +} + /// A glyph's procedure: its advance and box (`d1`, so it takes the text's colour) and its /// outline, filled; and its box in font units, `None` for a glyph with no outline (a space). fn glyph_procedure(font: &FontRef<'static>, id: GlyphId, advance: f32) -> (Vec, Option<[f32; 4]>) { @@ -207,17 +319,19 @@ fn glyph_procedure(font: &FontRef<'static>, id: GlyphId, advance: f32) -> (Vec String { - let mut s = String::from( - "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<00> \nendcodespacerange\n", +/// The CMap taking each code of a font (one byte, or two when `wide`) to the character its glyph +/// stands for. +fn to_unicode_cmap(codes: &[(u16, char)], wide: bool) -> String { + let space = if wide { "<0000> " } else { "<00> " }; + let mut s = format!( + "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n{space}\nendcodespacerange\n", ); // At most 100 entries to a block. - for (b, block) in glyphs.chunks(100).enumerate() { + for block in codes.chunks(100) { let _ = writeln!(s, "{} beginbfchar", block.len()); - for (i, (_, ch)) in block.iter().enumerate() { + for (code, ch) in block { let hex: String = ch.encode_utf16(&mut [0; 2]).iter().map(|u| format!("{u:04X}")).collect(); - let _ = writeln!(s, "<{:02X}> <{hex}>", b * 100 + i); + let _ = if wide { writeln!(s, "<{code:04X}> <{hex}>") } else { writeln!(s, "<{code:02X}> <{hex}>") }; } s.push_str("endbfchar\n"); } @@ -267,8 +381,8 @@ mod tests { #[test] fn the_unicode_map_spans_blocks_and_astral_characters() { - let glyphs: Vec<(GlyphId, char)> = (0..150).map(|i| (GlyphId(i), if i == 120 { '🙂' } else { 'é' })).collect(); - let cmap = to_unicode_cmap(&glyphs); + let glyphs: Vec<(u16, char)> = (0..150).map(|i| (i, if i == 120 { '🙂' } else { 'é' })).collect(); + let cmap = to_unicode_cmap(&glyphs, false); assert_eq!(cmap.matches("beginbfchar").count(), 2); assert!(cmap.contains("100 beginbfchar") && cmap.contains("50 beginbfchar")); assert!(cmap.contains("<00> <00E9>") && cmap.contains("<78> ")); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7aa9082afc..2097616d29 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1684,7 +1684,15 @@ impl RustGisApp { let georeference = self.ui.pdf_georeference; let session = &mut self.session; let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::layout::layout_bytes_with(session, li, pdf, dpi, true, georeference) + rustgis_engine::cmd::layout::layout_bytes_with( + session, + li, + pdf, + dpi, + true, + georeference, + rustgis_engine::render::pdf::Text::Fonts, + ) })) .unwrap_or_else(|_| Err("the layout export failed unexpectedly".into())); if let Err(e) = &r { diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 27ba5a7575..2747f51617 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -370,6 +370,13 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu are pictures cut to their shape. The `dpi` also sets how fine the vectors' detail is kept, as a PNG at that resolution would show it. A frame or page whose vectors would pass 256 MB (64 MB in the browser) is drawn as a picture instead, and the export says which. + Its text is set in the fonts it is drawn in, each embedded as a subset of its glyphs, so a vector + editor (Inkscape, Illustrator, Affinity, VectorCraft) opens it as text that can be edited; it can + be searched and copied in any PDF reader. A face whose licence forbids embedding or subsetting, + one drawn at another weight than its variable font file's default, or one whose file can't be + read is set as its letters' outlines instead, and the export names it with why. + `"pdf": {"text": "outlines"}` on `layout.export` sets all the text as outlines, as a print shop + asking for outlined type wants. A PDF is also a GeoPDF: each map frame is georeferenced (an ISO 32000 geospatial viewport, the form GDAL, QGIS, Acrobat and Avenza read), with its map's coordinate system as WKT and its EPSG code when it has one, so a reader shows coordinates and measures in it, and GDAL or QGIS open the From 12d65d402741e190029a3f3a0778ddde3d2e214a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 03:42:40 -0300 Subject: [PATCH 02/12] fix(render): review round 1 for embedded PDF fonts (#1815) - Test that each CID is its character's glyph: the subset's glyph has the face's own advance and outline, and /W has its width. - Look at Cancel between faces in pdf::write_with; once cancelled, the faces left are set in outlines (a cancelled export writes nothing). - embed(): the panic guard holds natively; in the browser only the bundled face reaches the subsetter. Said in its doc comment. - Docs name only the editor checked (VectorCraft). - Refused::SubsetTooLarge and DocumentTooLarge in place of TooLarge(usize); pdf_text matches the value directly and says it is checked for PNG and SVG exports too. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 13 ++++---- crates/render/src/pdf.rs | 7 ++++- crates/render/src/pdf/embed.rs | 56 ++++++++++++++++++++++++++------- docs/user-guide/layouts.md | 4 +-- 4 files changed, 60 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 650bd3d84a..71a783d97a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -4466,16 +4466,17 @@ pub(crate) fn pictured_notices(s: &mut Session, frames: &[(u32, String)], pages: } /// How `layout.export`'s `"pdf": {"text": …}` asks a PDF's text to be written (#1815): in its -/// fonts unless it says `"outlines"`. +/// fonts unless it says `"outlines"`. It is checked whatever the export writes, a PNG or SVG +/// too, so a script's mistake shows on its first run. fn pdf_text(p: &Value) -> Result { use rustgis_render::pdf::Text; let Some(pdf) = p.get("pdf").filter(|v| !v.is_null()) else { return Ok(Text::Fonts) }; let Some(pdf) = pdf.as_object() else { return Err(r#"pdf is an object: {"text": "fonts"|"outlines"}"#.into()) }; - match pdf.get("text").and_then(Value::as_str) { - None if pdf.get("text").is_none_or(Value::is_null) => Ok(Text::Fonts), - Some("fonts") => Ok(Text::Fonts), - Some("outlines") => Ok(Text::Outlines), - _ => Err(r#"pdf.text is "fonts" or "outlines""#.into()), + match pdf.get("text") { + None | Some(Value::Null) => Ok(Text::Fonts), + Some(v) if v == "fonts" => Ok(Text::Fonts), + Some(v) if v == "outlines" => Ok(Text::Outlines), + Some(_) => Err(r#"pdf.text is "fonts" or "outlines""#.into()), } } diff --git a/crates/render/src/pdf.rs b/crates/render/src/pdf.rs index 283ad60672..1be4cf1c4c 100644 --- a/crates/render/src/pdf.rs +++ b/crates/render/src/pdf.rs @@ -249,7 +249,9 @@ pub fn write(pages: &[Page], title: &str) -> Vec { } /// Writes the pages as a PDF document, its text as `text` says, and the faces set in outlines -/// though fonts were asked for. +/// though fonts were asked for. Each face is subset in one step; between faces it looks at +/// Cancel (`rustgis_data::progress`), and once cancelled sets the faces left in outlines, unsaid: +/// a cancelled export writes nothing. pub fn write_with(pages: &[Page], title: &str, text: Text) -> (Vec, Vec) { // Every face's glyphs, gathered before any is written: a face is embedded or not as a whole, // and its glyphs' codes are the subset's. @@ -264,6 +266,9 @@ pub fn write_with(pages: &[Page], title: &str, text: Text) -> (Vec, Vec { room = room.saturating_sub(e.file.len()); diff --git a/crates/render/src/pdf/embed.rs b/crates/render/src/pdf/embed.rs index 411693c070..1576010d1c 100644 --- a/crates/render/src/pdf/embed.rs +++ b/crates/render/src/pdf/embed.rs @@ -42,9 +42,10 @@ pub(super) enum Refused { NotInFile, /// Its file can't be read or subset. Unreadable(String), - /// Its subset would pass [`MAX_SUBSET`], or the document's faces [`MAX_EMBEDDED`]: the limit - /// passed, in bytes. - TooLarge(usize), + /// Its subset would pass [`MAX_SUBSET`]. + SubsetTooLarge, + /// With it, the document's embedded faces would pass [`MAX_EMBEDDED`]. + DocumentTooLarge, } impl std::fmt::Display for Refused { @@ -54,8 +55,8 @@ impl std::fmt::Display for Refused { Refused::Instance => f.write_str("it is drawn at another weight or width than its file's default"), Refused::NotInFile => f.write_str("its file doesn't hold it as drawn"), Refused::Unreadable(e) => write!(f, "its file could not be subset: {e}"), - Refused::TooLarge(limit) if *limit == MAX_SUBSET => write!(f, "its subset passes {} MB", MAX_SUBSET >> 20), - Refused::TooLarge(_) => write!(f, "the document's embedded faces would pass {} MB", MAX_EMBEDDED >> 20), + Refused::SubsetTooLarge => write!(f, "its subset passes {} MB", MAX_SUBSET >> 20), + Refused::DocumentTooLarge => write!(f, "the document's embedded faces would pass {} MB", MAX_EMBEDDED >> 20), } } } @@ -84,9 +85,12 @@ fn same_face(font: &FontRef<'_>, face: &ttf_parser::Face) -> bool { usize::from(face.number_of_glyphs()) == font.glyph_count() && font.units_per_em() == Some(f32::from(face.units_per_em())) } -/// The face `font` as a subset holding `glyphs`, or why it can't be. Never panics, whatever the -/// file holds: a subsetter that fails, or would, leaves the face to outlines. `room` is what the -/// document can still embed. +/// The face `font` as a subset holding `glyphs`, or why it can't be. A subsetter that fails +/// leaves the face to outlines; natively, one that panics on a hostile file does too (its panic +/// caught). In the browser a panic can't be caught (wasm32 aborts), but no file of the user's +/// reaches it there: fonts are read from disk (the interface's, installed families, CJK and script +/// faces), so the web has only the label face bundled with the app. `room` is what the document +/// can still embed. pub(super) fn embed(font: &FontRef<'_>, glyphs: &[GlyphId], room: usize) -> Result { let data = font.font_data(); // The face of the file that draws these glyphs as `font` does (a collection's faces can share @@ -124,10 +128,10 @@ pub(super) fn embed(font: &FontRef<'_>, glyphs: &[GlyphId], room: usize) -> Resu Err(_) => return Err(Refused::Unreadable("the subsetter failed".into())), }; if file.len() > MAX_SUBSET { - return Err(Refused::TooLarge(MAX_SUBSET)); + return Err(Refused::SubsetTooLarge); } if file.len() > room { - return Err(Refused::TooLarge(MAX_EMBEDDED)); + return Err(Refused::DocumentTooLarge); } let k = 1000.0 / f32::from(face.units_per_em().max(1)); let b = face.global_bounding_box(); @@ -249,6 +253,36 @@ mod tests { } let content = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|s| s.contains(" TJ")).unwrap(); assert!(content.contains("[<0001>") && content.contains("<0004>] TJ"), "codes are CIDs: {content}"); + // Each CID is its character's glyph: in the subset (CIDToGIDMap /Identity) the same + // advance and outline as the face's own glyph, and the same width in /W. + let subset = FontRef::try_from_slice(&file.1).unwrap(); + let cid_font = objs.iter().find(|o| o.0.contains("/Subtype /CIDFontType2")).map(|o| o.0.as_str()).unwrap(); + let w: Vec = cid_font + .split("/W [") + .nth(1) + .unwrap() + .split(" ]") + .next() + .unwrap() + .replace(['[', ']'], " ") + .split_whitespace() + .map(|v| v.parse().unwrap()) + .collect(); + let upm = font.units_per_em().unwrap(); + let mut checked = 0; + for line in cmap.lines().filter(|l| l.starts_with('<') && l.len() == 13 && *l != "<0000> ") { + let cid = u16::from_str_radix(&line[1..5], 16).unwrap(); + let ch = char::from_u32(u32::from_str_radix(&line[8..12], 16).unwrap()).unwrap(); + let (own, sub) = (font.glyph_id(ch), GlyphId(cid)); + assert_eq!(font.h_advance_unscaled(own), subset.h_advance_unscaled(sub), "{ch}: CID {cid}"); + let points = |f: &FontRef, g| f.outline(g).map(|o| o.curves.iter().map(curve_points).collect::>()); + assert_eq!(points(font, own), points(&subset, sub), "{ch}: CID {cid}'s outline"); + let width = + w.chunks(2).find(|p| p[0] == f32::from(cid)).map(|p| p[1]).unwrap_or_else(|| panic!("CID {cid} in {w:?}: {cid_font}")); + assert!((width - font.h_advance_unscaled(own) / upm * 1000.0).abs() < 0.01, "{ch}: /W {width}"); + checked += 1; + } + assert_eq!(checked, 4, "A, ç, ã, o"); // Outlines, as before, whatever the face allows. let (outlines, none) = write_with(&[page(font, "Ação")], "Fonts", Text::Outlines); assert!(none.is_empty() && outlines == write(&[page(font, "Ação")], "Fonts")); @@ -283,7 +317,7 @@ mod tests { let hack = FontRef::try_from_slice(epaint_default_fonts::HACK_REGULAR).unwrap(); assert!(!draws_alike(font, &hack, glyphs[0])); let full = embed(font, &glyphs, 10).err(); - assert_eq!(full, Some(Refused::TooLarge(MAX_EMBEDDED)), "past the room left"); + assert_eq!(full, Some(Refused::DocumentTooLarge), "past the room left"); assert_eq!(full.unwrap().to_string(), "the document's embedded faces would pass 32 MB"); } diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 2747f51617..460ad0e075 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -371,8 +371,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu PNG at that resolution would show it. A frame or page whose vectors would pass 256 MB (64 MB in the browser) is drawn as a picture instead, and the export says which. Its text is set in the fonts it is drawn in, each embedded as a subset of its glyphs, so a vector - editor (Inkscape, Illustrator, Affinity, VectorCraft) opens it as text that can be edited; it can - be searched and copied in any PDF reader. A face whose licence forbids embedding or subsetting, + editor that reads embedded fonts (VectorCraft, where it was checked) opens it as text that can be + edited; it can be searched and copied in any PDF reader. A face whose licence forbids embedding or subsetting, one drawn at another weight than its variable font file's default, or one whose file can't be read is set as its letters' outlines instead, and the export names it with why. `"pdf": {"text": "outlines"}` on `layout.export` sets all the text as outlines, as a print shop From 58c6894acd74dfcf0df763c1741b85137afed178 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 04:12:11 -0300 Subject: [PATCH 03/12] test(render): CFF faces embed as CIDFontType0 with the right glyphs (#1815) A CFF face of the test's own (testdata/test-cff.otf, 712 bytes, made with fontTools by the script in testdata/README.md) is embedded as a CIDFontType0 over an OpenType FontFile3 in PDF 1.6, each CID drawing its character's glyph with its width in /W. The TrueType test checks the same through the shared helper. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/pdf/embed.rs | 48 +++++++++++++++++++++------- crates/render/testdata/README.md | 37 +++++++++++++++++++++ crates/render/testdata/test-cff.otf | Bin 0 -> 712 bytes 3 files changed, 74 insertions(+), 11 deletions(-) create mode 100644 crates/render/testdata/README.md create mode 100644 crates/render/testdata/test-cff.otf diff --git a/crates/render/src/pdf/embed.rs b/crates/render/src/pdf/embed.rs index 1576010d1c..664c257bff 100644 --- a/crates/render/src/pdf/embed.rs +++ b/crates/render/src/pdf/embed.rs @@ -253,10 +253,23 @@ mod tests { } let content = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|s| s.contains(" TJ")).unwrap(); assert!(content.contains("[<0001>") && content.contains("<0004>] TJ"), "codes are CIDs: {content}"); - // Each CID is its character's glyph: in the subset (CIDToGIDMap /Identity) the same - // advance and outline as the face's own glyph, and the same width in /W. + // Each CID is its character's glyph (CIDToGIDMap /Identity), with its width in /W. + assert_eq!(cids_are_their_glyphs(font, &objs, "/Subtype /CIDFontType2"), 4, "A, ç, ã, o"); + // Outlines, as before, whatever the face allows. + let (outlines, none) = write_with(&[page(font, "Ação")], "Fonts", Text::Outlines); + assert!(none.is_empty() && outlines == write(&[page(font, "Ação")], "Fonts")); + let text = String::from_utf8_lossy(&outlines); + assert!(text.contains("/Subtype /Type3") && !text.contains("/Type0")); + } + + /// Checks, for every CID of the document's two-byte ToUnicode map, that the subset embedded + /// for the CID font whose dictionary holds `subtype` draws its character as `font` does at + /// that CID (the same advance and outline) and that /W has the face's width for it; how many + /// CIDs it checked. + fn cids_are_their_glyphs(font: &FontRef<'static>, objs: &[(String, Vec)], subtype: &str) -> usize { + let file = objs.iter().find(|o| o.0.contains("/Length1") || o.0.contains("/Subtype /OpenType")).unwrap(); let subset = FontRef::try_from_slice(&file.1).unwrap(); - let cid_font = objs.iter().find(|o| o.0.contains("/Subtype /CIDFontType2")).map(|o| o.0.as_str()).unwrap(); + let cid_font = objs.iter().find(|o| o.0.contains(subtype)).map(|o| o.0.as_str()).unwrap(); let w: Vec = cid_font .split("/W [") .nth(1) @@ -268,6 +281,7 @@ mod tests { .split_whitespace() .map(|v| v.parse().unwrap()) .collect(); + let cmap = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|s| s.contains("<0000> ")).unwrap(); let upm = font.units_per_em().unwrap(); let mut checked = 0; for line in cmap.lines().filter(|l| l.starts_with('<') && l.len() == 13 && *l != "<0000> ") { @@ -277,17 +291,29 @@ mod tests { assert_eq!(font.h_advance_unscaled(own), subset.h_advance_unscaled(sub), "{ch}: CID {cid}"); let points = |f: &FontRef, g| f.outline(g).map(|o| o.curves.iter().map(curve_points).collect::>()); assert_eq!(points(font, own), points(&subset, sub), "{ch}: CID {cid}'s outline"); - let width = - w.chunks(2).find(|p| p[0] == f32::from(cid)).map(|p| p[1]).unwrap_or_else(|| panic!("CID {cid} in {w:?}: {cid_font}")); + let width = w.chunks(2).find(|p| p[0] == f32::from(cid)).map(|p| p[1]).unwrap_or_else(|| panic!("CID {cid} in {w:?}")); assert!((width - font.h_advance_unscaled(own) / upm * 1000.0).abs() < 0.01, "{ch}: /W {width}"); checked += 1; } - assert_eq!(checked, 4, "A, ç, ã, o"); - // Outlines, as before, whatever the face allows. - let (outlines, none) = write_with(&[page(font, "Ação")], "Fonts", Text::Outlines); - assert!(none.is_empty() && outlines == write(&[page(font, "Ação")], "Fonts")); - let text = String::from_utf8_lossy(&outlines); - assert!(text.contains("/Subtype /Type3") && !text.contains("/Type0")); + checked + } + + /// A CFF face (an OpenType .otf) is embedded as a CIDFontType0 over its subset as an + /// OpenType file (FontFile3, PDF 1.6), each CID its character's glyph. The face is the + /// test's own (testdata/README.md): a square, a triangle and two bars, each its own width. + #[test] + fn a_cff_face_is_a_cid_font_type0() { + let bytes: &'static [u8] = include_bytes!("../../testdata/test-cff.otf"); + let font: &'static FontRef<'static> = Box::leak(Box::new(FontRef::try_from_slice(bytes).unwrap())); + let (pdf, outlined) = write_with(&[page(font, "CAB")], "CFF", Text::Fonts); + assert!(outlined.is_empty(), "{outlined:?}"); + let text = String::from_utf8_lossy(&pdf); + assert!(text.starts_with("%PDF-1.6") && !text.contains("/Type3"), "OpenType font files are PDF 1.6"); + let objs = objects(&pdf); + let cid_font = objs.iter().find(|o| o.0.contains("/Subtype /CIDFontType0")).map(|o| o.0.as_str()).unwrap(); + assert!(!cid_font.contains("/CIDToGIDMap"), "{cid_font}"); + assert!(objs.iter().any(|o| o.0.contains("/FontFile3")) && objs.iter().any(|o| o.0.contains("/Subtype /OpenType"))); + assert_eq!(cids_are_their_glyphs(font, &objs, "/Subtype /CIDFontType0"), 3, "C, A, B"); } /// A face whose licence forbids embedding (fsType 2) is set in outlines, and said. diff --git a/crates/render/testdata/README.md b/crates/render/testdata/README.md new file mode 100644 index 0000000000..b35ad9f2a7 --- /dev/null +++ b/crates/render/testdata/README.md @@ -0,0 +1,37 @@ +# Test data for rustgis-render + +- `test-cff.otf`: a CFF (OpenType .otf) face made for the PDF font tests (#1815), so that they need + no third-party font. It holds `.notdef` and three glyphs of distinct shapes and widths: `A` a + square (600 units wide), `B` a triangle (700) and `C` two bars (800), 1000 units per em, + `fsType` 0. It was made with fontTools 4 by the script below, and is part of RustGIS under its + licence. + +```python +from fontTools.fontBuilder import FontBuilder +from fontTools.pens.t2CharStringPen import T2CharStringPen + +fb = FontBuilder(1000, isTTF=False) +order = [".notdef", "A", "B", "C"] +fb.setupGlyphOrder(order) +fb.setupCharacterMap({ord("A"): "A", ord("B"): "B", ord("C"): "C"}) +adv = {".notdef": 500, "A": 600, "B": 700, "C": 800} + +def draw(name): + p = T2CharStringPen(adv[name], None) + if name == "A": + p.moveTo((50, 0)); p.lineTo((550, 0)); p.lineTo((550, 500)); p.lineTo((50, 500)); p.closePath() + elif name == "B": + p.moveTo((50, 0)); p.lineTo((650, 0)); p.lineTo((350, 700)); p.closePath() + elif name == "C": + p.moveTo((50, 0)); p.lineTo((250, 0)); p.lineTo((250, 600)); p.lineTo((50, 600)); p.closePath() + p.moveTo((500, 0)); p.lineTo((750, 0)); p.lineTo((750, 300)); p.lineTo((500, 300)); p.closePath() + return p.getCharString() + +fb.setupCFF("RustGISTestCFF", {"FullName": "RustGIS Test CFF"}, {g: draw(g) for g in order}, {}) +fb.setupHorizontalMetrics({g: (adv[g], 50) for g in order}) +fb.setupHorizontalHeader(ascent=800, descent=-200) +fb.setupNameTable({"familyName": "RustGIS Test CFF", "styleName": "Regular"}) +fb.setupOS2(sTypoAscender=800, sTypoDescender=-200, usWinAscent=800, usWinDescent=200, fsType=0) +fb.setupPost() +fb.save("test-cff.otf") +``` diff --git a/crates/render/testdata/test-cff.otf b/crates/render/testdata/test-cff.otf new file mode 100644 index 0000000000000000000000000000000000000000..7a3fcc1ab59db937134ab74925802816f5d64a84 GIT binary patch literal 712 zcmZ`$&r2IY6#iy*-C~hVv^63kETxCuDvLjQD5#B%JOjcocX>J$ID*50y9e&ifV0pWk0>4cwej&f2! z$PKujN^IZlE^pt+Ghzc$M=5+`IN=Lz;lh2GvZ)k;7iz8$knRBYC7)}{A%FvTXOzp zt>o<@hZ?E~u!=PDd{lrRVFyX1xN^jsyi Date: Thu, 12 Nov 2026 06:19:34 -0300 Subject: [PATCH 04/12] fix(engine): refuse an unknown key in layout.export's "pdf" (#1815) A misspelled key ({"txt": "outlines"}) left the text in fonts with nothing said. It is now refused, naming the keys "pdf" takes. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 9 ++++++++- crates/engine/src/tests.rs | 7 +++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 71a783d97a..070383352b 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -4465,13 +4465,20 @@ pub(crate) fn pictured_notices(s: &mut Session, frames: &[(u32, String)], pages: } } +/// The keys `layout.export`'s `"pdf"` takes. +const PDF_KEYS: &[&str] = &["text"]; + /// How `layout.export`'s `"pdf": {"text": …}` asks a PDF's text to be written (#1815): in its /// fonts unless it says `"outlines"`. It is checked whatever the export writes, a PNG or SVG -/// too, so a script's mistake shows on its first run. +/// too, so a script's mistake shows on its first run; a key it doesn't know is refused, with +/// the keys it takes. fn pdf_text(p: &Value) -> Result { use rustgis_render::pdf::Text; let Some(pdf) = p.get("pdf").filter(|v| !v.is_null()) else { return Ok(Text::Fonts) }; let Some(pdf) = pdf.as_object() else { return Err(r#"pdf is an object: {"text": "fonts"|"outlines"}"#.into()) }; + if let Some(key) = pdf.keys().find(|k| !PDF_KEYS.contains(&k.as_str())) { + return Err(format!("pdf has no key \"{key}\": its keys are {}", PDF_KEYS.join(", "))); + } match pdf.get("text") { None | Some(Value::Null) => Ok(Text::Fonts), Some(v) if v == "fonts" => Ok(Text::Fonts), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a0cee360eb..6537fee635 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -37130,9 +37130,12 @@ fn a_layout_pdf_sets_its_text_in_its_fonts() { let (outlines, said) = export(&mut s, json!({"pdf": {"text": "outlines"}})).unwrap(); assert!(outlines.contains("/Subtype /Type3") && !outlines.contains("/Type0"), "{said:?}"); assert_eq!(export(&mut s, json!({"pdf": {"text": "fonts"}})).unwrap().0.len(), pdf.len()); - for bad in [json!({"pdf": {"text": "curves"}}), json!({"pdf": "outlines"}), json!({"pdf": {"text": 1}})] { + for bad in + [json!({"pdf": {"text": "curves"}}), json!({"pdf": "outlines"}), json!({"pdf": {"text": 1}}), json!({"pdf": {"txt": "outlines"}})] + { let err = export(&mut s, bad.clone()).unwrap_err(); - assert!(err.contains("\"fonts\" or \"outlines\"") || err.contains("fonts\"|\"outlines"), "{bad}: {err}"); + let said = ["\"fonts\" or \"outlines\"", "fonts\"|\"outlines", "pdf has no key \"txt\": its keys are text"]; + assert!(said.iter().any(|s| err.contains(s)), "{bad}: {err}"); } let _ = std::fs::remove_file(&path); } From 9cd59022d675ca6462640135b0fd30f1bb61962d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 06:19:50 -0300 Subject: [PATCH 05/12] docs: attribute the CFF test font (#1815) Co-Authored-By: Claude Opus 5.5 --- ATTRIBUTION.md | 1 + 1 file changed, 1 insertion(+) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 4acf725637..5b4929513d 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -20,6 +20,7 @@ of use. | Worldviews (`countries_.geojson` and `original/countries_.geojson.gz` on [source.coop](https://source.coop/opengeos/data/rustgis/worldviews)), downloaded by the app when one is chosen, not part of it | Natural Earth's Admin 0 Countries (1:10m) and its points of view, with the sample countries' attributes by `scripts/worldviews.py` in [rustgis-assets](https://github.com/opengeos/rustgis-assets): simplified to 1:110m density, or at their original detail | Public domain | | QGIS screenshot (`qgis-world-atlas.webp` in [rustgis-assets](https://github.com/opengeos/rustgis-assets/tree/main/images)), on the [RustGIS and QGIS](docs/comparison/qgis.md) page | Taken by the RustGIS project: [QGIS](https://qgis.org) 4.2 showing the Natural Earth sample data above | QGIS is GPL-2.0-or-later; the data is public domain | | QGIS test corpus (`crates/map/testdata/qgis/generated/`: styles, projects and their sample data) | Dominik Strebel ([@pick2510](https://github.com/pick2510)) for the RustGIS project: written by [QGIS](https://qgis.org) 4.2.3 through its API, from `generate.py` there; the data is made up | Apache-2.0 | +| CFF test font (`crates/render/testdata/test-cff.otf`), read only by the PDF font tests | The RustGIS project: generated for this test with [fontTools](https://github.com/fonttools/fonttools) by the script in `crates/render/testdata/README.md`; its glyphs are made up | Apache-2.0 | | JAXA Earth catalog test copy (`crates/tiles/tests/data/jaxa_catalog.v2.md`), read only by tests | JAXA: the [JAXA Earth API](https://data.earth.jaxa.jp/) dataset catalog ([catalog.v2.md](https://data.earth.jaxa.jp/app/mcp/catalog.v2.md)), copied on 2026-11-08 | JAXA's [terms of use](https://earth.jaxa.jp/en/data/policy/): free to use and redistribute, with credit to JAXA | | Analysis reference corpus (`crates/analysis/tests/reference/`: layers and expected results) | Written for the RustGIS project from `generate.py` there: the layers are made up; the expected results were computed by [GEOS](https://libgeos.org) 3.13.1 through [Shapely](https://shapely.readthedocs.io) 2.1.2, and distances, buffers, areas and lengths by GeographicLib in [PROJ](https://proj.org) 9.5.1 through [pyproj](https://pyproj4.github.io/pyproj/) 3.7.2, run only to write them (GEOS is LGPL-2.1, Shapely BSD-3-Clause, PROJ and pyproj MIT; none is included in or linked into RustGIS) | Apache-2.0 | From 01e8018ccd9e8ae3616c559221f55c5642accd6a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 06:29:12 -0300 Subject: [PATCH 06/12] fix(render): name the collection face that draws the text in the notice (#1815) face_name takes the glyphs used and names the collection face that draws them as the export does (as embed picks it, through the shared drawn_as), falling back to the first with as many glyphs and units per em. The test comment says what its check does, and the test doc why Refused::Instance and NotInFile have no test. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/pdf.rs | 2 +- crates/render/src/pdf/embed.rs | 44 +++++++++++++++++++++------------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/crates/render/src/pdf.rs b/crates/render/src/pdf.rs index 1be4cf1c4c..b95a2af3e1 100644 --- a/crates/render/src/pdf.rs +++ b/crates/render/src/pdf.rs @@ -274,7 +274,7 @@ pub fn write_with(pages: &[Page], title: &str, text: Text) -> (Vec, Vec outlined.push(Outlined { face: embed::face_name(font), why: why.to_string() }), + Err(why) => outlined.push(Outlined { face: embed::face_name(font, &glyphs), why: why.to_string() }), } } // Georeferenced frames make the document PDF 1.7 with Adobe's extension level 3, where diff --git a/crates/render/src/pdf/embed.rs b/crates/render/src/pdf/embed.rs index 664c257bff..808b23fc45 100644 --- a/crates/render/src/pdf/embed.rs +++ b/crates/render/src/pdf/embed.rs @@ -62,9 +62,13 @@ impl std::fmt::Display for Refused { } /// A name for the face in a notice: its full name, else its family, else its PostScript name. -pub(super) fn face_name(font: &FontRef<'_>) -> String { +/// In a collection, the face that draws `glyphs` as `font` does ([`drawn_as`]); where none +/// does (another instance of a variable font), the first with as many glyphs and units per em. +pub(super) fn face_name(font: &FontRef<'_>, glyphs: &[GlyphId]) -> String { let data = font.font_data(); - let face = (0..collection_len(data)).find_map(|i| ttf_parser::Face::parse(data, i).ok().filter(|f| same_face(font, f))); + let index = drawn_as(font, glyphs) + .or_else(|| (0..collection_len(data)).find(|&i| ttf_parser::Face::parse(data, i).is_ok_and(|f| same_face(font, &f)))); + let face = index.and_then(|i| ttf_parser::Face::parse(data, i).ok()); face.and_then(|f| { [ttf_parser::name_id::FULL_NAME, ttf_parser::name_id::FAMILY, ttf_parser::name_id::POST_SCRIPT_NAME] .into_iter() @@ -85,6 +89,19 @@ fn same_face(font: &FontRef<'_>, face: &ttf_parser::Face) -> bool { usize::from(face.number_of_glyphs()) == font.glyph_count() && font.units_per_em() == Some(f32::from(face.units_per_em())) } +/// The face of `font`'s file that draws `glyphs` as `font` does, at the file's own default +/// instance: its index (a collection's faces can share glyphs; any that draws them alike will do). +fn drawn_as(font: &FontRef<'_>, glyphs: &[GlyphId]) -> Option { + let data = font.font_data(); + (0..collection_len(data)).find(|&i| { + FontRef::try_from_slice_and_index(data, i).is_ok_and(|fresh| { + fresh.glyph_count() == font.glyph_count() + && fresh.units_per_em() == font.units_per_em() + && glyphs.iter().all(|&g| draws_alike(font, &fresh, g)) + }) + }) +} + /// The face `font` as a subset holding `glyphs`, or why it can't be. A subsetter that fails /// leaves the face to outlines; natively, one that panics on a hostile file does too (its panic /// caught). In the browser a panic can't be caught (wasm32 aborts), but no file of the user's @@ -93,16 +110,7 @@ fn same_face(font: &FontRef<'_>, face: &ttf_parser::Face) -> bool { /// can still embed. pub(super) fn embed(font: &FontRef<'_>, glyphs: &[GlyphId], room: usize) -> Result { let data = font.font_data(); - // The face of the file that draws these glyphs as `font` does (a collection's faces can share - // glyphs; any that draws them alike will do), at the file's own default instance. - let index = (0..collection_len(data)).find(|&i| { - FontRef::try_from_slice_and_index(data, i).is_ok_and(|fresh| { - fresh.glyph_count() == font.glyph_count() - && fresh.units_per_em() == font.units_per_em() - && glyphs.iter().all(|&g| draws_alike(font, &fresh, g)) - }) - }); - let Some(index) = index else { + let Some(index) = drawn_as(font, glyphs) else { return Err(if ab_glyph::VariableFont::variations(font).is_empty() { Refused::NotInFile } else { Refused::Instance }); }; let face = ttf_parser::Face::parse(data, index).map_err(|e| Refused::Unreadable(e.to_string()))?; @@ -331,15 +339,17 @@ mod tests { assert_eq!(outlined[0].why, "its licence forbids embedding"); } - /// A face drawn at another instance than its file's default isn't the file's face: embedding - /// the file would draw it otherwise. A static face (Ubuntu Light) has none, so it is embedded; - /// a face its file doesn't hold as drawn is refused. + /// A face is embedded only from the file that draws it as the export does. A static face + /// (Ubuntu Light) is its file's own, so it is embedded; another file's glyphs draw otherwise, + /// so a face is never matched to one. (`Refused::Instance` needs a variable font drawn at + /// another weight, which no bundled face is; `Refused::NotInFile` is all but unreachable, + /// since `font_data` is the very file the face was read from.) #[test] fn only_the_face_as_drawn_is_embedded() { let font = face(|_| ()); let glyphs: Vec = "Rio".chars().map(|c| font.glyph_id(c)).collect(); assert!(embed(font, &glyphs, MAX_EMBEDDED).is_ok()); - // Another file's face, read from this one's bytes, draws its glyphs otherwise. + // Another file's glyphs draw otherwise, so a face is never matched to one. let hack = FontRef::try_from_slice(epaint_default_fonts::HACK_REGULAR).unwrap(); assert!(!draws_alike(font, &hack, glyphs[0])); let full = embed(font, &glyphs, 10).err(); @@ -368,7 +378,7 @@ mod tests { tried += 1; let glyphs: Vec = (0..40).map(GlyphId).collect(); let _ = embed(&font, &glyphs, MAX_EMBEDDED); - let _ = face_name(&font); + let _ = face_name(&font, &glyphs); } assert!(tried > 10, "{tried} scrambled files parsed"); } From deee8d69a16bc4ab729e52a882b65fc3aa555d01 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 18:00:01 -0300 Subject: [PATCH 07/12] test(engine): the outlined-faces notice, none, one, two and eleven (#1815) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 2 +- crates/engine/src/tests.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 48c3f5bd92..5691aaa734 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -4767,7 +4767,7 @@ fn layout_bytes_inner( /// Says which faces a PDF set in outlines though its text was to be in fonts (#1815), with why: /// their text is drawings, not text, in a vector editor. One notice, the faces counted. -fn outlined_notice(s: &mut Session, outlined: &[rustgis_render::pdf::Outlined]) { +pub(crate) fn outlined_notice(s: &mut Session, outlined: &[rustgis_render::pdf::Outlined]) { let n = outlined.len(); if n == 0 { return; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 387ec6d6d8..e8a3e5c175 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -38313,6 +38313,35 @@ fn must_be_covered_by_says_which_polygons_it_left_out_at_a_pole() { } } +/// The faces a PDF sets in outlines though fonts were asked for (#1815) are said in one notice: +/// none, nothing said; one face, singular; more, plural; past ten, the first ten and how many more. +#[test] +fn a_pdf_says_which_faces_it_sets_in_outlines() { + let mut s = Session::new(Project::default()); + let faces = |n: usize| -> Vec { + (1..=n).map(|i| rustgis_render::pdf::Outlined { face: format!("Face {i}"), why: "its licence forbids embedding".into() }).collect() + }; + let said = |s: &mut Session, n: usize| { + let mark = s.notice_mark(); + crate::cmd::layout::outlined_notice(s, &faces(n)); + s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>() + }; + assert!(said(&mut s, 0).is_empty(), "every face embedded, nothing said"); + let lead = "The PDF sets the text of"; + let tail = "as outlines, not as text a vector editor can edit:"; + assert_eq!(said(&mut s, 1), [format!("{lead} 1 face {tail} Face 1 (its licence forbids embedding)")]); + let two = said(&mut s, 2); + assert_eq!(two.len(), 1, "one notice"); + assert!( + two[0].starts_with(&format!("{lead} 2 faces {tail} Face 1 (")) && two[0].ends_with(", Face 2 (its licence forbids embedding)"), + "{two:?}" + ); + let eleven = said(&mut s, 11); + assert_eq!(eleven.len(), 1, "one notice"); + assert!(eleven[0].starts_with(&format!("{lead} 11 faces {tail}")), "{eleven:?}"); + assert!(eleven[0].contains("Face 10 (") && !eleven[0].contains("Face 11") && eleven[0].ends_with(", and 1 more"), "{eleven:?}"); +} + #[test] fn a_pdf_says_which_frames_and_pages_it_draws_as_pictures() { let mut s = Session::new(Project::default()); From e4d9b4ee67266ec8facef3eefe7e63dc16d412e2 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 18:03:26 -0300 Subject: [PATCH 08/12] feat(render): a label's halo is text in vector PDFs (#1815, halos) A halo is a copy of its text under it, filled and stroked as wide as the halo: in an embedded face, the same font in text rendering mode 2, marked as an artifact; in outlines (or a face set in Type 3), its glyph outlines filled and stroked, as before. GlyphRun gets halo, Canvas a halo mode that text.rs sets the label's own text in; the SVG strokes halo runs. Part of #1815. Depends on #1828. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/canvas.rs | 28 ++++++-- crates/render/src/pdf/content.rs | 34 +++++++++- crates/render/src/pdf/embed.rs | 43 ++++++++++++ crates/render/src/pdf/fonts.rs | 5 ++ crates/render/src/svg/vectors.rs | 26 +++++++- crates/render/src/text.rs | 110 ++++--------------------------- crates/render/src/vector.rs | 108 ++++++++++++++++++------------ docs/user-guide/layouts.md | 6 +- 8 files changed, 208 insertions(+), 152 deletions(-) diff --git a/crates/render/src/canvas.rs b/crates/render/src/canvas.rs index b5061c12fc..05aaadfb94 100644 --- a/crates/render/src/canvas.rs +++ b/crates/render/src/canvas.rs @@ -31,6 +31,8 @@ struct Recording { ts: Transform, /// A layer is open ([`Canvas::layer`]). layer: bool, + /// The glyphs kept are a halo this wide ([`Canvas::halo`]). + halo: Option, } impl Canvas { @@ -48,7 +50,7 @@ impl Canvas { pub fn recording(width: u32, height: u32) -> Option { let pm = Pixmap::new(width, height)?; let drawing = Drawing::new(width as f32, height as f32); - Some(Canvas { pm, rec: Some(Box::new(Recording { drawing, dirty: false, ts: Transform::identity(), layer: false })) }) + Some(Canvas { pm, rec: Some(Box::new(Recording { drawing, dirty: false, ts: Transform::identity(), layer: false, halo: None })) }) } /// Whether it records. @@ -205,6 +207,7 @@ impl Canvas { pub fn glyphs(&mut self, mut run: GlyphRun) { self.keep(|r| { run.transform = r.ts.pre_concat(run.transform); + run.halo = run.halo.or(r.halo); r.drawing.glyphs(run); }); } @@ -223,6 +226,17 @@ impl Canvas { } } + /// Draws with `f` as a halo `width` wide (#1815): the glyphs it keeps are a halo's copy of the + /// text, filled and stroked that wide (see [`vector::GlyphRun::halo`]), so a PDF writes the + /// halo as text too. Only a recording keeps halos so; a canvas that draws pixels runs `f`. + pub fn halo(&mut self, width: f32, f: impl FnOnce(&mut Canvas)) { + let old = self.rec.as_mut().map(|r| r.halo.replace(width)); + f(self); + if let (Some(r), Some(old)) = (&mut self.rec, old) { + r.halo = old; + } + } + /// Draws with `f` as one group composited at `opacity` (so what `f` draws overlapping shows /// once); a canvas that draws pixels runs `f` on itself, for callers that only group what /// they record. @@ -467,7 +481,7 @@ mod tests { } #[test] - fn a_label_keeps_its_halo_as_a_shape_and_its_text_once() { + fn a_label_keeps_its_halo_as_text_and_its_text_once() { let label = crate::PlacedLabel { text: "Memphis".into(), x: 50.0, @@ -493,9 +507,13 @@ mod tests { crate::text::draw(&mut c, &label, 1.0); let (_, _, items) = c.into_drawing().unwrap().finish(); let [Item::Group(halo), Item::Glyphs(run)] = items.as_slice() else { panic!("a halo and the text") }; - // The halo: the letters and their outline spread round them, opaque, in one coat. - assert!(matches!(halo.items.as_slice(), [Item::Fill { .. }, Item::Stroke { .. }])); - assert_eq!(run.glyphs.iter().map(|g| g.ch).collect::(), "Memphis"); + // The halo (#1815): a copy of the text under it, its glyphs filled and stroked twice the + // halo's reach (1.2 points) wide, opaque, in one coat. + let [Item::Glyphs(copy)] = halo.items.as_slice() else { panic!("the halo as a run of glyphs") }; + assert_eq!(copy.halo, Some(2.4)); + assert_eq!(copy.color, tiny_skia::Color::WHITE); + assert_eq!((copy.glyphs.as_slice(), copy.transform), (run.glyphs.as_slice(), run.transform), "the text's own glyphs, where it is"); + assert_eq!((run.halo, run.glyphs.iter().map(|g| g.ch).collect::().as_str()), (None, "Memphis")); // Turned with the label, not drawn as a turned picture. assert!(run.transform.ky.abs() > 0.1); // A halo of no width draws nothing, as on the pixels. diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index 846558c4f7..7db3f30457 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -260,6 +260,18 @@ impl Writer<'_> { /// Sets a run of glyphs in the document's fonts, each at its pen position. fn glyphs(&mut self, out: &mut Vec, st: &mut State, run: &GlyphRun) { + // A halo (#1815): in an embedded face, the same text filled and stroked (rendering mode + // 2), so an editor sees it as text too, marked as an artifact; in outlines (a Type 3 + // glyph is filled only), its glyphs' outlines filled and stroked, as before. + let halo = run.halo.filter(|w| w.is_finite() && *w > 0.0); + if let Some(w) = halo + && !self.fonts.is_real(run.font) + { + if let Some(path) = run.outline() { + self.fill_and_stroke(out, st, &path, run.color, FillRule::Winding, (run.color, &GlyphRun::halo_stroke(w)), run.transform); + } + return; + } let mut placed = Vec::with_capacity(run.glyphs.len()); for g in &run.glyphs { if let Some(p) = self.fonts.place(self.doc, run.font, g.id, g.ch) { @@ -271,7 +283,23 @@ impl Writer<'_> { } self.alpha(out, st, run.color.alpha()); set_color(out, &mut st.fill, run.color, "rg"); + if let Some(w) = halo { + // A text's stroke is in user space, not the text matrix's: the run's scale applied. + let t = run.transform; + let scale = (t.sx * t.sy - t.kx * t.ky).abs().sqrt(); + set_color(out, &mut st.stroke, run.color, "RG"); + stroke_state(out, st, &GlyphRun::halo_stroke(w * scale)); + } + if halo.is_some() { + // The copy is decoration, marked so (an artifact) for readers that leave artifacts out + // of what they copy and find. (An empty `ActualText` would hide it from every reader's + // text, but VectorCraft then drops the halo altogether.) + out.extend_from_slice(b"/Artifact BMC\n"); + } out.extend_from_slice(b"BT\n"); + if halo.is_some() { + out.extend_from_slice(b"2 Tr\n"); + } // Glyph space is y up: flipped into the run's y-down space. write_matrix(out, run.transform.pre_scale(1.0, -1.0)); out.extend_from_slice(b" Tm\n"); @@ -298,7 +326,8 @@ impl Writer<'_> { let _ = if p.wide { write!(out, "<{:04X}>", p.code) } else { write!(out, "<{:02X}>", p.code) }; pen = x + p.advance * size; } - out.extend_from_slice(b"] TJ\nET\n"); + // (The rendering mode is text state, kept past ET: set back for the text that follows.) + out.extend_from_slice(if halo.is_some() { b"] TJ\n0 Tr\nET\nEMC\n" } else { b"] TJ\nET\n" }); } /// Places a picture: an image object (with its alpha as a soft mask) drawn where it lies. @@ -720,6 +749,7 @@ mod tests { color: Color::from_rgba8(20, 20, 20, 255), transform: Transform::from_translate(210.0, 40.0), glyphs, + halo: None, }); let mut pic = Pixmap::new(4, 4).unwrap(); pic.fill(Color::from_rgba8(0, 160, 0, 200)); @@ -805,7 +835,7 @@ mod tests { let x = font.h_advance_unscaled(a) / upm * 20.0 + 5.0; let mut d = Drawing::new(100.0, 100.0); let glyphs = vec![Glyph { id: a, x: 0.0, ch: 'A' }, Glyph { id: v, x, ch: 'V' }]; - d.glyphs(GlyphRun { font, size: 20.0, color: Color::BLACK, transform: Transform::from_translate(10.0, 50.0), glyphs }); + d.glyphs(GlyphRun { font, size: 20.0, color: Color::BLACK, transform: Transform::from_translate(10.0, 50.0), glyphs, halo: None }); let objs = objects(&write(&[Page::drawing(d, 10.0, 10.0)], "")); let content = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|c| c.contains("TJ")).unwrap(); assert!(content.contains("1 0 0 -1 10 50 Tm\n") && content.contains("[<00>-250<01>] TJ"), "{content}"); diff --git a/crates/render/src/pdf/embed.rs b/crates/render/src/pdf/embed.rs index 71fa6bcf8d..550b8bd080 100644 --- a/crates/render/src/pdf/embed.rs +++ b/crates/render/src/pdf/embed.rs @@ -230,6 +230,7 @@ mod tests { color: Color::BLACK, transform: Transform::from_row(1.0, 0.0, kx, 1.0, 10.0, 40.0), glyphs: text.chars().zip(0..).map(|(ch, i)| Glyph { id: font.glyph_id(ch), x: 11.0 * i as f32, ch }).collect(), + halo: None, }; let mut d = Drawing::new(200.0, 100.0); d.glyphs(run(0.0)); @@ -324,6 +325,48 @@ mod tests { assert_eq!(cids_are_their_glyphs(font, &objs, "/Subtype /CIDFontType0"), 3, "C, A, B"); } + /// A halo (#1815) is its text again under it, filled and stroked: in an embedded face, the + /// same font in rendering mode 2, its stroke rounded and as wide as the run's scale makes it, + /// marked as an artifact; in outlines, its glyphs' outlines filled and stroked, as before. + #[test] + fn a_halo_is_its_text_filled_and_stroked() { + let font = face(|_| ()); + let run = |halo: Option, color: Color| GlyphRun { + font, + size: 20.0, + color, + transform: Transform::from_row(2.0, 0.0, 0.0, 2.0, 10.0, 40.0), + glyphs: "Rio".chars().zip(0..).map(|(ch, i)| Glyph { id: font.glyph_id(ch), x: 11.0 * i as f32, ch }).collect(), + halo, + }; + let page = || { + let mut d = Drawing::new(200.0, 100.0); + d.begin_group(0.9, rustgis_map::effects::Blend::Normal, None); + d.glyphs(run(Some(2.4), Color::WHITE)); + d.end_group(); + d.glyphs(run(None, Color::BLACK)); + Page::drawing(d, 100.0, 50.0) + }; + let streams = + |pdf: &[u8]| objects(pdf).into_iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).collect::>().join("\n"); + let (pdf, outlined) = write_with(&[page()], "Halo", Options { text: Text::Fonts, ..Options::default() }); + assert!(outlined.is_empty()); + let text = String::from_utf8_lossy(&pdf); + assert_eq!(text.matches("/Subtype /Type0").count(), 1, "the halo in the text's own font"); + let content = streams(&pdf); + let halo = content.split("/Artifact BMC\n").nth(1).and_then(|h| h.split("EMC\n").next()).unwrap_or_else(|| panic!("{content}")); + assert!(halo.starts_with("BT\n2 Tr\n") && halo.ends_with("] TJ\n0 Tr\nET\n"), "{halo}"); + // Stroked in white, rounded, the run's 2.4 pixels doubled by its scale. + assert!( + content.contains("1 1 1 RG") && content.contains("4.8 w") && content.contains("1 J") && content.contains("1 j"), + "{content}" + ); + assert_eq!(content.matches(" Tr\n").count(), 2, "the text itself is filled only"); + // In outlines: the halo as its glyphs' outlines, filled and stroked. + let outlines = streams(&write_with(&[page()], "Halo", Options { text: Text::Outlines, ..Options::default() }).0); + assert!(!outlines.contains(" Tr\n") && !outlines.contains("/Artifact") && outlines.contains("\nB\n"), "{outlines}"); + } + /// A face whose licence forbids embedding (fsType 2) is set in outlines, and said. #[test] fn a_face_that_forbids_embedding_is_set_in_outlines() { diff --git a/crates/render/src/pdf/fonts.rs b/crates/render/src/pdf/fonts.rs index 439e2ec01b..d20836f72f 100644 --- a/crates/render/src/pdf/fonts.rs +++ b/crates/render/src/pdf/fonts.rs @@ -75,6 +75,11 @@ impl Fonts { Fonts { real, real_by_font, ..Fonts::default() } } + /// Whether `font` is embedded as itself (else its glyphs go to Type 3 fonts). + pub fn is_real(&self, font: &FontRef<'static>) -> bool { + self.real_by_font.contains_key(&(std::ptr::from_ref(font) as usize)) + } + /// `id` of `font` (standing for `ch`), given a code in one of its Type 3 fonts the first time; /// `None` only past what a font can hold. pub fn place(&mut self, doc: &mut Doc, font: &'static FontRef<'static>, id: GlyphId, ch: char) -> Option { diff --git a/crates/render/src/svg/vectors.rs b/crates/render/src/svg/vectors.rs index 6e8b7052a3..aa6b42c162 100644 --- a/crates/render/src/svg/vectors.rs +++ b/crates/render/src/svg/vectors.rs @@ -199,7 +199,12 @@ fn glyphs(out: &mut String, defs: &mut Defs, run: &GlyphRun) { let face = std::ptr::from_ref(run.font) as usize; let k = run.size / upm; let text: String = run.glyphs.iter().map(|g| g.ch).collect(); - let _ = writeln!(out, r#""#, super::esc(&text), paint("fill", run.color), transform_attr(run.transform)); + // A halo's copy (#1815) stroked as well, its width in the glyphs' own units (each is placed + // scaled by `k`). + let stroke = run.halo.filter(|w| w.is_finite() && *w > 0.0 && k > 0.0).map_or(String::new(), |w| { + format!(r#"{} stroke-width="{}" stroke-linejoin="round" stroke-linecap="round""#, paint("stroke", run.color), trimmed(w / k, 4)) + }); + let _ = writeln!(out, r#""#, super::esc(&text), paint("fill", run.color), transform_attr(run.transform)); for g in &run.glyphs { let id = match defs.glyphs.get(&(face, g.id.0)) { Some(id) => id.clone(), @@ -378,7 +383,7 @@ mod tests { let o = font.glyph_id('o'); let glyphs = vec![Glyph { id: o, x: 0.0, ch: 'o' }, Glyph { id: font.glyph_id(' '), x: 6.0, ch: ' ' }, Glyph { id: o, x: 9.0, ch: 'o' }]; - d.glyphs(GlyphRun { font, size: 12.0, color: Color::BLACK, transform: Transform::from_translate(60.0, 40.0), glyphs }); + d.glyphs(GlyphRun { font, size: 12.0, color: Color::BLACK, transform: Transform::from_translate(60.0, 40.0), glyphs, halo: None }); let mut pic = tiny_skia::Pixmap::new(2, 2).unwrap(); pic.fill(Color::from_rgba8(0, 128, 0, 255)); d.image(pic.as_ref(), Transform::from_scale(5.0, 5.0), 0.5, false); @@ -415,6 +420,23 @@ mod tests { assert!(defs.text.contains(r#" 0.0) { + for line in placed.iter().filter(|_| r > 0.0) { if pm.overflowed() { break; } - let outline = if styled { - styled_outline(line, left, y, px, label_face(l), spacing) - } else { - plain_outline(line, left + lw / 2.0, y, px, l.bold) - }; - keep_halo(pm, outline, r, h); + keep_halo(pm, r, h, |c, color| put(c, line, color, (0.0, 0.0))); } } if ink != Ink::Halo { @@ -1036,7 +1031,8 @@ pub fn text_at(pm: &mut Canvas, text: &str, x: f32, y: f32, px_size: f32, color: Align::Right => x - measure(text, px_size / 1.33, bold) / 2.0, }; if halo && pm.is_recording() { - keep_halo(pm, plain_outline(text, cx, y, px_size, bold), (px_size * 0.09).max(1.0), Rgba::new(255, 255, 255, 230)); + let r = (px_size * 0.09).max(1.0); + keep_halo(pm, r, Rgba::new(255, 255, 255, 230), |c, color| draw_text(c, text, cx, y, px_size, color, bold, (0.0, 0.0))); } else if halo { let r = (px_size * 0.09).max(1.0); for (dx, dy) in [(-r, 0.0), (r, 0.0), (0.0, -r), (0.0, r)] { @@ -1071,98 +1067,16 @@ fn keep_glyphs( color: tiny_skia::Color::from_rgba8(color.r(), color.g(), color.b(), color.a()), transform: Transform::from_row(1.0, 0.0, kx, 1.0, origin.0, origin.1), glyphs: run.iter().map(|&(i, &(_, id, x, ch))| crate::vector::Glyph { id, x: x + spacing * i as f32, ch }).collect(), + halo: None, }); } } -/// The outline of one line of [`draw_text`]'s, centred on (`cx`, `cy`), as one path. -fn plain_outline(text: &str, cx: f32, cy: f32, px: f32, bold: bool) -> Option { - let f = font(bold)?; - let sf = f.as_scaled(em(f, px)); - let (glyphs, width) = shape(text, px, f, None); - let base = cy + (sf.ascent() + sf.descent()) / 2.0; - outline_of(&glyphs, (cx - width / 2.0, base), px, 0.0, |_| false) -} - -/// The outline of one line of [`styled_at`]'s, from `left`, as one path. -fn styled_outline(text: &str, left: f32, cy: f32, px: f32, face: Face, spacing: f32) -> Option { - let (f, slanted) = face_font(face)?; - let sf = f.as_scaled(em(f, px)); - let base = cy + (sf.ascent() + sf.descent()) / 2.0; - let (glyphs, _) = shape(text, px, f, sans_beside(f, face)); - outline_of(&glyphs, (left, base), px, spacing, |gf| leans(face, f, slanted, gf)) -} - -/// `glyphs`' outlines placed as [`keep_glyphs`] places them, in pixels, as one path. -fn outline_of( - glyphs: &[Shaped], - (x0, base): (f32, f32), - px: f32, - spacing: f32, - lean: impl Fn(&FontRef<'static>) -> bool, -) -> Option { - let mut pb = tiny_skia::PathBuilder::new(); - for (i, &(f, id, x, _)) in glyphs.iter().enumerate() { - // A face with no usable units per em is read at the usual 1000, as its glyphs are in the - // PDF's fonts. - let upm = f.units_per_em().filter(|u| u.is_finite() && *u > 0.0).unwrap_or(1000.0); - let Some(o) = f.outline(id) else { continue }; - let (k, slant, pen) = (px / upm, if lean(f) { SLANT } else { 0.0 }, x0 + x + spacing * i as f32); - // Font units (y up, from the pen on the baseline) to pixels. - let at = |p: ab_glyph::Point| (pen + (p.x + slant * p.y) * k, base - p.y * k); - let mut last: Option = None; - for c in &o.curves { - let (start, end) = match c { - ab_glyph::OutlineCurve::Line(a, b) | ab_glyph::OutlineCurve::Quad(a, _, b) | ab_glyph::OutlineCurve::Cubic(a, _, _, b) => { - (*a, *b) - } - }; - if last != Some(start) { - if last.is_some() { - pb.close(); - } - let (sx, sy) = at(start); - pb.move_to(sx, sy); - } - match c { - ab_glyph::OutlineCurve::Line(_, b) => { - let (bx, by) = at(*b); - pb.line_to(bx, by); - } - ab_glyph::OutlineCurve::Quad(_, k1, b) => { - let ((kx, ky), (bx, by)) = (at(*k1), at(*b)); - pb.quad_to(kx, ky, bx, by); - } - ab_glyph::OutlineCurve::Cubic(_, k1, k2, b) => { - let ((ax, ay), (cx, cy), (bx, by)) = (at(*k1), at(*k2), at(*b)); - pb.cubic_to(ax, ay, cx, cy, bx, by); - } - } - last = Some(end); - } - if last.is_some() { - pb.close(); - } - } - pb.finish() -} - -/// Keeps a halo `r` pixels wide round `outline` in `color`: the letters filled and their outlines -/// stroked twice `r` wide, rounded, both opaque in a group at the colour's alpha, so a see-through -/// halo is one coat where they overlap. -fn keep_halo(pm: &mut Canvas, outline: Option, r: f32, color: Rgba) { - let Some(path) = outline else { return }; - let stroke = tiny_skia::Stroke { - width: 2.0 * r, - line_cap: tiny_skia::LineCap::Round, - line_join: tiny_skia::LineJoin::Round, - ..tiny_skia::Stroke::default() - }; - let solid = crate::paint(color.with_alpha(255), 1.0); - pm.group(f32::from(color.a()) / 255.0, |c| { - c.fill_path(&path, &solid, tiny_skia::FillRule::Winding, Transform::identity(), None); - c.stroke_path(&path, &solid, &stroke, Transform::identity(), None); - }); +/// Keeps a halo `r` pixels wide in `color` round the text `draw` sets (given the colour to set it +/// in): a copy of its glyphs, filled and stroked twice `r` wide, rounded (#1815), opaque in a +/// group at the colour's alpha, so a see-through halo is one coat where glyphs overlap. +fn keep_halo(pm: &mut Canvas, r: f32, color: Rgba, draw: impl FnOnce(&mut Canvas, Rgba)) { + pm.group(f32::from(color.a()) / 255.0, |c| c.halo(2.0 * r, |c| draw(c, color.with_alpha(255)))); } #[cfg(test)] diff --git a/crates/render/src/vector.rs b/crates/render/src/vector.rs index c6766cea7c..befeecad64 100644 --- a/crates/render/src/vector.rs +++ b/crates/render/src/vector.rs @@ -103,6 +103,62 @@ pub struct GlyphRun { pub color: Color, pub transform: Transform, pub glyphs: Vec, + /// A halo's copy of the text, drawn under it (#1815): its glyphs filled and stroked this wide + /// (in the run's pixels), rounded, in `color`. `None` for the text itself. + pub halo: Option, +} + +impl GlyphRun { + /// The run's glyph outlines as one path, in the run's space (before `transform`); `None` + /// for a run with no outline (spaces). + pub(crate) fn outline(&self) -> Option { + let upm = self.font.units_per_em().filter(|u| u.is_finite() && *u > 0.0).unwrap_or(1000.0); + let k = self.size / upm; + let mut pb = tiny_skia::PathBuilder::new(); + for g in &self.glyphs { + let Some(o) = self.font.outline(g.id) else { continue }; + let at = |p: ab_glyph::Point| (g.x + p.x * k, -p.y * k); + let mut last = None; + for c in &o.curves { + let (a, e) = match c { + ab_glyph::OutlineCurve::Line(a, b) + | ab_glyph::OutlineCurve::Quad(a, _, b) + | ab_glyph::OutlineCurve::Cubic(a, _, _, b) => (*a, *b), + }; + if last != Some(a) { + if last.is_some() { + pb.close(); + } + let (x, y) = at(a); + pb.move_to(x, y); + } + match c { + ab_glyph::OutlineCurve::Line(_, b) => { + let (x, y) = at(*b); + pb.line_to(x, y); + } + ab_glyph::OutlineCurve::Quad(_, q, b) => { + let ((qx, qy), (x, y)) = (at(*q), at(*b)); + pb.quad_to(qx, qy, x, y); + } + ab_glyph::OutlineCurve::Cubic(_, q1, q2, b) => { + let ((ax, ay), (bx, by), (x, y)) = (at(*q1), at(*q2), at(*b)); + pb.cubic_to(ax, ay, bx, by, x, y); + } + } + last = Some(e); + } + if last.is_some() { + pb.close(); + } + } + pb.finish() + } + + /// The stroke a halo run's glyphs are drawn with: `width` wide, rounded. + pub(crate) fn halo_stroke(width: f32) -> Stroke { + Stroke { width, cap: LineCap::Round, join: LineJoin::Round, ..Stroke::default() } + } } /// A glyph at its pen position along the run, and the character it stands for (what copying @@ -418,8 +474,7 @@ pub(crate) fn without_layers(items: Vec) -> Vec { /// recording with what the renderer draws. #[cfg(test)] pub(crate) fn replay(items: &[Item], pm: &mut Pixmap, base: Transform) { - use ab_glyph::Font; - use tiny_skia::{GradientStop, Paint, PathBuilder, PixmapPaint, Point, SpreadMode}; + use tiny_skia::{GradientStop, Paint, PixmapPaint, Point, SpreadMode}; let paint = |c: Color| { let mut p = Paint::default(); p.set_color(c); @@ -463,48 +518,14 @@ pub(crate) fn replay(items: &[Item], pm: &mut Pixmap, base: Transform) { pm.stroke_path(path, &paint(*color), &st, base.pre_concat(*transform), None); } Item::Glyphs(run) => { - let upm = run.font.units_per_em().unwrap_or(1000.0); - let k = run.size / upm; - let mut pb = PathBuilder::new(); - for g in &run.glyphs { - let Some(o) = run.font.outline(g.id) else { continue }; - let at = |p: ab_glyph::Point| (g.x + p.x * k, -p.y * k); - let mut last = None; - for c in &o.curves { - let (a, e) = match c { - ab_glyph::OutlineCurve::Line(a, b) - | ab_glyph::OutlineCurve::Quad(a, _, b) - | ab_glyph::OutlineCurve::Cubic(a, _, _, b) => (*a, *b), - }; - if last != Some(a) { - if last.is_some() { - pb.close(); - } - let (x, y) = at(a); - pb.move_to(x, y); - } - match c { - ab_glyph::OutlineCurve::Line(_, b) => { - let (x, y) = at(*b); - pb.line_to(x, y); - } - ab_glyph::OutlineCurve::Quad(_, q, b) => { - let ((qx, qy), (x, y)) = (at(*q), at(*b)); - pb.quad_to(qx, qy, x, y); - } - ab_glyph::OutlineCurve::Cubic(_, q1, q2, b) => { - let ((ax, ay), (bx, by), (x, y)) = (at(*q1), at(*q2), at(*b)); - pb.cubic_to(ax, ay, bx, by, x, y); - } - } - last = Some(e); + if let Some(path) = run.outline() { + let at = base.pre_concat(run.transform); + pm.fill_path(&path, &paint(run.color), tiny_skia::FillRule::Winding, at, None); + if let Some(w) = run.halo { + let s = GlyphRun::halo_stroke(w); + let st = tiny_skia::Stroke { width: s.width, line_cap: s.cap, line_join: s.join, ..tiny_skia::Stroke::default() }; + pm.stroke_path(&path, &paint(run.color), &st, at, None); } - if last.is_some() { - pb.close(); - } - } - if let Some(path) = pb.finish() { - pm.fill_path(&path, &paint(run.color), tiny_skia::FillRule::Winding, base.pre_concat(run.transform), None); } } Item::Image(image) => { @@ -598,6 +619,7 @@ mod tests { color: Color::BLACK, transform: Transform::identity(), glyphs: vec![Glyph { id: ab_glyph::Font::glyph_id(font, 'W'), x: 0.0, ch: 'W' }], + halo: None, }; let mut page = Drawing::new(10.0, 10.0); page.glyphs(run()); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index f79e5c1a17..9c18b9fecb 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -405,8 +405,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu edited; it can be searched and copied in any PDF reader. A face whose licence forbids embedding or subsetting, one drawn at another weight than its variable font file's default, or one whose file can't be read is set as its letters' outlines instead, and the export names it with why. - `"pdf": {"text": "outlines"}` on `layout.export` sets all the text as outlines, as a print shop - asking for outlined type wants. + A label's halo is a copy of its text under it, filled and stroked as wide as the halo, so it is + text too (marked as decoration, an artifact, for readers that leave those out of what they copy). + `"pdf": {"text": "outlines"}` on `layout.export` sets all the text, halos too, as outlines, as a + print shop asking for outlined type wants. Its page has layers (PDF optional content groups), which a vector editor that reads them opens as layers (VectorCraft, where it was checked), and PDF readers list in their layers panel: one for each element, named after it, and inside a map frame's, one for each map layer and one From 1d62ab93719808b5c7a9b273217fe715e05a897d Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 18:24:35 -0300 Subject: [PATCH 09/12] fix(render): a halo of no width draws nothing (#1815, halos) Canvas::halo with a width that is not a positive number drew its text as plain text in the halo colour in a PDF or SVG, where the pixels draw nothing. It now draws nothing. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/canvas.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/render/src/canvas.rs b/crates/render/src/canvas.rs index 05aaadfb94..7c7650d9bd 100644 --- a/crates/render/src/canvas.rs +++ b/crates/render/src/canvas.rs @@ -228,8 +228,12 @@ impl Canvas { /// Draws with `f` as a halo `width` wide (#1815): the glyphs it keeps are a halo's copy of the /// text, filled and stroked that wide (see [`vector::GlyphRun::halo`]), so a PDF writes the - /// halo as text too. Only a recording keeps halos so; a canvas that draws pixels runs `f`. + /// halo as text too. Only a recording keeps halos so; a canvas that draws pixels runs `f`. A + /// width that isn't a positive number is no halo: nothing is drawn, as on the pixels. pub fn halo(&mut self, width: f32, f: impl FnOnce(&mut Canvas)) { + if !(width.is_finite() && width > 0.0) { + return; + } let old = self.rec.as_mut().map(|r| r.halo.replace(width)); f(self); if let (Some(r), Some(old)) = (&mut self.rec, old) { @@ -480,6 +484,30 @@ mod tests { assert_eq!(alpha(27), Some(0), "the clip past the child"); } + /// A halo of no width, or of one that isn't a number, draws nothing (#1815): not a copy of + /// the text in the halo's colour set as plain text. + #[test] + fn a_halo_of_no_width_draws_nothing() { + let font = crate::text::label_font().unwrap(); + let run = || GlyphRun { + font, + size: 12.0, + color: Color::WHITE, + transform: Transform::identity(), + glyphs: vec![crate::vector::Glyph { id: ab_glyph::Font::glyph_id(font, 'A'), x: 0.0, ch: 'A' }], + halo: None, + }; + for width in [0.0, -1.0, f32::NAN, f32::INFINITY] { + let mut c = Canvas::recording(40, 20).unwrap(); + c.halo(width, |c| c.glyphs(run())); + assert!(c.into_drawing().unwrap().is_empty(), "{width}"); + } + let mut c = Canvas::recording(40, 20).unwrap(); + c.halo(2.0, |c| c.glyphs(run())); + let (_, _, items) = c.into_drawing().unwrap().finish(); + assert!(matches!(items.as_slice(), [Item::Glyphs(r)] if r.halo == Some(2.0))); + } + #[test] fn a_label_keeps_its_halo_as_text_and_its_text_once() { let label = crate::PlacedLabel { From 5e557eef9a5916a403a3b5c93455e04bdd86d617 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 21:34:05 -0300 Subject: [PATCH 10/12] fix(render): a subset tag follows its face file (#1815, halos) The six-letter tag also hashes the face file's size and bytes, so two files with the same PostScript name and glyphs get two tags. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/pdf/embed.rs | 35 +++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/crates/render/src/pdf/embed.rs b/crates/render/src/pdf/embed.rs index 550b8bd080..1d37217b39 100644 --- a/crates/render/src/pdf/embed.rs +++ b/crates/render/src/pdf/embed.rs @@ -153,7 +153,7 @@ pub(super) fn embed(font: &FontRef<'_>, glyphs: &[GlyphId], room: usize) -> Resu let name = if name.is_empty() { "Face".to_string() } else { name }; Ok(Embedded { cff: face.tables().cff.is_some(), - name: format!("{}+{name}", tag(&name, glyphs)), + name: format!("{}+{name}", tag(&name, glyphs, data)), remapper, bbox: [f32::from(b.x_min) * k, f32::from(b.y_min) * k, f32::from(b.x_max) * k, f32::from(b.y_max) * k], ascent: f32::from(face.ascender()) * k, @@ -188,11 +188,25 @@ fn curve_points(c: &OutlineCurve) -> (u8, [(f32, f32); 4]) { } } -/// A subset's six-letter tag, from its face's name and glyphs: the same subset, the same tag. -fn tag(name: &str, glyphs: &[GlyphId]) -> String { +/// A subset's six-letter tag, from its face's name, glyphs and file (its size and bytes): the same +/// subset, the same tag, and two files with the same name and glyphs, two tags. +fn tag(name: &str, glyphs: &[GlyphId], file: &[u8]) -> String { let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in name.bytes().chain(glyphs.iter().flat_map(|g| g.0.to_le_bytes())) { - h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); + let mut mix = |v: u64| h = (h ^ v).wrapping_mul(0x0100_0000_01b3); + for b in name.bytes() { + mix(u64::from(b)); + } + for g in glyphs { + mix(u64::from(g.0)); + } + mix(file.len() as u64); + // The file eight bytes at a time (a large face is read once, quickly), then what is left. + let (words, rest) = file.as_chunks::<8>(); + for b in rest { + mix(u64::from(*b)); + } + for w in words { + mix(u64::from_le_bytes(*w)); } (0..6).map(|i| char::from(b'A' + ((h >> (i * 5)) % 26) as u8)).collect() } @@ -310,6 +324,17 @@ mod tests { /// A CFF face (an OpenType .otf) is embedded as a CIDFontType0 over its subset as an /// OpenType file (FontFile3, PDF 1.6), each CID its character's glyph. The face is the /// test's own (testdata/README.md): a square, a triangle and two bars, each its own width. + /// A subset's tag follows its face's file, not only its name and glyphs: two files with the + /// same name and glyphs get two tags (#1815). + #[test] + fn a_subset_tag_follows_its_file() { + let glyphs = [GlyphId(3), GlyphId(7)]; + let (a, b) = (tag("Face", &glyphs, b"one file"), tag("Face", &glyphs, b"another file")); + assert_eq!(a, tag("Face", &glyphs, b"one file"), "the same subset, the same tag"); + assert_ne!(a, b); + assert!(a.len() == 6 && a.chars().all(|c| c.is_ascii_uppercase()), "{a}"); + } + #[test] fn a_cff_face_is_a_cid_font_type0() { let bytes: &'static [u8] = include_bytes!("../../testdata/test-cff.otf"); From 54d217f0c0b363b83dd41dbbee1cedb2d6cfc7ef Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 13 Nov 2026 02:04:14 -0300 Subject: [PATCH 11/12] fix(render): an SVG halo copy is hidden from screen readers (#1815, halos) The halo's copy of a label is aria-hidden instead of repeating the text's aria-label, so a screen reader reads the label once (the PDF marks it an artifact). The subset-tag test moves above the CFF test's doc comment. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/pdf/embed.rs | 6 +++--- crates/render/src/svg/vectors.rs | 15 ++++++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/render/src/pdf/embed.rs b/crates/render/src/pdf/embed.rs index 1d37217b39..135df2f225 100644 --- a/crates/render/src/pdf/embed.rs +++ b/crates/render/src/pdf/embed.rs @@ -321,9 +321,6 @@ mod tests { checked } - /// A CFF face (an OpenType .otf) is embedded as a CIDFontType0 over its subset as an - /// OpenType file (FontFile3, PDF 1.6), each CID its character's glyph. The face is the - /// test's own (testdata/README.md): a square, a triangle and two bars, each its own width. /// A subset's tag follows its face's file, not only its name and glyphs: two files with the /// same name and glyphs get two tags (#1815). #[test] @@ -335,6 +332,9 @@ mod tests { assert!(a.len() == 6 && a.chars().all(|c| c.is_ascii_uppercase()), "{a}"); } + /// A CFF face (an OpenType .otf) is embedded as a CIDFontType0 over its subset as an + /// OpenType file (FontFile3, PDF 1.6), each CID its character's glyph. The face is the + /// test's own (testdata/README.md): a square, a triangle and two bars, each its own width. #[test] fn a_cff_face_is_a_cid_font_type0() { let bytes: &'static [u8] = include_bytes!("../../testdata/test-cff.otf"); diff --git a/crates/render/src/svg/vectors.rs b/crates/render/src/svg/vectors.rs index aa6b42c162..8967340301 100644 --- a/crates/render/src/svg/vectors.rs +++ b/crates/render/src/svg/vectors.rs @@ -204,7 +204,10 @@ fn glyphs(out: &mut String, defs: &mut Defs, run: &GlyphRun) { let stroke = run.halo.filter(|w| w.is_finite() && *w > 0.0 && k > 0.0).map_or(String::new(), |w| { format!(r#"{} stroke-width="{}" stroke-linejoin="round" stroke-linecap="round""#, paint("stroke", run.color), trimmed(w / k, 4)) }); - let _ = writeln!(out, r#""#, super::esc(&text), paint("fill", run.color), transform_attr(run.transform)); + // The halo's copy is decoration: hidden from screen readers, which read the label once (as a + // PDF marks it an artifact). + let label = if run.halo.is_some() { r#" aria-hidden="true""#.to_string() } else { format!(r#" aria-label="{}""#, super::esc(&text)) }; + let _ = writeln!(out, r#""#, paint("fill", run.color), transform_attr(run.transform)); for g in &run.glyphs { let id = match defs.glyphs.get(&(face, g.id.0)) { Some(id) => id.clone(), @@ -421,20 +424,26 @@ mod tests { } /// A halo's copy of the text (#1815) is the run stroked as well, rounded, its width in the - /// glyphs' own units so that it is the run's once they are scaled. + /// glyphs' own units so that it is the run's once they are scaled; it is hidden from screen + /// readers, and the text over it keeps its label, so the label is read once. #[test] fn a_halo_run_is_stroked() { let font = crate::text::label_font().unwrap(); let glyphs = vec![Glyph { id: ab_glyph::Font::glyph_id(font, 'H'), x: 0.0, ch: 'H' }]; let upm = ab_glyph::Font::units_per_em(font).unwrap(); let mut d = Drawing::new(40.0, 40.0); - d.glyphs(GlyphRun { font, size: 10.0, color: Color::WHITE, transform: Transform::identity(), glyphs, halo: Some(2.0) }); + let run = |color, halo| GlyphRun { font, size: 10.0, color, transform: Transform::identity(), glyphs: glyphs.clone(), halo }; + d.glyphs(run(Color::WHITE, Some(2.0))); + d.glyphs(run(Color::BLACK, None)); let (_, _, list) = d.finish(); let (mut svg, mut defs) = (String::new(), Defs::default()); items(&mut svg, &mut defs, &list).unwrap(); let width = format!(r#"stroke-width="{}""#, trimmed(2.0 / (10.0 / upm), 4)); assert!(svg.contains(r##"stroke="#ffffff""##) && svg.contains(&width), "{svg}"); assert!(svg.contains(r#"stroke-linejoin="round" stroke-linecap="round""#), "{svg}"); + let groups: Vec<&str> = svg.lines().filter(|l| l.starts_with("