ttf-parser-0.24.1/.cargo_vcs_info.json 0000644 00000000136 00000000001 0013207 0 ustar {
"git": {
"sha1": "dd0dcf1fd18d208414377e327c39b56f84c8778d"
},
"path_in_vcs": ""
} ttf-parser-0.24.1/.github/workflows/main.yml 0000644 0000000 0000000 00000002675 10461020230 0017055 0 ustar 0000000 0000000 name: Rust
on: [push, pull_request]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
rust:
- 1.51.0
- stable
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: ${{ matrix.rust }}
override: true
- name: Build with no default features
run: cargo build --no-default-features --features=no-std-float
- name: Build with std
run: cargo build --no-default-features --features=std
- name: Build with variable-fonts
run: cargo build --no-default-features --features=variable-fonts,no-std-float
- name: Build with all features
run: cargo build --all-features
- name: Run tests
run: cargo test
- name: Build C API
working-directory: c-api
run: cargo build --no-default-features
- name: Build C API with variable-fonts
working-directory: c-api
run: cargo build --no-default-features --features=variable-fonts
- name: Test C API
working-directory: c-api
run: |
cargo build
gcc test.c -o test -L./target/debug/ -lttfparser -Werror -fsanitize=address
env LD_LIBRARY_PATH=./target/debug/ ./test
- name: Build benches
working-directory: benches
run: cargo bench dummy # `cargo build` will not actually build it
ttf-parser-0.24.1/.gitignore 0000644 0000000 0000000 00000000065 10461020230 0013770 0 ustar 0000000 0000000 target
Cargo.lock
.directory
.DS_Store
.vscode
.idea
ttf-parser-0.24.1/CHANGELOG.md 0000644 0000000 0000000 00000050121 10461020230 0013607 0 ustar 0000000 0000000 # Change Log
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
## [0.24.1] - 2024-08-05
### Fixed
- (`kerx`) `kerx::SubtablesIter` wasn't updating the current subtable index.
## [0.24.0] - 2024-07-02
### Changed
- Make `core_maths` dependency optional.
When building for `no_std` one must enable `no-std-float` build feature now.
## [0.23.0] - 2024-07-02
### Changed
- Use `core_maths` instead of `libm`. Should simplify the build process.
Thanks to [LaurenzV](https://github.com/LaurenzV).
### Removed
- `no-std-float` build flag. Should be handled automatically now.
## [0.22.0] - 2024-06-29
### Added
- `Face::glyph_phantom_points`
- `hvar::Table::right_side_bearing_offset`. Thanks to [LaurenzV](https://github.com/LaurenzV).
- `vvar::Table::advance_offset`. Thanks to [LaurenzV](https://github.com/LaurenzV).
- `vvar::Table::top_side_bearing_offset`. Thanks to [LaurenzV](https://github.com/LaurenzV).
- `vvar::Table::bottom_side_bearing_offset`. Thanks to [LaurenzV](https://github.com/LaurenzV).
- `vvar::Table::vertical_origin_offset`. Thanks to [LaurenzV](https://github.com/LaurenzV).
- `colr::Table::clip_box`. Thanks to [LaurenzV](https://github.com/LaurenzV).
### Changed
- `no_std` build of `ttf-parser` requires `--features=no-std-float` now.
This is because we need trigonometry functions to flatten transforms in `COLR`.
Thanks to [LaurenzV](https://github.com/LaurenzV).
- `colr::Painter` no longer has `push_translate`, `push_scale`, `push_rotate` and `push_skew`.
Only `push_transform` left.
Thanks to [LaurenzV](https://github.com/LaurenzV).
- Split `hvar::Table` into `hvar::Table` and `vvar::Table`.
Previously, we treated both `HVAR` and `VVAR` tables as identical,
but `VVAR` actually has additional fields.
Thanks to [LaurenzV](https://github.com/LaurenzV).
- Rename `hvar::Table::side_bearing_offset` into `hvar::Table::left_side_bearing_offset`.
Thanks to [LaurenzV](https://github.com/LaurenzV).
### Fixed
- `Face::glyph_hor_advance` and `Face::glyph_ver_advance` include `gvar`'s phantom points
when `HVAR`/`VVAR` tables are missing. Affects only variable fonts.
- (`CFF`) Allow MoveTo with width commands in nested subroutines.
- `opentype_layout::LookupFlags::mark_attachment_type` parsing.
- (`CFF`) Allow empty charsets in `cff::parse_charset`.
Thanks to [LaurenzV](https://github.com/LaurenzV).
- (`gvar`) Empty sub-glyphs/components is no longer an error.
Thanks to [LaurenzV](https://github.com/LaurenzV).
- (`GSUB`/`GPOS`) Allow `NULL` offsets in `ChainedContextLookup` Format2 subtables.
Thanks to [LaurenzV](https://github.com/LaurenzV).
- `Face::glyph_y_origin` properly handles variable fonts now.
Thanks to [LaurenzV](https://github.com/LaurenzV).
- (`kerx`) Fix `AnchorPoints` parsing.
Thanks to [LaurenzV](https://github.com/LaurenzV).
### Removed
- `push_translate`, `push_scale`, `push_rotate` and `push_skew` from `colr::Painter`.
Use `colr::Painter::push_transform` instead.
Thanks to [LaurenzV](https://github.com/LaurenzV).
## [0.21.1] - 2024-05-11
### Fixed
- Delta set length calculation in variable fonts.
Thanks to [LaurenzV](https://github.com/LaurenzV).
Got broken in the previous version.
## [0.21.0] - 2024-05-10
### Added
- `COLR` / `CPAL` v1 support.
Thanks to [LaurenzV](https://github.com/LaurenzV).
### Changed
- Replace `Face::is_bitmap_embedding_allowed` with `Face::is_outline_embedding_allowed`.
The old one had a bool flag flipped.
Thanks to [Fuzzyzilla](https://github.com/Fuzzyzilla).
- Increase lenience of embed permissions for older OS/2 versions.
Thanks to [Fuzzyzilla](https://github.com/Fuzzyzilla).
- Bump MSRV to 1.51
## [0.20.0] - 2023-10-15
### Added
- `COLR` / `CPAL` v0 support.
Thanks to [laurmaedje](https://github.com/laurmaedje).
### Changed
- `svg::SvgDocumentsList` returns `svg::SvgDocument` and not just `&[u8]` now.
Thanks to [wjian23](https://github.com/wjian23).
- `Face::set_variation` allows duplicated axes now.
## [0.19.2] - 2023-09-13
### Added
- `cff::Table::glyph_cid`
## [0.19.1] - 2023-06-20
### Fixed
- `cff::Table::glyph_width` returns a correct width when subroutines are present.
## [0.19.0] - 2023-04-17
### Added
- `bdat`, `bloc`, `EBDT` and `EBLC` tables support.
Thanks to [dzamkov](https://github.com/dzamkov).
- `BitmapMono`, `BitmapMonoPacked`, `BitmapGray2`, `BitmapGray2Packed`, `BitmapGray4`,
`BitmapGray4Packed`, `BitmapGray8` and `BitmapPremulBgra32` variants to `RasterImageFormat`.
### Fixed
- `CBLC` table parsing.
Thanks to [dzamkov](https://github.com/dzamkov).
## [0.18.1] - 2023-01-10
### Fixed
- (`MATH`) Handle NULL offsets.
Thanks to [laurmaedje](https://github.com/laurmaedje).
## [0.18.0] - 2022-12-25
### Added
- `Face::permissions`
- `Face::is_subsetting_allowed`
- `Face::is_bitmap_embedding_allowed`
- `Face::unicode_ranges`
- `os2::Table::permissions`
- `os2::Table::is_subsetting_allowed`
- `os2::Table::is_bitmap_embedding_allowed`
- `os2::Table::unicode_ranges`
- `name::Name::language`
- `Language` enum with all Windows languages.
### Changed
- Using a non-zero index in `Face::parse` for a regular font will return
`FaceParsingError::FaceIndexOutOfBounds` now. Thanks to [Pietrek14](https://github.com/Pietrek14).
## [0.17.0] - 2022-09-28
### Added
- `MATH` table support. Thanks to [ruifengx](https://github.com/ruifengx)
and [laurmaedje](https://github.com/laurmaedje).
### Fixed
- (CFF) Fix large tables parsing.
## [0.16.0] - 2022-09-18
### Added
- CFF Encoding support.
- `cff::Table::glyph_index`
- `cff::Table::glyph_index_by_name`
- `cff::Table::glyph_width`
- `cff::Table::number_of_glyphs`
- `cff::Table::matrix`
- `post::Table::glyph_name`
- `post::Table::glyph_index_by_name`
- `post::Table::names`
- `Face::glyph_index_by_name`
- `RawFace` fields and `TableRecord` struct are public now.
### Changed
- `Face::from_slice` was replaced by `Face::parse`.
- `RawFace::from_slice` was replaced by `RawFace::parse`.
- `post::Table::names` is a method and not a field now.
- Use `post::Table::glyph_name` instead of `post::Table::names.get()`.
### Fixed
- (hmtx/vmtx) Allow missing additional side bearings.
- (loca) Allow incomplete table.
- Reduce strictness of some table length checks.
- (post) `post::Names::len` was returning a wrong value. Now this method is gone completely.
You can use `post::Table::names().count()` instead.
## [0.15.2] - 2022-06-17
### Fixed
- Missing advance and side bearing offsets in `HVAR`/`VVAR` is not an error. Simply ignore them.
## [0.15.1] - 2022-06-04
### Fixed
- (cmap) `cmap::Subtable4::glyph_index` correctly handles malformed glyph offsets now.
- (cmap) `cmap::Subtable4::codepoints` no longer includes `0xFFFF` codepoint.
- (SVG) Fixed table parsing. Thanks to [Shubhamj280](https://github.com/Shubhamj280)
## [0.15.0] - 2022-02-20
### Added
- `apple-layout` build feature.
- `ankr`, `feat`, `kerx`, `morx` and `trak` tables.
- `kern` AAT subtable format 1.
- `RawFace`
### Changed
- The `parser` module is private now again.
## [0.14.0] - 2021-12-28
### Changed
- (cmap) `cmap::Subtable::glyph_index` and `cmap::Subtable::glyph_variation_index` accept
`u32` instead of `char` now.
- (glyf) ~7% faster outline parsing.
## [0.13.4] - 2021-11-23
### Fixed
- (CFF) Panic during `seac` resolving.
- (CFF) Stack overflow during `seac` resolving.
## [0.13.3] - 2021-11-19
### Fixed
- (glyf) Endless loop during malformed file parsing.
## [0.13.2] - 2021-10-28
### Added
- `gvar-alloc` build feature that unlocks `gvar` table limits by using heap.
Thanks to [OrionNebula](https://github.com/OrionNebula)
## [0.13.1] - 2021-10-27
### Fixed
- `Face::line_gap` logic.
## [0.13.0] - 2021-10-24
### Added
- Complete GSUB and GPOS tables support. Available under the `opentype-layout` feature.
- Public access to all supported TrueType tables. This allows a low-level, but still safe,
access to internal data layout, which can be used for performance optimization, like caching.
- `Style` enum and `Face::style` method.
- `Face::glyph_name` can be disabled via the `glyph-names` feature to reduce binary size.
### Changed
- Improved ascender/descender/line_gap resolving logic.
- `Face` methods: `has_glyph_classes`, `glyph_class`, `glyph_mark_attachment_class`,
`is_mark_glyph` and `glyph_variation_delta` are moved to `gdef::Table`.
- The `Names` struct is no longer an iterator, but a container.
You have to call `into_iter()` manually.
- The `VariationAxes` struct is no longer an iterator, but a container.
You have to call `into_iter()` manually.
- Most of the `Name` struct methods become public fields.
- `Face::units_per_em` no longer returns `Option`.
- (`cmap`) Improved subtable 12 performance. Thanks to [xnuk](https://github.com/xnuk)
### Removed
- (c-api) `ttfp_glyph_class`, `ttfp_get_glyph_class`, `ttfp_get_glyph_mark_attachment_class`,
`ttfp_is_mark_glyph`, `ttfp_glyph_variation_delta` and `ttfp_has_table`.
- `TableName` enum and `Face::has_table`. Tables can be access directly now.
- `Face::character_mapping_subtables`. Use `Face::tables().cmap` instead.
- `Face::kerning_subtables`. Use `Face::tables().kern` instead.
### Fixed
- `Iterator::count` implementation for `cmap::Subtables`, `name::Names` and `LazyArrayIter32`.
## [0.12.3] - 2021-06-27
### Changed
- (`glyf`) Always use a calculated bbox.
## [0.12.2] - 2021-06-11
### Fixed
- `Face::glyph_bounding_box` for variable `glyf`.
- (`glyf`) Do not skip glyphs with zero-sized bbox.
## [0.12.1] - 2021-05-24
### Added
- Support Format 13 subtables in `cmap::Subtable::is_unicode`.
Thanks to [csmulhern](https://github.com/csmulhern)
- Derive more traits by default. Thanks to [dhardy](https://github.com/dhardy)
## [0.12.0] - 2021-02-14
### Changed
- `Face::ascender` and `Face::descender` will use
[usWinAscent](https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswinascent) and
[usWinDescent](https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswindescent)
when `USE_TYPO_METRICS` flag is not set in `OS/2` table.
Previously, those values were ignored and
[hhea::ascender](https://docs.microsoft.com/en-us/typography/opentype/spec/hhea#ascender) and
[hhea::descender](https://docs.microsoft.com/en-us/typography/opentype/spec/hhea#descender)
were used. Now `hhea` table values will be used only when `OS/2` table is not present.
- `Face::outline_glyph` and `Face::glyph_bounding_box` in case of a `glyf` table
can fallback to a calculated bbox when the embedded bbox is malformed now.
## [0.11.0] - 2021-02-04
### Added
- `FaceTables`, which allowed to load `Face` not only from a single chunk of data,
but also in a per-table way. Which is useful for WOFF parsing.
No changes to the API.
Thanks to [fschutt](https://github.com/fschutt)
## [0.10.1] - 2021-01-21
### Changed
- Update a font used for tests.
## [0.10.0] - 2021-01-16
### Added
- `variable-fonts` build feature. Enabled by default.
By disabling it you can reduce `ttf-parser` binary size overhead almost twice.
### Changed
- (`gvar`) Increase the maximum number of variation tuples from 16 to 32.
Increases stack usage and makes `gvar` parsing 10% slower now.
### Fixed
- (`CFF`) Fix `seac` processing. Thanks to [wezm](https://github.com/wezm)
## [0.9.0] - 2020-12-05
### Removed
- `kern` AAT subtable 1 aka `kern::state_machine`.
Mainly because it's useless without a proper shaping.
## [0.8.3] - 2020-11-15
### Added
- `Face::glyph_variation_delta`
### Fixed
- `Iterator::nth` implementation for `cmap::Subtables` and `Names`.
## [0.8.2] - 2020-07-31
### Added
- `cmap::Subtable::codepoints`
### Fixed
- (cmap) Incorrectly returning glyph ID `0` instead of `None` for format 0
- (cmap) Possible invalid glyph mapping for format 2
## [0.8.1] - 2020-07-29
### Added
- `Face::is_monospaced`
- `Face::italic_angle`
- `Face::typographic_ascender`
- `Face::typographic_descender`
- `Face::typographic_line_gap`
- `Face::capital_height`
## [0.8.0] - 2020-07-21
### Added
- Allow `true` magic.
- `FaceParsingError`
- `NormalizedCoordinate`
- `Face::variation_coordinates`
- `Face::has_non_default_variation_coordinates`
- `Face::glyph_name` can lookup CFF names too.
- `Face::table_data`
- `Face::character_mapping_subtables`
### Changed
- (CFF,CFF2) 10% faster parsing.
- `Face::from_slice` returns `Result` now.
- `Name::platform_id` returns `PlatformId` instead of `Option` now.
- The `cmap` module became public.
### Fixed
- `Face::width` parsing.
- Possible u32 overflow on 32-bit platforms during `Face::from_slice`.
- (cmap) `Face::glyph_variation_index` processing when the encoding table has only one glyph.
## [0.7.0] - 2020-07-16
### Added
- (CFF) CID fonts support.
- (CFF) `seac` support.
- `Font::global_bounding_box`
### Changed
- Rename `Font` to `Face`, because this is what it actually is.
- Rename `Font::from_data` to `Font::from_slice` to match serde and other libraries.
- Rename `Name::name_utf8` to `Name::to_string`.
### Removed
- `Font::family_name` and `Font::post_script_name`. They were a bit confusing.
Prefer:
```
face.names().find(|name| name.name_id() == name_id::FULL_NAME).and_then(|name| name.to_string())
```
## [0.6.2] - 2020-07-02
### Added
- `Name::is_unicode`
- `Font::family_name` will load names with Windows Symbol encoding now.
### Fixed
- `Font::glyph_bounding_box` will apply variation in case of `gvar` fonts.
## [0.6.1] - 2020-05-19
### Fixed
- (`kern`) Support fonts that ignore the subtable size limit.
## [0.6.0] - 2020-05-18
### Added
- `sbix`, `CBLC`, `CBDT` and `SVG` tables support.
- `Font::glyph_raster_image` and `Font::glyph_svg_image`.
- `Font::kerning_subtables` with subtable formats 0..3 support.
### Changed
- (c-api) The library doesn't allocate `ttfp_font` anymore. All allocations should be
handled by the caller from now.
### Removed
- `Font::glyphs_kerning`. Use `Font::kerning_subtables` instead.
- (c-api) `ttfp_create_font` and `ttfp_destroy_font`.
Use `ttfp_font_size_of` + `ttfp_font_init` instead.
```c
ttfp_font *font = (ttfp_font*)alloca(ttfp_font_size_of());
ttfp_font_init(font_data, font_data_size, 0, font);
```
- Logging support. We haven't used it anyway.
### Fixed
- (`gvar`) Integer overflow.
- (`cmap`) Integer overflow during subtable format 2 parsing.
- (`CFF`, `CFF2`) DICT number parsing.
- `Font::glyph_*_advance` will return `None` when glyph ID
is larger than the number of metrics in the table.
- Ignore variation offset in `Font::glyph_*_advance` and `Font::glyph_*_side_bearing`
when `HVAR`/`VVAR` tables are missing.
Previously returned `None` which is incorrect.
## [0.5.0] - 2020-03-19
### Added
- Variable fonts support.
- C API.
- `gvar`, `CFF2`, `avar`, `fvar`, `HVAR`, `VVAR` and `MVAR` tables support.
- `Font::variation_axes`
- `Font::set_variation`
- `Font::is_variable`
- `Tag` type.
### Fixed
- Multiple issues due to arithmetic overflow.
## [0.4.0] - 2020-02-24
**A major rewrite.**
### Added
- `Font::glyph_bounding_box`
- `Font::glyph_name`
- `Font::has_glyph_classes`
- `Font::glyph_class`
- `Font::glyph_mark_attachment_class`
- `Font::is_mark_glyph`
- `Font::glyph_y_origin`
- `Font::vertical_ascender`
- `Font::vertical_descender`
- `Font::vertical_height`
- `Font::vertical_line_gap`
- Optional `log` dependency.
### Changed
- `Font::outline_glyph` now accepts `&mut dyn OutlineBuilder` and not `&mut impl OutlineBuilder`.
- `Font::ascender`, `Font::descender` and `Font::line_gap` will check `USE_TYPO_METRICS`
flag in OS/2 table now.
- `glyph_hor_metrics` was split into `glyph_hor_advance` and `glyph_hor_side_bearing`.
- `glyph_ver_metrics` was split into `glyph_ver_advance` and `glyph_ver_side_bearing`.
- `CFFError` is no longer public.
### Removed
- `Error` enum. All methods will return `Option` now.
- All `unsafe`.
### Fixed
- `glyph_hor_side_bearing` parsing when the number of metrics is less than the total number of glyphs.
- Multiple CFF parsing fixes. The parser is more strict now.
## [0.3.0] - 2019-09-26
### Added
- `no_std` compatibility.
### Changed
- The library has one `unsafe` block now.
- 35% faster `family_name()` method.
- 25% faster `from_data()` method for TrueType fonts.
- The `Name` struct has a new API. Public fields became public functions
and data is parsed on demand and not beforehand.
## [0.2.2] - 2019-08-12
### Fixed
- Allow format 12 subtables with *Unicode full repertoire* in `cmap`.
## [0.2.1] - 2019-08-12
### Fixed
- Check that `cmap` subtable encoding is Unicode.
## [0.2.0] - 2019-07-10
### Added
- CFF support.
- Basic kerning support.
- All `cmap` subtable formats except Mixed Coverage (8) are supported.
- Vertical metrics querying from the `vmtx` table.
- OpenType fonts are allowed now.
### Changed
- A major rewrite. TrueType tables are no longer public.
- Use `GlyphId` instead of `u16`.
### Removed
- `GDEF` table parsing.
[Unreleased]: https://github.com/RazrFalcon/ttf-parser/compare/v0.24.1...HEAD
[0.24.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.24.0...v0.24.1
[0.24.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.23.0...v0.24.0
[0.23.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.22.0...v0.23.0
[0.22.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.21.1...v0.22.0
[0.21.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.21.0...v0.21.1
[0.21.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.20.0...v0.21.0
[0.20.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.19.2...v0.20.0
[0.19.2]: https://github.com/RazrFalcon/ttf-parser/compare/v0.19.1...v0.19.2
[0.19.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.19.0...v0.19.1
[0.19.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.18.1...v0.19.0
[0.18.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.18.0...v0.18.1
[0.18.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.17.0...v0.18.0
[0.17.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.16.0...v0.17.0
[0.16.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.15.2...v0.16.0
[0.15.2]: https://github.com/RazrFalcon/ttf-parser/compare/v0.15.1...v0.15.2
[0.15.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.15.0...v0.15.1
[0.15.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.14.0...v0.15.0
[0.14.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.13.4...v0.14.0
[0.13.4]: https://github.com/RazrFalcon/ttf-parser/compare/v0.13.3...v0.13.4
[0.13.3]: https://github.com/RazrFalcon/ttf-parser/compare/v0.13.2...v0.13.3
[0.13.2]: https://github.com/RazrFalcon/ttf-parser/compare/v0.13.1...v0.13.2
[0.13.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.13.0...v0.13.1
[0.13.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.12.3...v0.13.0
[0.12.3]: https://github.com/RazrFalcon/ttf-parser/compare/v0.12.2...v0.12.3
[0.12.2]: https://github.com/RazrFalcon/ttf-parser/compare/v0.12.1...v0.12.2
[0.12.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.12.0...v0.12.1
[0.12.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.11.0...v0.12.0
[0.11.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.10.1...v0.11.0
[0.10.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.10.0...v0.10.1
[0.10.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.9.0...v0.10.0
[0.9.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.8.3...v0.9.0
[0.8.3]: https://github.com/RazrFalcon/ttf-parser/compare/v0.8.2...v0.8.3
[0.8.2]: https://github.com/RazrFalcon/ttf-parser/compare/v0.8.1...v0.8.2
[0.8.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.8.0...v0.8.1
[0.8.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.7.0...v0.8.0
[0.7.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.6.2...v0.7.0
[0.6.2]: https://github.com/RazrFalcon/ttf-parser/compare/v0.6.1...v0.6.2
[0.6.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.6.0...v0.6.1
[0.6.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.5.0...v0.6.0
[0.5.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.4.0...v0.5.0
[0.4.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.3.0...v0.4.0
[0.3.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.2.2...v0.3.0
[0.2.2]: https://github.com/RazrFalcon/ttf-parser/compare/v0.2.1...v0.2.2
[0.2.1]: https://github.com/RazrFalcon/ttf-parser/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/RazrFalcon/ttf-parser/compare/v0.1.0...v0.2.0
ttf-parser-0.24.1/Cargo.lock 0000644 00000004030 00000000001 0011157 0 ustar # This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "arrayref"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bytemuck"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15"
[[package]]
name = "core_maths"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3b02505ccb8c50b0aa21ace0fc08c3e53adebd4e58caa18a36152803c7709a3"
dependencies = [
"libm",
]
[[package]]
name = "libm"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058"
[[package]]
name = "pico-args"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
[[package]]
name = "strict-num"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
[[package]]
name = "tiny-skia-path"
version = "0.11.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93"
dependencies = [
"arrayref",
"bytemuck",
"strict-num",
]
[[package]]
name = "ttf-parser"
version = "0.24.1"
dependencies = [
"base64",
"core_maths",
"pico-args",
"tiny-skia-path",
"xmlwriter",
]
[[package]]
name = "xmlwriter"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
ttf-parser-0.24.1/Cargo.toml 0000644 00000002676 00000000001 0011220 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
name = "ttf-parser"
version = "0.24.1"
authors = ["Yevhenii Reizner "]
exclude = ["benches/**"]
description = "A high-level, safe, zero-allocation font parser for TrueType, OpenType, and AAT."
documentation = "https://docs.rs/ttf-parser/"
readme = "README.md"
keywords = [
"ttf",
"truetype",
"opentype",
]
categories = ["parser-implementations"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/RazrFalcon/ttf-parser"
[dependencies.core_maths]
version = "0.1.0"
optional = true
[dev-dependencies.base64]
version = "0.22.1"
[dev-dependencies.pico-args]
version = "0.5"
[dev-dependencies.tiny-skia-path]
version = "0.11.4"
[dev-dependencies.xmlwriter]
version = "0.1"
[features]
apple-layout = []
default = [
"std",
"opentype-layout",
"apple-layout",
"variable-fonts",
"glyph-names",
]
glyph-names = []
gvar-alloc = ["std"]
no-std-float = ["core_maths"]
opentype-layout = []
std = []
variable-fonts = []
ttf-parser-0.24.1/Cargo.toml.orig 0000644 00000003655 00000000001 0012155 0 ustar [package]
name = "ttf-parser"
version = "0.24.1"
authors = ["Yevhenii Reizner "]
keywords = ["ttf", "truetype", "opentype"]
categories = ["parser-implementations"]
license = "MIT OR Apache-2.0"
description = "A high-level, safe, zero-allocation font parser for TrueType, OpenType, and AAT."
repository = "https://github.com/RazrFalcon/ttf-parser"
documentation = "https://docs.rs/ttf-parser/"
readme = "README.md"
edition = "2018"
exclude = ["benches/**"]
[dependencies]
core_maths = { version = "0.1.0", optional = true } # only for no_std builds
[features]
default = ["std", "opentype-layout", "apple-layout", "variable-fonts", "glyph-names"]
# Enables the use of the standard library.
# When disabled, the `no-std-float` feature must be enabled instead.
std = []
no-std-float = ["core_maths"]
# Enables variable fonts support. Increases binary size almost twice.
# Includes avar, CFF2, fvar, gvar, HVAR, MVAR and VVAR tables.
variable-fonts = []
# Enables GDEF, GPOS, GSUB and MATH tables.
opentype-layout = []
# Enables ankr, feat, format1 subtable in kern, kerx, morx and trak tables.
apple-layout = []
# Enables glyph name query via `Face::glyph_name`.
# TrueType fonts do not store default glyph names, to reduce file size,
# which means we have to store them in ttf-parser. And there are almost 500 of them.
# By disabling this feature a user can reduce binary size a bit.
glyph-names = []
# Enables heap allocations during gvar table parsing used by Apple's variable fonts.
# Due to the way gvar table is structured, we cannot avoid allocations.
# By default, only up to 32 variable tuples will be allocated on the stack,
# while the spec allows up to 4095. Most variable fonts use 10-20 tuples,
# so our limit is suitable for most of the cases. But if you need full support, you have to
# enable this feature.
gvar-alloc = ["std"]
[dev-dependencies]
base64 = "0.22.1"
pico-args = "0.5"
tiny-skia-path = "0.11.4"
xmlwriter = "0.1"
ttf-parser-0.24.1/Cargo.toml.orig 0000644 0000000 0000000 00000003655 10461020230 0014677 0 ustar 0000000 0000000 [package]
name = "ttf-parser"
version = "0.24.1"
authors = ["Yevhenii Reizner "]
keywords = ["ttf", "truetype", "opentype"]
categories = ["parser-implementations"]
license = "MIT OR Apache-2.0"
description = "A high-level, safe, zero-allocation font parser for TrueType, OpenType, and AAT."
repository = "https://github.com/RazrFalcon/ttf-parser"
documentation = "https://docs.rs/ttf-parser/"
readme = "README.md"
edition = "2018"
exclude = ["benches/**"]
[dependencies]
core_maths = { version = "0.1.0", optional = true } # only for no_std builds
[features]
default = ["std", "opentype-layout", "apple-layout", "variable-fonts", "glyph-names"]
# Enables the use of the standard library.
# When disabled, the `no-std-float` feature must be enabled instead.
std = []
no-std-float = ["core_maths"]
# Enables variable fonts support. Increases binary size almost twice.
# Includes avar, CFF2, fvar, gvar, HVAR, MVAR and VVAR tables.
variable-fonts = []
# Enables GDEF, GPOS, GSUB and MATH tables.
opentype-layout = []
# Enables ankr, feat, format1 subtable in kern, kerx, morx and trak tables.
apple-layout = []
# Enables glyph name query via `Face::glyph_name`.
# TrueType fonts do not store default glyph names, to reduce file size,
# which means we have to store them in ttf-parser. And there are almost 500 of them.
# By disabling this feature a user can reduce binary size a bit.
glyph-names = []
# Enables heap allocations during gvar table parsing used by Apple's variable fonts.
# Due to the way gvar table is structured, we cannot avoid allocations.
# By default, only up to 32 variable tuples will be allocated on the stack,
# while the spec allows up to 4095. Most variable fonts use 10-20 tuples,
# so our limit is suitable for most of the cases. But if you need full support, you have to
# enable this feature.
gvar-alloc = ["std"]
[dev-dependencies]
base64 = "0.22.1"
pico-args = "0.5"
tiny-skia-path = "0.11.4"
xmlwriter = "0.1"
ttf-parser-0.24.1/LICENSE-APACHE 0000644 0000000 0000000 00000025137 10461020230 0013733 0 ustar 0000000 0000000 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.
ttf-parser-0.24.1/LICENSE-MIT 0000644 0000000 0000000 00000002045 10461020230 0013434 0 ustar 0000000 0000000 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.
ttf-parser-0.24.1/README.md 0000644 0000000 0000000 00000027327 10461020230 0013271 0 ustar 0000000 0000000 ## ttf-parser

[](https://crates.io/crates/ttf-parser)
[](https://docs.rs/ttf-parser)
[](https://www.rust-lang.org)

A high-level, safe, zero-allocation font parser for
[TrueType](https://docs.microsoft.com/en-us/typography/truetype/),
[OpenType](https://docs.microsoft.com/en-us/typography/opentype/spec/), and
[AAT](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6AATIntro.html).
Can be used as a Rust or C library.
### Features
- A high-level API for most common properties, hiding all parsing and data resolving logic.
- A low-level, but safe API to access TrueType tables data.
- Highly configurable. You can disable most of the features, reducing binary size.
You can also parse TrueType tables separately, without loading the whole font/face.
- Zero heap allocations.
- Zero unsafe.
- Zero dependencies.
- `no_std`/WASM compatible.
- A basic [C API](./c-api).
- Fast.
- Stateless. All parsing methods are immutable.
- Simple and maintainable code (no magic numbers).
### Safety
- The library must not panic. Any panic considered as a critical bug and should be reported.
- The library forbids unsafe code.
- No heap allocations, so crash due to OOM is not possible.
- All recursive methods have a depth limit.
- Technically, should use less than 64KiB of stack in the worst case scenario.
- Most of arithmetic operations are checked.
- Most of numeric casts are checked.
### Alternatives
It's very hard to compare different libraries, so we are using table-based comparison.
There are roughly three types of TrueType tables:
- A table with a list of properties (like `head`, `OS/2`, etc.).
If a library tries to parse it at all then we mark it as supported.
- A table that contains a single type of data (`glyf`, `CFF` (kinda), `hmtx`, etc.).
Can only be supported or not.
- A table that contains multiple subtables (`cmap`, `kern`, `GPOS`, etc.).
Can be partially supported and we note which subtables are actually supported.
| Feature/Library | ttf-parser | FreeType | stb_truetype |
| ----------------- | :--------------------: | :-----------------: | :----------------------------: |
| Memory safe | ✓ | | |
| Thread safe | ✓ | | ~ (mostly reentrant) |
| Zero allocation | ✓ | | |
| Variable fonts | ✓ | ✓ | |
| Rendering | -1 | ✓ | ~ (very primitive) |
| `ankr` table | ✓ | | |
| `avar` table | ✓ | ✓ | |
| `bdat` table | ~ (no 4) | ✓ | |
| `bloc` table | ✓ | ✓ | |
| `CBDT` table | ~ (no 8, 9) | ✓ | |
| `CBLC` table | ✓ | ✓ | |
| `COLR` table | ✓ | ✓ | |
| `CPAL` table | ✓ | ✓ | |
| `CFF ` table | ✓ | ✓ | ~ (no `seac` support) |
| `CFF2` table | ✓ | ✓ | |
| `cmap` table | ~ (no 8) | ✓ | ~ (no 2,8,10,14; Unicode-only) |
| `EBDT` table | ~ (no 8, 9) | ✓ | |
| `EBLC` table | ✓ | ✓ | |
| `feat` table | ✓ | | |
| `fvar` table | ✓ | ✓ | |
| `gasp` table | | ✓ | |
| `GDEF` table | ~ | | |
| `glyf` table | ~2 | ✓ | ~2 |
| `GPOS` table | ✓ | | ~ (only 2) |
| `GSUB` table | ✓ | | |
| `gvar` table | ✓ | ✓ | |
| `head` table | ✓ | ✓ | ✓ |
| `hhea` table | ✓ | ✓ | ✓ |
| `hmtx` table | ✓ | ✓ | ✓ |
| `HVAR` table | ✓ | ✓ | |
| `kern` table | ✓ | ~ (only 0) | ~ (only 0) |
| `kerx` table | ✓ | | |
| `MATH` table | ✓ | | |
| `maxp` table | ✓ | ✓ | ✓ |
| `morx` table | ✓ | | |
| `MVAR` table | ✓ | ✓ | |
| `name` table | ✓ | ✓ | |
| `OS/2` table | ✓ | ✓ | |
| `post` table | ✓ | ✓ | |
| `sbix` table | ~ (PNG only) | ~ (PNG only) | |
| `SVG ` table | ✓ | ✓ | ✓ |
| `trak` table | ✓ | | |
| `vhea` table | ✓ | ✓ | |
| `vmtx` table | ✓ | ✓ | |
| `VORG` table | ✓ | ✓ | |
| `VVAR` table | ✓ | ✓ | |
| Language | Rust + C API | C | C |
| Tested version | 0.17.0 | 2.12.0 | 1.24 |
| License | MIT / Apache-2.0 | FTL / GPLv2 | public domain |
Legend:
- ✓ - supported
- ~ - partial
- *nothing* - not supported
Notes:
1. While `ttf-parser` doesn't support rendering by itself,
there are multiple rendering libraries on top of it:
[rusttype](https://gitlab.redox-os.org/redox-os/rusttype),
[ab-glyph](https://github.com/alexheretic/ab-glyph)
and [fontdue](https://github.com/mooman219/fontdue).
2. Matching points are not supported.
### Performance
TrueType fonts designed for fast querying, so most of the methods are very fast.
The main exception is glyph outlining. Glyphs can be stored using two different methods:
using [Glyph Data Format](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf)
and [Compact Font Format](http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/font/pdfs/5176.CFF.pdf) (pdf).
The first one is fairly simple which makes it faster to process.
The second one is basically a tiny language with a stack-based VM, which makes it way harder to process.
The [benchmark](./benches/outline/) tests how long it takes to outline all glyphs in a font.
x86 (AMD 3700X)
| Table/Library | ttf-parser | FreeType | stb_truetype |
| ------------- | -------------: | ---------: | -------------: |
| `glyf` | `0.901 ms` | `1.171 ms` | **`0.675 ms`** |
| `gvar` | **`2.972 ms`** | `4.132 ms` | - |
| `CFF` | **`1.197 ms`** | `5.647 ms` | `2.813 ms` |
| `CFF2` | **`1.968 ms`** | `6.392 ms` | - |
ARM (Apple M1)
| Table/Library | ttf-parser | FreeType | stb_truetype |
| ------------- | -------------: | ---------: | -------------: |
| `glyf` | **`0.550 ms`** | `0.854 ms` | `0.703 ms` |
| `gvar` | **`2.270 ms`** | `4.594 ms` | - |
| `CFF` | **`1.054 ms`** | `5.223 ms` | `3.262 ms` |
| `CFF2` | **`1.765 ms`** | `5.995 ms` | - |
**Note:** FreeType is surprisingly slow, so I'm worried that I've messed something up.
And here are some methods benchmarks:
```text
test outline_glyph_276_from_cff2 ... bench: 867 ns/iter (+/- 15)
test from_data_otf_cff ... bench: 968 ns/iter (+/- 13)
test from_data_otf_cff2 ... bench: 887 ns/iter (+/- 25)
test outline_glyph_276_from_cff ... bench: 678 ns/iter (+/- 41)
test outline_glyph_276_from_glyf ... bench: 649 ns/iter (+/- 11)
test outline_glyph_8_from_cff2 ... bench: 534 ns/iter (+/- 14)
test from_data_ttf ... bench: 467 ns/iter (+/- 11)
test glyph_name_post_276 ... bench: 223 ns/iter (+/- 5)
test outline_glyph_8_from_cff ... bench: 315 ns/iter (+/- 13)
test outline_glyph_8_from_glyf ... bench: 291 ns/iter (+/- 5)
test family_name ... bench: 183 ns/iter (+/- 102)
test glyph_name_cff_276 ... bench: 62 ns/iter (+/- 1)
test glyph_index_u41 ... bench: 16 ns/iter (+/- 0)
test glyph_name_cff_8 ... bench: 5 ns/iter (+/- 0)
test glyph_name_post_8 ... bench: 2 ns/iter (+/- 0)
test subscript_metrics ... bench: 2 ns/iter (+/- 0)
test glyph_hor_advance ... bench: 2 ns/iter (+/- 0)
test glyph_hor_side_bearing ... bench: 2 ns/iter (+/- 0)
test glyph_name_8 ... bench: 1 ns/iter (+/- 0)
test ascender ... bench: 1 ns/iter (+/- 0)
test underline_metrics ... bench: 1 ns/iter (+/- 0)
test strikeout_metrics ... bench: 1 ns/iter (+/- 0)
test x_height ... bench: 1 ns/iter (+/- 0)
test units_per_em ... bench: 0.5 ns/iter (+/- 0)
test width ... bench: 0.2 ns/iter (+/- 0)
```
### License
Licensed under either of
- Apache License, Version 2.0
([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license
([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
ttf-parser-0.24.1/examples/font-info.rs 0000644 0000000 0000000 00000007172 10461020230 0016071 0 ustar 0000000 0000000 fn main() {
let args: Vec<_> = std::env::args().collect();
if args.len() != 2 {
println!("Usage:\n\tfont-info font.ttf");
std::process::exit(1);
}
let font_data = std::fs::read(&args[1]).unwrap();
let now = std::time::Instant::now();
let face = match ttf_parser::Face::parse(&font_data, 0) {
Ok(f) => f,
Err(e) => {
eprint!("Error: {}.", e);
std::process::exit(1);
}
};
let mut family_names = Vec::new();
for name in face.names() {
if name.name_id == ttf_parser::name_id::FULL_NAME && name.is_unicode() {
if let Some(family_name) = name.to_string() {
let language = name.language();
family_names.push(format!(
"{} ({}, {})",
family_name,
language.primary_language(),
language.region()
));
}
}
}
let post_script_name = face
.names()
.into_iter()
.find(|name| name.name_id == ttf_parser::name_id::POST_SCRIPT_NAME && name.is_unicode())
.and_then(|name| name.to_string());
println!("Family names: {:?}", family_names);
println!("PostScript name: {:?}", post_script_name);
println!("Units per EM: {:?}", face.units_per_em());
println!("Ascender: {}", face.ascender());
println!("Descender: {}", face.descender());
println!("Line gap: {}", face.line_gap());
println!("Global bbox: {:?}", face.global_bounding_box());
println!("Number of glyphs: {}", face.number_of_glyphs());
println!("Underline: {:?}", face.underline_metrics());
println!("X height: {:?}", face.x_height());
println!("Weight: {:?}", face.weight());
println!("Width: {:?}", face.width());
println!("Regular: {}", face.is_regular());
println!("Italic: {}", face.is_italic());
println!("Bold: {}", face.is_bold());
println!("Oblique: {}", face.is_oblique());
println!("Strikeout: {:?}", face.strikeout_metrics());
println!("Subscript: {:?}", face.subscript_metrics());
println!("Superscript: {:?}", face.superscript_metrics());
println!("Permissions: {:?}", face.permissions());
println!("Variable: {:?}", face.is_variable());
#[cfg(feature = "opentype-layout")]
{
if let Some(ref table) = face.tables().gpos {
print_opentype_layout("positioning", table);
}
if let Some(ref table) = face.tables().gsub {
print_opentype_layout("substitution", table);
}
}
#[cfg(feature = "variable-fonts")]
{
if face.is_variable() {
println!("Variation axes:");
for axis in face.variation_axes() {
println!(
" {} {}..{}, default {}",
axis.tag, axis.min_value, axis.max_value, axis.def_value
);
}
}
}
println!("Elapsed: {}us", now.elapsed().as_micros());
}
fn print_opentype_layout(name: &str, table: &ttf_parser::opentype_layout::LayoutTable) {
println!("OpenType {}:", name);
println!(" Scripts:");
for script in table.scripts {
println!(" {}", script.tag);
if script.languages.is_empty() {
println!(" No languages");
continue;
}
println!(" Languages:");
for lang in script.languages {
println!(" {}", lang.tag);
}
}
let mut features: Vec<_> = table.features.into_iter().map(|f| f.tag).collect();
features.dedup();
println!(" Features:");
for feature in features {
println!(" {}", feature);
}
}
ttf-parser-0.24.1/examples/font2svg.rs 0000644 0000000 0000000 00000052144 10461020230 0015741 0 ustar 0000000 0000000 #![allow(clippy::too_many_arguments)]
use base64::engine::general_purpose::STANDARD;
use std::io::Write;
use std::path::PathBuf;
use ttf_parser as ttf;
use ttf_parser::colr::{ClipBox, Paint};
use ttf_parser::{RgbaColor, Transform};
const FONT_SIZE: f64 = 128.0;
const COLUMNS: u32 = 100;
const HELP: &str = "\
Usage:
font2svg font.ttf out.svg
font2svg --variations 'wght:500;wdth:200' font.ttf out.svg
font2svg --colr-palette 1 colr-font.ttf out.svg
";
struct Args {
#[allow(dead_code)]
variations: Vec,
colr_palette: u16,
ttf_path: PathBuf,
svg_path: PathBuf,
}
fn main() {
let args = match parse_args() {
Ok(v) => v,
Err(e) => {
eprintln!("Error: {}.", e);
print!("{}", HELP);
std::process::exit(1);
}
};
if let Err(e) = process(args) {
eprintln!("Error: {}.", e);
std::process::exit(1);
}
}
fn parse_args() -> Result> {
let mut args = pico_args::Arguments::from_env();
if args.contains(["-h", "--help"]) {
print!("{}", HELP);
std::process::exit(0);
}
let variations = args.opt_value_from_fn("--variations", parse_variations)?;
let colr_palette: u16 = args.opt_value_from_str("--colr-palette")?.unwrap_or(0);
let free = args.finish();
if free.len() != 2 {
return Err("invalid number of arguments".into());
}
Ok(Args {
variations: variations.unwrap_or_default(),
colr_palette,
ttf_path: PathBuf::from(&free[0]),
svg_path: PathBuf::from(&free[1]),
})
}
fn parse_variations(s: &str) -> Result, &'static str> {
let mut variations = Vec::new();
for part in s.split(';') {
let mut iter = part.split(':');
let axis = iter.next().ok_or("failed to parse a variation")?;
let axis = ttf::Tag::from_bytes_lossy(axis.as_bytes());
let value = iter.next().ok_or("failed to parse a variation")?;
let value: f32 = value.parse().map_err(|_| "failed to parse a variation")?;
variations.push(ttf::Variation { axis, value });
}
Ok(variations)
}
fn process(args: Args) -> Result<(), Box> {
let font_data = std::fs::read(&args.ttf_path)?;
// Exclude IO operations.
let now = std::time::Instant::now();
#[allow(unused_mut)]
let mut face = ttf::Face::parse(&font_data, 0)?;
if face.is_variable() {
#[cfg(feature = "variable-fonts")]
{
for variation in args.variations {
face.set_variation(variation.axis, variation.value)
.ok_or("failed to create variation coordinates")?;
}
}
}
if face.tables().colr.is_some() {
if let Some(total) = face.color_palettes() {
if args.colr_palette >= total.get() {
return Err(format!("only {} palettes are available", total).into());
}
}
}
let num_glyphs = face.number_of_glyphs();
let units_per_em = face.units_per_em();
let scale = FONT_SIZE / units_per_em as f64;
let cell_size = face.height() as f64 * FONT_SIZE / units_per_em as f64;
let rows = (num_glyphs as f64 / COLUMNS as f64).ceil() as u32;
let mut svg = xmlwriter::XmlWriter::with_capacity(
num_glyphs as usize * 512,
xmlwriter::Options::default(),
);
svg.start_element("svg");
svg.write_attribute("xmlns", "http://www.w3.org/2000/svg");
svg.write_attribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
svg.write_attribute_fmt(
"viewBox",
format_args!(
"{} {} {} {}",
0,
0,
cell_size * COLUMNS as f64,
cell_size * rows as f64
),
);
draw_grid(num_glyphs, cell_size, &mut svg);
let mut path_buf = String::with_capacity(256);
let mut row = 0;
let mut column = 0;
let mut gradient_index = 1;
let mut clip_path_index = 1;
for id in 0..num_glyphs {
let gid = ttf::GlyphId(id);
let x = column as f64 * cell_size;
let y = row as f64 * cell_size;
svg.start_element("text");
svg.write_attribute("x", &(x + 2.0));
svg.write_attribute("y", &(y + cell_size - 4.0));
svg.write_attribute("font-size", "36");
svg.write_attribute("fill", "gray");
svg.write_text_fmt(format_args!("{}", &id));
svg.end_element();
if face.is_color_glyph(gid) {
color_glyph(
x,
y,
&face,
args.colr_palette,
gid,
cell_size,
scale,
&mut gradient_index,
&mut clip_path_index,
&mut svg,
&mut path_buf,
);
} else if let Some(img) = face.glyph_raster_image(gid, u16::MAX) {
svg.start_element("image");
svg.write_attribute("x", &(x + 2.0 + img.x as f64));
svg.write_attribute("y", &(y - img.y as f64));
svg.write_attribute("width", &img.width);
svg.write_attribute("height", &img.height);
svg.write_attribute_raw("xlink:href", |buf| {
buf.extend_from_slice(b"data:image/png;base64, ");
let mut enc = base64::write::EncoderWriter::new(buf, &STANDARD);
enc.write_all(img.data).unwrap();
enc.finish().unwrap();
});
svg.end_element();
} else if let Some(img) = face.glyph_svg_image(gid) {
svg.start_element("image");
svg.write_attribute("x", &(x + 2.0));
svg.write_attribute("y", &(y + cell_size));
svg.write_attribute("width", &cell_size);
svg.write_attribute("height", &cell_size);
svg.write_attribute_raw("xlink:href", |buf| {
buf.extend_from_slice(b"data:image/svg+xml;base64, ");
let mut enc = base64::write::EncoderWriter::new(buf, &STANDARD);
enc.write_all(img.data).unwrap();
enc.finish().unwrap();
});
svg.end_element();
} else {
glyph_to_path(x, y, &face, gid, cell_size, scale, &mut svg, &mut path_buf);
}
column += 1;
if column == COLUMNS {
column = 0;
row += 1;
}
}
println!("Elapsed: {}ms", now.elapsed().as_micros() as f64 / 1000.0);
std::fs::write(&args.svg_path, svg.end_document())?;
Ok(())
}
fn draw_grid(n_glyphs: u16, cell_size: f64, svg: &mut xmlwriter::XmlWriter) {
let columns = COLUMNS;
let rows = (n_glyphs as f64 / columns as f64).ceil() as u32;
let width = columns as f64 * cell_size;
let height = rows as f64 * cell_size;
svg.start_element("path");
svg.write_attribute("fill", "none");
svg.write_attribute("stroke", "black");
svg.write_attribute("stroke-width", "5");
let mut path = String::with_capacity(256);
use std::fmt::Write;
let mut x = 0.0;
for _ in 0..=columns {
write!(&mut path, "M {} {} L {} {} ", x, 0.0, x, height).unwrap();
x += cell_size;
}
let mut y = 0.0;
for _ in 0..=rows {
write!(&mut path, "M {} {} L {} {} ", 0.0, y, width, y).unwrap();
y += cell_size;
}
path.pop();
svg.write_attribute("d", &path);
svg.end_element();
}
struct Builder<'a>(&'a mut String);
impl Builder<'_> {
fn finish(&mut self) {
if !self.0.is_empty() {
self.0.pop(); // remove trailing space
}
}
}
impl ttf::OutlineBuilder for Builder<'_> {
fn move_to(&mut self, x: f32, y: f32) {
use std::fmt::Write;
write!(self.0, "M {} {} ", x, y).unwrap()
}
fn line_to(&mut self, x: f32, y: f32) {
use std::fmt::Write;
write!(self.0, "L {} {} ", x, y).unwrap()
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
use std::fmt::Write;
write!(self.0, "Q {} {} {} {} ", x1, y1, x, y).unwrap()
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
use std::fmt::Write;
write!(self.0, "C {} {} {} {} {} {} ", x1, y1, x2, y2, x, y).unwrap()
}
fn close(&mut self) {
self.0.push_str("Z ")
}
}
fn glyph_to_path(
x: f64,
y: f64,
face: &ttf::Face,
glyph_id: ttf::GlyphId,
cell_size: f64,
scale: f64,
svg: &mut xmlwriter::XmlWriter,
path_buf: &mut String,
) {
path_buf.clear();
let mut builder = Builder(path_buf);
let bbox = match face.outline_glyph(glyph_id, &mut builder) {
Some(v) => v,
None => return,
};
builder.finish();
let bbox_w = (bbox.x_max as f64 - bbox.x_min as f64) * scale;
let dx = (cell_size - bbox_w) / 2.0;
let y = y + cell_size + face.descender() as f64 * scale;
let transform = format!("matrix({} 0 0 {} {} {})", scale, -scale, x + dx, y);
svg.start_element("path");
svg.write_attribute("d", path_buf);
svg.write_attribute("transform", &transform);
svg.end_element();
{
let bbox_h = (bbox.y_max as f64 - bbox.y_min as f64) * scale;
let bbox_x = x + dx + bbox.x_min as f64 * scale;
let bbox_y = y - bbox.y_max as f64 * scale;
svg.start_element("rect");
svg.write_attribute("x", &bbox_x);
svg.write_attribute("y", &bbox_y);
svg.write_attribute("width", &bbox_w);
svg.write_attribute("height", &bbox_h);
svg.write_attribute("fill", "none");
svg.write_attribute("stroke", "green");
svg.end_element();
}
}
// NOTE: this is not a feature-full implementation and just a demo.
struct GlyphPainter<'a> {
face: &'a ttf::Face<'a>,
svg: &'a mut xmlwriter::XmlWriter,
path_buf: &'a mut String,
gradient_index: usize,
clip_path_index: usize,
palette_index: u16,
transform: ttf::Transform,
outline_transform: ttf::Transform,
transforms_stack: Vec,
}
impl<'a> GlyphPainter<'a> {
fn write_gradient_stops(&mut self, stops: ttf::colr::GradientStopsIter) {
for stop in stops {
self.svg.start_element("stop");
self.svg.write_attribute("offset", &stop.stop_offset);
self.svg.write_color_attribute("stop-color", stop.color);
let opacity = f32::from(stop.color.alpha) / 255.0;
self.svg.write_attribute("stop-opacity", &opacity);
self.svg.end_element();
}
}
fn paint_solid(&mut self, color: ttf::RgbaColor) {
self.svg.start_element("path");
self.svg.write_color_attribute("fill", color);
let opacity = f32::from(color.alpha) / 255.0;
self.svg.write_attribute("fill-opacity", &opacity);
self.svg
.write_transform_attribute("transform", self.outline_transform);
self.svg.write_attribute("d", self.path_buf);
self.svg.end_element();
}
fn paint_linear_gradient(&mut self, gradient: ttf::colr::LinearGradient<'a>) {
let gradient_id = format!("lg{}", self.gradient_index);
self.gradient_index += 1;
let gradient_transform = paint_transform(self.outline_transform, self.transform);
// TODO: We ignore x2, y2. Have to apply them somehow.
// TODO: The way spreadMode works in ttf and svg is a bit different. In SVG, the spreadMode
// will always be applied based on x1/y1 and x2/y2. However, in TTF the spreadMode will
// be applied from the first/last stop. So if we have a gradient with x1=0 x2=1, and
// a stop at x=0.4 and x=0.6, then in SVG we will always see a padding, while in ttf
// we will see the actual spreadMode. We need to account for that somehow.
self.svg.start_element("linearGradient");
self.svg.write_attribute("id", &gradient_id);
self.svg.write_attribute("x1", &gradient.x0);
self.svg.write_attribute("y1", &gradient.y0);
self.svg.write_attribute("x2", &gradient.x1);
self.svg.write_attribute("y2", &gradient.y1);
self.svg.write_attribute("gradientUnits", &"userSpaceOnUse");
self.svg.write_spread_method_attribute(gradient.extend);
self.svg
.write_transform_attribute("gradientTransform", gradient_transform);
self.write_gradient_stops(gradient.stops(
self.palette_index,
#[cfg(feature = "variable-fonts")]
self.face.variation_coordinates(),
));
self.svg.end_element();
self.svg.start_element("path");
self.svg
.write_attribute_fmt("fill", format_args!("url(#{})", gradient_id));
self.svg
.write_transform_attribute("transform", self.outline_transform);
self.svg.write_attribute("d", self.path_buf);
self.svg.end_element();
}
fn paint_radial_gradient(&mut self, gradient: ttf::colr::RadialGradient<'a>) {
let gradient_id = format!("rg{}", self.gradient_index);
self.gradient_index += 1;
self.svg.start_element("radialGradient");
self.svg.write_attribute("id", &gradient_id);
self.svg.write_attribute("cx", &gradient.x1);
self.svg.write_attribute("cy", &gradient.y1);
self.svg.write_attribute("r", &gradient.r1);
self.svg.write_attribute("fr", &gradient.r0);
self.svg.write_attribute("fx", &gradient.x0);
self.svg.write_attribute("fy", &gradient.y0);
self.svg.write_attribute("gradientUnits", &"userSpaceOnUse");
self.svg.write_spread_method_attribute(gradient.extend);
self.svg
.write_transform_attribute("gradientTransform", self.transform);
self.write_gradient_stops(gradient.stops(
self.palette_index,
#[cfg(feature = "variable-fonts")]
self.face.variation_coordinates(),
));
self.svg.end_element();
self.svg.start_element("path");
self.svg
.write_attribute_fmt("fill", format_args!("url(#{})", gradient_id));
self.svg
.write_transform_attribute("transform", self.outline_transform);
self.svg.write_attribute("d", self.path_buf);
self.svg.end_element();
}
fn paint_sweep_gradient(&mut self, _: ttf::colr::SweepGradient<'a>) {
println!("Warning: sweep gradients are not supported.")
}
}
fn paint_transform(outline_transform: Transform, transform: Transform) -> Transform {
let outline_transform = tiny_skia_path::Transform::from_row(
outline_transform.a,
outline_transform.b,
outline_transform.c,
outline_transform.d,
outline_transform.e,
outline_transform.f,
);
let gradient_transform = tiny_skia_path::Transform::from_row(
transform.a,
transform.b,
transform.c,
transform.d,
transform.e,
transform.f,
);
let gradient_transform = outline_transform
.invert()
.unwrap()
.pre_concat(gradient_transform);
ttf_parser::Transform {
a: gradient_transform.sx,
b: gradient_transform.ky,
c: gradient_transform.kx,
d: gradient_transform.sy,
e: gradient_transform.tx,
f: gradient_transform.ty,
}
}
impl GlyphPainter<'_> {
fn clip_with_path(&mut self, path: &str) {
let clip_id = format!("cp{}", self.clip_path_index);
self.clip_path_index += 1;
self.svg.start_element("clipPath");
self.svg.write_attribute("id", &clip_id);
self.svg.start_element("path");
self.svg
.write_transform_attribute("transform", self.outline_transform);
self.svg.write_attribute("d", &path);
self.svg.end_element();
self.svg.end_element();
self.svg.start_element("g");
self.svg
.write_attribute_fmt("clip-path", format_args!("url(#{})", clip_id));
}
}
impl<'a> ttf::colr::Painter<'a> for GlyphPainter<'a> {
fn outline_glyph(&mut self, glyph_id: ttf::GlyphId) {
self.path_buf.clear();
let mut builder = Builder(self.path_buf);
match self.face.outline_glyph(glyph_id, &mut builder) {
Some(v) => v,
None => return,
};
builder.finish();
// We have to write outline using the current transform.
self.outline_transform = self.transform;
}
fn push_layer(&mut self, mode: ttf::colr::CompositeMode) {
self.svg.start_element("g");
use ttf::colr::CompositeMode;
// TODO: Need to figure out how to represent the other blend modes
// in SVG.
let mode = match mode {
CompositeMode::SourceOver => "normal",
CompositeMode::Screen => "screen",
CompositeMode::Overlay => "overlay",
CompositeMode::Darken => "darken",
CompositeMode::Lighten => "lighten",
CompositeMode::ColorDodge => "color-dodge",
CompositeMode::ColorBurn => "color-burn",
CompositeMode::HardLight => "hard-light",
CompositeMode::SoftLight => "soft-light",
CompositeMode::Difference => "difference",
CompositeMode::Exclusion => "exclusion",
CompositeMode::Multiply => "multiply",
CompositeMode::Hue => "hue",
CompositeMode::Saturation => "saturation",
CompositeMode::Color => "color",
CompositeMode::Luminosity => "luminosity",
_ => {
println!("Warning: unsupported blend mode: {:?}", mode);
"normal"
}
};
self.svg.write_attribute_fmt(
"style",
format_args!("mix-blend-mode: {}; isolation: isolate", mode),
);
}
fn pop_layer(&mut self) {
self.svg.end_element(); // g
}
fn push_transform(&mut self, transform: ttf::Transform) {
self.transforms_stack.push(self.transform);
self.transform = ttf::Transform::combine(self.transform, transform);
}
fn paint(&mut self, paint: Paint<'a>) {
match paint {
Paint::Solid(color) => self.paint_solid(color),
Paint::LinearGradient(lg) => self.paint_linear_gradient(lg),
Paint::RadialGradient(rg) => self.paint_radial_gradient(rg),
Paint::SweepGradient(sg) => self.paint_sweep_gradient(sg),
}
}
fn pop_transform(&mut self) {
if let Some(ts) = self.transforms_stack.pop() {
self.transform = ts
}
}
fn push_clip(&mut self) {
self.clip_with_path(&self.path_buf.clone());
}
fn pop_clip(&mut self) {
self.svg.end_element();
}
fn push_clip_box(&mut self, clipbox: ClipBox) {
let x_min = clipbox.x_min;
let x_max = clipbox.x_max;
let y_min = clipbox.y_min;
let y_max = clipbox.y_max;
let clip_path = format!(
"M {} {} L {} {} L {} {} L {} {} Z",
x_min, y_min, x_max, y_min, x_max, y_max, x_min, y_max
);
self.clip_with_path(&clip_path);
}
}
fn color_glyph(
x: f64,
y: f64,
face: &ttf::Face,
palette_index: u16,
glyph_id: ttf::GlyphId,
cell_size: f64,
scale: f64,
gradient_index: &mut usize,
clip_path_index: &mut usize,
svg: &mut xmlwriter::XmlWriter,
path_buf: &mut String,
) {
let y = y + cell_size + face.descender() as f64 * scale;
let transform = format!("matrix({} 0 0 {} {} {})", scale, -scale, x, y);
svg.start_element("g");
svg.write_attribute("transform", &transform);
let mut painter = GlyphPainter {
face,
svg,
path_buf,
gradient_index: *gradient_index,
clip_path_index: *clip_path_index,
palette_index,
transform: ttf::Transform::default(),
outline_transform: ttf::Transform::default(),
transforms_stack: vec![ttf::Transform::default()],
};
face.paint_color_glyph(
glyph_id,
palette_index,
RgbaColor::new(0, 0, 0, 255),
&mut painter,
);
*gradient_index = painter.gradient_index;
*clip_path_index = painter.clip_path_index;
svg.end_element();
}
trait XmlWriterExt {
fn write_color_attribute(&mut self, name: &str, ts: ttf::RgbaColor);
fn write_transform_attribute(&mut self, name: &str, ts: ttf::Transform);
fn write_spread_method_attribute(&mut self, method: ttf::colr::GradientExtend);
}
impl XmlWriterExt for xmlwriter::XmlWriter {
fn write_color_attribute(&mut self, name: &str, color: ttf::RgbaColor) {
self.write_attribute_fmt(
name,
format_args!("rgb({}, {}, {})", color.red, color.green, color.blue),
);
}
fn write_transform_attribute(&mut self, name: &str, ts: ttf::Transform) {
if ts.is_default() {
return;
}
self.write_attribute_fmt(
name,
format_args!(
"matrix({} {} {} {} {} {})",
ts.a, ts.b, ts.c, ts.d, ts.e, ts.f
),
);
}
fn write_spread_method_attribute(&mut self, extend: ttf::colr::GradientExtend) {
self.write_attribute(
"spreadMethod",
match extend {
ttf::colr::GradientExtend::Pad => &"pad",
ttf::colr::GradientExtend::Repeat => &"repeat",
ttf::colr::GradientExtend::Reflect => &"reflect",
},
);
}
}
ttf-parser-0.24.1/examples/wasm/.gitignore 0000644 0000000 0000000 00000000007 10461020230 0016551 0 ustar 0000000 0000000 *.wasm
ttf-parser-0.24.1/examples/wasm/README.md 0000644 0000000 0000000 00000000602 10461020230 0016041 0 ustar 0000000 0000000 # ttf-parser as a WebAssembly module
## Build
```sh
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown --release --manifest-path ../../c-api/Cargo.toml
cp ../../c-api/target/wasm32-unknown-unknown/release/ttfparser.wasm .
```
## Run
You can use any webserver that can serve `index.html`. Here is a Python example:
```sh
python -m http.server
```
ttf-parser-0.24.1/examples/wasm/TTC.ttc 0000644 0000000 0000000 00000005060 10461020230 0015733 0 ustar 0000000 0000000 ttcf pDSIG OS/2g# `cmap1" t cvt p fpgm t gasp x glyfR4 hheadxD 6hheaT $ $hmtx H loca ^ L ` maxp p name> bpostr% 7prep
, pDSIG OS/2g# `cmap1" t cvt p fpgm t gasp x glyfR4 hheadxD 6hheaT $ $hmtx H loca ^ L ` maxp p name> bpostr% 7prep
, 2 NONE & , \ @
. &