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 | 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 d761b76408..5691aaa734 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), "pdf"?: {"layers"?: bool (default true: each element, and in a map frame each layer and its labels, a PDF layer that vector editors open as a layer; 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"?: {"layers"?: bool (default true: each element, and in a map frame each layer and its labels, a PDF layer that vector editors open as a layer; false: none), "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(); @@ -4623,7 +4623,7 @@ pub fn layout_bytes(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool) } /// [`layout_bytes`], a PDF's map frames georeferenced only when `georeference` (#1191), written -/// as `options` say (its layers, #1815). Returns an actionable error if a linked archive changes +/// as `options` say (its layers and text, #1815). Returns an actionable error if a linked archive changes /// while the pages are drawn. pub fn layout_bytes_with( s: &mut Session, @@ -4757,7 +4757,30 @@ fn layout_bytes_inner( 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_with(&pages, &saved.name, options)) } 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, options); + 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. +pub(crate) 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 @@ -4874,15 +4897,17 @@ pub(crate) fn pictured_notices(s: &mut Session, frames: &[(u32, String)], pages: } /// The keys `layout.export`'s `"pdf"` takes. -const PDF_KEYS: &[&str] = &["layers"]; +const PDF_KEYS: &[&str] = &["layers", "text"]; -/// How `layout.export`'s `"pdf": {…}` asks a PDF to be written: with its layers unless -/// `"layers": false` (#1815). A key it doesn't know is refused, with the keys it takes. +/// How `layout.export`'s `"pdf": {…}` asks a PDF to be written (#1815): with its layers unless +/// `"layers": false`, its text in its fonts unless `"text": "outlines"`. It is checked whatever +/// the export writes, a PNG or SVG 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_options(p: &Value) -> Result { + use rustgis_render::pdf::Text; let mut options = rustgis_render::pdf::Options::default(); let Some(pdf) = p.get("pdf").filter(|v| !v.is_null()) else { return Ok(options) }; - let Some(pdf) = pdf.as_object() else { return Err(r#"pdf is an object: {"layers": true|false}"#.into()) }; - // A key it doesn't know (a typo) is refused, not left to change nothing unsaid. + let Some(pdf) = pdf.as_object() else { return Err(r#"pdf is an object: {"layers": true|false, "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(", "))); } @@ -4891,6 +4916,12 @@ fn pdf_options(p: &Value) -> Result { Some(Value::Bool(on)) => options.layers = *on, Some(_) => return Err("pdf.layers is true or false".into()), } + options.text = match pdf.get("text") { + None | Some(Value::Null) => Text::Fonts, + Some(v) if v == "fonts" => Text::Fonts, + Some(v) if v == "outlines" => Text::Outlines, + Some(_) => return Err(r#"pdf.text is "fonts" or "outlines""#.into()), + }; Ok(options) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8a66bdacc4..e8a3e5c175 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9712,9 +9712,9 @@ fn layouts_compose_export_and_round_trip() { let pdf = std::fs::read(&pdf_path).unwrap(); let count = format!("/Count {pages}"); assert!(pdf.windows(count.len()).any(|w| w == count.as_bytes()), "one PDF page per series page"); - // Kept as vectors: its text in outline fonts, no page a picture, and nothing too large. + // Kept as vectors: its text in its fonts (#1815), no page a picture, and nothing too large. let has = |needle: &[u8]| pdf.windows(needle.len()).any(|w| w == needle); - assert!(has(b"/Subtype /Type3") && has(b"/ToUnicode") && has(b"/Contents")); + assert!(has(b"/Subtype /Type0") && has(b"/ToUnicode") && has(b"/Contents")); assert!(!has(b"/Im0 Do"), "no page is one picture"); assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("as pictures, not vectors"))); assert_eq!(s.project.layouts[0].series.as_ref().unwrap().page, 1, "the shown page is restored"); @@ -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()); @@ -38338,6 +38367,65 @@ fn a_pdf_says_which_frames_and_pages_it_draws_as_pictures() { ); } +/// A layout's PDF sets its text in its faces, embedded as subsets (#1815): a layout text and a +/// map's labels come out as Type 0 fonts over CID fonts, their text read back through each font's +/// map; `"pdf": {"text": "outlines"}` keeps the Type 3 outlines, and anything else is refused. +#[test] +fn a_layout_pdf_sets_its_text_in_its_fonts() { + let mut s = world(); + s.run("labels.field", &json!({"layer": "Countries", "field": "name"})).unwrap(); + s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "map"})).unwrap(); + s.run("layout.addElement", &json!({"kind": "text", "text": "Ocupação do solo"})).unwrap(); + let path = std::env::temp_dir().join(format!("rustgis-fonts-{}.pdf", std::process::id())); + // Removed however the test ends. + struct Removed(std::path::PathBuf); + impl Drop for Removed { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + let _removed = Removed(path.clone()); + let export = |s: &mut Session, p: Value| { + let mark = s.notice_mark(); + let mut p = p; + p["path"] = json!(path); + p["dpi"] = json!(72); + s.run("layout.export", &p).map(|_| { + let said: Vec = 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:?}"); + export(&mut s, json!({"pdf": {"text": "fonts"}})).unwrap(); + assert!(std::fs::read(&path).unwrap() == raw, "\"fonts\" is the default, byte for byte"); + 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(); + let said = ["\"fonts\" or \"outlines\"", "fonts\"|\"outlines", "pdf has no key \"txt\": its keys are layers, text"]; + assert!(said.iter().any(|s| err.contains(s)), "{bad}: {err}"); + } +} + /// A layout's PDF has layers (#1815): each element an optional content group named after it, /// its map frame's map layers and their labels inside the frame's; the GeoPDF viewports stay. /// `"pdf": {"layers": false}` leaves them out, a bad value is refused, and a layout with no map 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 7d285d1acf..b9ef7d7abe 100644 --- a/crates/render/src/pdf.rs +++ b/crates/render/src/pdf.rs @@ -1,15 +1,17 @@ //! 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. A drawing's layers (layout elements, map layers, their labels) -//! become optional content groups, which vector editors open as layers ([`Options::layers`]). +//! 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. A +//! drawing's layers (layout elements, map layers, their labels) become optional content groups, +//! which vector editors open as layers ([`Options::layers`]). 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 @@ -225,6 +227,24 @@ impl Doc { } } +/// 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, +} + /// How a document is written. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Options { @@ -233,11 +253,13 @@ pub struct Options { /// so a vector editor that reads optional content (VectorCraft, where it was checked) opens /// the page with them as its layers. Off, the page is the same, without them. pub layers: bool, + /// How its vector text is written: in its faces, or in outlines ([`Text`]). + pub text: Text, } impl Default for Options { fn default() -> Options { - Options { layers: true } + Options { layers: true, text: Text::Fonts } } } @@ -304,20 +326,51 @@ fn has_layer(items: &[Item]) -> bool { items.iter().any(|i| matches!(i, Item::Group(g) if g.layer.is_some() || has_layer(&g.items))) } -/// Writes the pages as a PDF document, with their layers ([`Options::default`]). +/// Writes the pages as a PDF document, with their layers, its text in outlines +/// ([`Text::Outlines`]). pub fn write(pages: &[Page], title: &str) -> Vec { - write_with(pages, title, Options::default()) + write_with(pages, title, Options { text: Text::Outlines, ..Options::default() }).0 } -/// Writes the pages as a PDF document, as `options` say. -pub fn write_with(pages: &[Page], title: &str, options: Options) -> Vec { +/// Writes the pages as a PDF document, as `options` say, and the faces set in outlines 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, options: Options) -> (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 options.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 { + if rustgis_data::progress::check().is_err() { + break; + } + 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, &glyphs), 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); layers (optional content) - // make it 1.5; 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; layers (optional content) make it 1.5; what else it + // holds is 1.4. let geo = pages.iter().any(|p| !p.viewports.is_empty()); let layered = options.layers && pages.iter().any(|p| matches!(&p.content, Content::Vector { items, .. } if has_layer(items))); let mut doc = if geo { Doc::of_version("1.7") + } else if real.iter().any(|(_, e)| e.cff) { + Doc::of_version("1.6") } else if layered { Doc::of_version("1.5") } else { @@ -325,7 +378,7 @@ pub fn write_with(pages: &[Page], title: &str, options: Options) -> Vec { }; 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); let mut layers = Layers { on: layered, ..Layers::default() }; 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); @@ -368,7 +421,34 @@ pub fn write_with(pages: &[Page], title: &str, options: Options) -> 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 @@ -611,7 +691,7 @@ pub(crate) mod tests { let page = objs.iter().find(|o| o.0.contains("/Properties <<")).map(|o| &o.0).unwrap(); assert!(page.contains(&format!("/OC{title} {title} 0 R")), "{page}"); // Without layers: no groups, no marks, and the same drawing. - let plain = write_with(&[layered_page()], "Layers", Options { layers: false }); + let plain = write_with(&[layered_page()], "Layers", Options { layers: false, text: Text::Outlines }).0; let plain_text = String::from_utf8_lossy(&plain); assert!(plain_text.starts_with("%PDF-1.4") && !plain_text.contains("/OCProperties") && !plain_text.contains("/Type /OCG")); let plain_content = diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index c983f7966e..846558c4f7 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -258,7 +258,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 { @@ -295,7 +295,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..71fa6bcf8d --- /dev/null +++ b/crates/render/src/pdf/embed.rs @@ -0,0 +1,386 @@ +//! 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`]. + SubsetTooLarge, + /// With it, the document's embedded faces would pass [`MAX_EMBEDDED`]. + DocumentTooLarge, +} + +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::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), + } + } +} + +/// A name for the face in a notice: its full name, else its family, else its PostScript name. +/// 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 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() + .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 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 +/// 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(); + 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()))?; + 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::SubsetTooLarge); + } + if file.len() > room { + return Err(Refused::DocumentTooLarge); + } + 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::{Options, 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", Options { text: Text::Fonts, ..Options::default() }); + 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}"); + // 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", Options { text: Text::Outlines, ..Options::default() }); + 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)).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 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> ") { + 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:?}")); + assert!((width - font.h_advance_unscaled(own) / upm * 1000.0).abs() < 0.01, "{ch}: /W {width}"); + checked += 1; + } + 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", Options { text: Text::Fonts, ..Options::default() }); + 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. + #[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", Options { text: Text::Fonts, ..Options::default() }); + 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 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 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(); + 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"); + } + + /// A font file cut short or scrambled (in its glyphs, its table directory or its metrics) that + /// the font parser still reads never panics embedding or naming its face: the face is embedded, + /// or refused with the reason. + #[test] + fn embedding_a_scrambled_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, &glyphs); + } + 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/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 0000000000..7a3fcc1ab5 Binary files /dev/null and b/crates/render/testdata/test-cff.otf differ diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index d611fc40da..7520922fb1 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -400,6 +400,16 @@ 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 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 is set as its letters' outlines + instead, and the export names it with why, when its licence forbids embedding or subsetting or + allows embedding bitmaps only; when it is drawn at another weight or width than its variable font + file's default; when its file doesn't hold it as drawn; when its file can't be subset (a damaged + file, or a CFF2 variable font); when its subset would pass 8 MB; or when the document's + embedded faces would pass 32 MB. + `"pdf": {"text": "outlines"}` on `layout.export` sets all the text 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