From c60251359cbc45616805f4e0035bf3aed0fc7a0f Mon Sep 17 00:00:00 2001 From: Caleb Fontenot Date: Mon, 22 Apr 2024 13:28:24 -0500 Subject: [PATCH] Add mem free printing (I need it to verify a suspicion relating to a bug) --- node_modules/.package-lock.json | 113 + node_modules/lv_font_conv/CHANGELOG.md | 164 + node_modules/lv_font_conv/LICENSE | 22 + node_modules/lv_font_conv/README.md | 150 + node_modules/lv_font_conv/lib/app_error.js | 9 + node_modules/lv_font_conv/lib/cli.js | 318 + .../lv_font_conv/lib/collect_font_data.js | 173 + node_modules/lv_font_conv/lib/convert.js | 30 + .../lib/font/cmap_build_subtables.js | 105 + .../lv_font_conv/lib/font/compress.js | 107 + node_modules/lv_font_conv/lib/font/font.js | 131 + .../lv_font_conv/lib/font/table_cmap.js | 201 + .../lv_font_conv/lib/font/table_glyf.js | 147 + .../lv_font_conv/lib/font/table_head.js | 99 + .../lv_font_conv/lib/font/table_kern.js | 256 + .../lv_font_conv/lib/font/table_loca.js | 42 + .../lv_font_conv/lib/freetype/index.js | 317 + .../lv_font_conv/lib/freetype/render.c | 83 + node_modules/lv_font_conv/lib/ranger.js | 51 + node_modules/lv_font_conv/lib/utils.js | 131 + node_modules/lv_font_conv/lib/writers/bin.js | 17 + node_modules/lv_font_conv/lib/writers/dump.js | 68 + .../lv_font_conv/lib/writers/lvgl/index.js | 17 + .../lv_font_conv/lib/writers/lvgl/lv_font.js | 98 + .../lib/writers/lvgl/lv_table_cmap.js | 125 + .../lib/writers/lvgl/lv_table_glyf.js | 121 + .../lib/writers/lvgl/lv_table_head.js | 99 + .../lib/writers/lvgl/lv_table_kern.js | 121 + node_modules/lv_font_conv/lv_font_conv.js | 17 + .../node_modules/argparse/CHANGELOG.md | 216 + .../node_modules/argparse/LICENSE | 254 + .../node_modules/argparse/README.md | 84 + .../node_modules/argparse/argparse.js | 3707 ++++ .../node_modules/argparse/lib/sub.js | 67 + .../node_modules/argparse/lib/textwrap.js | 440 + .../node_modules/argparse/package.json | 67 + .../bit-buffer/.github/workflows/ci.yml | 36 + .../node_modules/bit-buffer/LICENSE | 21 + .../node_modules/bit-buffer/README.md | 148 + .../node_modules/bit-buffer/bit-buffer.d.ts | 115 + .../node_modules/bit-buffer/bit-buffer.js | 502 + .../node_modules/bit-buffer/package.json | 71 + .../node_modules/bit-buffer/test.js | 628 + .../lv_font_conv/node_modules/debug/LICENSE | 19 + .../lv_font_conv/node_modules/debug/README.md | 455 + .../node_modules/debug/package.json | 111 + .../node_modules/debug/src/browser.js | 269 + .../node_modules/debug/src/common.js | 261 + .../node_modules/debug/src/index.js | 10 + .../node_modules/debug/src/node.js | 263 + .../node_modules/make-error/LICENSE | 5 + .../node_modules/make-error/README.md | 112 + .../make-error/dist/make-error.js | 1 + .../node_modules/make-error/index.d.ts | 47 + .../node_modules/make-error/index.js | 151 + .../node_modules/make-error/package.json | 95 + .../node_modules/mkdirp/CHANGELOG.md | 15 + .../lv_font_conv/node_modules/mkdirp/LICENSE | 21 + .../node_modules/mkdirp/bin/cmd.js | 68 + .../lv_font_conv/node_modules/mkdirp/index.js | 31 + .../node_modules/mkdirp/lib/find-made.js | 29 + .../node_modules/mkdirp/lib/mkdirp-manual.js | 64 + .../node_modules/mkdirp/lib/mkdirp-native.js | 39 + .../node_modules/mkdirp/lib/opts-arg.js | 23 + .../node_modules/mkdirp/lib/path-arg.js | 29 + .../node_modules/mkdirp/lib/use-native.js | 10 + .../node_modules/mkdirp/package.json | 78 + .../node_modules/mkdirp/readme.markdown | 266 + .../lv_font_conv/node_modules/ms/index.js | 162 + .../lv_font_conv/node_modules/ms/license.md | 21 + .../lv_font_conv/node_modules/ms/package.json | 72 + .../lv_font_conv/node_modules/ms/readme.md | 60 + .../node_modules/opentype.js/LICENSE | 20 + .../node_modules/opentype.js/README.md | 313 + .../node_modules/opentype.js/RELEASES.md | 267 + .../node_modules/opentype.js/bin/ot | 84 + .../node_modules/opentype.js/bin/server.js | 64 + .../node_modules/opentype.js/bin/test-render | 96 + .../node_modules/opentype.js/dist/opentype.js | 14254 ++++++++++++++++ .../node_modules/opentype.js/package.json | 102 + .../lv_font_conv/node_modules/pngjs/LICENSE | 20 + .../lv_font_conv/node_modules/pngjs/README.md | 433 + .../node_modules/pngjs/lib/bitmapper.js | 267 + .../node_modules/pngjs/lib/bitpacker.js | 158 + .../node_modules/pngjs/lib/chunkstream.js | 189 + .../node_modules/pngjs/lib/constants.js | 32 + .../node_modules/pngjs/lib/crc.js | 40 + .../node_modules/pngjs/lib/filter-pack.js | 171 + .../pngjs/lib/filter-parse-async.js | 24 + .../pngjs/lib/filter-parse-sync.js | 21 + .../node_modules/pngjs/lib/filter-parse.js | 177 + .../pngjs/lib/format-normaliser.js | 93 + .../node_modules/pngjs/lib/interlace.js | 95 + .../node_modules/pngjs/lib/packer-async.js | 50 + .../node_modules/pngjs/lib/packer-sync.js | 56 + .../node_modules/pngjs/lib/packer.js | 129 + .../node_modules/pngjs/lib/paeth-predictor.js | 16 + .../node_modules/pngjs/lib/parser-async.js | 169 + .../node_modules/pngjs/lib/parser-sync.js | 112 + .../node_modules/pngjs/lib/parser.js | 290 + .../node_modules/pngjs/lib/png-sync.js | 12 + .../node_modules/pngjs/lib/png.js | 194 + .../node_modules/pngjs/lib/sync-inflate.js | 168 + .../node_modules/pngjs/lib/sync-reader.js | 45 + .../node_modules/pngjs/package.json | 129 + .../LICENSE-MIT.txt | 20 + .../string.prototype.codepointat/README.md | 47 + .../codepointat.js | 54 + .../string.prototype.codepointat/package.json | 62 + .../node_modules/tiny-inflate/LICENSE | 21 + .../node_modules/tiny-inflate/index.js | 375 + .../node_modules/tiny-inflate/package.json | 60 + .../node_modules/tiny-inflate/readme.md | 31 + .../node_modules/tiny-inflate/test/index.js | 75 + .../node_modules/tiny-inflate/test/lorem.txt | 199 + node_modules/lv_font_conv/package.json | 61 + package-lock.json | 118 + package.json | 5 + src/displayapp/screens/WatchFaceTerminal.cpp | 11 +- src/displayapp/screens/WatchFaceTerminal.h | 1 + 120 files changed, 31903 insertions(+), 2 deletions(-) create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/lv_font_conv/CHANGELOG.md create mode 100644 node_modules/lv_font_conv/LICENSE create mode 100644 node_modules/lv_font_conv/README.md create mode 100644 node_modules/lv_font_conv/lib/app_error.js create mode 100644 node_modules/lv_font_conv/lib/cli.js create mode 100644 node_modules/lv_font_conv/lib/collect_font_data.js create mode 100644 node_modules/lv_font_conv/lib/convert.js create mode 100644 node_modules/lv_font_conv/lib/font/cmap_build_subtables.js create mode 100644 node_modules/lv_font_conv/lib/font/compress.js create mode 100644 node_modules/lv_font_conv/lib/font/font.js create mode 100644 node_modules/lv_font_conv/lib/font/table_cmap.js create mode 100644 node_modules/lv_font_conv/lib/font/table_glyf.js create mode 100644 node_modules/lv_font_conv/lib/font/table_head.js create mode 100644 node_modules/lv_font_conv/lib/font/table_kern.js create mode 100644 node_modules/lv_font_conv/lib/font/table_loca.js create mode 100644 node_modules/lv_font_conv/lib/freetype/index.js create mode 100644 node_modules/lv_font_conv/lib/freetype/render.c create mode 100644 node_modules/lv_font_conv/lib/ranger.js create mode 100644 node_modules/lv_font_conv/lib/utils.js create mode 100644 node_modules/lv_font_conv/lib/writers/bin.js create mode 100644 node_modules/lv_font_conv/lib/writers/dump.js create mode 100644 node_modules/lv_font_conv/lib/writers/lvgl/index.js create mode 100644 node_modules/lv_font_conv/lib/writers/lvgl/lv_font.js create mode 100644 node_modules/lv_font_conv/lib/writers/lvgl/lv_table_cmap.js create mode 100644 node_modules/lv_font_conv/lib/writers/lvgl/lv_table_glyf.js create mode 100644 node_modules/lv_font_conv/lib/writers/lvgl/lv_table_head.js create mode 100644 node_modules/lv_font_conv/lib/writers/lvgl/lv_table_kern.js create mode 100755 node_modules/lv_font_conv/lv_font_conv.js create mode 100644 node_modules/lv_font_conv/node_modules/argparse/CHANGELOG.md create mode 100644 node_modules/lv_font_conv/node_modules/argparse/LICENSE create mode 100644 node_modules/lv_font_conv/node_modules/argparse/README.md create mode 100644 node_modules/lv_font_conv/node_modules/argparse/argparse.js create mode 100644 node_modules/lv_font_conv/node_modules/argparse/lib/sub.js create mode 100644 node_modules/lv_font_conv/node_modules/argparse/lib/textwrap.js create mode 100644 node_modules/lv_font_conv/node_modules/argparse/package.json create mode 100644 node_modules/lv_font_conv/node_modules/bit-buffer/.github/workflows/ci.yml create mode 100644 node_modules/lv_font_conv/node_modules/bit-buffer/LICENSE create mode 100644 node_modules/lv_font_conv/node_modules/bit-buffer/README.md create mode 100644 node_modules/lv_font_conv/node_modules/bit-buffer/bit-buffer.d.ts create mode 100644 node_modules/lv_font_conv/node_modules/bit-buffer/bit-buffer.js create mode 100644 node_modules/lv_font_conv/node_modules/bit-buffer/package.json create mode 100644 node_modules/lv_font_conv/node_modules/bit-buffer/test.js create mode 100644 node_modules/lv_font_conv/node_modules/debug/LICENSE create mode 100644 node_modules/lv_font_conv/node_modules/debug/README.md create mode 100644 node_modules/lv_font_conv/node_modules/debug/package.json create mode 100644 node_modules/lv_font_conv/node_modules/debug/src/browser.js create mode 100644 node_modules/lv_font_conv/node_modules/debug/src/common.js create mode 100644 node_modules/lv_font_conv/node_modules/debug/src/index.js create mode 100644 node_modules/lv_font_conv/node_modules/debug/src/node.js create mode 100644 node_modules/lv_font_conv/node_modules/make-error/LICENSE create mode 100644 node_modules/lv_font_conv/node_modules/make-error/README.md create mode 100644 node_modules/lv_font_conv/node_modules/make-error/dist/make-error.js create mode 100644 node_modules/lv_font_conv/node_modules/make-error/index.d.ts create mode 100644 node_modules/lv_font_conv/node_modules/make-error/index.js create mode 100644 node_modules/lv_font_conv/node_modules/make-error/package.json create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/CHANGELOG.md create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/LICENSE create mode 100755 node_modules/lv_font_conv/node_modules/mkdirp/bin/cmd.js create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/index.js create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/lib/find-made.js create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/lib/mkdirp-manual.js create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/lib/mkdirp-native.js create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/lib/opts-arg.js create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/lib/path-arg.js create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/lib/use-native.js create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/package.json create mode 100644 node_modules/lv_font_conv/node_modules/mkdirp/readme.markdown create mode 100644 node_modules/lv_font_conv/node_modules/ms/index.js create mode 100644 node_modules/lv_font_conv/node_modules/ms/license.md create mode 100644 node_modules/lv_font_conv/node_modules/ms/package.json create mode 100644 node_modules/lv_font_conv/node_modules/ms/readme.md create mode 100644 node_modules/lv_font_conv/node_modules/opentype.js/LICENSE create mode 100644 node_modules/lv_font_conv/node_modules/opentype.js/README.md create mode 100644 node_modules/lv_font_conv/node_modules/opentype.js/RELEASES.md create mode 100755 node_modules/lv_font_conv/node_modules/opentype.js/bin/ot create mode 100755 node_modules/lv_font_conv/node_modules/opentype.js/bin/server.js create mode 100755 node_modules/lv_font_conv/node_modules/opentype.js/bin/test-render create mode 100644 node_modules/lv_font_conv/node_modules/opentype.js/dist/opentype.js create mode 100644 node_modules/lv_font_conv/node_modules/opentype.js/package.json create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/LICENSE create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/README.md create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/bitmapper.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/bitpacker.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/chunkstream.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/constants.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/crc.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/filter-pack.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse-async.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse-sync.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/format-normaliser.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/interlace.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/packer-async.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/packer-sync.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/packer.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/paeth-predictor.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/parser-async.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/parser-sync.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/parser.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/png-sync.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/png.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/sync-inflate.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/lib/sync-reader.js create mode 100644 node_modules/lv_font_conv/node_modules/pngjs/package.json create mode 100644 node_modules/lv_font_conv/node_modules/string.prototype.codepointat/LICENSE-MIT.txt create mode 100644 node_modules/lv_font_conv/node_modules/string.prototype.codepointat/README.md create mode 100644 node_modules/lv_font_conv/node_modules/string.prototype.codepointat/codepointat.js create mode 100644 node_modules/lv_font_conv/node_modules/string.prototype.codepointat/package.json create mode 100644 node_modules/lv_font_conv/node_modules/tiny-inflate/LICENSE create mode 100644 node_modules/lv_font_conv/node_modules/tiny-inflate/index.js create mode 100644 node_modules/lv_font_conv/node_modules/tiny-inflate/package.json create mode 100644 node_modules/lv_font_conv/node_modules/tiny-inflate/readme.md create mode 100644 node_modules/lv_font_conv/node_modules/tiny-inflate/test/index.js create mode 100644 node_modules/lv_font_conv/node_modules/tiny-inflate/test/lorem.txt create mode 100644 node_modules/lv_font_conv/package.json create mode 100644 package-lock.json create mode 100644 package.json diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 00000000..8ec04fe0 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,113 @@ +{ + "name": "InfiniTime", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/lv_font_conv": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/lv_font_conv/-/lv_font_conv-1.5.2.tgz", + "integrity": "sha512-0UapRSTkVP/pnB8Z4r2HDHx5p2dJx/xUG1+14u/WXo59mwuC7BahR+Bnx/66jKoDrG1wFQwn9ZzoyMxRHOD9bg==", + "bundleDependencies": [ + "argparse", + "bit-buffer", + "debug", + "make-error", + "mkdirp", + "opentype.js", + "pngjs" + ], + "dependencies": { + "argparse": "^2.0.0", + "bit-buffer": "^0.2.5", + "debug": "^4.1.1", + "make-error": "^1.3.5", + "mkdirp": "^1.0.4", + "opentype.js": "^1.1.0", + "pngjs": "^6.0.0" + }, + "bin": { + "lv_font_conv": "lv_font_conv.js" + } + }, + "node_modules/lv_font_conv/node_modules/argparse": { + "version": "2.0.1", + "inBundle": true, + "license": "Python-2.0" + }, + "node_modules/lv_font_conv/node_modules/bit-buffer": { + "version": "0.2.5", + "inBundle": true, + "license": "MIT" + }, + "node_modules/lv_font_conv/node_modules/debug": { + "version": "4.3.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/lv_font_conv/node_modules/make-error": { + "version": "1.3.6", + "inBundle": true, + "license": "ISC" + }, + "node_modules/lv_font_conv/node_modules/mkdirp": { + "version": "1.0.4", + "inBundle": true, + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/lv_font_conv/node_modules/ms": { + "version": "2.1.2", + "inBundle": true, + "license": "MIT" + }, + "node_modules/lv_font_conv/node_modules/opentype.js": { + "version": "1.3.3", + "inBundle": true, + "license": "MIT", + "dependencies": { + "string.prototype.codepointat": "^0.2.1", + "tiny-inflate": "^1.0.3" + }, + "bin": { + "ot": "bin/ot" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/lv_font_conv/node_modules/pngjs": { + "version": "6.0.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=12.13.0" + } + }, + "node_modules/lv_font_conv/node_modules/string.prototype.codepointat": { + "version": "0.2.1", + "inBundle": true, + "license": "MIT" + }, + "node_modules/lv_font_conv/node_modules/tiny-inflate": { + "version": "1.0.3", + "inBundle": true, + "license": "MIT" + } + } +} diff --git a/node_modules/lv_font_conv/CHANGELOG.md b/node_modules/lv_font_conv/CHANGELOG.md new file mode 100644 index 00000000..94512228 --- /dev/null +++ b/node_modules/lv_font_conv/CHANGELOG.md @@ -0,0 +1,164 @@ +1.5.2 / 2021-07-18 +------------------ + +- Fixed lvgl version check for v8+, #64. + + +1.5.1 / 2021-04-06 +------------------ + +- Fixed fail of CMAP generation for edge cases, #62. +- Dev deps bump. + + +1.5.0 / 2021-03-08 +------------------ + +- More `const` in generated font (for v8+), #59. + + +1.4.1 / 2021-01-26 +------------------ + +- Fix charcodes padding in comments, #54. + + +1.4.0 / 2021-01-03 +------------------ + +- Added OTF fonts support. +- Added `--use-color-info` for limited multi-tone glyphs support. + + +1.3.1 / 2020-12-28 +------------------ + +- Unify `lvgl.h` include. +- Updated repo refs (littlevgl => lvgl). +- Deps bump. +- Moved CI to github actions. + + +1.3.0 / 2020-10-25 +------------------ + +- Drop `lodash` use. +- Deps bump. + + +1.2.1 / 2020-10-24 +------------------ + +- Reduced npm package size (drop unneeded files before publish). + + +1.2.0 / 2020-10-24 +------------------ + +- Bump FreeType to 2.10.4. +- Bundle dependencies to npm package. + + +1.1.3 / 2020-09-22 +------------------ + +- lvgl: added `LV_FONT_FMT_TXT_LARGE` check or very large fonts. + + +1.1.2 / 2020-08-23 +------------------ + +- Fix: skip `glyph.advanceWidth` for monospace fonts, #43. +- Spec fix: version size should be 4 bytes, #44. +- Spec fix: bbox x/y bits => unsigned, #45. +- Bump argparse. +- Cleanup help formatter. + + +1.1.1 / 2020-08-01 +------------------ + +- `--version` should show number from `package.json`. + + +1.1.0 / 2020-07-27 +------------------ + +- Added `post.underlinePosition` & `post.underlineThickness` info to font header. + + +1.0.0 / 2020-06-26 +------------------ + +- Maintenance release. +- Set package version 1.x, to label package as stable. +- Deps bump. + + +0.4.3 / 2020-03-05 +------------------ + +- Enabled `--bpp 8` mode. + + +0.4.2 / 2020-01-05 +------------------ + +- Added `--lv_include` option to set alternate `lvgl.h` path. +- Added guards to hide `.subpx` property for lvgl 6.0 (supported from 6.1 only), #32. +- Dev deps bump + + +0.4.1 / 2019-12-09 +------------------ + +- Allow memory growth for FreeType build, #29. +- Dev deps bump. +- Web build update. + + +0.4.0 / 2019-11-29 +------------------ + +- Note, this release is for lvgl 6.1 and has potentially breaking changes + (see below). If you have compatibility issues with lvgl 6.0 - use previous + versions or update your code. +- Spec change: added subpixels info field to font header (header size increased). +- Updated `bin` & `lvgl` writers to match new spec. +- lvgl: fixed data type for kerning values (needs appropriate update + in LittlevGL 6.1+). +- Fix errors display (disable emscripten error catcher). + + +0.3.1 / 2019-10-24 +------------------ + +- Fixed "out of range" error for big `--size`. + + +0.3.0 / 2019-10-12 +------------------ + +- Added beta options `--lcd` & `--lcd-v` for subpixel rendering (still need + header info update). +- Added FreeType data properties to dump info. +- Fixed glyph width (missed fractional part after switch to FreeType). +- Fixed missed sigh for negative X/Y bitmap offsets. +- Deps bump. + + +0.2.0 / 2019-09-26 +------------------ + +- Use FreeType renderer. Should solve all regressions, reported in 0.1.0. +- Enforced light autohinting (horizontal lines only). +- Use special hinter for monochrome output (improve quality). +- API changed to async. +- Fix: added missed `.bitmap_format` field to lvgl writer. +- Fix: changed struct fields init order to match declaration, #25. + + +0.1.0 / 2019-09-03 +------------------ + +- First release. diff --git a/node_modules/lv_font_conv/LICENSE b/node_modules/lv_font_conv/LICENSE new file mode 100644 index 00000000..4dc31bfa --- /dev/null +++ b/node_modules/lv_font_conv/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2018 authors + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lv_font_conv/README.md b/node_modules/lv_font_conv/README.md new file mode 100644 index 00000000..6716ebd9 --- /dev/null +++ b/node_modules/lv_font_conv/README.md @@ -0,0 +1,150 @@ +lv_font_conv - font convertor to compact bitmap format +====================================================== + +[![CI](https://github.com/lvgl/lv_font_conv/workflows/CI/badge.svg?branch=master)](https://github.com/lvgl/lv_font_conv/actions) +[![NPM version](https://img.shields.io/npm/v/lv_font_conv.svg?style=flat)](https://www.npmjs.org/package/lv_font_conv) + +Converts TTF/WOFF/OTF fonts to __[compact format](https://github.com/lvgl/lv_font_conv/blob/master/doc/font_spec.md)__, suitable for small embedded systems. Main features are: + +- Allows bitonal and anti-aliased glyphs (1-4 bits per pixel). +- Preserves kerning info. +- Compression. +- Users can select required glyphs only (subsetting). +- Multiple font sources can be merged. +- Simple CLI interface, easy to integrate into external build systems. + + +## Install the script + +[node.js](https://nodejs.org/en/download/) v10+ required. + +Global install of the last version, execute as "lv_font_conv" + +```sh +# install release from npm registry +npm i lv_font_conv -g +# install from github's repo, master branch +npm i lvgl/lv_font_conv -g +``` + +**run via [npx](https://www.npmjs.com/package/npx) without install** + +```sh +# run from npm registry +npx lv_font_conv -h +# run from github master +npx github:lvgl/lv_font_conv -h +``` + +Note, runing via `npx` may take some time until modules installed, be patient. + + +## CLI params + +Common: + +- `--bpp` - bits per pixel (antialiasing). +- `--size` - output font size (pixels). +- `-o`, `--output` - output path (file or directory, depends on format). +- `--format` - output format. + - `--format dump` - dump glyph images and font info, useful for debug. + - `--format bin` - dump font in binary form (as described in [spec](https://github.com/lvgl/lv_font_conv/blob/master/doc/font_spec.md)). + - `--format lvgl` - dump font in [LittlevGL](https://github.com/lvgl/lvgl) format. +- `--force-fast-kern-format` - always use more fast kering storage format, + at cost of some size. If size difference appears, it will be displayed. +- `--lcd` - generate bitmaps with 3x horizontal resolution, for subpixel + smoothing. +- `--lcd-v` - generate bitmaps with 3x vertical resolution, for subpixel + smoothing. +- `--use-color-info` - try to use glyph color info from font to create + grayscale icons. Since gray tones are emulated via transparency, result + will be good on contrast background only. +- `--lv-include` - only with `--format lvgl`, set alternate path for `lvgl.h`. + +Per font: + +- `--font` - path to font file (ttf/woff/woff2/otf). May be used multiple time for + merge. +- `-r`, `--range` - single glyph or range + optional mapping, belongs to + previously declared `--font`. Can be used multiple times. Examples: + - `-r 0x1F450` - single value, dec or hex format. + - `-r 0x1F450-0x1F470` - range. + - `-r '0x1F450=>0xF005'` - single glyph with mapping. + - `-r '0x1F450-0x1F470=>0xF005'` - range with mapping. + - `-r 0x1F450 -r 0x1F451-0x1F470` - 2 ranges. + - `-r 0x1F450,0x1F451-0x1F470` - the same as above, but defined with single `-r`. +- `--symbols` - list of characters to copy (instead of numeric format in `-r`). + - `--symbols 0123456789.,` - extract chars to display numbers. +- `--autohint-off` - do not force autohinting ("light" is on by default). +- `--autohint-strong` - use more strong autohinting (will break kerning). + +Additional debug options: + +- `--no-compress` - disable built-in RLE compression. +- `--no-prefilter` - disable bitmap lines filter (XOR), used to improve + compression ratio. +- `--no-kerning` - drop kerning info to reduce size (not recommended). +- `--full-info` - don't shorten 'font_info.json' (include pixels data). + + +## Examples + +Merge english from Roboto Regular and icons from Font Awesome, and show debug +info: + +`env DEBUG=* lv_font_conv --font Roboto-Regular.ttf -r 0x20-0x7F --font FontAwesome.ttf -r 0xFE00=>0x81 --size 16 --format bin --bpp 3 --no-compress -o output.font` + +Merge english & russian from Roboto Regular, and show debug info: + +`env DEBUG=* lv_font_conv --font Roboto-Regular.ttf -r 0x20-0x7F -r 0x401,0x410-0x44F,0x451 --size 16 --format bin --bpp 3 --no-compress -o output.font` + +Dump all Roboto glyphs to inspect icons and font details: + +`lv_font_conv --font Roboto-Regular.ttf -r 0x20-0x7F --size 16 --format dump --bpp 3 -o ./dump` + +**Note**. Option `--no-compress` exists temporary, to avoid confusion until LVGL +adds compression support. + + +## Technical notes + +### Supported output formats + +1. **bin** - universal binary format, as described in https://github.com/lvgl/lv_font_conv/tree/master/doc. +2. **lvgl** - format for LittlevGL, C file. Has minor limitations and a bit + bigger size, because C does not allow to effectively define relative offsets + in data blocks. +3. **dump** - create folder with each glyph in separate image, and other font + data as `json`. Useful for debug. + +### Merged font metrics + +When multiple fonts merged into one, sources can have different metrics. Result +will follow principles below: + +1. No scaling. Glyphs will have exactly the same size, as intended by font authors. +2. The same baseline. +3. `OS/2` metrics (`sTypoAscender`, `sTypoDescender`, `sTypoLineGap`) will be + used from the first font in list. +4. `hhea` metrics (`ascender`, `descender`), defined as max/min point of all + font glyphs, are recalculated, according to new glyphs set. + + +## Development + +Current package includes WebAssembly build of FreeType with some helper +functions. Everything is wrapped into Docker and requires zero knowledge about +additional tools install. See `package.json` for additional commands. You may +need those if decide to upgrade FreeType or update helpers. + +This builds image with emscripten & freetype, usually should be done only once: + +``` +npm run build:dockerimage +``` + +This compiles helpers and creates WebAssembly files: + +``` +npm run build:freetype +``` diff --git a/node_modules/lv_font_conv/lib/app_error.js b/node_modules/lv_font_conv/lib/app_error.js new file mode 100644 index 00000000..98e9052e --- /dev/null +++ b/node_modules/lv_font_conv/lib/app_error.js @@ -0,0 +1,9 @@ +// Custom Error type to simplify error messaging +// +'use strict'; + + +//const ExtendableError = require('es6-error'); +//module.exports = class AppError extends ExtendableError {}; + +module.exports = require('make-error')('AppError'); diff --git a/node_modules/lv_font_conv/lib/cli.js b/node_modules/lv_font_conv/lib/cli.js new file mode 100644 index 00000000..a73a9b22 --- /dev/null +++ b/node_modules/lv_font_conv/lib/cli.js @@ -0,0 +1,318 @@ +// Parse input arguments and execute convertor + +'use strict'; + + +const argparse = require('argparse'); +const fs = require('fs'); +const mkdirp = require('mkdirp'); +const path = require('path'); +const convert = require('./convert'); + + +class ActionFontAdd extends argparse.Action { + call(parser, namespace, value/*, option_string*/) { + let items = (namespace[this.dest] || []).slice(); + items.push({ source_path: value, ranges: [] }); + namespace[this.dest] = items; + } +} + + +// add range or symbols to font; +// need to merge them into one array here so overrides work correctly +class ActionFontRangeAdd extends argparse.Action { + call(parser, namespace, value, option_string) { + let fonts = namespace.font || []; + + if (fonts.length === 0) { + parser.error(`argument ${option_string}: Only allowed after --font`); + } + + let lastFont = fonts[fonts.length - 1]; + + // { symbols: 'ABC' }, or { range: [ 65, 67, 65 ] } + lastFont.ranges.push({ [this.dest]: value }); + } +} + + +// add hinting option to font; +class ActionFontStoreTrue extends argparse.Action { + constructor(options) { + options = options || {}; + options.const = true; + options.default = options.default !== null ? options.default : false; + options.nargs = 0; + super(options); + } + + call(parser, namespace, value, option_string) { + let fonts = namespace.font || []; + + if (fonts.length === 0) { + parser.error(`argument ${option_string}: Only allowed after --font`); + } + + let lastFont = fonts[fonts.length - 1]; + + lastFont[this.dest] = this.const; + } +} + + +// Formatter with support of `\n` in Help texts. +class RawTextHelpFormatter2 extends argparse.RawDescriptionHelpFormatter { + // executes parent _split_lines for each line of the help, then flattens the result + _split_lines(text, width) { + return [].concat(...text.split('\n').map(line => super._split_lines(line, width))); + } +} + + +// parse decimal or hex code in unicode range +function unicode_point(str) { + let m = /^(?:(?:0x([0-9a-f]+))|([0-9]+))$/i.exec(str.trim()); + + if (!m) throw new TypeError(`${str} is not a number`); + + let [ , hex, dec ] = m; + + let value = hex ? parseInt(hex, 16) : parseInt(dec, 10); + + if (value > 0x10FFFF) throw new TypeError(`${str} is out of unicode range`); + + return value; +} + + +// parse range +function range(str) { + let result = []; + + for (let s of str.split(',')) { + let m = /^(.+?)(?:-(.+?))?(?:=>(.+?))?$/i.exec(s); + + let [ , start, end, mapped_start ] = m; + + if (!end) end = start; + if (!mapped_start) mapped_start = start; + + start = unicode_point(start); + end = unicode_point(end); + + if (start > end) throw new TypeError(`Invalid range: ${s}`); + + mapped_start = unicode_point(mapped_start); + + result.push(start, end, mapped_start); + } + + return result; +} + + +// exclude negative numbers and non-numbers +function positive_int(str) { + if (!/^\d+$/.test(str)) throw new TypeError(`${str} is not a valid number`); + + let n = parseInt(str, 10); + + if (n <= 0) throw new TypeError(`${str} is not a valid number`); + + return n; +} + + +module.exports.run = async function (argv, debug = false) { + + // + // Configure CLI + // + + let parser = new argparse.ArgumentParser({ + add_help: true, + formatter_class: RawTextHelpFormatter2 + }); + + if (debug) { + parser.exit = function (status, message) { + throw new Error(message); + }; + } + + parser.add_argument('-v', '--version', { + action: 'version', + version: require('../package.json').version + }); + + parser.add_argument('--size', { + metavar: 'PIXELS', + type: positive_int, + required: true, + help: 'Output font size, pixels.' + }); + + parser.add_argument('-o', '--output', { + metavar: '', + help: 'Output path.' + }); + + parser.add_argument('--bpp', { + choices: [ 1, 2, 3, 4, 8 ], + type: positive_int, + required: true, + help: 'Bits per pixel, for antialiasing.' + }); + + let lcd_group = parser.add_mutually_exclusive_group(); + + lcd_group.add_argument('--lcd', { + action: 'store_true', + default: false, + help: 'Enable subpixel rendering (horizontal pixel layout).' + }); + + lcd_group.add_argument('--lcd-v', { + action: 'store_true', + default: false, + help: 'Enable subpixel rendering (vertical pixel layout).' + }); + + parser.add_argument('--use-color-info', { + dest: 'use_color_info', + action: 'store_true', + default: false, + help: 'Try to use glyph color info from font to create grayscale icons. ' + + 'Since gray tones are emulated via transparency, result will be good on contrast background only.' + }); + + parser.add_argument('--format', { + choices: convert.formats, + required: true, + help: 'Output format.' + }); + + parser.add_argument('--font', { + metavar: '', + action: ActionFontAdd, + required: true, + help: 'Source font path. Can be used multiple times to merge glyphs from different fonts.' + }); + + parser.add_argument('-r', '--range', { + type: range, + action: ActionFontRangeAdd, + help: ` +Range of glyphs to copy. Can be used multiple times, belongs to previously declared "--font". Examples: + -r 0x1F450 + -r 0x20-0x7F + -r 32-127 + -r 32-127,0x1F450 + -r '0x1F450=>0xF005' + -r '0x1F450-0x1F470=>0xF005' +` + }); + + parser.add_argument('--symbols', { + action: ActionFontRangeAdd, + help: ` +List of characters to copy, belongs to previously declared "--font". Examples: + --symbols ,.0123456789 + --symbols abcdefghigklmnopqrstuvwxyz +` + }); + + parser.add_argument('--autohint-off', { + type: range, + action: ActionFontStoreTrue, + help: 'Disable autohinting for previously declared "--font"' + }); + + parser.add_argument('--autohint-strong', { + type: range, + action: ActionFontStoreTrue, + help: 'Use more strong autohinting for previously declared "--font" (will break kerning)' + }); + + parser.add_argument('--force-fast-kern-format', { + dest: 'fast_kerning', + action: 'store_true', + default: false, + help: 'Always use kern classes instead of pairs (might be larger but faster).' + }); + + parser.add_argument('--no-compress', { + dest: 'no_compress', + action: 'store_true', + default: false, + help: 'Disable built-in RLE compression.' + }); + + parser.add_argument('--no-prefilter', { + dest: 'no_prefilter', + action: 'store_true', + default: false, + help: 'Disable bitmap lines filter (XOR), used to improve compression ratio.' + }); + + parser.add_argument('--no-kerning', { + dest: 'no_kerning', + action: 'store_true', + default: false, + help: 'Drop kerning info to reduce size (not recommended).' + }); + + parser.add_argument('--lv-include', { + metavar: '', + help: 'Set alternate "lvgl.h" path (for --format lvgl).' + }); + + parser.add_argument('--full-info', { + dest: 'full_info', + action: 'store_true', + default: false, + help: 'Don\'t shorten "font_info.json" (include pixels data).' + }); + + // + // Process CLI options + // + + let args = parser.parse_args(argv.length ? argv : [ '-h' ]); + + for (let font of args.font) { + if (font.ranges.length === 0) { + parser.error(`You need to specify either "--range" or "--symbols" for font "${font.source_path}"`); + } + + try { + font.source_bin = fs.readFileSync(font.source_path); + } catch (err) { + parser.error(`Cannot read file "${font.source_path}": ${err.message}`); + } + } + + // + // Convert + // + + let files = await convert(args); + + // + // Store files + // + + for (let [ filename, data ] of Object.entries(files)) { + let dir = path.dirname(filename); + + mkdirp.sync(dir); + + fs.writeFileSync(filename, data); + } + +}; + + +// export for tests +module.exports._range = range; diff --git a/node_modules/lv_font_conv/lib/collect_font_data.js b/node_modules/lv_font_conv/lib/collect_font_data.js new file mode 100644 index 00000000..227c5835 --- /dev/null +++ b/node_modules/lv_font_conv/lib/collect_font_data.js @@ -0,0 +1,173 @@ +// Read fonts + +'use strict'; + + +const opentype = require('opentype.js'); +const ft_render = require('./freetype'); +const AppError = require('./app_error'); +const Ranger = require('./ranger'); + + +module.exports = async function collect_font_data(args) { + await ft_render.init(); + + // Duplicate font options as k/v for quick access + let fonts_options = {}; + args.font.forEach(f => { fonts_options[f.source_path] = f; }); + + // read fonts + let fonts_opentype = {}; + let fonts_freetype = {}; + + for (let { source_path, source_bin } of args.font) { + // don't load font again if it's specified multiple times in args + if (fonts_opentype[source_path]) continue; + + try { + let b = source_bin; + + if (Buffer.isBuffer(b)) { + // node.js Buffer -> ArrayBuffer + b = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); + } + + fonts_opentype[source_path] = opentype.parse(b); + } catch (err) { + throw new AppError(`Cannot load font "${source_path}": ${err.message}`); + } + + fonts_freetype[source_path] = ft_render.fontface_create(source_bin, args.size); + } + + // merge all ranges + let ranger = new Ranger(); + + for (let { source_path, ranges } of args.font) { + let font = fonts_freetype[source_path]; + + for (let item of ranges) { + /* eslint-disable max-depth */ + if (item.range) { + for (let i = 0; i < item.range.length; i += 3) { + let range = item.range.slice(i, i + 3); + let chars = ranger.add_range(source_path, ...range); + let is_empty = true; + + for (let code of chars) { + if (ft_render.glyph_exists(font, code)) { + is_empty = false; + break; + } + } + + if (is_empty) { + let a = '0x' + range[0].toString(16); + let b = '0x' + range[1].toString(16); + throw new AppError(`Font "${source_path}" doesn't have any characters included in range ${a}-${b}`); + } + } + } + + if (item.symbols) { + let chars = ranger.add_symbols(source_path, item.symbols); + let is_empty = true; + + for (let code of chars) { + if (ft_render.glyph_exists(font, code)) { + is_empty = false; + break; + } + } + + if (is_empty) { + throw new AppError(`Font "${source_path}" doesn't have any characters included in "${item.symbols}"`); + } + } + } + } + + let mapping = ranger.get(); + let glyphs = []; + let all_dst_charcodes = Object.keys(mapping).sort((a, b) => a - b).map(Number); + + for (let dst_code of all_dst_charcodes) { + let src_code = mapping[dst_code].code; + let src_font = mapping[dst_code].font; + + if (!ft_render.glyph_exists(fonts_freetype[src_font], src_code)) continue; + + let ft_result = ft_render.glyph_render( + fonts_freetype[src_font], + src_code, + { + autohint_off: fonts_options[src_font].autohint_off, + autohint_strong: fonts_options[src_font].autohint_strong, + lcd: args.lcd, + lcd_v: args.lcd_v, + mono: !args.lcd && !args.lcd_v && args.bpp === 1, + use_color_info: args.use_color_info + } + ); + + glyphs.push({ + code: dst_code, + advanceWidth: ft_result.advance_x, + bbox: { + x: ft_result.x, + y: ft_result.y - ft_result.height, + width: ft_result.width, + height: ft_result.height + }, + kerning: {}, + freetype: ft_result.freetype, + pixels: ft_result.pixels + }); + } + + if (!args.no_kerning) { + let existing_dst_charcodes = glyphs.map(g => g.code); + + for (let { code, kerning } of glyphs) { + let src_code = mapping[code].code; + let src_font = mapping[code].font; + let font = fonts_opentype[src_font]; + let glyph = font.charToGlyph(String.fromCodePoint(src_code)); + + for (let dst_code2 of existing_dst_charcodes) { + // can't merge kerning values from 2 different fonts + if (mapping[dst_code2].font !== src_font) continue; + + let src_code2 = mapping[dst_code2].code; + let glyph2 = font.charToGlyph(String.fromCodePoint(src_code2)); + let krn_value = font.getKerningValue(glyph, glyph2); + + if (krn_value) kerning[dst_code2] = krn_value * args.size / font.unitsPerEm; + + //let krn_value = ft_render.get_kerning(font, src_code, src_code2).x; + //if (krn_value) kerning[dst_code2] = krn_value; + } + } + } + + let first_font = fonts_freetype[args.font[0].source_path]; + let first_font_scale = args.size / first_font.units_per_em; + let os2_metrics = ft_render.fontface_os2_table(first_font); + let post_table = fonts_opentype[args.font[0].source_path].tables.post; + + for (let font of Object.values(fonts_freetype)) ft_render.fontface_destroy(font); + + ft_render.destroy(); + + return { + ascent: Math.max(...glyphs.map(g => g.bbox.y + g.bbox.height)), + descent: Math.min(...glyphs.map(g => g.bbox.y)), + typoAscent: Math.round(os2_metrics.typoAscent * first_font_scale), + typoDescent: Math.round(os2_metrics.typoDescent * first_font_scale), + typoLineGap: Math.round(os2_metrics.typoLineGap * first_font_scale), + size: args.size, + glyphs, + underlinePosition: Math.round(post_table.underlinePosition * first_font_scale), + underlineThickness: Math.round(post_table.underlineThickness * first_font_scale) + }; +}; diff --git a/node_modules/lv_font_conv/lib/convert.js b/node_modules/lv_font_conv/lib/convert.js new file mode 100644 index 00000000..0cf088a0 --- /dev/null +++ b/node_modules/lv_font_conv/lib/convert.js @@ -0,0 +1,30 @@ +// Internal API to convert input data into output font data +// Used by both CLI and Web wrappers. +'use strict'; + +const collect_font_data = require('./collect_font_data'); + +let writers = { + dump: require('./writers/dump'), + bin: require('./writers/bin'), + lvgl: require('./writers/lvgl') +}; + + +// +// Input: +// - args like from CLI (optionally extended with binary content of files) +// +// Output: +// - { name1: bin_data1, name2: bin_data2, ... } +// +// returns hash with files to write +// +module.exports = async function convert(args) { + let font_data = await collect_font_data(args); + let files = writers[args.format](args, font_data); + + return files; +}; + +module.exports.formats = Object.keys(writers); diff --git a/node_modules/lv_font_conv/lib/font/cmap_build_subtables.js b/node_modules/lv_font_conv/lib/font/cmap_build_subtables.js new file mode 100644 index 00000000..c80a219e --- /dev/null +++ b/node_modules/lv_font_conv/lib/font/cmap_build_subtables.js @@ -0,0 +1,105 @@ +// Find an optimal configuration of cmap tables representing set of codepoints, +// using simple breadth-first algorithm +// +// Assume that: +// - codepoints have one-to-one correspondence to glyph ids +// - glyph ids are always bigger for bigger codepoints +// - glyph ids are always consecutive (1..N without gaps) +// +// This way we can omit glyph ids from all calculations entirely: if codepoints +// fit in format0, then glyph ids also will. +// +// format6 is not considered, because if glyph ids can be delta-coded, +// multiple format0 tables are guaranteed to be smaller than a single format6. +// +// sparse format is not used because as long as glyph ids are consecutive, +// sparse_tiny will always be preferred. +// + +'use strict'; + + +function estimate_format0_tiny_size(/*start_code, end_code*/) { + return 16; +} + +function estimate_format0_size(start_code, end_code) { + return 16 + (end_code - start_code + 1); +} + +//function estimate_sparse_size(count) { +// return 16 + count * 4; +//} + +function estimate_sparse_tiny_size(count) { + return 16 + count * 2; +} + +module.exports = function cmap_split(all_codepoints) { + all_codepoints = all_codepoints.sort((a, b) => a - b); + + let min_paths = []; + + for (let i = 0; i < all_codepoints.length; i++) { + let min = { dist: Infinity }; + + for (let j = 0; j <= i; j++) { + let prev_dist = (j - 1 >= 0) ? min_paths[j - 1].dist : 0; + let s; + + if (all_codepoints[i] - all_codepoints[j] < 256) { + s = estimate_format0_size(all_codepoints[j], all_codepoints[i]); + + /* eslint-disable max-depth */ + if (prev_dist + s < min.dist) { + min = { + dist: prev_dist + s, + start: j, + end: i, + format: 'format0' + }; + } + } + + if (all_codepoints[i] - all_codepoints[j] < 256 && all_codepoints[i] - i === all_codepoints[j] - j) { + s = estimate_format0_tiny_size(all_codepoints[j], all_codepoints[i]); + + /* eslint-disable max-depth */ + if (prev_dist + s < min.dist) { + min = { + dist: prev_dist + s, + start: j, + end: i, + format: 'format0_tiny' + }; + } + } + + // tiny sparse will always be preferred over full sparse because glyph ids are consecutive + if (all_codepoints[i] - all_codepoints[j] < 65536) { + s = estimate_sparse_tiny_size(i - j + 1); + + if (prev_dist + s < min.dist) { + min = { + dist: prev_dist + s, + start: j, + end: i, + format: 'sparse_tiny' + }; + } + } + } + + min_paths[i] = min; + } + + let result = []; + + for (let i = all_codepoints.length - 1; i >= 0;) { + let path = min_paths[i]; + result.unshift([ path.format, all_codepoints.slice(path.start, path.end + 1) ]); + i = path.start - 1; + } + + return result; +}; diff --git a/node_modules/lv_font_conv/lib/font/compress.js b/node_modules/lv_font_conv/lib/font/compress.js new file mode 100644 index 00000000..aa30a3a1 --- /dev/null +++ b/node_modules/lv_font_conv/lib/font/compress.js @@ -0,0 +1,107 @@ +'use strict'; + +//const debug = require('debug')('compress'); + +function count_same(arr, offset) { + let same = 1; + let val = arr[offset]; + + for (let i = offset + 1; i < arr.length; i++) { + if (arr[i] !== val) break; + same++; + } + + return same; +} + +// +// Compress pixels with RLE-like algorythm (modified I3BN) +// +// 1. Require minimal repeat count (1) to enter I3BN mode +// 2. Increased 1-bit-replaced repeat limit (2 => 10) +// 3. Length of direct repetition counter reduced (8 => 6 bits). +// +// pixels - flat array of pixels (one per entry) +// options.bpp - bits per pixels +// +module.exports = function compress(bitStream, pixels, options) { + const opts = Object.assign({}, { repeat: 1 }, options); + + // Minimal repetitions count to enable RLE mode. + const RLE_SKIP_COUNT = 1; + // Number of repeats, when `1` used to replace data + // If more - write as number + const RLE_BIT_COLLAPSED_COUNT = 10; + + const RLE_COUNTER_BITS = 6; // (2^bits - 1) - max value + const RLE_COUNTER_MAX = (1 << RLE_COUNTER_BITS) - 1; + // Force flush if counter dencity exceeded. + const RLE_MAX_REPEATS = RLE_COUNTER_MAX + RLE_BIT_COLLAPSED_COUNT + 1; + + //let bits_start_offset = bitStream.index; + + let offset = 0; + + while (offset < pixels.length) { + const p = pixels[offset]; + + let same = count_same(pixels, offset); + + // Clamp value because RLE counter density is limited + if (same > RLE_MAX_REPEATS + RLE_SKIP_COUNT) { + same = RLE_MAX_REPEATS + RLE_SKIP_COUNT; + } + + //debug(`offset: ${offset}, count: ${same}, pixel: ${p}`); + + offset += same; + + // If not enough for RLE - write as is. + if (same <= RLE_SKIP_COUNT) { + for (let i = 0; i < same; i++) { + bitStream.writeBits(p, opts.bpp); + //debug(`==> ${opts.bpp} bits`); + } + continue; + } + + // First, write "skipped" head as is. + for (let i = 0; i < RLE_SKIP_COUNT; i++) { + bitStream.writeBits(p, opts.bpp); + //debug(`==> ${opts.bpp} bits`); + } + + same -= RLE_SKIP_COUNT; + + // Not reached state to use counter => dump bit-extended + if (same <= RLE_BIT_COLLAPSED_COUNT) { + bitStream.writeBits(p, opts.bpp); + //debug(`==> ${opts.bpp} bits (val)`); + for (let i = 0; i < same; i++) { + /*eslint-disable max-depth*/ + if (i < same - 1) { + bitStream.writeBits(1, 1); + //debug('==> 1 bit (rle repeat)'); + } else { + bitStream.writeBits(0, 1); + //debug('==> 1 bit (rle repeat last)'); + } + } + continue; + } + + same -= RLE_BIT_COLLAPSED_COUNT + 1; + + bitStream.writeBits(p, opts.bpp); + //debug(`==> ${opts.bpp} bits (val)`); + + for (let i = 0; i < RLE_BIT_COLLAPSED_COUNT + 1; i++) { + bitStream.writeBits(1, 1); + //debug('==> 1 bit (rle repeat)'); + } + bitStream.writeBits(same, RLE_COUNTER_BITS); + //debug(`==> 4 bits (rle repeat count ${same})`); + } + + //debug(`output bits: ${bitStream.index - bits_start_offset}`); +}; diff --git a/node_modules/lv_font_conv/lib/font/font.js b/node_modules/lv_font_conv/lib/font/font.js new file mode 100644 index 00000000..e5743629 --- /dev/null +++ b/node_modules/lv_font_conv/lib/font/font.js @@ -0,0 +1,131 @@ +// Font class to generate tables +'use strict'; + +const u = require('../utils'); +const debug = require('debug')('font'); +const Head = require('./table_head'); +const Cmap = require('./table_cmap'); +const Glyf = require('./table_glyf'); +const Loca = require('./table_loca'); +const Kern = require('./table_kern'); + +class Font { + constructor(fontData, options) { + this.src = fontData; + + this.opts = options; + + // Map chars to IDs (zero is reserved) + this.glyph_id = { 0: 0 }; + + this.last_id = 1; + this.createIDs(); + debug(`last_id: ${this.last_id}`); + + this.init_tables(); + + this.minY = Math.min(...this.src.glyphs.map(g => g.bbox.y)); + debug(`minY: ${this.minY}`); + this.maxY = Math.max(...this.src.glyphs.map(g => g.bbox.y + g.bbox.height)); + debug(`maxY: ${this.maxY}`); + + // 0 => 1 byte, 1 => 2 bytes + this.glyphIdFormat = Math.max(...Object.values(this.glyph_id)) > 255 ? 1 : 0; + debug(`glyphIdFormat: ${this.glyphIdFormat}`); + + // 1.0 by default, will be stored in font as FP12.4 + this.kerningScale = 1.0; + let kerningMax = Math.max(...this.src.glyphs.map(g => Object.values(g.kerning).map(Math.abs)).flat()); + if (kerningMax >= 7.5) this.kerningScale = Math.ceil(kerningMax / 7.5 * 16) / 16; + debug(`kerningScale: ${this.kerningScale}`); + + // 0 => int, 1 => FP4 + this.advanceWidthFormat = this.hasKerning() ? 1 : 0; + debug(`advanceWidthFormat: ${this.advanceWidthFormat}`); + + this.xy_bits = Math.max(...this.src.glyphs.map(g => Math.max( + u.signed_bits(g.bbox.x), u.signed_bits(g.bbox.y) + ))); + debug(`xy_bits: ${this.xy_bits}`); + + this.wh_bits = Math.max(...this.src.glyphs.map(g => Math.max( + u.unsigned_bits(g.bbox.width), u.unsigned_bits(g.bbox.height) + ))); + debug(`wh_bits: ${this.wh_bits}`); + + this.advanceWidthBits = Math.max(...this.src.glyphs.map( + g => u.signed_bits(this.widthToInt(g.advanceWidth)) + )); + debug(`advanceWidthBits: ${this.advanceWidthBits}`); + + let glyphs = this.src.glyphs; + + this.monospaced = glyphs.every((v, i, arr) => v.advanceWidth === arr[0].advanceWidth); + debug(`monospaced: ${this.monospaced}`); + + // This should stay in the end, because depends on previous variables + // 0 => 2 bytes, 1 => 4 bytes + this.indexToLocFormat = this.glyf.getSize() > 65535 ? 1 : 0; + debug(`indexToLocFormat: ${this.indexToLocFormat}`); + + this.subpixels_mode = options.lcd ? 1 : (options.lcd_v ? 2 : 0); + debug(`subpixels_mode: ${this.subpixels_mode}`); + } + + init_tables() { + this.head = new Head(this); + this.glyf = new Glyf(this); + this.cmap = new Cmap(this); + this.loca = new Loca(this); + this.kern = new Kern(this); + } + + createIDs() { + // Simplified, don't check dupes + this.last_id = 1; + + for (let i = 0; i < this.src.glyphs.length; i++) { + // reserve zero for special cases + this.glyph_id[this.src.glyphs[i].code] = this.last_id; + this.last_id++; + } + } + + hasKerning() { + if (this.opts.no_kerning) return false; + + for (let glyph of this.src.glyphs) { + if (glyph.kerning && Object.keys(glyph.kerning).length) return true; + } + return false; + } + + // Returns integer width, depending on format + widthToInt(val) { + if (this.advanceWidthFormat === 0) return Math.round(val); + + return Math.round(val * 16); + } + + // Convert kerning to FP4.4, useable for writer. Apply `kerningScale`. + kernToFP(val) { + return Math.round(val / this.kerningScale * 16); + } + + toBin() { + const result = Buffer.concat([ + this.head.toBin(), + this.cmap.toBin(), + this.loca.toBin(), + this.glyf.toBin(), + this.kern.toBin() + ]); + + debug(`font size: ${result.length}`); + + return result; + } +} + + +module.exports = Font; diff --git a/node_modules/lv_font_conv/lib/font/table_cmap.js b/node_modules/lv_font_conv/lib/font/table_cmap.js new file mode 100644 index 00000000..8e94bde1 --- /dev/null +++ b/node_modules/lv_font_conv/lib/font/table_cmap.js @@ -0,0 +1,201 @@ +'use strict'; + + +const build_subtables = require('./cmap_build_subtables'); +const u = require('../utils'); +const debug = require('debug')('font.table.cmap'); + + +const O_SIZE = 0; +const O_LABEL = O_SIZE + 4; +const O_COUNT = O_LABEL + 4; + +const HEAD_LENGTH = O_COUNT + 4; + +const SUB_FORMAT_0 = 0; +const SUB_FORMAT_0_TINY = 2; +const SUB_FORMAT_SPARSE = 1; +const SUB_FORMAT_SPARSE_TINY = 3; + + +class Cmap { + constructor(font) { + this.font = font; + this.label = 'cmap'; + + this.sub_heads = []; + this.sub_data = []; + + this.compiled = false; + } + + compile() { + if (this.compiled) return; + this.compiled = true; + + const f = this.font; + + let subtables_plan = build_subtables(f.src.glyphs.map(g => g.code)); + + const count_format0 = subtables_plan.filter(s => s[0] === 'format0').length; + const count_sparse = subtables_plan.length - count_format0; + debug(`${subtables_plan.length} subtable(s): ${count_format0} "format 0", ${count_sparse} "sparse"`); + + for (let [ format, codepoints ] of subtables_plan) { + let g = this.glyphByCode(codepoints[0]); + let start_glyph_id = f.glyph_id[g.code]; + let min_code = codepoints[0]; + let max_code = codepoints[codepoints.length - 1]; + let entries_count = max_code - min_code + 1; + let format_code = 0; + + if (format === 'format0_tiny') { + format_code = SUB_FORMAT_0_TINY; + this.sub_data.push(Buffer.alloc(0)); + } else if (format === 'format0') { + format_code = SUB_FORMAT_0; + this.sub_data.push(this.create_format0_data(min_code, max_code, start_glyph_id)); + } else if (format === 'sparse_tiny') { + entries_count = codepoints.length; + format_code = SUB_FORMAT_SPARSE_TINY; + this.sub_data.push(this.create_sparse_tiny_data(codepoints, start_glyph_id)); + } else { // assume format === 'sparse' + entries_count = codepoints.length; + format_code = SUB_FORMAT_SPARSE; + this.sub_data.push(this.create_sparse_data(codepoints, start_glyph_id)); + } + + this.sub_heads.push(this.createSubHeader( + min_code, + max_code - min_code + 1, + start_glyph_id, + entries_count, + format_code + )); + } + + this.subHeaderUpdateAllOffsets(); + } + + createSubHeader(rangeStart, rangeLen, glyphIdOffset, total, type) { + const buf = Buffer.alloc(16); + + // buf.writeUInt32LE(offset, 0); offset unknown at this moment + buf.writeUInt32LE(rangeStart, 4); + buf.writeUInt16LE(rangeLen, 8); + buf.writeUInt16LE(glyphIdOffset, 10); + buf.writeUInt16LE(total, 12); + buf.writeUInt8(type, 14); + + return buf; + } + + subHeaderUpdateOffset(header, val) { + header.writeUInt32LE(val, 0); + } + + subHeaderUpdateAllOffsets() { + for (let i = 0; i < this.sub_heads.length; i++) { + const offset = HEAD_LENGTH + + u.sum(this.sub_heads.map(h => h.length)) + + u.sum(this.sub_data.slice(0, i).map(d => d.length)); + + this.subHeaderUpdateOffset(this.sub_heads[i], offset); + } + } + + glyphByCode(code) { + for (let g of this.font.src.glyphs) { + if (g.code === code) return g; + } + + return null; + } + + + collect_format0_data(min_code, max_code, start_glyph_id) { + let data = []; + + for (let i = min_code; i <= max_code; i++) { + const g = this.glyphByCode(i); + + if (!g) { + data.push(0); + continue; + } + + const id_delta = this.font.glyph_id[g.code] - start_glyph_id; + + if (id_delta < 0 || id_delta > 255) throw new Error('Glyph ID delta out of Format 0 range'); + + data.push(id_delta); + } + + return data; + } + + create_format0_data(min_code, max_code, start_glyph_id) { + const data = this.collect_format0_data(min_code, max_code, start_glyph_id); + + return u.balign4(Buffer.from(data)); + } + + collect_sparse_data(codepoints, start_glyph_id) { + let codepoints_list = []; + let ids_list = []; + + for (let code of codepoints) { + let g = this.glyphByCode(code); + let id = this.font.glyph_id[g.code]; + + let code_delta = code - codepoints[0]; + let id_delta = id - start_glyph_id; + + if (code_delta < 0 || code_delta > 65535) throw new Error('Codepoint delta out of range'); + if (id_delta < 0 || id_delta > 65535) throw new Error('Glyph ID delta out of range'); + + codepoints_list.push(code_delta); + ids_list.push(id_delta); + } + + return { + codes: codepoints_list, + ids: ids_list + }; + } + + create_sparse_data(codepoints, start_glyph_id) { + const data = this.collect_sparse_data(codepoints, start_glyph_id); + + return u.balign4(Buffer.concat([ + u.bFromA16(data.codes), + u.bFromA16(data.ids) + ])); + } + + create_sparse_tiny_data(codepoints, start_glyph_id) { + const data = this.collect_sparse_data(codepoints, start_glyph_id); + + return u.balign4(u.bFromA16(data.codes)); + } + + toBin() { + if (!this.compiled) this.compile(); + + const buf = Buffer.concat([ + Buffer.alloc(HEAD_LENGTH), + Buffer.concat(this.sub_heads), + Buffer.concat(this.sub_data) + ]); + debug(`table size = ${buf.length}`); + + buf.writeUInt32LE(buf.length, O_SIZE); + buf.write(this.label, O_LABEL); + buf.writeUInt32LE(this.sub_heads.length, O_COUNT); + + return buf; + } +} + + +module.exports = Cmap; diff --git a/node_modules/lv_font_conv/lib/font/table_glyf.js b/node_modules/lv_font_conv/lib/font/table_glyf.js new file mode 100644 index 00000000..e7a62999 --- /dev/null +++ b/node_modules/lv_font_conv/lib/font/table_glyf.js @@ -0,0 +1,147 @@ +'use strict'; + +const u = require('../utils'); +const { BitStream } = require('bit-buffer'); +const debug = require('debug')('font.table.glyf'); +const compress = require('./compress'); + + +const O_SIZE = 0; +const O_LABEL = O_SIZE + 4; + +const HEAD_LENGTH = O_LABEL + 4; + + +class Glyf { + constructor(font) { + this.font = font; + this.label = 'glyf'; + + this.compiled = false; + + this.binData = []; + } + + // convert 8-bit opacity to bpp-bit + pixelsToBpp(pixels) { + const bpp = this.font.opts.bpp; + return pixels.map(line => line.map(p => (p >>> (8 - bpp)))); + } + + // Returns "binary stream" (Buffer) of compiled glyph data + compileGlyph(glyph) { + // Allocate memory, enough for eny storage formats + const buf = Buffer.alloc(100 + glyph.bbox.width * glyph.bbox.height * 4); + const bs = new BitStream(buf); + bs.bigEndian = true; + const f = this.font; + + // Store Width + if (!f.monospaced) { + let w = f.widthToInt(glyph.advanceWidth); + bs.writeBits(w, f.advanceWidthBits); + } + + // Store X, Y + bs.writeBits(glyph.bbox.x, f.xy_bits); + bs.writeBits(glyph.bbox.y, f.xy_bits); + bs.writeBits(glyph.bbox.width, f.wh_bits); + bs.writeBits(glyph.bbox.height, f.wh_bits); + + const pixels = this.pixelsToBpp(glyph.pixels); + + this.storePixels(bs, pixels); + + // Shrink size + const result = Buffer.alloc(bs.byteIndex); + buf.copy(result, 0, 0, bs.byteIndex); + + return result; + } + + storePixels(bitStream, pixels) { + if (this.getCompressionCode() === 0) this.storePixelsRaw(bitStream, pixels); + else this.storePixelsCompressed(bitStream, pixels); + } + + storePixelsRaw(bitStream, pixels) { + const bpp = this.font.opts.bpp; + + for (let y = 0; y < pixels.length; y++) { + const line = pixels[y]; + for (let x = 0; x < line.length; x++) { + bitStream.writeBits(line[x], bpp); + } + } + } + + storePixelsCompressed(bitStream, pixels) { + let p; + + if (this.font.opts.no_prefilter) p = pixels.flat(); + else p = u.prefilter(pixels).flat(); + + compress(bitStream, p, this.font.opts); + } + + // Create internal struct with binary data for each glyph + // Needed to calculate offsets & build final result + compile() { + this.compiled = true; + + this.binData = [ + Buffer.alloc(0) // Reserve id 0 + ]; + + const f = this.font; + + f.src.glyphs.forEach(g => { + const id = f.glyph_id[g.code]; + + this.binData[id] = this.compileGlyph(g); + }); + } + + toBin() { + if (!this.compiled) this.compile(); + + const buf = u.balign4(Buffer.concat([ + Buffer.alloc(HEAD_LENGTH), + Buffer.concat(this.binData) + ])); + + buf.writeUInt32LE(buf.length, O_SIZE); + buf.write(this.label, O_LABEL); + + debug(`table size = ${buf.length}`); + + return buf; + } + + getSize() { + if (!this.compiled) this.compile(); + + return u.align4(HEAD_LENGTH + u.sum(this.binData.map(b => b.length))); + } + + getOffset(id) { + if (!this.compiled) this.compile(); + + let offset = HEAD_LENGTH; + + for (let i = 0; i < id; i++) offset += this.binData[i].length; + + return offset; + } + + getCompressionCode() { + if (this.font.opts.no_compress) return 0; + if (this.font.opts.bpp === 1) return 0; + + if (this.font.opts.no_prefilter) return 2; + return 1; + } +} + + +module.exports = Glyf; diff --git a/node_modules/lv_font_conv/lib/font/table_head.js b/node_modules/lv_font_conv/lib/font/table_head.js new file mode 100644 index 00000000..4cb9f676 --- /dev/null +++ b/node_modules/lv_font_conv/lib/font/table_head.js @@ -0,0 +1,99 @@ +'use strict'; + + +const u = require('../utils'); +const debug = require('debug')('font.table.head'); + +const O_SIZE = 0; +const O_LABEL = O_SIZE + 4; +const O_VERSION = O_LABEL + 4; +const O_TABLES = O_VERSION + 4; +const O_FONT_SIZE = O_TABLES + 2; +const O_ASCENT = O_FONT_SIZE + 2; +const O_DESCENT = O_ASCENT + 2; +const O_TYPO_ASCENT = O_DESCENT + 2; +const O_TYPO_DESCENT = O_TYPO_ASCENT + 2; +const O_TYPO_LINE_GAP = O_TYPO_DESCENT + 2; +const O_MIN_Y = O_TYPO_LINE_GAP + 2; +const O_MAX_Y = O_MIN_Y + 2; +const O_DEF_ADVANCE_WIDTH = O_MAX_Y + 2; +const O_KERNING_SCALE = O_DEF_ADVANCE_WIDTH + 2; +const O_INDEX_TO_LOC_FORMAT = O_KERNING_SCALE + 2; +const O_GLYPH_ID_FORMAT = O_INDEX_TO_LOC_FORMAT + 1; +const O_ADVANCE_WIDTH_FORMAT = O_GLYPH_ID_FORMAT + 1; +const O_BITS_PER_PIXEL = O_ADVANCE_WIDTH_FORMAT + 1; +const O_XY_BITS = O_BITS_PER_PIXEL + 1; +const O_WH_BITS = O_XY_BITS + 1; +const O_ADVANCE_WIDTH_BITS = O_WH_BITS + 1; +const O_COMPRESSION_ID = O_ADVANCE_WIDTH_BITS + 1; +const O_SUBPIXELS_MODE = O_COMPRESSION_ID + 1; +const O_TMP_RESERVED1 = O_SUBPIXELS_MODE + 1; +const O_UNDERLINE_POSITION = O_TMP_RESERVED1 + 1; +const O_UNDERLINE_THICKNESS = O_UNDERLINE_POSITION + 2; +const HEAD_LENGTH = u.align4(O_UNDERLINE_THICKNESS + 2); + + +class Head { + constructor(font) { + this.font = font; + this.label = 'head'; + this.version = 1; + } + + toBin() { + const buf = Buffer.alloc(HEAD_LENGTH); + debug(`table size = ${buf.length}`); + + buf.writeUInt32LE(HEAD_LENGTH, O_SIZE); + buf.write(this.label, O_LABEL); + buf.writeUInt32LE(this.version, O_VERSION); + + const f = this.font; + + const tables_count = f.hasKerning() ? 4 : 3; + + buf.writeUInt16LE(tables_count, O_TABLES); + + buf.writeUInt16LE(f.src.size, O_FONT_SIZE); + buf.writeUInt16LE(f.src.ascent, O_ASCENT); + buf.writeInt16LE(f.src.descent, O_DESCENT); + + buf.writeUInt16LE(f.src.typoAscent, O_TYPO_ASCENT); + buf.writeInt16LE(f.src.typoDescent, O_TYPO_DESCENT); + buf.writeUInt16LE(f.src.typoLineGap, O_TYPO_LINE_GAP); + + buf.writeInt16LE(f.minY, O_MIN_Y); + buf.writeInt16LE(f.maxY, O_MAX_Y); + + if (f.monospaced) { + buf.writeUInt16LE(f.widthToInt(f.src.glyphs[0].advanceWidth), O_DEF_ADVANCE_WIDTH); + } else { + buf.writeUInt16LE(0, O_DEF_ADVANCE_WIDTH); + } + + buf.writeUInt16LE(Math.round(f.kerningScale * 16), O_KERNING_SCALE); // FP12.4 + + buf.writeUInt8(f.indexToLocFormat, O_INDEX_TO_LOC_FORMAT); + buf.writeUInt8(f.glyphIdFormat, O_GLYPH_ID_FORMAT); + buf.writeUInt8(f.advanceWidthFormat, O_ADVANCE_WIDTH_FORMAT); + + buf.writeUInt8(f.opts.bpp, O_BITS_PER_PIXEL); + buf.writeUInt8(f.xy_bits, O_XY_BITS); + buf.writeUInt8(f.wh_bits, O_WH_BITS); + + if (f.monospaced) buf.writeUInt8(0, O_ADVANCE_WIDTH_BITS); + else buf.writeUInt8(f.advanceWidthBits, O_ADVANCE_WIDTH_BITS); + + buf.writeUInt8(f.glyf.getCompressionCode(), O_COMPRESSION_ID); + + buf.writeUInt8(f.subpixels_mode, O_SUBPIXELS_MODE); + + buf.writeInt16LE(f.src.underlinePosition, O_UNDERLINE_POSITION); + buf.writeUInt16LE(f.src.underlineThickness, O_UNDERLINE_POSITION); + + return buf; + } +} + + +module.exports = Head; diff --git a/node_modules/lv_font_conv/lib/font/table_kern.js b/node_modules/lv_font_conv/lib/font/table_kern.js new file mode 100644 index 00000000..e879b3c7 --- /dev/null +++ b/node_modules/lv_font_conv/lib/font/table_kern.js @@ -0,0 +1,256 @@ +'use strict'; + +const u = require('../utils'); +const debug = require('debug')('font.table.kern'); + + +const O_SIZE = 0; +const O_LABEL = O_SIZE + 4; +const O_FORMAT = O_LABEL + 4; + +const HEAD_LENGTH = u.align4(O_FORMAT + 1); + + +class Kern { + constructor(font) { + this.font = font; + this.label = 'kern'; + this.format3_forced = false; + } + + collect_format0_data() { + const f = this.font; + const glyphs = u.sort_by(this.font.src.glyphs, g => f.glyph_id[g.code]); + const kernSorted = []; + + for (let g of glyphs) { + if (!g.kerning || !Object.keys(g.kerning).length) continue; + + const glyph_id = f.glyph_id[g.code]; + const paired = u.sort_by(Object.keys(g.kerning), code => f.glyph_id[code]); + + for (let code of paired) { + const glyph_id2 = f.glyph_id[code]; + kernSorted.push([ glyph_id, glyph_id2, g.kerning[code] ]); + } + } + + return kernSorted; + } + + create_format0_data() { + const f = this.font; + const glyphs = this.font.src.glyphs; + const kernSorted = this.collect_format0_data(); + + const count = kernSorted.length; + + const kerned_glyphs = glyphs.filter(g => Object.keys(g.kerning).length).length; + const kerning_list_max = Math.max(...glyphs.map(g => Object.keys(g.kerning).length)); + debug(`${kerned_glyphs} kerned glyphs of ${glyphs.length}, ${kerning_list_max} max list, ${count} total pairs`); + + const subheader = Buffer.alloc(4); + + subheader.writeUInt32LE(count, 0); + + const pairs_buf = Buffer.alloc((f.glyphIdFormat ? 4 : 2) * count); + + // Write kerning pairs + for (let i = 0; i < count; i++) { + if (f.glyphIdFormat === 0) { + pairs_buf.writeUInt8(kernSorted[i][0], 2 * i); + pairs_buf.writeUInt8(kernSorted[i][1], 2 * i + 1); + } else { + pairs_buf.writeUInt16LE(kernSorted[i][0], 4 * i); + pairs_buf.writeUInt16LE(kernSorted[i][1], 4 * i + 2); + } + } + + const values_buf = Buffer.alloc(count); + + // Write kerning values + for (let i = 0; i < count; i++) { + values_buf.writeInt8(f.kernToFP(kernSorted[i][2]), i); // FP4.4 + } + + let buf = Buffer.concat([ + subheader, + pairs_buf, + values_buf + ]); + + let buf_aligned = u.balign4(buf); + + debug(`table format0 size = ${buf_aligned.length}`); + return buf_aligned; + } + + collect_format3_data() { + const f = this.font; + const glyphs = u.sort_by(this.font.src.glyphs, g => f.glyph_id[g.code]); + + // extract kerning pairs for each character; + // left kernings are kerning values based on left char (already there), + // right kernings are kerning values based on right char (extracted from left) + const left_kernings = {}; + const right_kernings = {}; + + for (let g of glyphs) { + if (!g.kerning || !Object.keys(g.kerning).length) continue; + + const paired = Object.keys(g.kerning); + + left_kernings[g.code] = g.kerning; + + for (let code of paired) { + right_kernings[code] = right_kernings[code] || {}; + right_kernings[code][g.code] = g.kerning[code]; + } + } + + // input: + // - kernings, char => { hash: String, [char1]: Number, [char2]: Number, ... } + // + // returns: + // - array of [ char1, char2, ... ] + // + function build_classes(kernings) { + const classes = []; + + for (let code of Object.keys(kernings)) { + // for each kerning table calculate unique value representing it; + // keys needs to be sorted for this (but we're using numeric keys, so + // sorting happens automatically and can't be changed) + const hash = JSON.stringify(kernings[code]); + + classes[hash] = classes[hash] || []; + classes[hash].push(Number(code)); + } + + return Object.values(classes); + } + + const left_classes = build_classes(left_kernings); + debug(`unique left classes: ${left_classes.length}`); + + const right_classes = build_classes(right_kernings); + debug(`unique right classes: ${right_classes.length}`); + + if (left_classes.length >= 255 || right_classes.length >= 255) { + debug('too many classes for format3 subtable'); + return null; + } + + function kern_class_mapping(classes) { + const arr = Array(f.last_id).fill(0); + + classes.forEach((members, idx) => { + for (let code of members) { + arr[f.glyph_id[code]] = idx + 1; + } + }); + + return arr; + } + + function kern_class_values() { + const arr = []; + + for (let left_class of left_classes) { + for (let right_class of right_classes) { + let code1 = left_class[0]; + let code2 = right_class[0]; + arr.push(left_kernings[code1][code2] || 0); + } + } + + return arr; + } + + return { + left_classes: left_classes.length, + right_classes: right_classes.length, + left_mapping: kern_class_mapping(left_classes), + right_mapping: kern_class_mapping(right_classes), + values: kern_class_values() + }; + } + + create_format3_data() { + const f = this.font; + const { + left_classes, + right_classes, + left_mapping, + right_mapping, + values + } = this.collect_format3_data(); + + const subheader = Buffer.alloc(4); + subheader.writeUInt16LE(f.last_id); + subheader.writeUInt8(left_classes, 2); + subheader.writeUInt8(right_classes, 3); + + let buf = Buffer.concat([ + subheader, + Buffer.from(left_mapping), + Buffer.from(right_mapping), + Buffer.from(values.map(v => f.kernToFP(v))) + ]); + + let buf_aligned = u.balign4(buf); + + debug(`table format3 size = ${buf_aligned.length}`); + return buf_aligned; + } + + should_use_format3() { + if (!this.font.hasKerning()) return false; + + const format0_data = this.create_format0_data(); + const format3_data = this.create_format3_data(); + + if (format3_data && format3_data.length <= format0_data.length) return true; + + if (this.font.opts.fast_kerning && format3_data) { + this.format3_forced = true; + return true; + } + + return false; + } + + toBin() { + if (!this.font.hasKerning()) return Buffer.alloc(0); + + const format0_data = this.create_format0_data(); + const format3_data = this.create_format3_data(); + + let header = Buffer.alloc(HEAD_LENGTH); + + let data = format0_data; + header.writeUInt8(0, O_FORMAT); + + /* eslint-disable no-console */ + + if (this.should_use_format3()) { + data = format3_data; + header.writeUInt8(3, O_FORMAT); + + if (this.format3_forced) { + let diff = format3_data.length - format0_data.length; + console.log(`Forced faster kerning format (via classes). Size increase is ${diff} bytes.`); + } + } else if (this.font.opts.fast_kerning) { + console.log('Forced faster kerning format (via classes), but data exceeds it\'s limits. Continue use pairs.'); + } + + header.writeUInt32LE(header.length + data.length, O_SIZE); + header.write(this.label, O_LABEL); + + return Buffer.concat([ header, data ]); + } +} + + +module.exports = Kern; diff --git a/node_modules/lv_font_conv/lib/font/table_loca.js b/node_modules/lv_font_conv/lib/font/table_loca.js new file mode 100644 index 00000000..4aa50d22 --- /dev/null +++ b/node_modules/lv_font_conv/lib/font/table_loca.js @@ -0,0 +1,42 @@ +'use strict'; + + +const u = require('../utils'); +const debug = require('debug')('font.table.loca'); + + +const O_SIZE = 0; +const O_LABEL = O_SIZE + 4; +const O_COUNT = O_LABEL + 4; + +const HEAD_LENGTH = O_COUNT + 4; + + +class Loca { + constructor(font) { + this.font = font; + this.label = 'loca'; + } + + toBin() { + const f = this.font; + + const offsets = [ ...Array(f.last_id).keys() ].map(i => f.glyf.getOffset(i)); + + const buf = u.balign4(Buffer.concat([ + Buffer.alloc(HEAD_LENGTH), + f.indexToLocFormat ? u.bFromA32(offsets) : u.bFromA16(offsets) + ])); + + buf.writeUInt32LE(buf.length, O_SIZE); + buf.write(this.label, O_LABEL); + buf.writeUInt32LE(f.last_id, O_COUNT); + + debug(`table size = ${buf.length}`); + + return buf; + } +} + + +module.exports = Loca; diff --git a/node_modules/lv_font_conv/lib/freetype/index.js b/node_modules/lv_font_conv/lib/freetype/index.js new file mode 100644 index 00000000..d05f68c3 --- /dev/null +++ b/node_modules/lv_font_conv/lib/freetype/index.js @@ -0,0 +1,317 @@ +'use strict'; + + +const ft_render_fabric = require('./build/ft_render'); + +let m = null; // compiled module instance +let library = 0; // pointer to library struct in wasm memory + + +// workaround because of bug in emscripten: +// https://github.com/emscripten-core/emscripten/issues/5820 +const runtime_initialized = new Promise(resolve => { + ft_render_fabric().then(module_instance => { + m = module_instance; + resolve(); + }); +}); + +function from_16_16(fixed_point) { + return fixed_point / (1 << 16); +} + +function from_26_6(fixed_point) { + return fixed_point / (1 << 6); +} + +function int8_to_uint8(value) { + return value >= 0 ? value : value + 0x100; +} + +let FT_New_Memory_Face, + FT_Set_Char_Size, + FT_Set_Pixel_Sizes, + FT_Get_Char_Index, + FT_Load_Glyph, + FT_Get_Sfnt_Table, + FT_Get_Kerning, + FT_Done_Face; + +module.exports.init = async function () { + await runtime_initialized; + m._init_constants(); + + FT_New_Memory_Face = module.exports.FT_New_Memory_Face = + m.cwrap('FT_New_Memory_Face', 'number', [ 'number', 'number', 'number', 'number', 'number' ]); + + FT_Set_Char_Size = module.exports.FT_Set_Char_Size = + m.cwrap('FT_Set_Char_Size', 'number', [ 'number', 'number', 'number', 'number', 'number' ]); + + FT_Set_Pixel_Sizes = module.exports.FT_Set_Pixel_Sizes = + m.cwrap('FT_Set_Pixel_Sizes', 'number', [ 'number', 'number', 'number' ]); + + FT_Get_Char_Index = module.exports.FT_Get_Char_Index = + m.cwrap('FT_Get_Char_Index', 'number', [ 'number', 'number' ]); + + FT_Load_Glyph = module.exports.FT_Load_Glyph = + m.cwrap('FT_Load_Glyph', 'number', [ 'number', 'number', 'number' ]); + + FT_Get_Sfnt_Table = module.exports.FT_Get_Sfnt_Table = + m.cwrap('FT_Get_Sfnt_Table', 'number', [ 'number', 'number' ]); + + FT_Get_Kerning = module.exports.FT_Get_Kerning = + m.cwrap('FT_Get_Kerning', 'number', [ 'number', 'number', 'number', 'number', 'number' ]); + + FT_Done_Face = module.exports.FT_Done_Face = + m.cwrap('FT_Done_Face', 'number', [ 'number' ]); + + if (!library) { + let ptr = m._malloc(4); + + try { + let error = m.ccall('FT_Init_FreeType', 'number', [ 'number' ], [ ptr ]); + + if (error) throw new Error(`error in FT_Init_FreeType: ${error}`); + + library = m.getValue(ptr, 'i32'); + } finally { + m._free(ptr); + } + } +}; + + +module.exports.fontface_create = function (source, size) { + let error; + let face = { + ptr: 0, + font: m._malloc(source.length) + }; + + m.writeArrayToMemory(source, face.font); + + let ptr = m._malloc(4); + + try { + error = FT_New_Memory_Face(library, face.font, source.length, 0, ptr); + + if (error) throw new Error(`error in FT_New_Memory_Face: ${error}`); + + face.ptr = m.getValue(ptr, 'i32'); + } finally { + m._free(ptr); + } + + error = FT_Set_Char_Size(face.ptr, 0, size * 64, 300, 300); + + if (error) throw new Error(`error in FT_Set_Char_Size: ${error}`); + + error = FT_Set_Pixel_Sizes(face.ptr, 0, size); + + if (error) throw new Error(`error in FT_Set_Pixel_Sizes: ${error}`); + + let units_per_em = m.getValue(face.ptr + m.OFFSET_FACE_UNITS_PER_EM, 'i16'); + let ascender = m.getValue(face.ptr + m.OFFSET_FACE_ASCENDER, 'i16'); + let descender = m.getValue(face.ptr + m.OFFSET_FACE_DESCENDER, 'i16'); + let height = m.getValue(face.ptr + m.OFFSET_FACE_HEIGHT, 'i16'); + + return Object.assign(face, { + units_per_em, + ascender, + descender, + height + }); +}; + + +module.exports.fontface_os2_table = function (face) { + let sfnt_ptr = FT_Get_Sfnt_Table(face.ptr, m.FT_SFNT_OS2); + + if (!sfnt_ptr) throw new Error('os/2 table not found for this font'); + + let typoAscent = m.getValue(sfnt_ptr + m.OFFSET_TT_OS2_ASCENDER, 'i16'); + let typoDescent = m.getValue(sfnt_ptr + m.OFFSET_TT_OS2_DESCENDER, 'i16'); + let typoLineGap = m.getValue(sfnt_ptr + m.OFFSET_TT_OS2_LINEGAP, 'i16'); + + return { + typoAscent, + typoDescent, + typoLineGap + }; +}; + + +module.exports.get_kerning = function (face, code1, code2) { + let glyph1 = FT_Get_Char_Index(face.ptr, code1); + let glyph2 = FT_Get_Char_Index(face.ptr, code2); + let ptr = m._malloc(4 * 2); + + try { + let error = FT_Get_Kerning(face.ptr, glyph1, glyph2, m.FT_KERNING_DEFAULT, ptr); + + if (error) throw new Error(`error in FT_Get_Kerning: ${error}`); + } finally { + m._free(ptr); + } + + return { + x: from_26_6(m.getValue(ptr, 'i32')), + y: from_26_6(m.getValue(ptr + 4, 'i32')) + }; +}; + + +module.exports.glyph_exists = function (face, code) { + let glyph_index = FT_Get_Char_Index(face.ptr, code); + + return glyph_index !== 0; +}; + + +module.exports.glyph_render = function (face, code, opts = {}) { + let glyph_index = FT_Get_Char_Index(face.ptr, code); + + if (glyph_index === 0) throw new Error(`glyph does not exist for codepoint ${code}`); + + let load_flags = m.FT_LOAD_RENDER; + + if (opts.mono) { + load_flags |= m.FT_LOAD_TARGET_MONO; + + } else if (opts.lcd) { + load_flags |= m.FT_LOAD_TARGET_LCD; + + } else if (opts.lcd_v) { + load_flags |= m.FT_LOAD_TARGET_LCD_V; + + } else { + /* eslint-disable no-lonely-if */ + + // Use "light" by default, it changes horizontal lines only. + // "normal" is more strong (with vertical lines), but will break kerning, if + // no additional care taken. More advanced rendering requires upper level + // layout support (via Harfbuzz, for example). + if (!opts.autohint_strong) load_flags |= m.FT_LOAD_TARGET_LIGHT; + else load_flags |= m.FT_LOAD_TARGET_NORMAL; + } + + if (opts.autohint_off) load_flags |= m.FT_LOAD_NO_AUTOHINT; + else load_flags |= m.FT_LOAD_FORCE_AUTOHINT; + + if (opts.use_color_info) load_flags |= m.FT_LOAD_COLOR; + + let error = FT_Load_Glyph(face.ptr, glyph_index, load_flags); + + if (error) throw new Error(`error in FT_Load_Glyph: ${error}`); + + let glyph = m.getValue(face.ptr + m.OFFSET_FACE_GLYPH, 'i32'); + + let glyph_data = { + glyph_index: m.getValue(glyph + m.OFFSET_GLYPH_INDEX, 'i32'), + metrics: { + width: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_WIDTH, 'i32')), + height: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_HEIGHT, 'i32')), + horiBearingX: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_HORI_BEARING_X, 'i32')), + horiBearingY: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_HORI_BEARING_Y, 'i32')), + horiAdvance: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_HORI_ADVANCE, 'i32')), + vertBearingX: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_VERT_BEARING_X, 'i32')), + vertBearingY: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_VERT_BEARING_Y, 'i32')), + vertAdvance: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_METRICS_VERT_ADVANCE, 'i32')) + }, + linearHoriAdvance: from_16_16(m.getValue(glyph + m.OFFSET_GLYPH_LINEAR_HORI_ADVANCE, 'i32')), + linearVertAdvance: from_16_16(m.getValue(glyph + m.OFFSET_GLYPH_LINEAR_VERT_ADVANCE, 'i32')), + advance: { + x: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_ADVANCE_X, 'i32')), + y: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_ADVANCE_Y, 'i32')) + }, + bitmap: { + width: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_WIDTH, 'i32'), + rows: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_ROWS, 'i32'), + pitch: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_PITCH, 'i32'), + num_grays: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_NUM_GRAYS, 'i16'), + pixel_mode: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_PIXEL_MODE, 'i8'), + palette_mode: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_PALETTE_MODE, 'i8') + }, + bitmap_left: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_LEFT, 'i32'), + bitmap_top: m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_TOP, 'i32'), + lsb_delta: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_LSB_DELTA, 'i32')), + rsb_delta: from_26_6(m.getValue(glyph + m.OFFSET_GLYPH_RSB_DELTA, 'i32')) + }; + + let g_w = glyph_data.bitmap.width; + let g_h = glyph_data.bitmap.rows; + let g_x = glyph_data.bitmap_left; + let g_y = glyph_data.bitmap_top; + + let buffer = m.getValue(glyph + m.OFFSET_GLYPH_BITMAP_BUFFER, 'i32'); + let pitch = Math.abs(glyph_data.bitmap.pitch); + + let advance_x = glyph_data.linearHoriAdvance; + let advance_y = glyph_data.linearVertAdvance; + + let pixel_mode = glyph_data.bitmap.pixel_mode; + + let output = []; + + for (let y = 0; y < g_h; y++) { + let row_start = buffer + y * pitch; + let line = []; + + for (let x = 0; x < g_w; x++) { + if (pixel_mode === m.FT_PIXEL_MODE_MONO) { + let value = m.getValue(row_start + ~~(x / 8), 'i8'); + line.push(value & (1 << (7 - (x % 8))) ? 255 : 0); + } else if (pixel_mode === m.FT_PIXEL_MODE_BGRA) { + let blue = int8_to_uint8(m.getValue(row_start + (x * 4) + 0, 'i8')); + let green = int8_to_uint8(m.getValue(row_start + (x * 4) + 1, 'i8')); + let red = int8_to_uint8(m.getValue(row_start + (x * 4) + 2, 'i8')); + let alpha = int8_to_uint8(m.getValue(row_start + (x * 4) + 3, 'i8')); + // convert RGBA to grayscale + let grayscale = Math.round(0.299 * red + 0.587 * green + 0.114 * blue); + if (grayscale > 255) grayscale = 255; + // meld grayscale into alpha channel + alpha = ((255 - grayscale) * alpha) / 255; + line.push(alpha); + } else { + let value = m.getValue(row_start + x, 'i8'); + line.push(int8_to_uint8(value)); + } + } + + output.push(line); + } + + return { + x: g_x, + y: g_y, + width: g_w, + height: g_h, + advance_x, + advance_y, + pixels: output, + freetype: glyph_data + }; +}; + + +module.exports.fontface_destroy = function (face) { + let error = FT_Done_Face(face.ptr); + + if (error) throw new Error(`error in FT_Done_Face: ${error}`); + + m._free(face.font); + face.ptr = 0; + face.font = 0; +}; + + +module.exports.destroy = function () { + let error = m.ccall('FT_Done_FreeType', 'number', [ 'number' ], [ library ]); + + if (error) throw new Error(`error in FT_Done_FreeType: ${error}`); + + library = 0; + + // don't unload wasm - slows down tests too much + //m = null; +}; diff --git a/node_modules/lv_font_conv/lib/freetype/render.c b/node_modules/lv_font_conv/lib/freetype/render.c new file mode 100644 index 00000000..901d4974 --- /dev/null +++ b/node_modules/lv_font_conv/lib/freetype/render.c @@ -0,0 +1,83 @@ +#include +#include +#include FT_FREETYPE_H +#include FT_TRUETYPE_TABLES_H + +static void set_js_variable(char* name, int value) { + char buffer[strlen(name) + 32]; + sprintf(buffer, "Module.%s = %d;", name, value); + emscripten_run_script(buffer); +} + +// Expose constants, used in calls from js +void init_constants() +{ + set_js_variable("FT_LOAD_DEFAULT", FT_LOAD_DEFAULT); + set_js_variable("FT_LOAD_NO_HINTING", FT_LOAD_NO_HINTING); + set_js_variable("FT_LOAD_RENDER", FT_LOAD_RENDER); + set_js_variable("FT_LOAD_FORCE_AUTOHINT", FT_LOAD_FORCE_AUTOHINT); + set_js_variable("FT_LOAD_PEDANTIC", FT_LOAD_PEDANTIC); + set_js_variable("FT_LOAD_MONOCHROME", FT_LOAD_MONOCHROME); + set_js_variable("FT_LOAD_NO_AUTOHINT", FT_LOAD_NO_AUTOHINT); + set_js_variable("FT_LOAD_COLOR", FT_LOAD_COLOR); + + set_js_variable("FT_LOAD_TARGET_NORMAL", FT_LOAD_TARGET_NORMAL); + set_js_variable("FT_LOAD_TARGET_LIGHT", FT_LOAD_TARGET_LIGHT); + set_js_variable("FT_LOAD_TARGET_MONO", FT_LOAD_TARGET_MONO); + set_js_variable("FT_LOAD_TARGET_LCD", FT_LOAD_TARGET_LCD); + set_js_variable("FT_LOAD_TARGET_LCD_V", FT_LOAD_TARGET_LCD_V); + + set_js_variable("FT_RENDER_MODE_NORMAL", FT_RENDER_MODE_NORMAL); + set_js_variable("FT_RENDER_MODE_MONO", FT_RENDER_MODE_MONO); + set_js_variable("FT_RENDER_MODE_LCD", FT_RENDER_MODE_LCD); + set_js_variable("FT_RENDER_MODE_LCD_V", FT_RENDER_MODE_LCD_V); + + set_js_variable("FT_KERNING_DEFAULT", FT_KERNING_DEFAULT); + set_js_variable("FT_KERNING_UNFITTED", FT_KERNING_UNFITTED); + set_js_variable("FT_KERNING_UNSCALED", FT_KERNING_UNSCALED); + + set_js_variable("FT_SFNT_OS2", FT_SFNT_OS2); + + set_js_variable("FT_FACE_FLAG_COLOR", FT_FACE_FLAG_COLOR); + + set_js_variable("FT_PIXEL_MODE_MONO", FT_PIXEL_MODE_MONO); + set_js_variable("FT_PIXEL_MODE_BGRA", FT_PIXEL_MODE_BGRA); + + set_js_variable("OFFSET_FACE_GLYPH", offsetof(FT_FaceRec, glyph)); + set_js_variable("OFFSET_FACE_UNITS_PER_EM", offsetof(FT_FaceRec, units_per_EM)); + set_js_variable("OFFSET_FACE_ASCENDER", offsetof(FT_FaceRec, ascender)); + set_js_variable("OFFSET_FACE_DESCENDER", offsetof(FT_FaceRec, descender)); + set_js_variable("OFFSET_FACE_HEIGHT", offsetof(FT_FaceRec, height)); + set_js_variable("OFFSET_FACE_FACE_FLAGS", offsetof(FT_FaceRec, face_flags)); + + set_js_variable("OFFSET_GLYPH_BITMAP_WIDTH", offsetof(FT_GlyphSlotRec, bitmap.width)); + set_js_variable("OFFSET_GLYPH_BITMAP_ROWS", offsetof(FT_GlyphSlotRec, bitmap.rows)); + set_js_variable("OFFSET_GLYPH_BITMAP_PITCH", offsetof(FT_GlyphSlotRec, bitmap.pitch)); + set_js_variable("OFFSET_GLYPH_BITMAP_BUFFER", offsetof(FT_GlyphSlotRec, bitmap.buffer)); + set_js_variable("OFFSET_GLYPH_BITMAP_NUM_GRAYS", offsetof(FT_GlyphSlotRec, bitmap.num_grays)); + set_js_variable("OFFSET_GLYPH_BITMAP_PIXEL_MODE", offsetof(FT_GlyphSlotRec, bitmap.pixel_mode)); + set_js_variable("OFFSET_GLYPH_BITMAP_PALETTE_MODE", offsetof(FT_GlyphSlotRec, bitmap.palette_mode)); + + set_js_variable("OFFSET_GLYPH_METRICS_WIDTH", offsetof(FT_GlyphSlotRec, metrics.width)); + set_js_variable("OFFSET_GLYPH_METRICS_HEIGHT", offsetof(FT_GlyphSlotRec, metrics.height)); + set_js_variable("OFFSET_GLYPH_METRICS_HORI_BEARING_X", offsetof(FT_GlyphSlotRec, metrics.horiBearingX)); + set_js_variable("OFFSET_GLYPH_METRICS_HORI_BEARING_Y", offsetof(FT_GlyphSlotRec, metrics.horiBearingY)); + set_js_variable("OFFSET_GLYPH_METRICS_HORI_ADVANCE", offsetof(FT_GlyphSlotRec, metrics.horiAdvance)); + set_js_variable("OFFSET_GLYPH_METRICS_VERT_BEARING_X", offsetof(FT_GlyphSlotRec, metrics.vertBearingX)); + set_js_variable("OFFSET_GLYPH_METRICS_VERT_BEARING_Y", offsetof(FT_GlyphSlotRec, metrics.vertBearingY)); + set_js_variable("OFFSET_GLYPH_METRICS_VERT_ADVANCE", offsetof(FT_GlyphSlotRec, metrics.vertAdvance)); + + set_js_variable("OFFSET_GLYPH_BITMAP_LEFT", offsetof(FT_GlyphSlotRec, bitmap_left)); + set_js_variable("OFFSET_GLYPH_BITMAP_TOP", offsetof(FT_GlyphSlotRec, bitmap_top)); + set_js_variable("OFFSET_GLYPH_INDEX", offsetof(FT_GlyphSlotRec, glyph_index)); + set_js_variable("OFFSET_GLYPH_LINEAR_HORI_ADVANCE", offsetof(FT_GlyphSlotRec, linearHoriAdvance)); + set_js_variable("OFFSET_GLYPH_LINEAR_VERT_ADVANCE", offsetof(FT_GlyphSlotRec, linearVertAdvance)); + set_js_variable("OFFSET_GLYPH_ADVANCE_X", offsetof(FT_GlyphSlotRec, advance.x)); + set_js_variable("OFFSET_GLYPH_ADVANCE_Y", offsetof(FT_GlyphSlotRec, advance.y)); + set_js_variable("OFFSET_GLYPH_LSB_DELTA", offsetof(FT_GlyphSlotRec, lsb_delta)); + set_js_variable("OFFSET_GLYPH_RSB_DELTA", offsetof(FT_GlyphSlotRec, rsb_delta)); + + set_js_variable("OFFSET_TT_OS2_ASCENDER", offsetof(TT_OS2, sTypoAscender)); + set_js_variable("OFFSET_TT_OS2_DESCENDER", offsetof(TT_OS2, sTypoDescender)); + set_js_variable("OFFSET_TT_OS2_LINEGAP", offsetof(TT_OS2, sTypoLineGap)); +} diff --git a/node_modules/lv_font_conv/lib/ranger.js b/node_modules/lv_font_conv/lib/ranger.js new file mode 100644 index 00000000..34372d75 --- /dev/null +++ b/node_modules/lv_font_conv/lib/ranger.js @@ -0,0 +1,51 @@ +// Merge ranges into single object + +'use strict'; + + +class Ranger { + constructor() { + this.data = {}; + } + + // input: + // -r 0x1F450 - single value, dec or hex format + // -r 0x1F450-0x1F470 - range + // -r 0x1F450=>0xF005 - single glyph with mapping + // -r 0x1F450-0x1F470=>0xF005 - range with mapping + add_range(font, start, end, mapped_start) { + let offset = mapped_start - start; + let output = []; + + for (let i = start; i <= end; i++) { + this._set_char(font, i, i + offset); + output.push(i); + } + + return output; + } + + // input: characters to copy, e.g. '1234567890abcdef' + add_symbols(font, str) { + let output = []; + + for (let chr of str) { + let code = chr.codePointAt(0); + this._set_char(font, code, code); + output.push(code); + } + + return output; + } + + _set_char(font, code, mapped_to) { + this.data[mapped_to] = { font, code }; + } + + get() { + return this.data; + } +} + + +module.exports = Ranger; diff --git a/node_modules/lv_font_conv/lib/utils.js b/node_modules/lv_font_conv/lib/utils.js new file mode 100644 index 00000000..0ca79322 --- /dev/null +++ b/node_modules/lv_font_conv/lib/utils.js @@ -0,0 +1,131 @@ +'use strict'; + + +function set_byte_depth(depth) { + return function (byte) { + // calculate significant bits, e.g. for depth=2 it's 0, 1, 2 or 3 + let value = ~~(byte / (256 >> depth)); + + // spread those bits around 0..255 range, e.g. for depth=2 it's 0, 85, 170 or 255 + let scale = (2 << (depth - 1)) - 1; + + return (value * 0xFFFF / scale) >> 8; + }; +} + + +module.exports.set_depth = function set_depth(glyph, depth) { + let pixels = []; + let fn = set_byte_depth(depth); + + for (let y = 0; y < glyph.bbox.height; y++) { + pixels.push(glyph.pixels[y].map(fn)); + } + + return Object.assign({}, glyph, { pixels }); +}; + + +function count_bits(val) { + let count = 0; + val = ~~val; + + while (val) { + count++; + val >>= 1; + } + + return count; +} + +// Minimal number of bits to store unsigned value +module.exports.unsigned_bits = count_bits; + +// Minimal number of bits to store signed value +module.exports.signed_bits = function signed_bits(val) { + if (val >= 0) return count_bits(val) + 1; + + return count_bits(Math.abs(val) - 1) + 1; +}; + +// Align value to 4x - useful to create word-aligned arrays +function align4(size) { + if (size % 4 === 0) return size; + return size + 4 - (size % 4); +} +module.exports.align4 = align4; + +// Align buffer length to 4x (returns copy with zero-filled tail) +module.exports.balign4 = function balign4(buf) { + let buf_aligned = Buffer.alloc(align4(buf.length)); + buf.copy(buf_aligned); + return buf_aligned; +}; + +// Pre-filter image to improve compression ratio +// In this case - XOR lines, because it's very effective +// in decompressor and does not depend on bpp. +module.exports.prefilter = function prefilter(pixels) { + return pixels.map((line, l_idx, arr) => { + if (l_idx === 0) return line.slice(); + + return line.map((p, idx) => p ^ arr[l_idx - 1][idx]); + }); +}; + + +// Convert array with uint16 data to buffer +module.exports.bFromA16 = function bFromA16(arr) { + const buf = Buffer.alloc(arr.length * 2); + + for (let i = 0; i < arr.length; i++) buf.writeUInt16LE(arr[i], i * 2); + + return buf; +}; + +// Convert array with uint32 data to buffer +module.exports.bFromA32 = function bFromA32(arr) { + const buf = Buffer.alloc(arr.length * 4); + + for (let i = 0; i < arr.length; i++) buf.writeUInt32LE(arr[i], i * 4); + + return buf; +}; + + +function chunk(arr, size) { + const result = []; + for (let i = 0; i < arr.length; i += size) { + result.push(arr.slice(i, i + size)); + } + return result; +} + +// Dump long array to multiline format with X columns and Y indent +module.exports.long_dump = function long_dump(arr, options = {}) { + const defaults = { + col: 8, + indent: 4, + hex: false + }; + + let opts = Object.assign({}, defaults, options); + let indent = ' '.repeat(opts.indent); + + return chunk(Array.from(arr), opts.col) + .map(l => l.map(v => (opts.hex ? `0x${v.toString(16)}` : v.toString()))) + .map(l => `${indent}${l.join(', ')}`) + .join(',\n'); +}; + +// stable sort by pick() result +module.exports.sort_by = function sort_by(arr, pick) { + return arr + .map((el, idx) => ({ el, idx })) + .sort((a, b) => (pick(a.el) - pick(b.el)) || (a.idx - b.idx)) + .map(({ el }) => el); +}; + +module.exports.sum = function sum(arr) { + return arr.reduce((a, v) => a + v, 0); +}; diff --git a/node_modules/lv_font_conv/lib/writers/bin.js b/node_modules/lv_font_conv/lib/writers/bin.js new file mode 100644 index 00000000..bb482080 --- /dev/null +++ b/node_modules/lv_font_conv/lib/writers/bin.js @@ -0,0 +1,17 @@ +// Write font in binary format +'use strict'; + + +const AppError = require('../app_error'); +const Font = require('../font/font'); + + +module.exports = function write_images(args, fontData) { + if (!args.output) throw new AppError('Output is required for "bin" writer'); + + const font = new Font(fontData, args); + + return { + [args.output]: font.toBin() + }; +}; diff --git a/node_modules/lv_font_conv/lib/writers/dump.js b/node_modules/lv_font_conv/lib/writers/dump.js new file mode 100644 index 00000000..150d3b99 --- /dev/null +++ b/node_modules/lv_font_conv/lib/writers/dump.js @@ -0,0 +1,68 @@ +// Write font data into png images + +'use strict'; + + +const path = require('path'); +const { PNG } = require('pngjs'); +const AppError = require('../app_error'); +const utils = require('../utils'); + +const normal_color = [ 255, 255, 255 ]; +const outside_color = [ 255, 127, 184 ]; + + +module.exports = function write_images(args, font) { + if (!args.output) throw new AppError('Output is required for "dump" writer'); + + let files = {}; + + let glyphs = font.glyphs.map(glyph => utils.set_depth(glyph, args.bpp)); + + for (let glyph of glyphs) { + let { code, advanceWidth, bbox, pixels } = glyph; + + advanceWidth = Math.round(advanceWidth); + + let minX = bbox.x; + let maxX = Math.max(bbox.x + bbox.width - 1, bbox.x); + let minY = Math.min(bbox.y, font.typoDescent); + let maxY = Math.max(bbox.y + bbox.height - 1, font.typoAscent); + + let png = new PNG({ width: maxX - minX + 1, height: maxY - minY + 1 }); + + /* eslint-disable max-depth */ + for (let pos = 0, y = maxY; y >= minY; y--) { + for (let x = minX; x <= maxX; x++) { + let value = 0; + + if (x >= bbox.x && x < bbox.x + bbox.width && y >= bbox.y && y < bbox.y + bbox.height) { + value = pixels[bbox.height - (y - bbox.y) - 1][x - bbox.x]; + } + + let r, g, b; + + if (x < 0 || x >= advanceWidth || y < font.typoDescent || y > font.typoAscent) { + [ r, g, b ] = outside_color; + } else { + [ r, g, b ] = normal_color; + } + + png.data[pos++] = (255 - value) * r / 255; + png.data[pos++] = (255 - value) * g / 255; + png.data[pos++] = (255 - value) * b / 255; + png.data[pos++] = 255; + } + } + + + files[path.join(args.output, `${code.toString(16)}.png`)] = PNG.sync.write(png); + } + + files[path.join(args.output, 'font_info.json')] = JSON.stringify( + font, + (k, v) => (k === 'pixels' && !args.full_info ? undefined : v), + 2); + + return files; +}; diff --git a/node_modules/lv_font_conv/lib/writers/lvgl/index.js b/node_modules/lv_font_conv/lib/writers/lvgl/index.js new file mode 100644 index 00000000..b592104f --- /dev/null +++ b/node_modules/lv_font_conv/lib/writers/lvgl/index.js @@ -0,0 +1,17 @@ +// Write font in lvgl format +'use strict'; + + +const AppError = require('../../app_error'); +const Font = require('./lv_font'); + + +module.exports = function write_images(args, fontData) { + if (!args.output) throw new AppError('Output is required for "lvgl" writer'); + + const font = new Font(fontData, args); + + return { + [args.output]: font.toLVGL() + }; +}; diff --git a/node_modules/lv_font_conv/lib/writers/lvgl/lv_font.js b/node_modules/lv_font_conv/lib/writers/lvgl/lv_font.js new file mode 100644 index 00000000..e3ad9c72 --- /dev/null +++ b/node_modules/lv_font_conv/lib/writers/lvgl/lv_font.js @@ -0,0 +1,98 @@ +'use strict'; + + +const path = require('path'); + +const Font = require('../../font/font'); +const Head = require('./lv_table_head'); +const Cmap = require('./lv_table_cmap'); +const Glyf = require('./lv_table_glyf'); +const Kern = require('./lv_table_kern'); +const AppError = require('../../app_error'); + + +class LvFont extends Font { + constructor(fontData, options) { + super(fontData, options); + + const ext = path.extname(options.output); + this.font_name = path.basename(options.output, ext); + + if (options.bpp === 3 & options.no_compress) { + throw new AppError('LittlevGL supports "--bpp 3" with compression only'); + } + } + + init_tables() { + this.head = new Head(this); + this.glyf = new Glyf(this); + this.cmap = new Cmap(this); + this.kern = new Kern(this); + } + + large_format_guard() { + let guard_required = false; + let glyphs_bin_size = 0; + + this.glyf.lv_data.forEach(d => { + glyphs_bin_size += d.bin.length; + + if (d.glyph.bbox.width > 255 || + d.glyph.bbox.height > 255 || + Math.abs(d.glyph.bbox.x) > 127 || + Math.abs(d.glyph.bbox.y) > 127 || + Math.round(d.glyph.advanceWidth * 16) > 4096) { + guard_required = true; + } + }); + + if (glyphs_bin_size > 1024 * 1024) guard_required = true; + + if (!guard_required) return ''; + + return ` +#if (LV_FONT_FMT_TXT_LARGE == 0) +# error "Too large font or glyphs in ${this.font_name.toUpperCase()}. Enable LV_FONT_FMT_TXT_LARGE in lv_conf.h") +#endif +`.trimLeft(); + } + + toLVGL() { + let guard_name = this.font_name.toUpperCase(); + + return `/******************************************************************************* + * Size: ${this.src.size} px + * Bpp: ${this.opts.bpp} + * Opts: ${process.argv.slice(2).join(' ')} + ******************************************************************************/ + +#ifdef LV_LVGL_H_INCLUDE_SIMPLE +#include "lvgl.h" +#else +#include "${this.opts.lv_include || 'lvgl/lvgl.h'}" +#endif + +#ifndef ${guard_name} +#define ${guard_name} 1 +#endif + +#if ${guard_name} + +${this.glyf.toLVGL()} + +${this.cmap.toLVGL()} + +${this.kern.toLVGL()} + +${this.head.toLVGL()} + +${this.large_format_guard()} + +#endif /*#if ${guard_name}*/ + +`; + } +} + + +module.exports = LvFont; diff --git a/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_cmap.js b/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_cmap.js new file mode 100644 index 00000000..56c1e6aa --- /dev/null +++ b/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_cmap.js @@ -0,0 +1,125 @@ +'use strict'; + + +const u = require('../../utils'); +const build_subtables = require('../../font/cmap_build_subtables'); +const Cmap = require('../../font/table_cmap'); + + +class LvCmap extends Cmap { + constructor(font) { + super(font); + + this.lv_compiled = false; + this.lv_subtables = []; + } + + lv_format2enum(name) { + switch (name) { + case 'format0_tiny': return 'LV_FONT_FMT_TXT_CMAP_FORMAT0_TINY'; + case 'format0': return 'LV_FONT_FMT_TXT_CMAP_FORMAT0_FULL'; + case 'sparse_tiny': return 'LV_FONT_FMT_TXT_CMAP_SPARSE_TINY'; + case 'sparse': return 'LV_FONT_FMT_TXT_CMAP_SPARSE_FULL'; + default: throw new Error('Unknown subtable format'); + } + } + + lv_compile() { + if (this.lv_compiled) return; + this.lv_compiled = true; + + const f = this.font; + + let subtables_plan = build_subtables(f.src.glyphs.map(g => g.code)); + let idx = 0; + + for (let [ format, codepoints ] of subtables_plan) { + let g = this.glyphByCode(codepoints[0]); + let start_glyph_id = f.glyph_id[g.code]; + let min_code = codepoints[0]; + let max_code = codepoints[codepoints.length - 1]; + + let has_charcodes = false; + let has_ids = false; + let defs = ''; + let entries_count = 0; + + if (format === 'format0_tiny') { + // use default empty values + } else if (format === 'format0') { + has_ids = true; + let d = this.collect_format0_data(min_code, max_code, start_glyph_id); + entries_count = d.length; + + defs = ` +static const uint8_t glyph_id_ofs_list_${idx}[] = { +${u.long_dump(d)} +}; +`.trim(); + + } else if (format === 'sparse_tiny') { + has_charcodes = true; + let d = this.collect_sparse_data(codepoints, start_glyph_id); + entries_count = d.codes.length; + + defs = ` +static const uint16_t unicode_list_${idx}[] = { +${u.long_dump(d.codes, { hex: true })} +}; +`.trim(); + + } else { // assume format === 'sparse' + has_charcodes = true; + has_ids = true; + let d = this.collect_sparse_data(codepoints, start_glyph_id); + entries_count = d.codes.length; + + defs = ` +static const uint16_t unicode_list_${idx}[] = { +${u.long_dump(d.codes, { hex: true })} +}; +static const uint16_t glyph_id_ofs_list_${idx}[] = { +${u.long_dump(d.ids)} +}; +`.trim(); + } + + const u_list = has_charcodes ? `unicode_list_${idx}` : 'NULL'; + const id_list = has_ids ? `glyph_id_ofs_list_${idx}` : 'NULL'; + + /* eslint-disable max-len */ + const head = ` { + .range_start = ${min_code}, .range_length = ${max_code - min_code + 1}, .glyph_id_start = ${start_glyph_id}, + .unicode_list = ${u_list}, .glyph_id_ofs_list = ${id_list}, .list_length = ${entries_count}, .type = ${this.lv_format2enum(format)} + }`; + + this.lv_subtables.push({ + defs, + head + }); + + idx++; + } + } + + toLVGL() { + this.lv_compile(); + + return ` +/*--------------------- + * CHARACTER MAPPING + *--------------------*/ + +${this.lv_subtables.map(d => d.defs).filter(Boolean).join('\n\n')} + +/*Collect the unicode lists and glyph_id offsets*/ +static const lv_font_fmt_txt_cmap_t cmaps[] = +{ +${this.lv_subtables.map(d => d.head).join(',\n')} +}; + `.trim(); + } +} + + +module.exports = LvCmap; diff --git a/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_glyf.js b/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_glyf.js new file mode 100644 index 00000000..3f14851f --- /dev/null +++ b/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_glyf.js @@ -0,0 +1,121 @@ +'use strict'; + + +const { BitStream } = require('bit-buffer'); +const u = require('../../utils'); +const Glyf = require('../../font/table_glyf'); + + +class LvGlyf extends Glyf { + constructor(font) { + super(font); + + this.lv_data = []; + this.lv_compiled = false; + } + + lv_bitmap(glyph) { + const buf = Buffer.alloc(100 + glyph.bbox.width * glyph.bbox.height * 4); + const bs = new BitStream(buf); + bs.bigEndian = true; + + const pixels = this.font.glyf.pixelsToBpp(glyph.pixels); + + this.font.glyf.storePixels(bs, pixels); + + const glyph_bitmap = Buffer.alloc(bs.byteIndex); + buf.copy(glyph_bitmap, 0, 0, bs.byteIndex); + + return glyph_bitmap; + } + + lv_compile() { + if (this.lv_compiled) return; + + this.lv_compiled = true; + + const f = this.font; + this.lv_data = []; + let offset = 0; + + f.src.glyphs.forEach(g => { + const id = f.glyph_id[g.code]; + const bin = this.lv_bitmap(g); + this.lv_data[id] = { + bin, + offset, + glyph: g + }; + offset += bin.length; + }); + } + + to_lv_bitmaps() { + this.lv_compile(); + + let result = []; + this.lv_data.forEach((d, idx) => { + if (idx === 0) return; + const code_hex = d.glyph.code.toString(16).toUpperCase(); + const code_str = JSON.stringify(String.fromCodePoint(d.glyph.code)); + + let txt = ` /* U+${code_hex.padStart(4, '0')} ${code_str} */ +${u.long_dump(d.bin, { hex: true })}`; + + if (idx < this.lv_data.length - 1) { + // skip comma for zero data + txt += d.bin.length ? ',\n\n' : '\n'; + } + + result.push(txt); + }); + + return result.join(''); + } + + to_lv_glyph_dsc() { + this.lv_compile(); + + /* eslint-disable max-len */ + + let result = [ ' {.bitmap_index = 0, .adv_w = 0, .box_w = 0, .box_h = 0, .ofs_x = 0, .ofs_y = 0} /* id = 0 reserved */' ]; + + this.lv_data.forEach(d => { + const idx = d.offset, + adv_w = Math.round(d.glyph.advanceWidth * 16), + h = d.glyph.bbox.height, + w = d.glyph.bbox.width, + x = d.glyph.bbox.x, + y = d.glyph.bbox.y; + result.push(` {.bitmap_index = ${idx}, .adv_w = ${adv_w}, .box_w = ${w}, .box_h = ${h}, .ofs_x = ${x}, .ofs_y = ${y}}`); + }); + + return result.join(',\n'); + } + + + toLVGL() { + return ` +/*----------------- + * BITMAPS + *----------------*/ + +/*Store the image of the glyphs*/ +static LV_ATTRIBUTE_LARGE_CONST const uint8_t glyph_bitmap[] = { +${this.to_lv_bitmaps()} +}; + + +/*--------------------- + * GLYPH DESCRIPTION + *--------------------*/ + +static const lv_font_fmt_txt_glyph_dsc_t glyph_dsc[] = { +${this.to_lv_glyph_dsc()} +}; +`.trim(); + } +} + + +module.exports = LvGlyf; diff --git a/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_head.js b/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_head.js new file mode 100644 index 00000000..f5c0173e --- /dev/null +++ b/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_head.js @@ -0,0 +1,99 @@ +'use strict'; + + +const Head = require('../../font/table_head'); + + +class LvHead extends Head { + constructor(font) { + super(font); + } + + kern_ref() { + const f = this.font; + + if (!f.hasKerning()) { + return { + scale: '0', + dsc: 'NULL', + classes: '0' + }; + } + + if (!f.kern.should_use_format3()) { + return { + scale: `${Math.round(f.kerningScale * 16)}`, + dsc: '&kern_pairs', + classes: '0' + }; + } + + return { + scale: `${Math.round(f.kerningScale * 16)}`, + dsc: '&kern_classes', + classes: '1' + }; + } + + toLVGL() { + const f = this.font; + const kern = this.kern_ref(); + const subpixels = (f.subpixels_mode === 0) ? 'LV_FONT_SUBPX_NONE' : + (f.subpixels_mode === 1) ? 'LV_FONT_SUBPX_HOR' : 'LV_FONT_SUBPX_VER'; + + return ` +/*-------------------- + * ALL CUSTOM DATA + *--------------------*/ + +#if LV_VERSION_CHECK(8, 0, 0) +/*Store all the custom data of the font*/ +static lv_font_fmt_txt_glyph_cache_t cache; +static const lv_font_fmt_txt_dsc_t font_dsc = { +#else +static lv_font_fmt_txt_dsc_t font_dsc = { +#endif + .glyph_bitmap = glyph_bitmap, + .glyph_dsc = glyph_dsc, + .cmaps = cmaps, + .kern_dsc = ${kern.dsc}, + .kern_scale = ${kern.scale}, + .cmap_num = ${f.cmap.toBin().readUInt32LE(8)}, + .bpp = ${f.opts.bpp}, + .kern_classes = ${kern.classes}, + .bitmap_format = ${f.glyf.getCompressionCode()}, +#if LV_VERSION_CHECK(8, 0, 0) + .cache = &cache +#endif +}; + + +/*----------------- + * PUBLIC FONT + *----------------*/ + +/*Initialize a public general font descriptor*/ +#if LV_VERSION_CHECK(8, 0, 0) +const lv_font_t ${f.font_name} = { +#else +lv_font_t ${f.font_name} = { +#endif + .get_glyph_dsc = lv_font_get_glyph_dsc_fmt_txt, /*Function pointer to get glyph's data*/ + .get_glyph_bitmap = lv_font_get_bitmap_fmt_txt, /*Function pointer to get glyph's bitmap*/ + .line_height = ${f.src.ascent - f.src.descent}, /*The maximum line height required by the font*/ + .base_line = ${-f.src.descent}, /*Baseline measured from the bottom of the line*/ +#if !(LVGL_VERSION_MAJOR == 6 && LVGL_VERSION_MINOR == 0) + .subpx = ${subpixels}, +#endif +#if LV_VERSION_CHECK(7, 4, 0) || LVGL_VERSION_MAJOR >= 8 + .underline_position = ${f.src.underlinePosition}, + .underline_thickness = ${f.src.underlineThickness}, +#endif + .dsc = &font_dsc /*The custom font data. Will be accessed by \`get_glyph_bitmap/dsc\` */ +}; +`.trim(); + } +} + + +module.exports = LvHead; diff --git a/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_kern.js b/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_kern.js new file mode 100644 index 00000000..e50ba427 --- /dev/null +++ b/node_modules/lv_font_conv/lib/writers/lvgl/lv_table_kern.js @@ -0,0 +1,121 @@ +'use strict'; + + +const u = require('../../utils'); +const Kern = require('../../font/table_kern'); + + +class LvKern extends Kern { + constructor(font) { + super(font); + } + + to_lv_format0() { + const f = this.font; + let kern_pairs = this.collect_format0_data(); + + return ` +/*----------------- + * KERNING + *----------------*/ + + +/*Pair left and right glyphs for kerning*/ +static const ${f.glyphIdFormat ? 'uint16_t' : 'uint8_t'} kern_pair_glyph_ids[] = +{ +${kern_pairs.map(pair => ` ${pair[0]}, ${pair[1]}`).join(',\n')} +}; + +/* Kerning between the respective left and right glyphs + * 4.4 format which needs to scaled with \`kern_scale\`*/ +static const int8_t kern_pair_values[] = +{ +${u.long_dump(kern_pairs.map(pair => f.kernToFP(pair[2])))} +}; + +/*Collect the kern pair's data in one place*/ +static const lv_font_fmt_txt_kern_pair_t kern_pairs = +{ + .glyph_ids = kern_pair_glyph_ids, + .values = kern_pair_values, + .pair_cnt = ${kern_pairs.length}, + .glyph_ids_size = ${f.glyphIdFormat} +}; + + +`.trim(); + } + + to_lv_format3() { + const f = this.font; + const { + left_classes, + right_classes, + left_mapping, + right_mapping, + values + } = this.collect_format3_data(); + + return ` +/*----------------- + * KERNING + *----------------*/ + + +/*Map glyph_ids to kern left classes*/ +static const uint8_t kern_left_class_mapping[] = +{ +${u.long_dump(left_mapping)} +}; + +/*Map glyph_ids to kern right classes*/ +static const uint8_t kern_right_class_mapping[] = +{ +${u.long_dump(right_mapping)} +}; + +/*Kern values between classes*/ +static const int8_t kern_class_values[] = +{ +${u.long_dump(values.map(v => f.kernToFP(v)))} +}; + + +/*Collect the kern class' data in one place*/ +static const lv_font_fmt_txt_kern_classes_t kern_classes = +{ + .class_pair_values = kern_class_values, + .left_class_mapping = kern_left_class_mapping, + .right_class_mapping = kern_right_class_mapping, + .left_class_cnt = ${left_classes}, + .right_class_cnt = ${right_classes}, +}; + + +`.trim(); + } + + toLVGL() { + const f = this.font; + + if (!f.hasKerning()) return ''; + + /* eslint-disable no-console */ + + if (f.kern.should_use_format3()) { + if (f.kern.format3_forced) { + let diff = this.create_format3_data().length - this.create_format0_data().length; + console.log(`Forced faster kerning format (via classes). Size increase is ${diff} bytes.`); + } + return this.to_lv_format3(); + } + + if (this.font.opts.fast_kerning) { + console.log('Forced faster kerning format (via classes), but data exceeds it\'s limits. Continue use pairs.'); + } + return this.to_lv_format0(); + } +} + + +module.exports = LvKern; diff --git a/node_modules/lv_font_conv/lv_font_conv.js b/node_modules/lv_font_conv/lv_font_conv.js new file mode 100755 index 00000000..f76cbde4 --- /dev/null +++ b/node_modules/lv_font_conv/lv_font_conv.js @@ -0,0 +1,17 @@ +#!/usr/bin/env node + +'use strict'; + +const AppError = require('./lib/app_error'); + +require('./lib/cli').run(process.argv.slice(2)).catch(err => { + /*eslint-disable no-console*/ + if (err instanceof AppError) { + // Try to beautify normal errors + console.error(err.message.trim()); + } else { + // Print crashes + console.error(err.stack); + } + process.exit(1); +}); diff --git a/node_modules/lv_font_conv/node_modules/argparse/CHANGELOG.md b/node_modules/lv_font_conv/node_modules/argparse/CHANGELOG.md new file mode 100644 index 00000000..dc39ed69 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/argparse/CHANGELOG.md @@ -0,0 +1,216 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [2.0.1] - 2020-08-29 +### Fixed +- Fix issue with `process.argv` when used with interpreters (`coffee`, `ts-node`, etc.), #150. + + +## [2.0.0] - 2020-08-14 +### Changed +- Full rewrite. Now port from python 3.9.0 & more precise following. + See [doc](./doc) for difference and migration info. +- node.js 10+ required +- Removed most of local docs in favour of original ones. + + +## [1.0.10] - 2018-02-15 +### Fixed +- Use .concat instead of + for arrays, #122. + + +## [1.0.9] - 2016-09-29 +### Changed +- Rerelease after 1.0.8 - deps cleanup. + + +## [1.0.8] - 2016-09-29 +### Changed +- Maintenance (deps bump, fix node 6.5+ tests, coverage report). + + +## [1.0.7] - 2016-03-17 +### Changed +- Teach `addArgument` to accept string arg names. #97, @tomxtobin. + + +## [1.0.6] - 2016-02-06 +### Changed +- Maintenance: moved to eslint & updated CS. + + +## [1.0.5] - 2016-02-05 +### Changed +- Removed lodash dependency to significantly reduce install size. + Thanks to @mourner. + + +## [1.0.4] - 2016-01-17 +### Changed +- Maintenance: lodash update to 4.0.0. + + +## [1.0.3] - 2015-10-27 +### Fixed +- Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple. + + +## [1.0.2] - 2015-03-22 +### Changed +- Relaxed lodash version dependency. + + +## [1.0.1] - 2015-02-20 +### Changed +- Changed dependencies to be compatible with ancient nodejs. + + +## [1.0.0] - 2015-02-19 +### Changed +- Maintenance release. +- Replaced `underscore` with `lodash`. +- Bumped version to 1.0.0 to better reflect semver meaning. +- HISTORY.md -> CHANGELOG.md + + +## [0.1.16] - 2013-12-01 +### Changed +- Maintenance release. Updated dependencies and docs. + + +## [0.1.15] - 2013-05-13 +### Fixed +- Fixed #55, @trebor89 + + +## [0.1.14] - 2013-05-12 +### Fixed +- Fixed #62, @maxtaco + + +## [0.1.13] - 2013-04-08 +### Changed +- Added `.npmignore` to reduce package size + + +## [0.1.12] - 2013-02-10 +### Fixed +- Fixed conflictHandler (#46), @hpaulj + + +## [0.1.11] - 2013-02-07 +### Added +- Added 70+ tests (ported from python), @hpaulj +- Added conflictHandler, @applepicke +- Added fromfilePrefixChar, @hpaulj + +### Fixed +- Multiple bugfixes, @hpaulj + + +## [0.1.10] - 2012-12-30 +### Added +- Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) + support, thanks to @hpaulj + +### Fixed +- Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj + + +## [0.1.9] - 2012-12-27 +### Fixed +- Fixed option dest interferens with other options (issue #23), thanks to @hpaulj +- Fixed default value behavior with `*` positionals, thanks to @hpaulj +- Improve `getDefault()` behavior, thanks to @hpaulj +- Improve negative argument parsing, thanks to @hpaulj + + +## [0.1.8] - 2012-12-01 +### Fixed +- Fixed parser parents (issue #19), thanks to @hpaulj +- Fixed negative argument parse (issue #20), thanks to @hpaulj + + +## [0.1.7] - 2012-10-14 +### Fixed +- Fixed 'choices' argument parse (issue #16) +- Fixed stderr output (issue #15) + + +## [0.1.6] - 2012-09-09 +### Fixed +- Fixed check for conflict of options (thanks to @tomxtobin) + + +## [0.1.5] - 2012-09-03 +### Fixed +- Fix parser #setDefaults method (thanks to @tomxtobin) + + +## [0.1.4] - 2012-07-30 +### Fixed +- Fixed pseudo-argument support (thanks to @CGamesPlay) +- Fixed addHelp default (should be true), if not set (thanks to @benblank) + + +## [0.1.3] - 2012-06-27 +### Fixed +- Fixed formatter api name: Formatter -> HelpFormatter + + +## [0.1.2] - 2012-05-29 +### Fixed +- Removed excess whitespace in help +- Fixed error reporting, when parcer with subcommands + called with empty arguments + +### Added +- Added basic tests + + +## [0.1.1] - 2012-05-23 +### Fixed +- Fixed line wrapping in help formatter +- Added better error reporting on invalid arguments + + +## [0.1.0] - 2012-05-16 +### Added +- First release. + + +[2.0.1]: https://github.com/nodeca/argparse/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/nodeca/argparse/compare/1.0.10...2.0.0 +[1.0.10]: https://github.com/nodeca/argparse/compare/1.0.9...1.0.10 +[1.0.9]: https://github.com/nodeca/argparse/compare/1.0.8...1.0.9 +[1.0.8]: https://github.com/nodeca/argparse/compare/1.0.7...1.0.8 +[1.0.7]: https://github.com/nodeca/argparse/compare/1.0.6...1.0.7 +[1.0.6]: https://github.com/nodeca/argparse/compare/1.0.5...1.0.6 +[1.0.5]: https://github.com/nodeca/argparse/compare/1.0.4...1.0.5 +[1.0.4]: https://github.com/nodeca/argparse/compare/1.0.3...1.0.4 +[1.0.3]: https://github.com/nodeca/argparse/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/argparse/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/argparse/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/argparse/compare/0.1.16...1.0.0 +[0.1.16]: https://github.com/nodeca/argparse/compare/0.1.15...0.1.16 +[0.1.15]: https://github.com/nodeca/argparse/compare/0.1.14...0.1.15 +[0.1.14]: https://github.com/nodeca/argparse/compare/0.1.13...0.1.14 +[0.1.13]: https://github.com/nodeca/argparse/compare/0.1.12...0.1.13 +[0.1.12]: https://github.com/nodeca/argparse/compare/0.1.11...0.1.12 +[0.1.11]: https://github.com/nodeca/argparse/compare/0.1.10...0.1.11 +[0.1.10]: https://github.com/nodeca/argparse/compare/0.1.9...0.1.10 +[0.1.9]: https://github.com/nodeca/argparse/compare/0.1.8...0.1.9 +[0.1.8]: https://github.com/nodeca/argparse/compare/0.1.7...0.1.8 +[0.1.7]: https://github.com/nodeca/argparse/compare/0.1.6...0.1.7 +[0.1.6]: https://github.com/nodeca/argparse/compare/0.1.5...0.1.6 +[0.1.5]: https://github.com/nodeca/argparse/compare/0.1.4...0.1.5 +[0.1.4]: https://github.com/nodeca/argparse/compare/0.1.3...0.1.4 +[0.1.3]: https://github.com/nodeca/argparse/compare/0.1.2...0.1.3 +[0.1.2]: https://github.com/nodeca/argparse/compare/0.1.1...0.1.2 +[0.1.1]: https://github.com/nodeca/argparse/compare/0.1.0...0.1.1 +[0.1.0]: https://github.com/nodeca/argparse/releases/tag/0.1.0 diff --git a/node_modules/lv_font_conv/node_modules/argparse/LICENSE b/node_modules/lv_font_conv/node_modules/argparse/LICENSE new file mode 100644 index 00000000..66a3ac80 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/argparse/LICENSE @@ -0,0 +1,254 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see http://www.opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the Internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the Internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/argparse/README.md b/node_modules/lv_font_conv/node_modules/argparse/README.md new file mode 100644 index 00000000..550b5c9b --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/argparse/README.md @@ -0,0 +1,84 @@ +argparse +======== + +[![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) +[![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) + +CLI arguments parser for node.js, with [sub-commands](https://docs.python.org/3.9/library/argparse.html#sub-commands) support. Port of python's [argparse](http://docs.python.org/dev/library/argparse.html) (version [3.9.0](https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py)). + +**Difference with original.** + +- JS has no keyword arguments support. + - Pass options instead: `new ArgumentParser({ description: 'example', add_help: true })`. +- JS has no python's types `int`, `float`, ... + - Use string-typed names: `.add_argument('-b', { type: 'int', help: 'help' })`. +- `%r` format specifier uses `require('util').inspect()`. + +More details in [doc](./doc). + + +Example +------- + +`test.js` file: + +```javascript +#!/usr/bin/env node +'use strict'; + +const { ArgumentParser } = require('argparse'); +const { version } = require('./package.json'); + +const parser = new ArgumentParser({ + description: 'Argparse example' +}); + +parser.add_argument('-v', '--version', { action: 'version', version }); +parser.add_argument('-f', '--foo', { help: 'foo bar' }); +parser.add_argument('-b', '--bar', { help: 'bar foo' }); +parser.add_argument('--baz', { help: 'baz bar' }); + +console.dir(parser.parse_args()); +``` + +Display help: + +``` +$ ./test.js -h +usage: test.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] + +Argparse example + +optional arguments: + -h, --help show this help message and exit + -v, --version show program's version number and exit + -f FOO, --foo FOO foo bar + -b BAR, --bar BAR bar foo + --baz BAZ baz bar +``` + +Parse arguments: + +``` +$ ./test.js -f=3 --bar=4 --baz 5 +{ foo: '3', bar: '4', baz: '5' } +``` + + +API docs +-------- + +Since this is a port with minimal divergence, there's no separate documentation. +Use original one instead, with notes about difference. + +1. [Original doc](https://docs.python.org/3.9/library/argparse.html). +2. [Original tutorial](https://docs.python.org/3.9/howto/argparse.html). +3. [Difference with python](./doc). + + +argparse for enterprise +----------------------- + +Available as part of the Tidelift Subscription + +The maintainers of argparse and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-argparse?utm_source=npm-argparse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/lv_font_conv/node_modules/argparse/argparse.js b/node_modules/lv_font_conv/node_modules/argparse/argparse.js new file mode 100644 index 00000000..2b8c8c63 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/argparse/argparse.js @@ -0,0 +1,3707 @@ +// Port of python's argparse module, version 3.9.0: +// https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py + +'use strict' + +// Copyright (C) 2010-2020 Python Software Foundation. +// Copyright (C) 2020 argparse.js authors + +/* + * Command-line parsing library + * + * This module is an optparse-inspired command-line parsing library that: + * + * - handles both optional and positional arguments + * - produces highly informative usage messages + * - supports parsers that dispatch to sub-parsers + * + * The following is a simple usage example that sums integers from the + * command-line and writes the result to a file:: + * + * parser = argparse.ArgumentParser( + * description='sum the integers at the command line') + * parser.add_argument( + * 'integers', metavar='int', nargs='+', type=int, + * help='an integer to be summed') + * parser.add_argument( + * '--log', default=sys.stdout, type=argparse.FileType('w'), + * help='the file where the sum should be written') + * args = parser.parse_args() + * args.log.write('%s' % sum(args.integers)) + * args.log.close() + * + * The module contains the following public classes: + * + * - ArgumentParser -- The main entry point for command-line parsing. As the + * example above shows, the add_argument() method is used to populate + * the parser with actions for optional and positional arguments. Then + * the parse_args() method is invoked to convert the args at the + * command-line into an object with attributes. + * + * - ArgumentError -- The exception raised by ArgumentParser objects when + * there are errors with the parser's actions. Errors raised while + * parsing the command-line are caught by ArgumentParser and emitted + * as command-line messages. + * + * - FileType -- A factory for defining types of files to be created. As the + * example above shows, instances of FileType are typically passed as + * the type= argument of add_argument() calls. + * + * - Action -- The base class for parser actions. Typically actions are + * selected by passing strings like 'store_true' or 'append_const' to + * the action= argument of add_argument(). However, for greater + * customization of ArgumentParser actions, subclasses of Action may + * be defined and passed as the action= argument. + * + * - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, + * ArgumentDefaultsHelpFormatter -- Formatter classes which + * may be passed as the formatter_class= argument to the + * ArgumentParser constructor. HelpFormatter is the default, + * RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser + * not to change the formatting for help text, and + * ArgumentDefaultsHelpFormatter adds information about argument defaults + * to the help. + * + * All other classes in this module are considered implementation details. + * (Also note that HelpFormatter and RawDescriptionHelpFormatter are only + * considered public as object names -- the API of the formatter objects is + * still considered an implementation detail.) + */ + +const SUPPRESS = '==SUPPRESS==' + +const OPTIONAL = '?' +const ZERO_OR_MORE = '*' +const ONE_OR_MORE = '+' +const PARSER = 'A...' +const REMAINDER = '...' +const _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' + + +// ================================== +// Utility functions used for porting +// ================================== +const assert = require('assert') +const util = require('util') +const fs = require('fs') +const sub = require('./lib/sub') +const path = require('path') +const repr = util.inspect + +function get_argv() { + // omit first argument (which is assumed to be interpreter - `node`, `coffee`, `ts-node`, etc.) + return process.argv.slice(1) +} + +function get_terminal_size() { + return { + columns: +process.env.COLUMNS || process.stdout.columns || 80 + } +} + +function hasattr(object, name) { + return Object.prototype.hasOwnProperty.call(object, name) +} + +function getattr(object, name, value) { + return hasattr(object, name) ? object[name] : value +} + +function setattr(object, name, value) { + object[name] = value +} + +function setdefault(object, name, value) { + if (!hasattr(object, name)) object[name] = value + return object[name] +} + +function delattr(object, name) { + delete object[name] +} + +function range(from, to, step=1) { + // range(10) is equivalent to range(0, 10) + if (arguments.length === 1) [ to, from ] = [ from, 0 ] + if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') { + throw new TypeError('argument cannot be interpreted as an integer') + } + if (step === 0) throw new TypeError('range() arg 3 must not be zero') + + let result = [] + if (step > 0) { + for (let i = from; i < to; i += step) result.push(i) + } else { + for (let i = from; i > to; i += step) result.push(i) + } + return result +} + +function splitlines(str, keepends = false) { + let result + if (!keepends) { + result = str.split(/\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]/) + } else { + result = [] + let parts = str.split(/(\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029])/) + for (let i = 0; i < parts.length; i += 2) { + result.push(parts[i] + (i + 1 < parts.length ? parts[i + 1] : '')) + } + } + if (!result[result.length - 1]) result.pop() + return result +} + +function _string_lstrip(string, prefix_chars) { + let idx = 0 + while (idx < string.length && prefix_chars.includes(string[idx])) idx++ + return idx ? string.slice(idx) : string +} + +function _string_split(string, sep, maxsplit) { + let result = string.split(sep) + if (result.length > maxsplit) { + result = result.slice(0, maxsplit).concat([ result.slice(maxsplit).join(sep) ]) + } + return result +} + +function _array_equal(array1, array2) { + if (array1.length !== array2.length) return false + for (let i = 0; i < array1.length; i++) { + if (array1[i] !== array2[i]) return false + } + return true +} + +function _array_remove(array, item) { + let idx = array.indexOf(item) + if (idx === -1) throw new TypeError(sub('%r not in list', item)) + array.splice(idx, 1) +} + +// normalize choices to array; +// this isn't required in python because `in` and `map` operators work with anything, +// but in js dealing with multiple types here is too clunky +function _choices_to_array(choices) { + if (choices === undefined) { + return [] + } else if (Array.isArray(choices)) { + return choices + } else if (choices !== null && typeof choices[Symbol.iterator] === 'function') { + return Array.from(choices) + } else if (typeof choices === 'object' && choices !== null) { + return Object.keys(choices) + } else { + throw new Error(sub('invalid choices value: %r', choices)) + } +} + +// decorator that allows a class to be called without new +function _callable(cls) { + let result = { // object is needed for inferred class name + [cls.name]: function (...args) { + let this_class = new.target === result || !new.target + return Reflect.construct(cls, args, this_class ? cls : new.target) + } + } + result[cls.name].prototype = cls.prototype + // fix default tag for toString, e.g. [object Action] instead of [object Object] + cls.prototype[Symbol.toStringTag] = cls.name + return result[cls.name] +} + +function _alias(object, from, to) { + try { + let name = object.constructor.name + Object.defineProperty(object, from, { + value: util.deprecate(object[to], sub('%s.%s() is renamed to %s.%s()', + name, from, name, to)), + enumerable: false + }) + } catch {} +} + +// decorator that allows snake_case class methods to be called with camelCase and vice versa +function _camelcase_alias(_class) { + for (let name of Object.getOwnPropertyNames(_class.prototype)) { + let camelcase = name.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) + if (camelcase !== name) _alias(_class.prototype, camelcase, name) + } + return _class +} + +function _to_legacy_name(key) { + key = key.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) + if (key === 'default') key = 'defaultValue' + if (key === 'const') key = 'constant' + return key +} + +function _to_new_name(key) { + if (key === 'defaultValue') key = 'default' + if (key === 'constant') key = 'const' + key = key.replace(/[A-Z]/g, c => '_' + c.toLowerCase()) + return key +} + +// parse options +let no_default = Symbol('no_default_value') +function _parse_opts(args, descriptor) { + function get_name() { + let stack = new Error().stack.split('\n') + .map(x => x.match(/^ at (.*) \(.*\)$/)) + .filter(Boolean) + .map(m => m[1]) + .map(fn => fn.match(/[^ .]*$/)[0]) + + if (stack.length && stack[0] === get_name.name) stack.shift() + if (stack.length && stack[0] === _parse_opts.name) stack.shift() + return stack.length ? stack[0] : '' + } + + args = Array.from(args) + let kwargs = {} + let result = [] + let last_opt = args.length && args[args.length - 1] + + if (typeof last_opt === 'object' && last_opt !== null && !Array.isArray(last_opt) && + (!last_opt.constructor || last_opt.constructor.name === 'Object')) { + kwargs = Object.assign({}, args.pop()) + } + + // LEGACY (v1 compatibility): camelcase + let renames = [] + for (let key of Object.keys(descriptor)) { + let old_name = _to_legacy_name(key) + if (old_name !== key && (old_name in kwargs)) { + if (key in kwargs) { + // default and defaultValue specified at the same time, happens often in old tests + //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) + } else { + kwargs[key] = kwargs[old_name] + } + renames.push([ old_name, key ]) + delete kwargs[old_name] + } + } + if (renames.length) { + let name = get_name() + deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', + name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) + } + // end + + let missing_positionals = [] + let positional_count = args.length + + for (let [ key, def ] of Object.entries(descriptor)) { + if (key[0] === '*') { + if (key.length > 0 && key[1] === '*') { + // LEGACY (v1 compatibility): camelcase + let renames = [] + for (let key of Object.keys(kwargs)) { + let new_name = _to_new_name(key) + if (new_name !== key && (key in kwargs)) { + if (new_name in kwargs) { + // default and defaultValue specified at the same time, happens often in old tests + //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), new_name)) + } else { + kwargs[new_name] = kwargs[key] + } + renames.push([ key, new_name ]) + delete kwargs[key] + } + } + if (renames.length) { + let name = get_name() + deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', + name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) + } + // end + result.push(kwargs) + kwargs = {} + } else { + result.push(args) + args = [] + } + } else if (key in kwargs && args.length > 0) { + throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) + } else if (key in kwargs) { + result.push(kwargs[key]) + delete kwargs[key] + } else if (args.length > 0) { + result.push(args.shift()) + } else if (def !== no_default) { + result.push(def) + } else { + missing_positionals.push(key) + } + } + + if (Object.keys(kwargs).length) { + throw new TypeError(sub('%s() got an unexpected keyword argument %r', + get_name(), Object.keys(kwargs)[0])) + } + + if (args.length) { + let from = Object.entries(descriptor).filter(([ k, v ]) => k[0] !== '*' && v !== no_default).length + let to = Object.entries(descriptor).filter(([ k ]) => k[0] !== '*').length + throw new TypeError(sub('%s() takes %s positional argument%s but %s %s given', + get_name(), + from === to ? sub('from %s to %s', from, to) : to, + from === to && to === 1 ? '' : 's', + positional_count, + positional_count === 1 ? 'was' : 'were')) + } + + if (missing_positionals.length) { + let strs = missing_positionals.map(repr) + if (strs.length > 1) strs[strs.length - 1] = 'and ' + strs[strs.length - 1] + let str_joined = strs.join(strs.length === 2 ? '' : ', ') + throw new TypeError(sub('%s() missing %i required positional argument%s: %s', + get_name(), strs.length, strs.length === 1 ? '' : 's', str_joined)) + } + + return result +} + +let _deprecations = {} +function deprecate(id, string) { + _deprecations[id] = _deprecations[id] || util.deprecate(() => {}, string) + _deprecations[id]() +} + + +// ============================= +// Utility functions and classes +// ============================= +function _AttributeHolder(cls = Object) { + /* + * Abstract base class that provides __repr__. + * + * The __repr__ method returns a string in the format:: + * ClassName(attr=name, attr=name, ...) + * The attributes are determined either by a class-level attribute, + * '_kwarg_names', or by inspecting the instance __dict__. + */ + + return class _AttributeHolder extends cls { + [util.inspect.custom]() { + let type_name = this.constructor.name + let arg_strings = [] + let star_args = {} + for (let arg of this._get_args()) { + arg_strings.push(repr(arg)) + } + for (let [ name, value ] of this._get_kwargs()) { + if (/^[a-z_][a-z0-9_$]*$/i.test(name)) { + arg_strings.push(sub('%s=%r', name, value)) + } else { + star_args[name] = value + } + } + if (Object.keys(star_args).length) { + arg_strings.push(sub('**%s', repr(star_args))) + } + return sub('%s(%s)', type_name, arg_strings.join(', ')) + } + + toString() { + return this[util.inspect.custom]() + } + + _get_kwargs() { + return Object.entries(this) + } + + _get_args() { + return [] + } + } +} + + +function _copy_items(items) { + if (items === undefined) { + return [] + } + return items.slice(0) +} + + +// =============== +// Formatting Help +// =============== +const HelpFormatter = _camelcase_alias(_callable(class HelpFormatter { + /* + * Formatter for generating usage messages and argument help strings. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + constructor() { + let [ + prog, + indent_increment, + max_help_position, + width + ] = _parse_opts(arguments, { + prog: no_default, + indent_increment: 2, + max_help_position: 24, + width: undefined + }) + + // default setting for width + if (width === undefined) { + width = get_terminal_size().columns + width -= 2 + } + + this._prog = prog + this._indent_increment = indent_increment + this._max_help_position = Math.min(max_help_position, + Math.max(width - 20, indent_increment * 2)) + this._width = width + + this._current_indent = 0 + this._level = 0 + this._action_max_length = 0 + + this._root_section = this._Section(this, undefined) + this._current_section = this._root_section + + this._whitespace_matcher = /[ \t\n\r\f\v]+/g // equivalent to python /\s+/ with ASCII flag + this._long_break_matcher = /\n\n\n+/g + } + + // =============================== + // Section and indentation methods + // =============================== + _indent() { + this._current_indent += this._indent_increment + this._level += 1 + } + + _dedent() { + this._current_indent -= this._indent_increment + assert(this._current_indent >= 0, 'Indent decreased below 0.') + this._level -= 1 + } + + _add_item(func, args) { + this._current_section.items.push([ func, args ]) + } + + // ======================== + // Message building methods + // ======================== + start_section(heading) { + this._indent() + let section = this._Section(this, this._current_section, heading) + this._add_item(section.format_help.bind(section), []) + this._current_section = section + } + + end_section() { + this._current_section = this._current_section.parent + this._dedent() + } + + add_text(text) { + if (text !== SUPPRESS && text !== undefined) { + this._add_item(this._format_text.bind(this), [text]) + } + } + + add_usage(usage, actions, groups, prefix = undefined) { + if (usage !== SUPPRESS) { + let args = [ usage, actions, groups, prefix ] + this._add_item(this._format_usage.bind(this), args) + } + } + + add_argument(action) { + if (action.help !== SUPPRESS) { + + // find all invocations + let invocations = [this._format_action_invocation(action)] + for (let subaction of this._iter_indented_subactions(action)) { + invocations.push(this._format_action_invocation(subaction)) + } + + // update the maximum item length + let invocation_length = Math.max(...invocations.map(invocation => invocation.length)) + let action_length = invocation_length + this._current_indent + this._action_max_length = Math.max(this._action_max_length, + action_length) + + // add the item to the list + this._add_item(this._format_action.bind(this), [action]) + } + } + + add_arguments(actions) { + for (let action of actions) { + this.add_argument(action) + } + } + + // ======================= + // Help-formatting methods + // ======================= + format_help() { + let help = this._root_section.format_help() + if (help) { + help = help.replace(this._long_break_matcher, '\n\n') + help = help.replace(/^\n+|\n+$/g, '') + '\n' + } + return help + } + + _join_parts(part_strings) { + return part_strings.filter(part => part && part !== SUPPRESS).join('') + } + + _format_usage(usage, actions, groups, prefix) { + if (prefix === undefined) { + prefix = 'usage: ' + } + + // if usage is specified, use that + if (usage !== undefined) { + usage = sub(usage, { prog: this._prog }) + + // if no optionals or positionals are available, usage is just prog + } else if (usage === undefined && !actions.length) { + usage = sub('%(prog)s', { prog: this._prog }) + + // if optionals and positionals are available, calculate usage + } else if (usage === undefined) { + let prog = sub('%(prog)s', { prog: this._prog }) + + // split optionals from positionals + let optionals = [] + let positionals = [] + for (let action of actions) { + if (action.option_strings.length) { + optionals.push(action) + } else { + positionals.push(action) + } + } + + // build full usage string + let action_usage = this._format_actions_usage([].concat(optionals).concat(positionals), groups) + usage = [ prog, action_usage ].map(String).join(' ') + + // wrap the usage parts if it's too long + let text_width = this._width - this._current_indent + if (prefix.length + usage.length > text_width) { + + // break usage into wrappable parts + let part_regexp = /\(.*?\)+(?=\s|$)|\[.*?\]+(?=\s|$)|\S+/g + let opt_usage = this._format_actions_usage(optionals, groups) + let pos_usage = this._format_actions_usage(positionals, groups) + let opt_parts = opt_usage.match(part_regexp) || [] + let pos_parts = pos_usage.match(part_regexp) || [] + assert(opt_parts.join(' ') === opt_usage) + assert(pos_parts.join(' ') === pos_usage) + + // helper for wrapping lines + let get_lines = (parts, indent, prefix = undefined) => { + let lines = [] + let line = [] + let line_len + if (prefix !== undefined) { + line_len = prefix.length - 1 + } else { + line_len = indent.length - 1 + } + for (let part of parts) { + if (line_len + 1 + part.length > text_width && line) { + lines.push(indent + line.join(' ')) + line = [] + line_len = indent.length - 1 + } + line.push(part) + line_len += part.length + 1 + } + if (line.length) { + lines.push(indent + line.join(' ')) + } + if (prefix !== undefined) { + lines[0] = lines[0].slice(indent.length) + } + return lines + } + + let lines + + // if prog is short, follow it with optionals or positionals + if (prefix.length + prog.length <= 0.75 * text_width) { + let indent = ' '.repeat(prefix.length + prog.length + 1) + if (opt_parts.length) { + lines = get_lines([prog].concat(opt_parts), indent, prefix) + lines = lines.concat(get_lines(pos_parts, indent)) + } else if (pos_parts.length) { + lines = get_lines([prog].concat(pos_parts), indent, prefix) + } else { + lines = [prog] + } + + // if prog is long, put it on its own line + } else { + let indent = ' '.repeat(prefix.length) + let parts = [].concat(opt_parts).concat(pos_parts) + lines = get_lines(parts, indent) + if (lines.length > 1) { + lines = [] + lines = lines.concat(get_lines(opt_parts, indent)) + lines = lines.concat(get_lines(pos_parts, indent)) + } + lines = [prog].concat(lines) + } + + // join lines into usage + usage = lines.join('\n') + } + } + + // prefix with 'usage:' + return sub('%s%s\n\n', prefix, usage) + } + + _format_actions_usage(actions, groups) { + // find group indices and identify actions in groups + let group_actions = new Set() + let inserts = {} + for (let group of groups) { + let start = actions.indexOf(group._group_actions[0]) + if (start === -1) { + continue + } else { + let end = start + group._group_actions.length + if (_array_equal(actions.slice(start, end), group._group_actions)) { + for (let action of group._group_actions) { + group_actions.add(action) + } + if (!group.required) { + if (start in inserts) { + inserts[start] += ' [' + } else { + inserts[start] = '[' + } + if (end in inserts) { + inserts[end] += ']' + } else { + inserts[end] = ']' + } + } else { + if (start in inserts) { + inserts[start] += ' (' + } else { + inserts[start] = '(' + } + if (end in inserts) { + inserts[end] += ')' + } else { + inserts[end] = ')' + } + } + for (let i of range(start + 1, end)) { + inserts[i] = '|' + } + } + } + } + + // collect all actions format strings + let parts = [] + for (let [ i, action ] of Object.entries(actions)) { + + // suppressed arguments are marked with None + // remove | separators for suppressed arguments + if (action.help === SUPPRESS) { + parts.push(undefined) + if (inserts[+i] === '|') { + delete inserts[+i] + } else if (inserts[+i + 1] === '|') { + delete inserts[+i + 1] + } + + // produce all arg strings + } else if (!action.option_strings.length) { + let default_value = this._get_default_metavar_for_positional(action) + let part = this._format_args(action, default_value) + + // if it's in a group, strip the outer [] + if (group_actions.has(action)) { + if (part[0] === '[' && part[part.length - 1] === ']') { + part = part.slice(1, -1) + } + } + + // add the action string to the list + parts.push(part) + + // produce the first way to invoke the option in brackets + } else { + let option_string = action.option_strings[0] + let part + + // if the Optional doesn't take a value, format is: + // -s or --long + if (action.nargs === 0) { + part = action.format_usage() + + // if the Optional takes a value, format is: + // -s ARGS or --long ARGS + } else { + let default_value = this._get_default_metavar_for_optional(action) + let args_string = this._format_args(action, default_value) + part = sub('%s %s', option_string, args_string) + } + + // make it look optional if it's not required or in a group + if (!action.required && !group_actions.has(action)) { + part = sub('[%s]', part) + } + + // add the action string to the list + parts.push(part) + } + } + + // insert things at the necessary indices + for (let i of Object.keys(inserts).map(Number).sort((a, b) => b - a)) { + parts.splice(+i, 0, inserts[+i]) + } + + // join all the action items with spaces + let text = parts.filter(Boolean).join(' ') + + // clean up separators for mutually exclusive groups + text = text.replace(/([\[(]) /g, '$1') + text = text.replace(/ ([\])])/g, '$1') + text = text.replace(/[\[(] *[\])]/g, '') + text = text.replace(/\(([^|]*)\)/g, '$1', text) + text = text.trim() + + // return the text + return text + } + + _format_text(text) { + if (text.includes('%(prog)')) { + text = sub(text, { prog: this._prog }) + } + let text_width = Math.max(this._width - this._current_indent, 11) + let indent = ' '.repeat(this._current_indent) + return this._fill_text(text, text_width, indent) + '\n\n' + } + + _format_action(action) { + // determine the required width and the entry label + let help_position = Math.min(this._action_max_length + 2, + this._max_help_position) + let help_width = Math.max(this._width - help_position, 11) + let action_width = help_position - this._current_indent - 2 + let action_header = this._format_action_invocation(action) + let indent_first + + // no help; start on same line and add a final newline + if (!action.help) { + let tup = [ this._current_indent, '', action_header ] + action_header = sub('%*s%s\n', ...tup) + + // short action name; start on the same line and pad two spaces + } else if (action_header.length <= action_width) { + let tup = [ this._current_indent, '', action_width, action_header ] + action_header = sub('%*s%-*s ', ...tup) + indent_first = 0 + + // long action name; start on the next line + } else { + let tup = [ this._current_indent, '', action_header ] + action_header = sub('%*s%s\n', ...tup) + indent_first = help_position + } + + // collect the pieces of the action help + let parts = [action_header] + + // if there was help for the action, add lines of help text + if (action.help) { + let help_text = this._expand_help(action) + let help_lines = this._split_lines(help_text, help_width) + parts.push(sub('%*s%s\n', indent_first, '', help_lines[0])) + for (let line of help_lines.slice(1)) { + parts.push(sub('%*s%s\n', help_position, '', line)) + } + + // or add a newline if the description doesn't end with one + } else if (!action_header.endsWith('\n')) { + parts.push('\n') + } + + // if there are any sub-actions, add their help as well + for (let subaction of this._iter_indented_subactions(action)) { + parts.push(this._format_action(subaction)) + } + + // return a single string + return this._join_parts(parts) + } + + _format_action_invocation(action) { + if (!action.option_strings.length) { + let default_value = this._get_default_metavar_for_positional(action) + let metavar = this._metavar_formatter(action, default_value)(1)[0] + return metavar + + } else { + let parts = [] + + // if the Optional doesn't take a value, format is: + // -s, --long + if (action.nargs === 0) { + parts = parts.concat(action.option_strings) + + // if the Optional takes a value, format is: + // -s ARGS, --long ARGS + } else { + let default_value = this._get_default_metavar_for_optional(action) + let args_string = this._format_args(action, default_value) + for (let option_string of action.option_strings) { + parts.push(sub('%s %s', option_string, args_string)) + } + } + + return parts.join(', ') + } + } + + _metavar_formatter(action, default_metavar) { + let result + if (action.metavar !== undefined) { + result = action.metavar + } else if (action.choices !== undefined) { + let choice_strs = _choices_to_array(action.choices).map(String) + result = sub('{%s}', choice_strs.join(',')) + } else { + result = default_metavar + } + + function format(tuple_size) { + if (Array.isArray(result)) { + return result + } else { + return Array(tuple_size).fill(result) + } + } + return format + } + + _format_args(action, default_metavar) { + let get_metavar = this._metavar_formatter(action, default_metavar) + let result + if (action.nargs === undefined) { + result = sub('%s', ...get_metavar(1)) + } else if (action.nargs === OPTIONAL) { + result = sub('[%s]', ...get_metavar(1)) + } else if (action.nargs === ZERO_OR_MORE) { + let metavar = get_metavar(1) + if (metavar.length === 2) { + result = sub('[%s [%s ...]]', ...metavar) + } else { + result = sub('[%s ...]', ...metavar) + } + } else if (action.nargs === ONE_OR_MORE) { + result = sub('%s [%s ...]', ...get_metavar(2)) + } else if (action.nargs === REMAINDER) { + result = '...' + } else if (action.nargs === PARSER) { + result = sub('%s ...', ...get_metavar(1)) + } else if (action.nargs === SUPPRESS) { + result = '' + } else { + let formats + try { + formats = range(action.nargs).map(() => '%s') + } catch (err) { + throw new TypeError('invalid nargs value') + } + result = sub(formats.join(' '), ...get_metavar(action.nargs)) + } + return result + } + + _expand_help(action) { + let params = Object.assign({ prog: this._prog }, action) + for (let name of Object.keys(params)) { + if (params[name] === SUPPRESS) { + delete params[name] + } + } + for (let name of Object.keys(params)) { + if (params[name] && params[name].name) { + params[name] = params[name].name + } + } + if (params.choices !== undefined) { + let choices_str = _choices_to_array(params.choices).map(String).join(', ') + params.choices = choices_str + } + // LEGACY (v1 compatibility): camelcase + for (let key of Object.keys(params)) { + let old_name = _to_legacy_name(key) + if (old_name !== key) { + params[old_name] = params[key] + } + } + // end + return sub(this._get_help_string(action), params) + } + + * _iter_indented_subactions(action) { + if (typeof action._get_subactions === 'function') { + this._indent() + yield* action._get_subactions() + this._dedent() + } + } + + _split_lines(text, width) { + text = text.replace(this._whitespace_matcher, ' ').trim() + // The textwrap module is used only for formatting help. + // Delay its import for speeding up the common usage of argparse. + let textwrap = require('./lib/textwrap') + return textwrap.wrap(text, { width }) + } + + _fill_text(text, width, indent) { + text = text.replace(this._whitespace_matcher, ' ').trim() + let textwrap = require('./lib/textwrap') + return textwrap.fill(text, { width, + initial_indent: indent, + subsequent_indent: indent }) + } + + _get_help_string(action) { + return action.help + } + + _get_default_metavar_for_optional(action) { + return action.dest.toUpperCase() + } + + _get_default_metavar_for_positional(action) { + return action.dest + } +})) + +HelpFormatter.prototype._Section = _callable(class _Section { + + constructor(formatter, parent, heading = undefined) { + this.formatter = formatter + this.parent = parent + this.heading = heading + this.items = [] + } + + format_help() { + // format the indented section + if (this.parent !== undefined) { + this.formatter._indent() + } + let item_help = this.formatter._join_parts(this.items.map(([ func, args ]) => func.apply(null, args))) + if (this.parent !== undefined) { + this.formatter._dedent() + } + + // return nothing if the section was empty + if (!item_help) { + return '' + } + + // add the heading if the section was non-empty + let heading + if (this.heading !== SUPPRESS && this.heading !== undefined) { + let current_indent = this.formatter._current_indent + heading = sub('%*s%s:\n', current_indent, '', this.heading) + } else { + heading = '' + } + + // join the section-initial newline, the heading and the help + return this.formatter._join_parts(['\n', heading, item_help, '\n']) + } +}) + + +const RawDescriptionHelpFormatter = _camelcase_alias(_callable(class RawDescriptionHelpFormatter extends HelpFormatter { + /* + * Help message formatter which retains any formatting in descriptions. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _fill_text(text, width, indent) { + return splitlines(text, true).map(line => indent + line).join('') + } +})) + + +const RawTextHelpFormatter = _camelcase_alias(_callable(class RawTextHelpFormatter extends RawDescriptionHelpFormatter { + /* + * Help message formatter which retains formatting of all help text. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _split_lines(text/*, width*/) { + return splitlines(text) + } +})) + + +const ArgumentDefaultsHelpFormatter = _camelcase_alias(_callable(class ArgumentDefaultsHelpFormatter extends HelpFormatter { + /* + * Help message formatter which adds default values to argument help. + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _get_help_string(action) { + let help = action.help + // LEGACY (v1 compatibility): additional check for defaultValue needed + if (!action.help.includes('%(default)') && !action.help.includes('%(defaultValue)')) { + if (action.default !== SUPPRESS) { + let defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] + if (action.option_strings.length || defaulting_nargs.includes(action.nargs)) { + help += ' (default: %(default)s)' + } + } + } + return help + } +})) + + +const MetavarTypeHelpFormatter = _camelcase_alias(_callable(class MetavarTypeHelpFormatter extends HelpFormatter { + /* + * Help message formatter which uses the argument 'type' as the default + * metavar value (instead of the argument 'dest') + * + * Only the name of this class is considered a public API. All the methods + * provided by the class are considered an implementation detail. + */ + + _get_default_metavar_for_optional(action) { + return typeof action.type === 'function' ? action.type.name : action.type + } + + _get_default_metavar_for_positional(action) { + return typeof action.type === 'function' ? action.type.name : action.type + } +})) + + +// ===================== +// Options and Arguments +// ===================== +function _get_action_name(argument) { + if (argument === undefined) { + return undefined + } else if (argument.option_strings.length) { + return argument.option_strings.join('/') + } else if (![ undefined, SUPPRESS ].includes(argument.metavar)) { + return argument.metavar + } else if (![ undefined, SUPPRESS ].includes(argument.dest)) { + return argument.dest + } else { + return undefined + } +} + + +const ArgumentError = _callable(class ArgumentError extends Error { + /* + * An error from creating or using an argument (optional or positional). + * + * The string value of this exception is the message, augmented with + * information about the argument that caused it. + */ + + constructor(argument, message) { + super() + this.name = 'ArgumentError' + this._argument_name = _get_action_name(argument) + this._message = message + this.message = this.str() + } + + str() { + let format + if (this._argument_name === undefined) { + format = '%(message)s' + } else { + format = 'argument %(argument_name)s: %(message)s' + } + return sub(format, { message: this._message, + argument_name: this._argument_name }) + } +}) + + +const ArgumentTypeError = _callable(class ArgumentTypeError extends Error { + /* + * An error from trying to convert a command line string to a type. + */ + + constructor(message) { + super(message) + this.name = 'ArgumentTypeError' + } +}) + + +// ============== +// Action classes +// ============== +const Action = _camelcase_alias(_callable(class Action extends _AttributeHolder(Function) { + /* + * Information about how to convert command line strings to Python objects. + * + * Action objects are used by an ArgumentParser to represent the information + * needed to parse a single argument from one or more strings from the + * command line. The keyword arguments to the Action constructor are also + * all attributes of Action instances. + * + * Keyword Arguments: + * + * - option_strings -- A list of command-line option strings which + * should be associated with this action. + * + * - dest -- The name of the attribute to hold the created object(s) + * + * - nargs -- The number of command-line arguments that should be + * consumed. By default, one argument will be consumed and a single + * value will be produced. Other values include: + * - N (an integer) consumes N arguments (and produces a list) + * - '?' consumes zero or one arguments + * - '*' consumes zero or more arguments (and produces a list) + * - '+' consumes one or more arguments (and produces a list) + * Note that the difference between the default and nargs=1 is that + * with the default, a single value will be produced, while with + * nargs=1, a list containing a single value will be produced. + * + * - const -- The value to be produced if the option is specified and the + * option uses an action that takes no values. + * + * - default -- The value to be produced if the option is not specified. + * + * - type -- A callable that accepts a single string argument, and + * returns the converted value. The standard Python types str, int, + * float, and complex are useful examples of such callables. If None, + * str is used. + * + * - choices -- A container of values that should be allowed. If not None, + * after a command-line argument has been converted to the appropriate + * type, an exception will be raised if it is not a member of this + * collection. + * + * - required -- True if the action must always be specified at the + * command line. This is only meaningful for optional command-line + * arguments. + * + * - help -- The help string describing the argument. + * + * - metavar -- The name to be used for the option's argument with the + * help string. If None, the 'dest' value will be used as the name. + */ + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + // when this class is called as a function, redirect it to .call() method of itself + super('return arguments.callee.call.apply(arguments.callee, arguments)') + + this.option_strings = option_strings + this.dest = dest + this.nargs = nargs + this.const = const_value + this.default = default_value + this.type = type + this.choices = choices + this.required = required + this.help = help + this.metavar = metavar + } + + _get_kwargs() { + let names = [ + 'option_strings', + 'dest', + 'nargs', + 'const', + 'default', + 'type', + 'choices', + 'help', + 'metavar' + ] + return names.map(name => [ name, getattr(this, name) ]) + } + + format_usage() { + return this.option_strings[0] + } + + call(/*parser, namespace, values, option_string = undefined*/) { + throw new Error('.call() not defined') + } +})) + + +const BooleanOptionalAction = _camelcase_alias(_callable(class BooleanOptionalAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + let _option_strings = [] + for (let option_string of option_strings) { + _option_strings.push(option_string) + + if (option_string.startsWith('--')) { + option_string = '--no-' + option_string.slice(2) + _option_strings.push(option_string) + } + } + + if (help !== undefined && default_value !== undefined) { + help += ` (default: ${default_value})` + } + + super({ + option_strings: _option_strings, + dest, + nargs: 0, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values, option_string = undefined) { + if (this.option_strings.includes(option_string)) { + setattr(namespace, this.dest, !option_string.startsWith('--no-')) + } + } + + format_usage() { + return this.option_strings.join(' | ') + } +})) + + +const _StoreAction = _callable(class _StoreAction extends Action { + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + if (nargs === 0) { + throw new TypeError('nargs for store actions must be != 0; if you ' + + 'have nothing to store, actions such as store ' + + 'true or store const may be more appropriate') + } + if (const_value !== undefined && nargs !== OPTIONAL) { + throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) + } + super({ + option_strings, + dest, + nargs, + const: const_value, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values/*, option_string = undefined*/) { + setattr(namespace, this.dest, values) + } +}) + + +const _StoreConstAction = _callable(class _StoreConstAction extends Action { + + constructor() { + let [ + option_strings, + dest, + const_value, + default_value, + required, + help + //, metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + const: no_default, + default: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + const: const_value, + default: default_value, + required, + help + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + setattr(namespace, this.dest, this.const) + } +}) + + +const _StoreTrueAction = _callable(class _StoreTrueAction extends _StoreConstAction { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: false, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + const: true, + default: default_value, + required, + help + }) + } +}) + + +const _StoreFalseAction = _callable(class _StoreFalseAction extends _StoreConstAction { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: true, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + const: false, + default: default_value, + required, + help + }) + } +}) + + +const _AppendAction = _callable(class _AppendAction extends Action { + + constructor() { + let [ + option_strings, + dest, + nargs, + const_value, + default_value, + type, + choices, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + nargs: undefined, + const: undefined, + default: undefined, + type: undefined, + choices: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + if (nargs === 0) { + throw new TypeError('nargs for append actions must be != 0; if arg ' + + 'strings are not supplying the value to append, ' + + 'the append const action may be more appropriate') + } + if (const_value !== undefined && nargs !== OPTIONAL) { + throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) + } + super({ + option_strings, + dest, + nargs, + const: const_value, + default: default_value, + type, + choices, + required, + help, + metavar + }) + } + + call(parser, namespace, values/*, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items.push(values) + setattr(namespace, this.dest, items) + } +}) + + +const _AppendConstAction = _callable(class _AppendConstAction extends Action { + + constructor() { + let [ + option_strings, + dest, + const_value, + default_value, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + const: no_default, + default: undefined, + required: false, + help: undefined, + metavar: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + const: const_value, + default: default_value, + required, + help, + metavar + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items.push(this.const) + setattr(namespace, this.dest, items) + } +}) + + +const _CountAction = _callable(class _CountAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + required, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: no_default, + default: undefined, + required: false, + help: undefined + }) + + super({ + option_strings, + dest, + nargs: 0, + default: default_value, + required, + help + }) + } + + call(parser, namespace/*, values, option_string = undefined*/) { + let count = getattr(namespace, this.dest, undefined) + if (count === undefined) { + count = 0 + } + setattr(namespace, this.dest, count + 1) + } +}) + + +const _HelpAction = _callable(class _HelpAction extends Action { + + constructor() { + let [ + option_strings, + dest, + default_value, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + dest: SUPPRESS, + default: SUPPRESS, + help: undefined + }) + + super({ + option_strings, + dest, + default: default_value, + nargs: 0, + help + }) + } + + call(parser/*, namespace, values, option_string = undefined*/) { + parser.print_help() + parser.exit() + } +}) + + +const _VersionAction = _callable(class _VersionAction extends Action { + + constructor() { + let [ + option_strings, + version, + dest, + default_value, + help + ] = _parse_opts(arguments, { + option_strings: no_default, + version: undefined, + dest: SUPPRESS, + default: SUPPRESS, + help: "show program's version number and exit" + }) + + super({ + option_strings, + dest, + default: default_value, + nargs: 0, + help + }) + this.version = version + } + + call(parser/*, namespace, values, option_string = undefined*/) { + let version = this.version + if (version === undefined) { + version = parser.version + } + let formatter = parser._get_formatter() + formatter.add_text(version) + parser._print_message(formatter.format_help(), process.stdout) + parser.exit() + } +}) + + +const _SubParsersAction = _camelcase_alias(_callable(class _SubParsersAction extends Action { + + constructor() { + let [ + option_strings, + prog, + parser_class, + dest, + required, + help, + metavar + ] = _parse_opts(arguments, { + option_strings: no_default, + prog: no_default, + parser_class: no_default, + dest: SUPPRESS, + required: false, + help: undefined, + metavar: undefined + }) + + let name_parser_map = {} + + super({ + option_strings, + dest, + nargs: PARSER, + choices: name_parser_map, + required, + help, + metavar + }) + + this._prog_prefix = prog + this._parser_class = parser_class + this._name_parser_map = name_parser_map + this._choices_actions = [] + } + + add_parser() { + let [ + name, + kwargs + ] = _parse_opts(arguments, { + name: no_default, + '**kwargs': no_default + }) + + // set prog from the existing prefix + if (kwargs.prog === undefined) { + kwargs.prog = sub('%s %s', this._prog_prefix, name) + } + + let aliases = getattr(kwargs, 'aliases', []) + delete kwargs.aliases + + // create a pseudo-action to hold the choice help + if ('help' in kwargs) { + let help = kwargs.help + delete kwargs.help + let choice_action = this._ChoicesPseudoAction(name, aliases, help) + this._choices_actions.push(choice_action) + } + + // create the parser and add it to the map + let parser = new this._parser_class(kwargs) + this._name_parser_map[name] = parser + + // make parser available under aliases also + for (let alias of aliases) { + this._name_parser_map[alias] = parser + } + + return parser + } + + _get_subactions() { + return this._choices_actions + } + + call(parser, namespace, values/*, option_string = undefined*/) { + let parser_name = values[0] + let arg_strings = values.slice(1) + + // set the parser name if requested + if (this.dest !== SUPPRESS) { + setattr(namespace, this.dest, parser_name) + } + + // select the parser + if (hasattr(this._name_parser_map, parser_name)) { + parser = this._name_parser_map[parser_name] + } else { + let args = {parser_name, + choices: this._name_parser_map.join(', ')} + let msg = sub('unknown parser %(parser_name)r (choices: %(choices)s)', args) + throw new ArgumentError(this, msg) + } + + // parse all the remaining options into the namespace + // store any unrecognized options on the object, so that the top + // level parser can decide what to do with them + + // In case this subparser defines new defaults, we parse them + // in a new namespace object and then update the original + // namespace for the relevant parts. + let subnamespace + [ subnamespace, arg_strings ] = parser.parse_known_args(arg_strings, undefined) + for (let [ key, value ] of Object.entries(subnamespace)) { + setattr(namespace, key, value) + } + + if (arg_strings.length) { + setdefault(namespace, _UNRECOGNIZED_ARGS_ATTR, []) + getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).push(...arg_strings) + } + } +})) + + +_SubParsersAction.prototype._ChoicesPseudoAction = _callable(class _ChoicesPseudoAction extends Action { + constructor(name, aliases, help) { + let metavar = name, dest = name + if (aliases.length) { + metavar += sub(' (%s)', aliases.join(', ')) + } + super({ option_strings: [], dest, help, metavar }) + } +}) + + +const _ExtendAction = _callable(class _ExtendAction extends _AppendAction { + call(parser, namespace, values/*, option_string = undefined*/) { + let items = getattr(namespace, this.dest, undefined) + items = _copy_items(items) + items = items.concat(values) + setattr(namespace, this.dest, items) + } +}) + + +// ============== +// Type classes +// ============== +const FileType = _callable(class FileType extends Function { + /* + * Factory for creating file object types + * + * Instances of FileType are typically passed as type= arguments to the + * ArgumentParser add_argument() method. + * + * Keyword Arguments: + * - mode -- A string indicating how the file is to be opened. Accepts the + * same values as the builtin open() function. + * - bufsize -- The file's desired buffer size. Accepts the same values as + * the builtin open() function. + * - encoding -- The file's encoding. Accepts the same values as the + * builtin open() function. + * - errors -- A string indicating how encoding and decoding errors are to + * be handled. Accepts the same value as the builtin open() function. + */ + + constructor() { + let [ + flags, + encoding, + mode, + autoClose, + emitClose, + start, + end, + highWaterMark, + fs + ] = _parse_opts(arguments, { + flags: 'r', + encoding: undefined, + mode: undefined, // 0o666 + autoClose: undefined, // true + emitClose: undefined, // false + start: undefined, // 0 + end: undefined, // Infinity + highWaterMark: undefined, // 64 * 1024 + fs: undefined + }) + + // when this class is called as a function, redirect it to .call() method of itself + super('return arguments.callee.call.apply(arguments.callee, arguments)') + + Object.defineProperty(this, 'name', { + get() { + return sub('FileType(%r)', flags) + } + }) + this._flags = flags + this._options = {} + if (encoding !== undefined) this._options.encoding = encoding + if (mode !== undefined) this._options.mode = mode + if (autoClose !== undefined) this._options.autoClose = autoClose + if (emitClose !== undefined) this._options.emitClose = emitClose + if (start !== undefined) this._options.start = start + if (end !== undefined) this._options.end = end + if (highWaterMark !== undefined) this._options.highWaterMark = highWaterMark + if (fs !== undefined) this._options.fs = fs + } + + call(string) { + // the special argument "-" means sys.std{in,out} + if (string === '-') { + if (this._flags.includes('r')) { + return process.stdin + } else if (this._flags.includes('w')) { + return process.stdout + } else { + let msg = sub('argument "-" with mode %r', this._flags) + throw new TypeError(msg) + } + } + + // all other arguments are used as file names + let fd + try { + fd = fs.openSync(string, this._flags, this._options.mode) + } catch (e) { + let args = { filename: string, error: e.message } + let message = "can't open '%(filename)s': %(error)s" + throw new ArgumentTypeError(sub(message, args)) + } + + let options = Object.assign({ fd, flags: this._flags }, this._options) + if (this._flags.includes('r')) { + return fs.createReadStream(undefined, options) + } else if (this._flags.includes('w')) { + return fs.createWriteStream(undefined, options) + } else { + let msg = sub('argument "%s" with mode %r', string, this._flags) + throw new TypeError(msg) + } + } + + [util.inspect.custom]() { + let args = [ this._flags ] + let kwargs = Object.entries(this._options).map(([ k, v ]) => { + if (k === 'mode') v = { value: v, [util.inspect.custom]() { return '0o' + this.value.toString(8) } } + return [ k, v ] + }) + let args_str = [] + .concat(args.filter(arg => arg !== -1).map(repr)) + .concat(kwargs.filter(([/*kw*/, arg]) => arg !== undefined) + .map(([kw, arg]) => sub('%s=%r', kw, arg))) + .join(', ') + return sub('%s(%s)', this.constructor.name, args_str) + } + + toString() { + return this[util.inspect.custom]() + } +}) + +// =========================== +// Optional and Positional Parsing +// =========================== +const Namespace = _callable(class Namespace extends _AttributeHolder() { + /* + * Simple object for storing attributes. + * + * Implements equality by attribute names and values, and provides a simple + * string representation. + */ + + constructor(options = {}) { + super() + Object.assign(this, options) + } +}) + +// unset string tag to mimic plain object +Namespace.prototype[Symbol.toStringTag] = undefined + + +const _ActionsContainer = _camelcase_alias(_callable(class _ActionsContainer { + + constructor() { + let [ + description, + prefix_chars, + argument_default, + conflict_handler + ] = _parse_opts(arguments, { + description: no_default, + prefix_chars: no_default, + argument_default: no_default, + conflict_handler: no_default + }) + + this.description = description + this.argument_default = argument_default + this.prefix_chars = prefix_chars + this.conflict_handler = conflict_handler + + // set up registries + this._registries = {} + + // register actions + this.register('action', undefined, _StoreAction) + this.register('action', 'store', _StoreAction) + this.register('action', 'store_const', _StoreConstAction) + this.register('action', 'store_true', _StoreTrueAction) + this.register('action', 'store_false', _StoreFalseAction) + this.register('action', 'append', _AppendAction) + this.register('action', 'append_const', _AppendConstAction) + this.register('action', 'count', _CountAction) + this.register('action', 'help', _HelpAction) + this.register('action', 'version', _VersionAction) + this.register('action', 'parsers', _SubParsersAction) + this.register('action', 'extend', _ExtendAction) + // LEGACY (v1 compatibility): camelcase variants + ;[ 'storeConst', 'storeTrue', 'storeFalse', 'appendConst' ].forEach(old_name => { + let new_name = _to_new_name(old_name) + this.register('action', old_name, util.deprecate(this._registry_get('action', new_name), + sub('{action: "%s"} is renamed to {action: "%s"}', old_name, new_name))) + }) + // end + + // raise an exception if the conflict handler is invalid + this._get_handler() + + // action storage + this._actions = [] + this._option_string_actions = {} + + // groups + this._action_groups = [] + this._mutually_exclusive_groups = [] + + // defaults storage + this._defaults = {} + + // determines whether an "option" looks like a negative number + this._negative_number_matcher = /^-\d+$|^-\d*\.\d+$/ + + // whether or not there are any optionals that look like negative + // numbers -- uses a list so it can be shared and edited + this._has_negative_number_optionals = [] + } + + // ==================== + // Registration methods + // ==================== + register(registry_name, value, object) { + let registry = setdefault(this._registries, registry_name, {}) + registry[value] = object + } + + _registry_get(registry_name, value, default_value = undefined) { + return getattr(this._registries[registry_name], value, default_value) + } + + // ================================== + // Namespace default accessor methods + // ================================== + set_defaults(kwargs) { + Object.assign(this._defaults, kwargs) + + // if these defaults match any existing arguments, replace + // the previous default on the object with the new one + for (let action of this._actions) { + if (action.dest in kwargs) { + action.default = kwargs[action.dest] + } + } + } + + get_default(dest) { + for (let action of this._actions) { + if (action.dest === dest && action.default !== undefined) { + return action.default + } + } + return this._defaults[dest] + } + + + // ======================= + // Adding argument actions + // ======================= + add_argument() { + /* + * add_argument(dest, ..., name=value, ...) + * add_argument(option_string, option_string, ..., name=value, ...) + */ + let [ + args, + kwargs + ] = _parse_opts(arguments, { + '*args': no_default, + '**kwargs': no_default + }) + // LEGACY (v1 compatibility), old-style add_argument([ args ], { options }) + if (args.length === 1 && Array.isArray(args[0])) { + args = args[0] + deprecate('argument-array', + sub('use add_argument(%(args)s, {...}) instead of add_argument([ %(args)s ], { ... })', { + args: args.map(repr).join(', ') + })) + } + // end + + // if no positional args are supplied or only one is supplied and + // it doesn't look like an option string, parse a positional + // argument + let chars = this.prefix_chars + if (!args.length || args.length === 1 && !chars.includes(args[0][0])) { + if (args.length && 'dest' in kwargs) { + throw new TypeError('dest supplied twice for positional argument') + } + kwargs = this._get_positional_kwargs(...args, kwargs) + + // otherwise, we're adding an optional argument + } else { + kwargs = this._get_optional_kwargs(...args, kwargs) + } + + // if no default was supplied, use the parser-level default + if (!('default' in kwargs)) { + let dest = kwargs.dest + if (dest in this._defaults) { + kwargs.default = this._defaults[dest] + } else if (this.argument_default !== undefined) { + kwargs.default = this.argument_default + } + } + + // create the action object, and add it to the parser + let action_class = this._pop_action_class(kwargs) + if (typeof action_class !== 'function') { + throw new TypeError(sub('unknown action "%s"', action_class)) + } + // eslint-disable-next-line new-cap + let action = new action_class(kwargs) + + // raise an error if the action type is not callable + let type_func = this._registry_get('type', action.type, action.type) + if (typeof type_func !== 'function') { + throw new TypeError(sub('%r is not callable', type_func)) + } + + if (type_func === FileType) { + throw new TypeError(sub('%r is a FileType class object, instance of it' + + ' must be passed', type_func)) + } + + // raise an error if the metavar does not match the type + if ('_get_formatter' in this) { + try { + this._get_formatter()._format_args(action, undefined) + } catch (err) { + // check for 'invalid nargs value' is an artifact of TypeError and ValueError in js being the same + if (err instanceof TypeError && err.message !== 'invalid nargs value') { + throw new TypeError('length of metavar tuple does not match nargs') + } else { + throw err + } + } + } + + return this._add_action(action) + } + + add_argument_group() { + let group = _ArgumentGroup(this, ...arguments) + this._action_groups.push(group) + return group + } + + add_mutually_exclusive_group() { + // eslint-disable-next-line no-use-before-define + let group = _MutuallyExclusiveGroup(this, ...arguments) + this._mutually_exclusive_groups.push(group) + return group + } + + _add_action(action) { + // resolve any conflicts + this._check_conflict(action) + + // add to actions list + this._actions.push(action) + action.container = this + + // index the action by any option strings it has + for (let option_string of action.option_strings) { + this._option_string_actions[option_string] = action + } + + // set the flag if any option strings look like negative numbers + for (let option_string of action.option_strings) { + if (this._negative_number_matcher.test(option_string)) { + if (!this._has_negative_number_optionals.length) { + this._has_negative_number_optionals.push(true) + } + } + } + + // return the created action + return action + } + + _remove_action(action) { + _array_remove(this._actions, action) + } + + _add_container_actions(container) { + // collect groups by titles + let title_group_map = {} + for (let group of this._action_groups) { + if (group.title in title_group_map) { + let msg = 'cannot merge actions - two groups are named %r' + throw new TypeError(sub(msg, group.title)) + } + title_group_map[group.title] = group + } + + // map each action to its group + let group_map = new Map() + for (let group of container._action_groups) { + + // if a group with the title exists, use that, otherwise + // create a new group matching the container's group + if (!(group.title in title_group_map)) { + title_group_map[group.title] = this.add_argument_group({ + title: group.title, + description: group.description, + conflict_handler: group.conflict_handler + }) + } + + // map the actions to their new group + for (let action of group._group_actions) { + group_map.set(action, title_group_map[group.title]) + } + } + + // add container's mutually exclusive groups + // NOTE: if add_mutually_exclusive_group ever gains title= and + // description= then this code will need to be expanded as above + for (let group of container._mutually_exclusive_groups) { + let mutex_group = this.add_mutually_exclusive_group({ + required: group.required + }) + + // map the actions to their new mutex group + for (let action of group._group_actions) { + group_map.set(action, mutex_group) + } + } + + // add all actions to this container or their group + for (let action of container._actions) { + group_map.get(action)._add_action(action) + } + } + + _get_positional_kwargs() { + let [ + dest, + kwargs + ] = _parse_opts(arguments, { + dest: no_default, + '**kwargs': no_default + }) + + // make sure required is not specified + if ('required' in kwargs) { + let msg = "'required' is an invalid argument for positionals" + throw new TypeError(msg) + } + + // mark positional arguments as required if at least one is + // always required + if (![OPTIONAL, ZERO_OR_MORE].includes(kwargs.nargs)) { + kwargs.required = true + } + if (kwargs.nargs === ZERO_OR_MORE && !('default' in kwargs)) { + kwargs.required = true + } + + // return the keyword arguments with no option strings + return Object.assign(kwargs, { dest, option_strings: [] }) + } + + _get_optional_kwargs() { + let [ + args, + kwargs + ] = _parse_opts(arguments, { + '*args': no_default, + '**kwargs': no_default + }) + + // determine short and long option strings + let option_strings = [] + let long_option_strings = [] + let option_string + for (option_string of args) { + // error on strings that don't start with an appropriate prefix + if (!this.prefix_chars.includes(option_string[0])) { + let args = {option: option_string, + prefix_chars: this.prefix_chars} + let msg = 'invalid option string %(option)r: ' + + 'must start with a character %(prefix_chars)r' + throw new TypeError(sub(msg, args)) + } + + // strings starting with two prefix characters are long options + option_strings.push(option_string) + if (option_string.length > 1 && this.prefix_chars.includes(option_string[1])) { + long_option_strings.push(option_string) + } + } + + // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' + let dest = kwargs.dest + delete kwargs.dest + if (dest === undefined) { + let dest_option_string + if (long_option_strings.length) { + dest_option_string = long_option_strings[0] + } else { + dest_option_string = option_strings[0] + } + dest = _string_lstrip(dest_option_string, this.prefix_chars) + if (!dest) { + let msg = 'dest= is required for options like %r' + throw new TypeError(sub(msg, option_string)) + } + dest = dest.replace(/-/g, '_') + } + + // return the updated keyword arguments + return Object.assign(kwargs, { dest, option_strings }) + } + + _pop_action_class(kwargs, default_value = undefined) { + let action = getattr(kwargs, 'action', default_value) + delete kwargs.action + return this._registry_get('action', action, action) + } + + _get_handler() { + // determine function from conflict handler string + let handler_func_name = sub('_handle_conflict_%s', this.conflict_handler) + if (typeof this[handler_func_name] === 'function') { + return this[handler_func_name] + } else { + let msg = 'invalid conflict_resolution value: %r' + throw new TypeError(sub(msg, this.conflict_handler)) + } + } + + _check_conflict(action) { + + // find all options that conflict with this option + let confl_optionals = [] + for (let option_string of action.option_strings) { + if (hasattr(this._option_string_actions, option_string)) { + let confl_optional = this._option_string_actions[option_string] + confl_optionals.push([ option_string, confl_optional ]) + } + } + + // resolve any conflicts + if (confl_optionals.length) { + let conflict_handler = this._get_handler() + conflict_handler.call(this, action, confl_optionals) + } + } + + _handle_conflict_error(action, conflicting_actions) { + let message = conflicting_actions.length === 1 ? + 'conflicting option string: %s' : + 'conflicting option strings: %s' + let conflict_string = conflicting_actions.map(([ option_string/*, action*/ ]) => option_string).join(', ') + throw new ArgumentError(action, sub(message, conflict_string)) + } + + _handle_conflict_resolve(action, conflicting_actions) { + + // remove all conflicting options + for (let [ option_string, action ] of conflicting_actions) { + + // remove the conflicting option + _array_remove(action.option_strings, option_string) + delete this._option_string_actions[option_string] + + // if the option now has no option string, remove it from the + // container holding it + if (!action.option_strings.length) { + action.container._remove_action(action) + } + } + } +})) + + +const _ArgumentGroup = _callable(class _ArgumentGroup extends _ActionsContainer { + + constructor() { + let [ + container, + title, + description, + kwargs + ] = _parse_opts(arguments, { + container: no_default, + title: undefined, + description: undefined, + '**kwargs': no_default + }) + + // add any missing keyword arguments by checking the container + setdefault(kwargs, 'conflict_handler', container.conflict_handler) + setdefault(kwargs, 'prefix_chars', container.prefix_chars) + setdefault(kwargs, 'argument_default', container.argument_default) + super(Object.assign({ description }, kwargs)) + + // group attributes + this.title = title + this._group_actions = [] + + // share most attributes with the container + this._registries = container._registries + this._actions = container._actions + this._option_string_actions = container._option_string_actions + this._defaults = container._defaults + this._has_negative_number_optionals = + container._has_negative_number_optionals + this._mutually_exclusive_groups = container._mutually_exclusive_groups + } + + _add_action(action) { + action = super._add_action(action) + this._group_actions.push(action) + return action + } + + _remove_action(action) { + super._remove_action(action) + _array_remove(this._group_actions, action) + } +}) + + +const _MutuallyExclusiveGroup = _callable(class _MutuallyExclusiveGroup extends _ArgumentGroup { + + constructor() { + let [ + container, + required + ] = _parse_opts(arguments, { + container: no_default, + required: false + }) + + super(container) + this.required = required + this._container = container + } + + _add_action(action) { + if (action.required) { + let msg = 'mutually exclusive arguments must be optional' + throw new TypeError(msg) + } + action = this._container._add_action(action) + this._group_actions.push(action) + return action + } + + _remove_action(action) { + this._container._remove_action(action) + _array_remove(this._group_actions, action) + } +}) + + +const ArgumentParser = _camelcase_alias(_callable(class ArgumentParser extends _AttributeHolder(_ActionsContainer) { + /* + * Object for parsing command line strings into Python objects. + * + * Keyword Arguments: + * - prog -- The name of the program (default: sys.argv[0]) + * - usage -- A usage message (default: auto-generated from arguments) + * - description -- A description of what the program does + * - epilog -- Text following the argument descriptions + * - parents -- Parsers whose arguments should be copied into this one + * - formatter_class -- HelpFormatter class for printing help messages + * - prefix_chars -- Characters that prefix optional arguments + * - fromfile_prefix_chars -- Characters that prefix files containing + * additional arguments + * - argument_default -- The default value for all arguments + * - conflict_handler -- String indicating how to handle conflicts + * - add_help -- Add a -h/-help option + * - allow_abbrev -- Allow long options to be abbreviated unambiguously + * - exit_on_error -- Determines whether or not ArgumentParser exits with + * error info when an error occurs + */ + + constructor() { + let [ + prog, + usage, + description, + epilog, + parents, + formatter_class, + prefix_chars, + fromfile_prefix_chars, + argument_default, + conflict_handler, + add_help, + allow_abbrev, + exit_on_error, + debug, // LEGACY (v1 compatibility), debug mode + version // LEGACY (v1 compatibility), version + ] = _parse_opts(arguments, { + prog: undefined, + usage: undefined, + description: undefined, + epilog: undefined, + parents: [], + formatter_class: HelpFormatter, + prefix_chars: '-', + fromfile_prefix_chars: undefined, + argument_default: undefined, + conflict_handler: 'error', + add_help: true, + allow_abbrev: true, + exit_on_error: true, + debug: undefined, // LEGACY (v1 compatibility), debug mode + version: undefined // LEGACY (v1 compatibility), version + }) + + // LEGACY (v1 compatibility) + if (debug !== undefined) { + deprecate('debug', + 'The "debug" argument to ArgumentParser is deprecated. Please ' + + 'override ArgumentParser.exit function instead.' + ) + } + + if (version !== undefined) { + deprecate('version', + 'The "version" argument to ArgumentParser is deprecated. Please use ' + + "add_argument(..., { action: 'version', version: 'N', ... }) instead." + ) + } + // end + + super({ + description, + prefix_chars, + argument_default, + conflict_handler + }) + + // default setting for prog + if (prog === undefined) { + prog = path.basename(get_argv()[0] || '') + } + + this.prog = prog + this.usage = usage + this.epilog = epilog + this.formatter_class = formatter_class + this.fromfile_prefix_chars = fromfile_prefix_chars + this.add_help = add_help + this.allow_abbrev = allow_abbrev + this.exit_on_error = exit_on_error + // LEGACY (v1 compatibility), debug mode + this.debug = debug + // end + + this._positionals = this.add_argument_group('positional arguments') + this._optionals = this.add_argument_group('optional arguments') + this._subparsers = undefined + + // register types + function identity(string) { + return string + } + this.register('type', undefined, identity) + this.register('type', null, identity) + this.register('type', 'auto', identity) + this.register('type', 'int', function (x) { + let result = Number(x) + if (!Number.isInteger(result)) { + throw new TypeError(sub('could not convert string to int: %r', x)) + } + return result + }) + this.register('type', 'float', function (x) { + let result = Number(x) + if (isNaN(result)) { + throw new TypeError(sub('could not convert string to float: %r', x)) + } + return result + }) + this.register('type', 'str', String) + // LEGACY (v1 compatibility): custom types + this.register('type', 'string', + util.deprecate(String, 'use {type:"str"} or {type:String} instead of {type:"string"}')) + // end + + // add help argument if necessary + // (using explicit default to override global argument_default) + let default_prefix = prefix_chars.includes('-') ? '-' : prefix_chars[0] + if (this.add_help) { + this.add_argument( + default_prefix + 'h', + default_prefix.repeat(2) + 'help', + { + action: 'help', + default: SUPPRESS, + help: 'show this help message and exit' + } + ) + } + // LEGACY (v1 compatibility), version + if (version) { + this.add_argument( + default_prefix + 'v', + default_prefix.repeat(2) + 'version', + { + action: 'version', + default: SUPPRESS, + version: this.version, + help: "show program's version number and exit" + } + ) + } + // end + + // add parent arguments and defaults + for (let parent of parents) { + this._add_container_actions(parent) + Object.assign(this._defaults, parent._defaults) + } + } + + // ======================= + // Pretty __repr__ methods + // ======================= + _get_kwargs() { + let names = [ + 'prog', + 'usage', + 'description', + 'formatter_class', + 'conflict_handler', + 'add_help' + ] + return names.map(name => [ name, getattr(this, name) ]) + } + + // ================================== + // Optional/Positional adding methods + // ================================== + add_subparsers() { + let [ + kwargs + ] = _parse_opts(arguments, { + '**kwargs': no_default + }) + + if (this._subparsers !== undefined) { + this.error('cannot have multiple subparser arguments') + } + + // add the parser class to the arguments if it's not present + setdefault(kwargs, 'parser_class', this.constructor) + + if ('title' in kwargs || 'description' in kwargs) { + let title = getattr(kwargs, 'title', 'subcommands') + let description = getattr(kwargs, 'description', undefined) + delete kwargs.title + delete kwargs.description + this._subparsers = this.add_argument_group(title, description) + } else { + this._subparsers = this._positionals + } + + // prog defaults to the usage message of this parser, skipping + // optional arguments and with no "usage:" prefix + if (kwargs.prog === undefined) { + let formatter = this._get_formatter() + let positionals = this._get_positional_actions() + let groups = this._mutually_exclusive_groups + formatter.add_usage(this.usage, positionals, groups, '') + kwargs.prog = formatter.format_help().trim() + } + + // create the parsers action and add it to the positionals list + let parsers_class = this._pop_action_class(kwargs, 'parsers') + // eslint-disable-next-line new-cap + let action = new parsers_class(Object.assign({ option_strings: [] }, kwargs)) + this._subparsers._add_action(action) + + // return the created parsers action + return action + } + + _add_action(action) { + if (action.option_strings.length) { + this._optionals._add_action(action) + } else { + this._positionals._add_action(action) + } + return action + } + + _get_optional_actions() { + return this._actions.filter(action => action.option_strings.length) + } + + _get_positional_actions() { + return this._actions.filter(action => !action.option_strings.length) + } + + // ===================================== + // Command line argument parsing methods + // ===================================== + parse_args(args = undefined, namespace = undefined) { + let argv + [ args, argv ] = this.parse_known_args(args, namespace) + if (argv && argv.length > 0) { + let msg = 'unrecognized arguments: %s' + this.error(sub(msg, argv.join(' '))) + } + return args + } + + parse_known_args(args = undefined, namespace = undefined) { + if (args === undefined) { + args = get_argv().slice(1) + } + + // default Namespace built from parser defaults + if (namespace === undefined) { + namespace = new Namespace() + } + + // add any action defaults that aren't present + for (let action of this._actions) { + if (action.dest !== SUPPRESS) { + if (!hasattr(namespace, action.dest)) { + if (action.default !== SUPPRESS) { + setattr(namespace, action.dest, action.default) + } + } + } + } + + // add any parser defaults that aren't present + for (let dest of Object.keys(this._defaults)) { + if (!hasattr(namespace, dest)) { + setattr(namespace, dest, this._defaults[dest]) + } + } + + // parse the arguments and exit if there are any errors + if (this.exit_on_error) { + try { + [ namespace, args ] = this._parse_known_args(args, namespace) + } catch (err) { + if (err instanceof ArgumentError) { + this.error(err.message) + } else { + throw err + } + } + } else { + [ namespace, args ] = this._parse_known_args(args, namespace) + } + + if (hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) { + args = args.concat(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) + delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) + } + + return [ namespace, args ] + } + + _parse_known_args(arg_strings, namespace) { + // replace arg strings that are file references + if (this.fromfile_prefix_chars !== undefined) { + arg_strings = this._read_args_from_files(arg_strings) + } + + // map all mutually exclusive arguments to the other arguments + // they can't occur with + let action_conflicts = new Map() + for (let mutex_group of this._mutually_exclusive_groups) { + let group_actions = mutex_group._group_actions + for (let [ i, mutex_action ] of Object.entries(mutex_group._group_actions)) { + let conflicts = action_conflicts.get(mutex_action) || [] + conflicts = conflicts.concat(group_actions.slice(0, +i)) + conflicts = conflicts.concat(group_actions.slice(+i + 1)) + action_conflicts.set(mutex_action, conflicts) + } + } + + // find all option indices, and determine the arg_string_pattern + // which has an 'O' if there is an option at an index, + // an 'A' if there is an argument, or a '-' if there is a '--' + let option_string_indices = {} + let arg_string_pattern_parts = [] + let arg_strings_iter = Object.entries(arg_strings)[Symbol.iterator]() + for (let [ i, arg_string ] of arg_strings_iter) { + + // all args after -- are non-options + if (arg_string === '--') { + arg_string_pattern_parts.push('-') + for ([ i, arg_string ] of arg_strings_iter) { + arg_string_pattern_parts.push('A') + } + + // otherwise, add the arg to the arg strings + // and note the index if it was an option + } else { + let option_tuple = this._parse_optional(arg_string) + let pattern + if (option_tuple === undefined) { + pattern = 'A' + } else { + option_string_indices[i] = option_tuple + pattern = 'O' + } + arg_string_pattern_parts.push(pattern) + } + } + + // join the pieces together to form the pattern + let arg_strings_pattern = arg_string_pattern_parts.join('') + + // converts arg strings to the appropriate and then takes the action + let seen_actions = new Set() + let seen_non_default_actions = new Set() + let extras + + let take_action = (action, argument_strings, option_string = undefined) => { + seen_actions.add(action) + let argument_values = this._get_values(action, argument_strings) + + // error if this argument is not allowed with other previously + // seen arguments, assuming that actions that use the default + // value don't really count as "present" + if (argument_values !== action.default) { + seen_non_default_actions.add(action) + for (let conflict_action of action_conflicts.get(action) || []) { + if (seen_non_default_actions.has(conflict_action)) { + let msg = 'not allowed with argument %s' + let action_name = _get_action_name(conflict_action) + throw new ArgumentError(action, sub(msg, action_name)) + } + } + } + + // take the action if we didn't receive a SUPPRESS value + // (e.g. from a default) + if (argument_values !== SUPPRESS) { + action(this, namespace, argument_values, option_string) + } + } + + // function to convert arg_strings into an optional action + let consume_optional = start_index => { + + // get the optional identified at this index + let option_tuple = option_string_indices[start_index] + let [ action, option_string, explicit_arg ] = option_tuple + + // identify additional optionals in the same arg string + // (e.g. -xyz is the same as -x -y -z if no args are required) + let action_tuples = [] + let stop + for (;;) { + + // if we found no optional action, skip it + if (action === undefined) { + extras.push(arg_strings[start_index]) + return start_index + 1 + } + + // if there is an explicit argument, try to match the + // optional's string arguments to only this + if (explicit_arg !== undefined) { + let arg_count = this._match_argument(action, 'A') + + // if the action is a single-dash option and takes no + // arguments, try to parse more single-dash options out + // of the tail of the option string + let chars = this.prefix_chars + if (arg_count === 0 && !chars.includes(option_string[1])) { + action_tuples.push([ action, [], option_string ]) + let char = option_string[0] + option_string = char + explicit_arg[0] + let new_explicit_arg = explicit_arg.slice(1) || undefined + let optionals_map = this._option_string_actions + if (hasattr(optionals_map, option_string)) { + action = optionals_map[option_string] + explicit_arg = new_explicit_arg + } else { + let msg = 'ignored explicit argument %r' + throw new ArgumentError(action, sub(msg, explicit_arg)) + } + + // if the action expect exactly one argument, we've + // successfully matched the option; exit the loop + } else if (arg_count === 1) { + stop = start_index + 1 + let args = [ explicit_arg ] + action_tuples.push([ action, args, option_string ]) + break + + // error if a double-dash option did not use the + // explicit argument + } else { + let msg = 'ignored explicit argument %r' + throw new ArgumentError(action, sub(msg, explicit_arg)) + } + + // if there is no explicit argument, try to match the + // optional's string arguments with the following strings + // if successful, exit the loop + } else { + let start = start_index + 1 + let selected_patterns = arg_strings_pattern.slice(start) + let arg_count = this._match_argument(action, selected_patterns) + stop = start + arg_count + let args = arg_strings.slice(start, stop) + action_tuples.push([ action, args, option_string ]) + break + } + } + + // add the Optional to the list and return the index at which + // the Optional's string args stopped + assert(action_tuples.length) + for (let [ action, args, option_string ] of action_tuples) { + take_action(action, args, option_string) + } + return stop + } + + // the list of Positionals left to be parsed; this is modified + // by consume_positionals() + let positionals = this._get_positional_actions() + + // function to convert arg_strings into positional actions + let consume_positionals = start_index => { + // match as many Positionals as possible + let selected_pattern = arg_strings_pattern.slice(start_index) + let arg_counts = this._match_arguments_partial(positionals, selected_pattern) + + // slice off the appropriate arg strings for each Positional + // and add the Positional and its args to the list + for (let i = 0; i < positionals.length && i < arg_counts.length; i++) { + let action = positionals[i] + let arg_count = arg_counts[i] + let args = arg_strings.slice(start_index, start_index + arg_count) + start_index += arg_count + take_action(action, args) + } + + // slice off the Positionals that we just parsed and return the + // index at which the Positionals' string args stopped + positionals = positionals.slice(arg_counts.length) + return start_index + } + + // consume Positionals and Optionals alternately, until we have + // passed the last option string + extras = [] + let start_index = 0 + let max_option_string_index = Math.max(-1, ...Object.keys(option_string_indices).map(Number)) + while (start_index <= max_option_string_index) { + + // consume any Positionals preceding the next option + let next_option_string_index = Math.min( + // eslint-disable-next-line no-loop-func + ...Object.keys(option_string_indices).map(Number).filter(index => index >= start_index) + ) + if (start_index !== next_option_string_index) { + let positionals_end_index = consume_positionals(start_index) + + // only try to parse the next optional if we didn't consume + // the option string during the positionals parsing + if (positionals_end_index > start_index) { + start_index = positionals_end_index + continue + } else { + start_index = positionals_end_index + } + } + + // if we consumed all the positionals we could and we're not + // at the index of an option string, there were extra arguments + if (!(start_index in option_string_indices)) { + let strings = arg_strings.slice(start_index, next_option_string_index) + extras = extras.concat(strings) + start_index = next_option_string_index + } + + // consume the next optional and any arguments for it + start_index = consume_optional(start_index) + } + + // consume any positionals following the last Optional + let stop_index = consume_positionals(start_index) + + // if we didn't consume all the argument strings, there were extras + extras = extras.concat(arg_strings.slice(stop_index)) + + // make sure all required actions were present and also convert + // action defaults which were not given as arguments + let required_actions = [] + for (let action of this._actions) { + if (!seen_actions.has(action)) { + if (action.required) { + required_actions.push(_get_action_name(action)) + } else { + // Convert action default now instead of doing it before + // parsing arguments to avoid calling convert functions + // twice (which may fail) if the argument was given, but + // only if it was defined already in the namespace + if (action.default !== undefined && + typeof action.default === 'string' && + hasattr(namespace, action.dest) && + action.default === getattr(namespace, action.dest)) { + setattr(namespace, action.dest, + this._get_value(action, action.default)) + } + } + } + } + + if (required_actions.length) { + this.error(sub('the following arguments are required: %s', + required_actions.join(', '))) + } + + // make sure all required groups had one option present + for (let group of this._mutually_exclusive_groups) { + if (group.required) { + let no_actions_used = true + for (let action of group._group_actions) { + if (seen_non_default_actions.has(action)) { + no_actions_used = false + break + } + } + + // if no actions were used, report the error + if (no_actions_used) { + let names = group._group_actions + .filter(action => action.help !== SUPPRESS) + .map(action => _get_action_name(action)) + let msg = 'one of the arguments %s is required' + this.error(sub(msg, names.join(' '))) + } + } + } + + // return the updated namespace and the extra arguments + return [ namespace, extras ] + } + + _read_args_from_files(arg_strings) { + // expand arguments referencing files + let new_arg_strings = [] + for (let arg_string of arg_strings) { + + // for regular arguments, just add them back into the list + if (!arg_string || !this.fromfile_prefix_chars.includes(arg_string[0])) { + new_arg_strings.push(arg_string) + + // replace arguments referencing files with the file content + } else { + try { + let args_file = fs.readFileSync(arg_string.slice(1), 'utf8') + let arg_strings = [] + for (let arg_line of splitlines(args_file)) { + for (let arg of this.convert_arg_line_to_args(arg_line)) { + arg_strings.push(arg) + } + } + arg_strings = this._read_args_from_files(arg_strings) + new_arg_strings = new_arg_strings.concat(arg_strings) + } catch (err) { + this.error(err.message) + } + } + } + + // return the modified argument list + return new_arg_strings + } + + convert_arg_line_to_args(arg_line) { + return [arg_line] + } + + _match_argument(action, arg_strings_pattern) { + // match the pattern for this action to the arg strings + let nargs_pattern = this._get_nargs_pattern(action) + let match = arg_strings_pattern.match(new RegExp('^' + nargs_pattern)) + + // raise an exception if we weren't able to find a match + if (match === null) { + let nargs_errors = { + undefined: 'expected one argument', + [OPTIONAL]: 'expected at most one argument', + [ONE_OR_MORE]: 'expected at least one argument' + } + let msg = nargs_errors[action.nargs] + if (msg === undefined) { + msg = sub(action.nargs === 1 ? 'expected %s argument' : 'expected %s arguments', action.nargs) + } + throw new ArgumentError(action, msg) + } + + // return the number of arguments matched + return match[1].length + } + + _match_arguments_partial(actions, arg_strings_pattern) { + // progressively shorten the actions list by slicing off the + // final actions until we find a match + let result = [] + for (let i of range(actions.length, 0, -1)) { + let actions_slice = actions.slice(0, i) + let pattern = actions_slice.map(action => this._get_nargs_pattern(action)).join('') + let match = arg_strings_pattern.match(new RegExp('^' + pattern)) + if (match !== null) { + result = result.concat(match.slice(1).map(string => string.length)) + break + } + } + + // return the list of arg string counts + return result + } + + _parse_optional(arg_string) { + // if it's an empty string, it was meant to be a positional + if (!arg_string) { + return undefined + } + + // if it doesn't start with a prefix, it was meant to be positional + if (!this.prefix_chars.includes(arg_string[0])) { + return undefined + } + + // if the option string is present in the parser, return the action + if (arg_string in this._option_string_actions) { + let action = this._option_string_actions[arg_string] + return [ action, arg_string, undefined ] + } + + // if it's just a single character, it was meant to be positional + if (arg_string.length === 1) { + return undefined + } + + // if the option string before the "=" is present, return the action + if (arg_string.includes('=')) { + let [ option_string, explicit_arg ] = _string_split(arg_string, '=', 1) + if (option_string in this._option_string_actions) { + let action = this._option_string_actions[option_string] + return [ action, option_string, explicit_arg ] + } + } + + // search through all possible prefixes of the option string + // and all actions in the parser for possible interpretations + let option_tuples = this._get_option_tuples(arg_string) + + // if multiple actions match, the option string was ambiguous + if (option_tuples.length > 1) { + let options = option_tuples.map(([ /*action*/, option_string/*, explicit_arg*/ ]) => option_string).join(', ') + let args = {option: arg_string, matches: options} + let msg = 'ambiguous option: %(option)s could match %(matches)s' + this.error(sub(msg, args)) + + // if exactly one action matched, this segmentation is good, + // so return the parsed action + } else if (option_tuples.length === 1) { + let [ option_tuple ] = option_tuples + return option_tuple + } + + // if it was not found as an option, but it looks like a negative + // number, it was meant to be positional + // unless there are negative-number-like options + if (this._negative_number_matcher.test(arg_string)) { + if (!this._has_negative_number_optionals.length) { + return undefined + } + } + + // if it contains a space, it was meant to be a positional + if (arg_string.includes(' ')) { + return undefined + } + + // it was meant to be an optional but there is no such option + // in this parser (though it might be a valid option in a subparser) + return [ undefined, arg_string, undefined ] + } + + _get_option_tuples(option_string) { + let result = [] + + // option strings starting with two prefix characters are only + // split at the '=' + let chars = this.prefix_chars + if (chars.includes(option_string[0]) && chars.includes(option_string[1])) { + if (this.allow_abbrev) { + let option_prefix, explicit_arg + if (option_string.includes('=')) { + [ option_prefix, explicit_arg ] = _string_split(option_string, '=', 1) + } else { + option_prefix = option_string + explicit_arg = undefined + } + for (let option_string of Object.keys(this._option_string_actions)) { + if (option_string.startsWith(option_prefix)) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, explicit_arg ] + result.push(tup) + } + } + } + + // single character options can be concatenated with their arguments + // but multiple character options always have to have their argument + // separate + } else if (chars.includes(option_string[0]) && !chars.includes(option_string[1])) { + let option_prefix = option_string + let explicit_arg = undefined + let short_option_prefix = option_string.slice(0, 2) + let short_explicit_arg = option_string.slice(2) + + for (let option_string of Object.keys(this._option_string_actions)) { + if (option_string === short_option_prefix) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, short_explicit_arg ] + result.push(tup) + } else if (option_string.startsWith(option_prefix)) { + let action = this._option_string_actions[option_string] + let tup = [ action, option_string, explicit_arg ] + result.push(tup) + } + } + + // shouldn't ever get here + } else { + this.error(sub('unexpected option string: %s', option_string)) + } + + // return the collected option tuples + return result + } + + _get_nargs_pattern(action) { + // in all examples below, we have to allow for '--' args + // which are represented as '-' in the pattern + let nargs = action.nargs + let nargs_pattern + + // the default (None) is assumed to be a single argument + if (nargs === undefined) { + nargs_pattern = '(-*A-*)' + + // allow zero or one arguments + } else if (nargs === OPTIONAL) { + nargs_pattern = '(-*A?-*)' + + // allow zero or more arguments + } else if (nargs === ZERO_OR_MORE) { + nargs_pattern = '(-*[A-]*)' + + // allow one or more arguments + } else if (nargs === ONE_OR_MORE) { + nargs_pattern = '(-*A[A-]*)' + + // allow any number of options or arguments + } else if (nargs === REMAINDER) { + nargs_pattern = '([-AO]*)' + + // allow one argument followed by any number of options or arguments + } else if (nargs === PARSER) { + nargs_pattern = '(-*A[-AO]*)' + + // suppress action, like nargs=0 + } else if (nargs === SUPPRESS) { + nargs_pattern = '(-*-*)' + + // all others should be integers + } else { + nargs_pattern = sub('(-*%s-*)', 'A'.repeat(nargs).split('').join('-*')) + } + + // if this is an optional action, -- is not allowed + if (action.option_strings.length) { + nargs_pattern = nargs_pattern.replace(/-\*/g, '') + nargs_pattern = nargs_pattern.replace(/-/g, '') + } + + // return the pattern + return nargs_pattern + } + + // ======================== + // Alt command line argument parsing, allowing free intermix + // ======================== + + parse_intermixed_args(args = undefined, namespace = undefined) { + let argv + [ args, argv ] = this.parse_known_intermixed_args(args, namespace) + if (argv.length) { + let msg = 'unrecognized arguments: %s' + this.error(sub(msg, argv.join(' '))) + } + return args + } + + parse_known_intermixed_args(args = undefined, namespace = undefined) { + // returns a namespace and list of extras + // + // positional can be freely intermixed with optionals. optionals are + // first parsed with all positional arguments deactivated. The 'extras' + // are then parsed. If the parser definition is incompatible with the + // intermixed assumptions (e.g. use of REMAINDER, subparsers) a + // TypeError is raised. + // + // positionals are 'deactivated' by setting nargs and default to + // SUPPRESS. This blocks the addition of that positional to the + // namespace + + let extras + let positionals = this._get_positional_actions() + let a = positionals.filter(action => [ PARSER, REMAINDER ].includes(action.nargs)) + if (a.length) { + throw new TypeError(sub('parse_intermixed_args: positional arg' + + ' with nargs=%s', a[0].nargs)) + } + + for (let group of this._mutually_exclusive_groups) { + for (let action of group._group_actions) { + if (positionals.includes(action)) { + throw new TypeError('parse_intermixed_args: positional in' + + ' mutuallyExclusiveGroup') + } + } + } + + let save_usage + try { + save_usage = this.usage + let remaining_args + try { + if (this.usage === undefined) { + // capture the full usage for use in error messages + this.usage = this.format_usage().slice(7) + } + for (let action of positionals) { + // deactivate positionals + action.save_nargs = action.nargs + // action.nargs = 0 + action.nargs = SUPPRESS + action.save_default = action.default + action.default = SUPPRESS + } + [ namespace, remaining_args ] = this.parse_known_args(args, + namespace) + for (let action of positionals) { + // remove the empty positional values from namespace + let attr = getattr(namespace, action.dest) + if (Array.isArray(attr) && attr.length === 0) { + // eslint-disable-next-line no-console + console.warn(sub('Do not expect %s in %s', action.dest, namespace)) + delattr(namespace, action.dest) + } + } + } finally { + // restore nargs and usage before exiting + for (let action of positionals) { + action.nargs = action.save_nargs + action.default = action.save_default + } + } + let optionals = this._get_optional_actions() + try { + // parse positionals. optionals aren't normally required, but + // they could be, so make sure they aren't. + for (let action of optionals) { + action.save_required = action.required + action.required = false + } + for (let group of this._mutually_exclusive_groups) { + group.save_required = group.required + group.required = false + } + [ namespace, extras ] = this.parse_known_args(remaining_args, + namespace) + } finally { + // restore parser values before exiting + for (let action of optionals) { + action.required = action.save_required + } + for (let group of this._mutually_exclusive_groups) { + group.required = group.save_required + } + } + } finally { + this.usage = save_usage + } + return [ namespace, extras ] + } + + // ======================== + // Value conversion methods + // ======================== + _get_values(action, arg_strings) { + // for everything but PARSER, REMAINDER args, strip out first '--' + if (![PARSER, REMAINDER].includes(action.nargs)) { + try { + _array_remove(arg_strings, '--') + } catch (err) {} + } + + let value + // optional argument produces a default when not present + if (!arg_strings.length && action.nargs === OPTIONAL) { + if (action.option_strings.length) { + value = action.const + } else { + value = action.default + } + if (typeof value === 'string') { + value = this._get_value(action, value) + this._check_value(action, value) + } + + // when nargs='*' on a positional, if there were no command-line + // args, use the default if it is anything other than None + } else if (!arg_strings.length && action.nargs === ZERO_OR_MORE && + !action.option_strings.length) { + if (action.default !== undefined) { + value = action.default + } else { + value = arg_strings + } + this._check_value(action, value) + + // single argument or optional argument produces a single value + } else if (arg_strings.length === 1 && [undefined, OPTIONAL].includes(action.nargs)) { + let arg_string = arg_strings[0] + value = this._get_value(action, arg_string) + this._check_value(action, value) + + // REMAINDER arguments convert all values, checking none + } else if (action.nargs === REMAINDER) { + value = arg_strings.map(v => this._get_value(action, v)) + + // PARSER arguments convert all values, but check only the first + } else if (action.nargs === PARSER) { + value = arg_strings.map(v => this._get_value(action, v)) + this._check_value(action, value[0]) + + // SUPPRESS argument does not put anything in the namespace + } else if (action.nargs === SUPPRESS) { + value = SUPPRESS + + // all other types of nargs produce a list + } else { + value = arg_strings.map(v => this._get_value(action, v)) + for (let v of value) { + this._check_value(action, v) + } + } + + // return the converted value + return value + } + + _get_value(action, arg_string) { + let type_func = this._registry_get('type', action.type, action.type) + if (typeof type_func !== 'function') { + let msg = '%r is not callable' + throw new ArgumentError(action, sub(msg, type_func)) + } + + // convert the value to the appropriate type + let result + try { + try { + result = type_func(arg_string) + } catch (err) { + // Dear TC39, why would you ever consider making es6 classes not callable? + // We had one universal interface, [[Call]], which worked for anything + // (with familiar this-instanceof guard for classes). Now we have two. + if (err instanceof TypeError && + /Class constructor .* cannot be invoked without 'new'/.test(err.message)) { + // eslint-disable-next-line new-cap + result = new type_func(arg_string) + } else { + throw err + } + } + + } catch (err) { + // ArgumentTypeErrors indicate errors + if (err instanceof ArgumentTypeError) { + //let name = getattr(action.type, 'name', repr(action.type)) + let msg = err.message + throw new ArgumentError(action, msg) + + // TypeErrors or ValueErrors also indicate errors + } else if (err instanceof TypeError) { + let name = getattr(action.type, 'name', repr(action.type)) + let args = {type: name, value: arg_string} + let msg = 'invalid %(type)s value: %(value)r' + throw new ArgumentError(action, sub(msg, args)) + } else { + throw err + } + } + + // return the converted value + return result + } + + _check_value(action, value) { + // converted value must be one of the choices (if specified) + if (action.choices !== undefined && !_choices_to_array(action.choices).includes(value)) { + let args = {value, + choices: _choices_to_array(action.choices).map(repr).join(', ')} + let msg = 'invalid choice: %(value)r (choose from %(choices)s)' + throw new ArgumentError(action, sub(msg, args)) + } + } + + // ======================= + // Help-formatting methods + // ======================= + format_usage() { + let formatter = this._get_formatter() + formatter.add_usage(this.usage, this._actions, + this._mutually_exclusive_groups) + return formatter.format_help() + } + + format_help() { + let formatter = this._get_formatter() + + // usage + formatter.add_usage(this.usage, this._actions, + this._mutually_exclusive_groups) + + // description + formatter.add_text(this.description) + + // positionals, optionals and user-defined groups + for (let action_group of this._action_groups) { + formatter.start_section(action_group.title) + formatter.add_text(action_group.description) + formatter.add_arguments(action_group._group_actions) + formatter.end_section() + } + + // epilog + formatter.add_text(this.epilog) + + // determine help from format above + return formatter.format_help() + } + + _get_formatter() { + // eslint-disable-next-line new-cap + return new this.formatter_class({ prog: this.prog }) + } + + // ===================== + // Help-printing methods + // ===================== + print_usage(file = undefined) { + if (file === undefined) file = process.stdout + this._print_message(this.format_usage(), file) + } + + print_help(file = undefined) { + if (file === undefined) file = process.stdout + this._print_message(this.format_help(), file) + } + + _print_message(message, file = undefined) { + if (message) { + if (file === undefined) file = process.stderr + file.write(message) + } + } + + // =============== + // Exiting methods + // =============== + exit(status = 0, message = undefined) { + if (message) { + this._print_message(message, process.stderr) + } + process.exit(status) + } + + error(message) { + /* + * error(message: string) + * + * Prints a usage message incorporating the message to stderr and + * exits. + * + * If you override this in a subclass, it should not return -- it + * should either exit or raise an exception. + */ + + // LEGACY (v1 compatibility), debug mode + if (this.debug === true) throw new Error(message) + // end + this.print_usage(process.stderr) + let args = {prog: this.prog, message: message} + this.exit(2, sub('%(prog)s: error: %(message)s\n', args)) + } +})) + + +module.exports = { + ArgumentParser, + ArgumentError, + ArgumentTypeError, + BooleanOptionalAction, + FileType, + HelpFormatter, + ArgumentDefaultsHelpFormatter, + RawDescriptionHelpFormatter, + RawTextHelpFormatter, + MetavarTypeHelpFormatter, + Namespace, + Action, + ONE_OR_MORE, + OPTIONAL, + PARSER, + REMAINDER, + SUPPRESS, + ZERO_OR_MORE +} + +// LEGACY (v1 compatibility), Const alias +Object.defineProperty(module.exports, 'Const', { + get() { + let result = {} + Object.entries({ ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE }).forEach(([ n, v ]) => { + Object.defineProperty(result, n, { + get() { + deprecate(n, sub('use argparse.%s instead of argparse.Const.%s', n, n)) + return v + } + }) + }) + Object.entries({ _UNRECOGNIZED_ARGS_ATTR }).forEach(([ n, v ]) => { + Object.defineProperty(result, n, { + get() { + deprecate(n, sub('argparse.Const.%s is an internal symbol and will no longer be available', n)) + return v + } + }) + }) + return result + }, + enumerable: false +}) +// end diff --git a/node_modules/lv_font_conv/node_modules/argparse/lib/sub.js b/node_modules/lv_font_conv/node_modules/argparse/lib/sub.js new file mode 100644 index 00000000..e3eb3215 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/argparse/lib/sub.js @@ -0,0 +1,67 @@ +// Limited implementation of python % string operator, supports only %s and %r for now +// (other formats are not used here, but may appear in custom templates) + +'use strict' + +const { inspect } = require('util') + + +module.exports = function sub(pattern, ...values) { + let regex = /%(?:(%)|(-)?(\*)?(?:\((\w+)\))?([A-Za-z]))/g + + let result = pattern.replace(regex, function (_, is_literal, is_left_align, is_padded, name, format) { + if (is_literal) return '%' + + let padded_count = 0 + if (is_padded) { + if (values.length === 0) throw new TypeError('not enough arguments for format string') + padded_count = values.shift() + if (!Number.isInteger(padded_count)) throw new TypeError('* wants int') + } + + let str + if (name !== undefined) { + let dict = values[0] + if (typeof dict !== 'object' || dict === null) throw new TypeError('format requires a mapping') + if (!(name in dict)) throw new TypeError(`no such key: '${name}'`) + str = dict[name] + } else { + if (values.length === 0) throw new TypeError('not enough arguments for format string') + str = values.shift() + } + + switch (format) { + case 's': + str = String(str) + break + case 'r': + str = inspect(str) + break + case 'd': + case 'i': + if (typeof str !== 'number') { + throw new TypeError(`%${format} format: a number is required, not ${typeof str}`) + } + str = String(str.toFixed(0)) + break + default: + throw new TypeError(`unsupported format character '${format}'`) + } + + if (padded_count > 0) { + return is_left_align ? str.padEnd(padded_count) : str.padStart(padded_count) + } else { + return str + } + }) + + if (values.length) { + if (values.length === 1 && typeof values[0] === 'object' && values[0] !== null) { + // mapping + } else { + throw new TypeError('not all arguments converted during string formatting') + } + } + + return result +} diff --git a/node_modules/lv_font_conv/node_modules/argparse/lib/textwrap.js b/node_modules/lv_font_conv/node_modules/argparse/lib/textwrap.js new file mode 100644 index 00000000..23d51cdb --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/argparse/lib/textwrap.js @@ -0,0 +1,440 @@ +// Partial port of python's argparse module, version 3.9.0 (only wrap and fill functions): +// https://github.com/python/cpython/blob/v3.9.0b4/Lib/textwrap.py + +'use strict' + +/* + * Text wrapping and filling. + */ + +// Copyright (C) 1999-2001 Gregory P. Ward. +// Copyright (C) 2002, 2003 Python Software Foundation. +// Copyright (C) 2020 argparse.js authors +// Originally written by Greg Ward + +// Hardcode the recognized whitespace characters to the US-ASCII +// whitespace characters. The main reason for doing this is that +// some Unicode spaces (like \u00a0) are non-breaking whitespaces. +// +// This less funky little regex just split on recognized spaces. E.g. +// "Hello there -- you goof-ball, use the -b option!" +// splits into +// Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ +const wordsep_simple_re = /([\t\n\x0b\x0c\r ]+)/ + +class TextWrapper { + /* + * Object for wrapping/filling text. The public interface consists of + * the wrap() and fill() methods; the other methods are just there for + * subclasses to override in order to tweak the default behaviour. + * If you want to completely replace the main wrapping algorithm, + * you'll probably have to override _wrap_chunks(). + * + * Several instance attributes control various aspects of wrapping: + * width (default: 70) + * the maximum width of wrapped lines (unless break_long_words + * is false) + * initial_indent (default: "") + * string that will be prepended to the first line of wrapped + * output. Counts towards the line's width. + * subsequent_indent (default: "") + * string that will be prepended to all lines save the first + * of wrapped output; also counts towards each line's width. + * expand_tabs (default: true) + * Expand tabs in input text to spaces before further processing. + * Each tab will become 0 .. 'tabsize' spaces, depending on its position + * in its line. If false, each tab is treated as a single character. + * tabsize (default: 8) + * Expand tabs in input text to 0 .. 'tabsize' spaces, unless + * 'expand_tabs' is false. + * replace_whitespace (default: true) + * Replace all whitespace characters in the input text by spaces + * after tab expansion. Note that if expand_tabs is false and + * replace_whitespace is true, every tab will be converted to a + * single space! + * fix_sentence_endings (default: false) + * Ensure that sentence-ending punctuation is always followed + * by two spaces. Off by default because the algorithm is + * (unavoidably) imperfect. + * break_long_words (default: true) + * Break words longer than 'width'. If false, those words will not + * be broken, and some lines might be longer than 'width'. + * break_on_hyphens (default: true) + * Allow breaking hyphenated words. If true, wrapping will occur + * preferably on whitespaces and right after hyphens part of + * compound words. + * drop_whitespace (default: true) + * Drop leading and trailing whitespace from lines. + * max_lines (default: None) + * Truncate wrapped lines. + * placeholder (default: ' [...]') + * Append to the last line of truncated text. + */ + + constructor(options = {}) { + let { + width = 70, + initial_indent = '', + subsequent_indent = '', + expand_tabs = true, + replace_whitespace = true, + fix_sentence_endings = false, + break_long_words = true, + drop_whitespace = true, + break_on_hyphens = true, + tabsize = 8, + max_lines = undefined, + placeholder=' [...]' + } = options + + this.width = width + this.initial_indent = initial_indent + this.subsequent_indent = subsequent_indent + this.expand_tabs = expand_tabs + this.replace_whitespace = replace_whitespace + this.fix_sentence_endings = fix_sentence_endings + this.break_long_words = break_long_words + this.drop_whitespace = drop_whitespace + this.break_on_hyphens = break_on_hyphens + this.tabsize = tabsize + this.max_lines = max_lines + this.placeholder = placeholder + } + + + // -- Private methods ----------------------------------------------- + // (possibly useful for subclasses to override) + + _munge_whitespace(text) { + /* + * _munge_whitespace(text : string) -> string + * + * Munge whitespace in text: expand tabs and convert all other + * whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz" + * becomes " foo bar baz". + */ + if (this.expand_tabs) { + text = text.replace(/\t/g, ' '.repeat(this.tabsize)) // not strictly correct in js + } + if (this.replace_whitespace) { + text = text.replace(/[\t\n\x0b\x0c\r]/g, ' ') + } + return text + } + + _split(text) { + /* + * _split(text : string) -> [string] + * + * Split the text to wrap into indivisible chunks. Chunks are + * not quite the same as words; see _wrap_chunks() for full + * details. As an example, the text + * Look, goof-ball -- use the -b option! + * breaks into the following chunks: + * 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', + * 'use', ' ', 'the', ' ', '-b', ' ', 'option!' + * if break_on_hyphens is True, or in: + * 'Look,', ' ', 'goof-ball', ' ', '--', ' ', + * 'use', ' ', 'the', ' ', '-b', ' ', option!' + * otherwise. + */ + let chunks = text.split(wordsep_simple_re) + chunks = chunks.filter(Boolean) + return chunks + } + + _handle_long_word(reversed_chunks, cur_line, cur_len, width) { + /* + * _handle_long_word(chunks : [string], + * cur_line : [string], + * cur_len : int, width : int) + * + * Handle a chunk of text (most likely a word, not whitespace) that + * is too long to fit in any line. + */ + // Figure out when indent is larger than the specified width, and make + // sure at least one character is stripped off on every pass + let space_left + if (width < 1) { + space_left = 1 + } else { + space_left = width - cur_len + } + + // If we're allowed to break long words, then do so: put as much + // of the next chunk onto the current line as will fit. + if (this.break_long_words) { + cur_line.push(reversed_chunks[reversed_chunks.length - 1].slice(0, space_left)) + reversed_chunks[reversed_chunks.length - 1] = reversed_chunks[reversed_chunks.length - 1].slice(space_left) + + // Otherwise, we have to preserve the long word intact. Only add + // it to the current line if there's nothing already there -- + // that minimizes how much we violate the width constraint. + } else if (!cur_line) { + cur_line.push(...reversed_chunks.pop()) + } + + // If we're not allowed to break long words, and there's already + // text on the current line, do nothing. Next time through the + // main loop of _wrap_chunks(), we'll wind up here again, but + // cur_len will be zero, so the next line will be entirely + // devoted to the long word that we can't handle right now. + } + + _wrap_chunks(chunks) { + /* + * _wrap_chunks(chunks : [string]) -> [string] + * + * Wrap a sequence of text chunks and return a list of lines of + * length 'self.width' or less. (If 'break_long_words' is false, + * some lines may be longer than this.) Chunks correspond roughly + * to words and the whitespace between them: each chunk is + * indivisible (modulo 'break_long_words'), but a line break can + * come between any two chunks. Chunks should not have internal + * whitespace; ie. a chunk is either all whitespace or a "word". + * Whitespace chunks will be removed from the beginning and end of + * lines, but apart from that whitespace is preserved. + */ + let lines = [] + let indent + if (this.width <= 0) { + throw Error(`invalid width ${this.width} (must be > 0)`) + } + if (this.max_lines !== undefined) { + if (this.max_lines > 1) { + indent = this.subsequent_indent + } else { + indent = this.initial_indent + } + if (indent.length + this.placeholder.trimStart().length > this.width) { + throw Error('placeholder too large for max width') + } + } + + // Arrange in reverse order so items can be efficiently popped + // from a stack of chucks. + chunks = chunks.reverse() + + while (chunks.length > 0) { + + // Start the list of chunks that will make up the current line. + // cur_len is just the length of all the chunks in cur_line. + let cur_line = [] + let cur_len = 0 + + // Figure out which static string will prefix this line. + let indent + if (lines) { + indent = this.subsequent_indent + } else { + indent = this.initial_indent + } + + // Maximum width for this line. + let width = this.width - indent.length + + // First chunk on line is whitespace -- drop it, unless this + // is the very beginning of the text (ie. no lines started yet). + if (this.drop_whitespace && chunks[chunks.length - 1].trim() === '' && lines.length > 0) { + chunks.pop() + } + + while (chunks.length > 0) { + let l = chunks[chunks.length - 1].length + + // Can at least squeeze this chunk onto the current line. + if (cur_len + l <= width) { + cur_line.push(chunks.pop()) + cur_len += l + + // Nope, this line is full. + } else { + break + } + } + + // The current line is full, and the next chunk is too big to + // fit on *any* line (not just this one). + if (chunks.length && chunks[chunks.length - 1].length > width) { + this._handle_long_word(chunks, cur_line, cur_len, width) + cur_len = cur_line.map(l => l.length).reduce((a, b) => a + b, 0) + } + + // If the last chunk on this line is all whitespace, drop it. + if (this.drop_whitespace && cur_line.length > 0 && cur_line[cur_line.length - 1].trim() === '') { + cur_len -= cur_line[cur_line.length - 1].length + cur_line.pop() + } + + if (cur_line) { + if (this.max_lines === undefined || + lines.length + 1 < this.max_lines || + (chunks.length === 0 || + this.drop_whitespace && + chunks.length === 1 && + !chunks[0].trim()) && cur_len <= width) { + // Convert current line back to a string and store it in + // list of all lines (return value). + lines.push(indent + cur_line.join('')) + } else { + let had_break = false + while (cur_line) { + if (cur_line[cur_line.length - 1].trim() && + cur_len + this.placeholder.length <= width) { + cur_line.push(this.placeholder) + lines.push(indent + cur_line.join('')) + had_break = true + break + } + cur_len -= cur_line[-1].length + cur_line.pop() + } + if (!had_break) { + if (lines) { + let prev_line = lines[lines.length - 1].trimEnd() + if (prev_line.length + this.placeholder.length <= + this.width) { + lines[lines.length - 1] = prev_line + this.placeholder + break + } + } + lines.push(indent + this.placeholder.lstrip()) + } + break + } + } + } + + return lines + } + + _split_chunks(text) { + text = this._munge_whitespace(text) + return this._split(text) + } + + // -- Public interface ---------------------------------------------- + + wrap(text) { + /* + * wrap(text : string) -> [string] + * + * Reformat the single paragraph in 'text' so it fits in lines of + * no more than 'self.width' columns, and return a list of wrapped + * lines. Tabs in 'text' are expanded with string.expandtabs(), + * and all other whitespace characters (including newline) are + * converted to space. + */ + let chunks = this._split_chunks(text) + // not implemented in js + //if (this.fix_sentence_endings) { + // this._fix_sentence_endings(chunks) + //} + return this._wrap_chunks(chunks) + } + + fill(text) { + /* + * fill(text : string) -> string + * + * Reformat the single paragraph in 'text' to fit in lines of no + * more than 'self.width' columns, and return a new string + * containing the entire wrapped paragraph. + */ + return this.wrap(text).join('\n') + } +} + + +// -- Convenience interface --------------------------------------------- + +function wrap(text, options = {}) { + /* + * Wrap a single paragraph of text, returning a list of wrapped lines. + * + * Reformat the single paragraph in 'text' so it fits in lines of no + * more than 'width' columns, and return a list of wrapped lines. By + * default, tabs in 'text' are expanded with string.expandtabs(), and + * all other whitespace characters (including newline) are converted to + * space. See TextWrapper class for available keyword args to customize + * wrapping behaviour. + */ + let { width = 70, ...kwargs } = options + let w = new TextWrapper(Object.assign({ width }, kwargs)) + return w.wrap(text) +} + +function fill(text, options = {}) { + /* + * Fill a single paragraph of text, returning a new string. + * + * Reformat the single paragraph in 'text' to fit in lines of no more + * than 'width' columns, and return a new string containing the entire + * wrapped paragraph. As with wrap(), tabs are expanded and other + * whitespace characters converted to space. See TextWrapper class for + * available keyword args to customize wrapping behaviour. + */ + let { width = 70, ...kwargs } = options + let w = new TextWrapper(Object.assign({ width }, kwargs)) + return w.fill(text) +} + +// -- Loosely related functionality ------------------------------------- + +let _whitespace_only_re = /^[ \t]+$/mg +let _leading_whitespace_re = /(^[ \t]*)(?:[^ \t\n])/mg + +function dedent(text) { + /* + * Remove any common leading whitespace from every line in `text`. + * + * This can be used to make triple-quoted strings line up with the left + * edge of the display, while still presenting them in the source code + * in indented form. + * + * Note that tabs and spaces are both treated as whitespace, but they + * are not equal: the lines " hello" and "\\thello" are + * considered to have no common leading whitespace. + * + * Entirely blank lines are normalized to a newline character. + */ + // Look for the longest leading string of spaces and tabs common to + // all lines. + let margin = undefined + text = text.replace(_whitespace_only_re, '') + let indents = text.match(_leading_whitespace_re) || [] + for (let indent of indents) { + indent = indent.slice(0, -1) + + if (margin === undefined) { + margin = indent + + // Current line more deeply indented than previous winner: + // no change (previous winner is still on top). + } else if (indent.startsWith(margin)) { + // pass + + // Current line consistent with and no deeper than previous winner: + // it's the new winner. + } else if (margin.startsWith(indent)) { + margin = indent + + // Find the largest common whitespace between current line and previous + // winner. + } else { + for (let i = 0; i < margin.length && i < indent.length; i++) { + if (margin[i] !== indent[i]) { + margin = margin.slice(0, i) + break + } + } + } + } + + if (margin) { + text = text.replace(new RegExp('^' + margin, 'mg'), '') + } + return text +} + +module.exports = { wrap, fill, dedent } diff --git a/node_modules/lv_font_conv/node_modules/argparse/package.json b/node_modules/lv_font_conv/node_modules/argparse/package.json new file mode 100644 index 00000000..22fb0a3e --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/argparse/package.json @@ -0,0 +1,67 @@ +{ + "_args": [ + [ + "argparse@2.0.1", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "argparse@2.0.1", + "_id": "argparse@2.0.1", + "_inBundle": false, + "_integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "_location": "/argparse", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "argparse@2.0.1", + "name": "argparse", + "escapedName": "argparse", + "rawSpec": "2.0.1", + "saveSpec": null, + "fetchSpec": "2.0.1" + }, + "_requiredBy": [ + "/", + "/mocha/js-yaml" + ], + "_resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "_spec": "2.0.1", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "bugs": { + "url": "https://github.com/nodeca/argparse/issues" + }, + "description": "CLI arguments parser. Native port of python's argparse.", + "devDependencies": { + "@babel/eslint-parser": "^7.11.0", + "@babel/plugin-syntax-class-properties": "^7.10.4", + "eslint": "^7.5.0", + "mocha": "^8.0.1", + "nyc": "^15.1.0" + }, + "files": [ + "argparse.js", + "lib/" + ], + "homepage": "https://github.com/nodeca/argparse#readme", + "keywords": [ + "cli", + "parser", + "argparse", + "option", + "args" + ], + "license": "Python-2.0", + "main": "argparse.js", + "name": "argparse", + "repository": { + "type": "git", + "url": "git+https://github.com/nodeca/argparse.git" + }, + "scripts": { + "coverage": "npm run test && nyc report --reporter html", + "lint": "eslint .", + "test": "npm run lint && nyc mocha" + }, + "version": "2.0.1" +} diff --git a/node_modules/lv_font_conv/node_modules/bit-buffer/.github/workflows/ci.yml b/node_modules/lv_font_conv/node_modules/bit-buffer/.github/workflows/ci.yml new file mode 100644 index 00000000..8f0f168b --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/bit-buffer/.github/workflows/ci.yml @@ -0,0 +1,36 @@ +name: Node.js CI + +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [10.x, 12.x, 14.x, 15.x] + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - run: npm ci + - run: npm test + + lint: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [10.x, 12.x, 14.x, 15.x] + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - run: npm ci + - run: npm run lint diff --git a/node_modules/lv_font_conv/node_modules/bit-buffer/LICENSE b/node_modules/lv_font_conv/node_modules/bit-buffer/LICENSE new file mode 100644 index 00000000..9194ecce --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/bit-buffer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 bit-buffer developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/bit-buffer/README.md b/node_modules/lv_font_conv/node_modules/bit-buffer/README.md new file mode 100644 index 00000000..3ecf4ab7 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/bit-buffer/README.md @@ -0,0 +1,148 @@ +# BitBuffer + +![Node.js CI](https://github.com/inolen/bit-buffer/workflows/Node.js%20CI/badge.svg) + +BitBuffer provides two objects, `BitView` and `BitStream`. `BitView` is a wrapper for ArrayBuffers, similar to JavaScript's [DataView](https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays/DataView), but with support for bit-level reads and writes. `BitStream` is a wrapper for a `BitView` used to help maintain your current buffer position, as well as to provide higher-level read / write operations such as for ASCII strings. + +## BitView + +### Attributes + +```javascript +bb.buffer // Underlying ArrayBuffer. +``` + +```javascript +bb.bigEndian = true; // Switch to big endian (default is little) +``` + +### Methods + +#### BitView(buffer, optional byteOffset, optional byteLength) + +Default constructor, takes in a single argument of an ArrayBuffer. Optional are the `byteOffset` and `byteLength` arguments to offset and truncate the view's representation of the buffer. + +### getBits(offset, bits, signed) + +Reads `bits` number of bits starting at `offset`, twiddling the bits appropriately to return a proper 32-bit signed or unsigned value. NOTE: While JavaScript numbers are 64-bit floating-point values, we don't bother with anything other than the first 32 bits. + +### getInt8, getUint8, getInt16, getUint16, getInt32, getUint32(offset) + +Shortcuts for getBits, setting the correct `bits` / `signed` values. + +### getFloat32(offset) + +Gets 32 bits from `offset`, and coerces and returns as a proper float32 value. + +### getFloat64(offset) + +Gets 64 bits from `offset`, and coerces and returns as a proper float64 value. + +### setBits(offset, value, bits) + +Sets `bits` number of bits at `offset`. + +### setInt8, setUint8, setInt16, setUint16, setInt32, setUint32(offset) + +Shortcuts for setBits, setting the correct `bits` count. + +### setFloat32(offset) + +Coerces a float32 to uint32 and sets at `offset`. + +### setFloat64(offset) + +Coerces a float64 to two uint32s and sets at `offset`. + + +## BitStream + +### Attributes + +```javascript +bb.byteIndex; // Get current index in bytes. +bb.byteIndex = 0; // Set current index in bytes. +``` + +```javascript +bb.view; // Underlying BitView +``` + +```javascript +bb.length; // Get the length of the stream in bits +``` + +```javascript +bb.bitsLeft; // The number of bits left in the stream +``` + +```javascript +bb.index; // Get the current index in bits +bb.index = 0// Set the current index in bits +``` + +```javascript +bb.bigEndian = true; // Switch to big endian (default is little) +``` + +### Methods + +#### BitStream(view) + +Default constructor, takes in a single argument of a `BitView`, `ArrayBuffer` or node `Buffer`. + +#### BitSteam(buffer, optional byteOffset, optional byteLength) + +Shortcut constructor that initializes a new `BitView(buffer, byteOffset, byteLength)` for the stream to use. + +#### readBits(bits, signed) + +Returns `bits` numbers of bits from the view at the current index, updating the index. + +#### writeBits(value, bits) + +Sets `bits` numbers of bits from `value` in the view at the current index, updating the index. + +#### readUint8(), readUint16(), readUint32(), readInt8(), readInt16(), readInt32() + +Read a 8, 16 or 32 bits (unsigned) integer at the current index, updating the index. + +#### writeUint8(value), writeUint16(value), writeUint32(value), writeInt8(value), writeInt16(value), writeInt32(value) + +Write 8, 16 or 32 bits from `value` as (unsigned) integer at the current index, updating the index. + +#### readFloat32(), readFloat64() + +Read a 32 or 64 bit floating point number at the current index, updating the index. + +#### writeFloat32(value), writeFloat64() + +Set 32 or 64 bits from `value` as floating point value at the current index, updating the index. + +#### readBoolean() + +Read a single bit from the view at the current index, updating the index. + +#### writeBoolean(value) + +Write a single bit to the view at the current index, updating the index. + +#### readASCIIString(optional bytes), readUTF8String(optional bytes) + +Reads bytes from the underlying view at the current index until either `bytes` count is reached or a 0x00 terminator is reached. + +#### writeASCIIString(string, optional bytes), writeUTF8String(string, optional bytes) + +Writes a string followed by a NULL character to the underlying view starting at the current index. If the string is longer than `bytes` it will be truncated, and if it is shorter 0x00 will be written in its place. + +#### readBitStream(length) + +Create a new `BitStream` from the underlying view starting the the current index and a length of `length` bits. Updating the index of the existing `BitStream` + +#### readArrayBuffer(byteLength) + +Read `byteLength` bytes of data from the underlying view as `ArrayBuffer`, updating the index. + +## license + +MIT diff --git a/node_modules/lv_font_conv/node_modules/bit-buffer/bit-buffer.d.ts b/node_modules/lv_font_conv/node_modules/bit-buffer/bit-buffer.d.ts new file mode 100644 index 00000000..72c4b13e --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/bit-buffer/bit-buffer.d.ts @@ -0,0 +1,115 @@ +declare module 'bit-buffer' { + import {Buffer} from 'buffer'; + + export class BitView { + constructor(buffer: ArrayBuffer | Buffer, byteLength?: number); + + readonly buffer: Buffer; + readonly byteLength: number; + bigEndian: boolean; + + getBits(offset: number, bits: number, signed?: boolean): number; + + getInt8(offset: number): number; + + getInt16(offset: number): number; + + getInt32(offset: number): number; + + getUint8(offset: number): number; + + getUint16(offset: number): number; + + getUint32(offset: number): number; + + getFloat32(offset: number): number; + + getFloat64(offset: number): number; + + setBits(offset: number, value: number, bits: number); + + setInt8(offset: number); + + setInt16(offset: number); + + setInt32(offset: number); + + setUint8(offset: number); + + setUint16(offset: number); + + setUint32(offset: number); + + setFloat32(offset: number, value: number); + + setFloat64(offset: number, value: number); + } + + export class BitStream { + constructor(source: ArrayBuffer | Buffer | BitView, byteOffset?: number, byteLength?: number) + + readonly length: number; + readonly bitsLeft: number; + readonly buffer: Buffer; + readonly view: BitView; + byteIndex: number; + index: number; + bigEndian: boolean; + + readBits(bits: number, signed?: boolean): number; + + writeBits(value: number, bits: number); + + readBoolean(): boolean; + + readInt8(): number; + + readUint8(): number; + + readInt16(): number; + + readUint16(): number; + + readInt32(): number; + + readUint32(): number; + + readFloat32(): number; + + readFloat64(): number; + + writeBoolean(value: boolean); + + writeInt8(value: number); + + writeUint8(value: number); + + writeInt16(value: number); + + writeUint16(value: number); + + writeInt32(value: number); + + writeUint32(value: number); + + writeFloat32(value: number); + + writeFloat64(value: number); + + readASCIIString(length?: number): string; + + readUTF8String(length?: number): string; + + writeASCIIString(data: string, length?: number); + + writeUTF8String(data: string, length?: number); + + readBitStream(length: number): BitStream; + + readArrayBuffer(byteLength: number): Uint8Array; + + writeBitStream(stream: BitStream, length?: number); + + writeArrayBuffer(buffer: BitStream, length?: number); + } +} diff --git a/node_modules/lv_font_conv/node_modules/bit-buffer/bit-buffer.js b/node_modules/lv_font_conv/node_modules/bit-buffer/bit-buffer.js new file mode 100644 index 00000000..60c7f795 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/bit-buffer/bit-buffer.js @@ -0,0 +1,502 @@ +(function (root) { + +/********************************************************** + * + * BitView + * + * BitView provides a similar interface to the standard + * DataView, but with support for bit-level reads / writes. + * + **********************************************************/ +var BitView = function (source, byteOffset, byteLength) { + var isBuffer = source instanceof ArrayBuffer || + (typeof Buffer !== 'undefined' && source instanceof Buffer); + + if (!isBuffer) { + throw new Error('Must specify a valid ArrayBuffer or Buffer.'); + } + + byteOffset = byteOffset || 0; + byteLength = byteLength || source.byteLength /* ArrayBuffer */ || source.length /* Buffer */; + + this._view = new Uint8Array(source.buffer || source, byteOffset, byteLength); + + this.bigEndian = false; +}; + +// Used to massage fp values so we can operate on them +// at the bit level. +BitView._scratch = new DataView(new ArrayBuffer(8)); + +Object.defineProperty(BitView.prototype, 'buffer', { + get: function () { return typeof Buffer !== 'undefined' ? Buffer.from(this._view.buffer) : this._view.buffer; }, + enumerable: true, + configurable: false +}); + +Object.defineProperty(BitView.prototype, 'byteLength', { + get: function () { return this._view.length; }, + enumerable: true, + configurable: false +}); + +BitView.prototype._setBit = function (offset, on) { + if (on) { + this._view[offset >> 3] |= 1 << (offset & 7); + } else { + this._view[offset >> 3] &= ~(1 << (offset & 7)); + } +}; + +BitView.prototype.getBits = function (offset, bits, signed) { + var available = (this._view.length * 8 - offset); + + if (bits > available) { + throw new Error('Cannot get ' + bits + ' bit(s) from offset ' + offset + ', ' + available + ' available'); + } + + var value = 0; + for (var i = 0; i < bits;) { + var remaining = bits - i; + var bitOffset = offset & 7; + var currentByte = this._view[offset >> 3]; + + // the max number of bits we can read from the current byte + var read = Math.min(remaining, 8 - bitOffset); + + var mask, readBits; + if (this.bigEndian) { + // create a mask with the correct bit width + mask = ~(0xFF << read); + // shift the bits we want to the start of the byte and mask of the rest + readBits = (currentByte >> (8 - read - bitOffset)) & mask; + + value <<= read; + value |= readBits; + } else { + // create a mask with the correct bit width + mask = ~(0xFF << read); + // shift the bits we want to the start of the byte and mask off the rest + readBits = (currentByte >> bitOffset) & mask; + + value |= readBits << i; + } + + offset += read; + i += read; + } + + if (signed) { + // If we're not working with a full 32 bits, check the + // imaginary MSB for this bit count and convert to a + // valid 32-bit signed value if set. + if (bits !== 32 && value & (1 << (bits - 1))) { + value |= -1 ^ ((1 << bits) - 1); + } + + return value; + } + + return value >>> 0; +}; + +BitView.prototype.setBits = function (offset, value, bits) { + var available = (this._view.length * 8 - offset); + + if (bits > available) { + throw new Error('Cannot set ' + bits + ' bit(s) from offset ' + offset + ', ' + available + ' available'); + } + + for (var i = 0; i < bits;) { + var remaining = bits - i; + var bitOffset = offset & 7; + var byteOffset = offset >> 3; + var wrote = Math.min(remaining, 8 - bitOffset); + + var mask, writeBits, destMask; + if (this.bigEndian) { + // create a mask with the correct bit width + mask = ~(~0 << wrote); + // shift the bits we want to the start of the byte and mask of the rest + writeBits = (value >> (bits - i - wrote)) & mask; + + var destShift = 8 - bitOffset - wrote; + // destination mask to zero all the bits we're changing first + destMask = ~(mask << destShift); + + this._view[byteOffset] = + (this._view[byteOffset] & destMask) + | (writeBits << destShift); + + } else { + // create a mask with the correct bit width + mask = ~(0xFF << wrote); + // shift the bits we want to the start of the byte and mask of the rest + writeBits = value & mask; + value >>= wrote; + + // destination mask to zero all the bits we're changing first + destMask = ~(mask << bitOffset); + + this._view[byteOffset] = + (this._view[byteOffset] & destMask) + | (writeBits << bitOffset); + } + + offset += wrote; + i += wrote; + } +}; + +BitView.prototype.getBoolean = function (offset) { + return this.getBits(offset, 1, false) !== 0; +}; +BitView.prototype.getInt8 = function (offset) { + return this.getBits(offset, 8, true); +}; +BitView.prototype.getUint8 = function (offset) { + return this.getBits(offset, 8, false); +}; +BitView.prototype.getInt16 = function (offset) { + return this.getBits(offset, 16, true); +}; +BitView.prototype.getUint16 = function (offset) { + return this.getBits(offset, 16, false); +}; +BitView.prototype.getInt32 = function (offset) { + return this.getBits(offset, 32, true); +}; +BitView.prototype.getUint32 = function (offset) { + return this.getBits(offset, 32, false); +}; +BitView.prototype.getFloat32 = function (offset) { + BitView._scratch.setUint32(0, this.getUint32(offset)); + return BitView._scratch.getFloat32(0); +}; +BitView.prototype.getFloat64 = function (offset) { + BitView._scratch.setUint32(0, this.getUint32(offset)); + // DataView offset is in bytes. + BitView._scratch.setUint32(4, this.getUint32(offset+32)); + return BitView._scratch.getFloat64(0); +}; + +BitView.prototype.setBoolean = function (offset, value) { + this.setBits(offset, value ? 1 : 0, 1); +}; +BitView.prototype.setInt8 = +BitView.prototype.setUint8 = function (offset, value) { + this.setBits(offset, value, 8); +}; +BitView.prototype.setInt16 = +BitView.prototype.setUint16 = function (offset, value) { + this.setBits(offset, value, 16); +}; +BitView.prototype.setInt32 = +BitView.prototype.setUint32 = function (offset, value) { + this.setBits(offset, value, 32); +}; +BitView.prototype.setFloat32 = function (offset, value) { + BitView._scratch.setFloat32(0, value); + this.setBits(offset, BitView._scratch.getUint32(0), 32); +}; +BitView.prototype.setFloat64 = function (offset, value) { + BitView._scratch.setFloat64(0, value); + this.setBits(offset, BitView._scratch.getUint32(0), 32); + this.setBits(offset+32, BitView._scratch.getUint32(4), 32); +}; +BitView.prototype.getArrayBuffer = function (offset, byteLength) { + var buffer = new Uint8Array(byteLength); + for (var i = 0; i < byteLength; i++) { + buffer[i] = this.getUint8(offset + (i * 8)); + } + return buffer; +}; + +/********************************************************** + * + * BitStream + * + * Small wrapper for a BitView to maintain your position, + * as well as to handle reading / writing of string data + * to the underlying buffer. + * + **********************************************************/ +var reader = function (name, size) { + return function () { + if (this._index + size > this._length) { + throw new Error('Trying to read past the end of the stream'); + } + var val = this._view[name](this._index); + this._index += size; + return val; + }; +}; + +var writer = function (name, size) { + return function (value) { + this._view[name](this._index, value); + this._index += size; + }; +}; + +function readASCIIString(stream, bytes) { + return readString(stream, bytes, false); +} + +function readUTF8String(stream, bytes) { + return readString(stream, bytes, true); +} + +function readString(stream, bytes, utf8) { + if (bytes === 0) { + return ''; + } + var i = 0; + var chars = []; + var append = true; + var fixedLength = !!bytes; + if (!bytes) { + bytes = Math.floor((stream._length - stream._index) / 8); + } + + // Read while we still have space available, or until we've + // hit the fixed byte length passed in. + while (i < bytes) { + var c = stream.readUint8(); + + // Stop appending chars once we hit 0x00 + if (c === 0x00) { + append = false; + + // If we don't have a fixed length to read, break out now. + if (!fixedLength) { + break; + } + } + if (append) { + chars.push(c); + } + + i++; + } + + var string = String.fromCharCode.apply(null, chars); + if (utf8) { + try { + return decodeURIComponent(escape(string)); // https://stackoverflow.com/a/17192845 + } catch (e) { + return string; + } + } else { + return string; + } +} + +function writeASCIIString(stream, string, bytes) { + var length = bytes || string.length + 1; // + 1 for NULL + + for (var i = 0; i < length; i++) { + stream.writeUint8(i < string.length ? string.charCodeAt(i) : 0x00); + } +} + +function writeUTF8String(stream, string, bytes) { + var byteArray = stringToByteArray(string); + + var length = bytes || byteArray.length + 1; // + 1 for NULL + for (var i = 0; i < length; i++) { + stream.writeUint8(i < byteArray.length ? byteArray[i] : 0x00); + } +} + +function stringToByteArray(str) { // https://gist.github.com/volodymyr-mykhailyk/2923227 + var b = [], i, unicode; + for (i = 0; i < str.length; i++) { + unicode = str.charCodeAt(i); + // 0x00000000 - 0x0000007f -> 0xxxxxxx + if (unicode <= 0x7f) { + b.push(unicode); + // 0x00000080 - 0x000007ff -> 110xxxxx 10xxxxxx + } else if (unicode <= 0x7ff) { + b.push((unicode >> 6) | 0xc0); + b.push((unicode & 0x3F) | 0x80); + // 0x00000800 - 0x0000ffff -> 1110xxxx 10xxxxxx 10xxxxxx + } else if (unicode <= 0xffff) { + b.push((unicode >> 12) | 0xe0); + b.push(((unicode >> 6) & 0x3f) | 0x80); + b.push((unicode & 0x3f) | 0x80); + // 0x00010000 - 0x001fffff -> 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + } else { + b.push((unicode >> 18) | 0xf0); + b.push(((unicode >> 12) & 0x3f) | 0x80); + b.push(((unicode >> 6) & 0x3f) | 0x80); + b.push((unicode & 0x3f) | 0x80); + } + } + + return b; +} + +var BitStream = function (source, byteOffset, byteLength) { + var isBuffer = source instanceof ArrayBuffer || + (typeof Buffer !== 'undefined' && source instanceof Buffer); + + if (!(source instanceof BitView) && !isBuffer) { + throw new Error('Must specify a valid BitView, ArrayBuffer or Buffer'); + } + + if (isBuffer) { + this._view = new BitView(source, byteOffset, byteLength); + } else { + this._view = source; + } + + this._index = 0; + this._startIndex = 0; + this._length = this._view.byteLength * 8; +}; + +Object.defineProperty(BitStream.prototype, 'index', { + get: function () { return this._index - this._startIndex; }, + set: function (val) { this._index = val + this._startIndex; }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(BitStream.prototype, 'length', { + get: function () { return this._length - this._startIndex; }, + set: function (val) { this._length = val + this._startIndex; }, + enumerable : true, + configurable: true +}); + +Object.defineProperty(BitStream.prototype, 'bitsLeft', { + get: function () { return this._length - this._index; }, + enumerable : true, + configurable: true +}); + +Object.defineProperty(BitStream.prototype, 'byteIndex', { + // Ceil the returned value, over compensating for the amount of + // bits written to the stream. + get: function () { return Math.ceil(this._index / 8); }, + set: function (val) { this._index = val * 8; }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(BitStream.prototype, 'buffer', { + get: function () { return this._view.buffer; }, + enumerable: true, + configurable: false +}); + +Object.defineProperty(BitStream.prototype, 'view', { + get: function () { return this._view; }, + enumerable: true, + configurable: false +}); + +Object.defineProperty(BitStream.prototype, 'bigEndian', { + get: function () { return this._view.bigEndian; }, + set: function (val) { this._view.bigEndian = val; }, + enumerable: true, + configurable: false +}); + +BitStream.prototype.readBits = function (bits, signed) { + var val = this._view.getBits(this._index, bits, signed); + this._index += bits; + return val; +}; + +BitStream.prototype.writeBits = function (value, bits) { + this._view.setBits(this._index, value, bits); + this._index += bits; +}; + +BitStream.prototype.readBoolean = reader('getBoolean', 1); +BitStream.prototype.readInt8 = reader('getInt8', 8); +BitStream.prototype.readUint8 = reader('getUint8', 8); +BitStream.prototype.readInt16 = reader('getInt16', 16); +BitStream.prototype.readUint16 = reader('getUint16', 16); +BitStream.prototype.readInt32 = reader('getInt32', 32); +BitStream.prototype.readUint32 = reader('getUint32', 32); +BitStream.prototype.readFloat32 = reader('getFloat32', 32); +BitStream.prototype.readFloat64 = reader('getFloat64', 64); + +BitStream.prototype.writeBoolean = writer('setBoolean', 1); +BitStream.prototype.writeInt8 = writer('setInt8', 8); +BitStream.prototype.writeUint8 = writer('setUint8', 8); +BitStream.prototype.writeInt16 = writer('setInt16', 16); +BitStream.prototype.writeUint16 = writer('setUint16', 16); +BitStream.prototype.writeInt32 = writer('setInt32', 32); +BitStream.prototype.writeUint32 = writer('setUint32', 32); +BitStream.prototype.writeFloat32 = writer('setFloat32', 32); +BitStream.prototype.writeFloat64 = writer('setFloat64', 64); + +BitStream.prototype.readASCIIString = function (bytes) { + return readASCIIString(this, bytes); +}; + +BitStream.prototype.readUTF8String = function (bytes) { + return readUTF8String(this, bytes); +}; + +BitStream.prototype.writeASCIIString = function (string, bytes) { + writeASCIIString(this, string, bytes); +}; + +BitStream.prototype.writeUTF8String = function (string, bytes) { + writeUTF8String(this, string, bytes); +}; +BitStream.prototype.readBitStream = function(bitLength) { + var slice = new BitStream(this._view); + slice._startIndex = this._index; + slice._index = this._index; + slice.length = bitLength; + this._index += bitLength; + return slice; +}; + +BitStream.prototype.writeBitStream = function(stream, length) { + if (!length) { + length = stream.bitsLeft; + } + + var bitsToWrite; + while (length > 0) { + bitsToWrite = Math.min(length, 32); + this.writeBits(stream.readBits(bitsToWrite), bitsToWrite); + length -= bitsToWrite; + } +}; + +BitStream.prototype.readArrayBuffer = function(byteLength) { + var buffer = this._view.getArrayBuffer(this._index, byteLength); + this._index += (byteLength * 8); + return buffer; +}; + +BitStream.prototype.writeArrayBuffer = function(buffer, byteLength) { + this.writeBitStream(new BitStream(buffer), byteLength * 8); +}; + +// AMD / RequireJS +if (typeof define !== 'undefined' && define.amd) { + define(function () { + return { + BitView: BitView, + BitStream: BitStream + }; + }); +} +// Node.js +else if (typeof module !== 'undefined' && module.exports) { + module.exports = { + BitView: BitView, + BitStream: BitStream + }; +} + +}(this)); diff --git a/node_modules/lv_font_conv/node_modules/bit-buffer/package.json b/node_modules/lv_font_conv/node_modules/bit-buffer/package.json new file mode 100644 index 00000000..f2e2d2ce --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/bit-buffer/package.json @@ -0,0 +1,71 @@ +{ + "_args": [ + [ + "bit-buffer@0.2.5", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "bit-buffer@0.2.5", + "_id": "bit-buffer@0.2.5", + "_inBundle": false, + "_integrity": "sha512-x1yGnmXvFg6e3DiyRztElbcn1bsCTFSoM/ncAzY62uE0JdTl5xlKJd0ooqLYoPbhdsnpehSIQrdIvclcZJYwiA==", + "_location": "/bit-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "bit-buffer@0.2.5", + "name": "bit-buffer", + "escapedName": "bit-buffer", + "rawSpec": "0.2.5", + "saveSpec": null, + "fetchSpec": "0.2.5" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/bit-buffer/-/bit-buffer-0.2.5.tgz", + "_spec": "0.2.5", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "author": { + "name": "Anthony Pesch" + }, + "bugs": { + "url": "https://github.com/inolen/bit-buffer/issues" + }, + "contributors": [ + { + "name": "Robin Appelman" + } + ], + "description": "Bit-level reads and writes for ArrayBuffers", + "devDependencies": { + "@types/node": "^14.14.22", + "jshint": "^2.12.0", + "mocha": "^8.2.1" + }, + "directories": { + "test": "test" + }, + "gitHead": "cd4417237bed1f22dd5adfd8a6b961ea7234d9c9", + "homepage": "https://github.com/inolen/bit-buffer#readme", + "keywords": [ + "dataview", + "arraybuffer", + "bit", + "bits" + ], + "license": "MIT", + "main": "bit-buffer.js", + "name": "bit-buffer", + "repository": { + "type": "git", + "url": "git://github.com/inolen/bit-buffer.git" + }, + "scripts": { + "lint": "jshint bit-buffer.js", + "test": "mocha --ui tdd" + }, + "types": "./bit-buffer.d.ts", + "version": "0.2.5" +} diff --git a/node_modules/lv_font_conv/node_modules/bit-buffer/test.js b/node_modules/lv_font_conv/node_modules/bit-buffer/test.js new file mode 100644 index 00000000..a53fc87b --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/bit-buffer/test.js @@ -0,0 +1,628 @@ +var assert = require('assert'), + BitView = require('./bit-buffer').BitView, + BitStream = require('./bit-buffer').BitStream; + +suite('BitBuffer', function () { + var array, bv, bsw, bsr; + + setup(function () { + array = new ArrayBuffer(64); + bv = new BitView(array); + bsw = new BitStream(bv); + // Test initializing straight from the array. + bsr = new BitStream(array); + }); + + test('Min / max signed 5 bits', function () { + var signed_max = (1 << 4) - 1; + + bsw.writeBits(signed_max, 5); + bsw.writeBits(-signed_max - 1, 5); + assert(bsr.readBits(5, true) === signed_max); + assert(bsr.readBits(5, true) === -signed_max - 1); + }); + + test('Min / max unsigned 5 bits', function () { + var unsigned_max = (1 << 5) - 1; + + bsw.writeBits(unsigned_max, 5); + bsw.writeBits(-unsigned_max, 5); + assert.equal(bsr.readBits(5), unsigned_max); + assert.equal(bsr.readBits(5), 1); + }); + + test('Min / max int8', function () { + var signed_max = 0x7F; + + bsw.writeInt8(signed_max); + bsw.writeInt8(-signed_max - 1); + assert.equal(bsr.readInt8(), signed_max); + assert.equal(bsr.readInt8(), -signed_max - 1); + }); + + test('Min / max uint8', function () { + var unsigned_max = 0xFF; + + bsw.writeUint8(unsigned_max); + bsw.writeUint8(-unsigned_max); + assert.equal(bsr.readUint8(), unsigned_max); + assert.equal(bsr.readUint8(), 1); + }); + + test('Min / max int16', function () { + var signed_max = 0x7FFF; + + bsw.writeInt16(signed_max); + bsw.writeInt16(-signed_max - 1); + assert.equal(bsr.readInt16(), signed_max); + assert.equal(bsr.readInt16(), -signed_max - 1); + }); + + test('Min / max uint16', function () { + var unsigned_max = 0xFFFF; + + bsw.writeUint16(unsigned_max); + bsw.writeUint16(-unsigned_max); + assert.equal(bsr.readUint16(), unsigned_max); + assert.equal(bsr.readUint16(), 1); + }); + + test('Min / max int32', function () { + var signed_max = 0x7FFFFFFF; + + bsw.writeInt32(signed_max); + bsw.writeInt32(-signed_max - 1); + assert.equal(bsr.readInt32(), signed_max); + assert.equal(bsr.readInt32(), -signed_max - 1); + }); + + test('Min / max uint32', function () { + var unsigned_max = 0xFFFFFFFF; + + bsw.writeUint32(unsigned_max); + bsw.writeUint32(-unsigned_max); + assert.equal(bsr.readUint32(), unsigned_max); + assert.equal(bsr.readUint32(), 1); + }); + + test('Unaligned reads', function () { + bsw.writeBits(13, 5); + bsw.writeUint8(0xFF); + bsw.writeBits(14, 5); + + assert.equal(bsr.readBits(5), 13); + assert.equal(bsr.readUint8(), 0xFF); + assert.equal(bsr.readBits(5), 14); + }); + + test('Min / max float32 (normal values)', function () { + var scratch = new DataView(new ArrayBuffer(8)); + + scratch.setUint32(0, 0x00800000); + scratch.setUint32(4, 0x7f7fffff); + + var min = scratch.getFloat32(0); + var max = scratch.getFloat32(4); + + bsw.writeFloat32(min); + bsw.writeFloat32(max); + + assert.equal(bsr.readFloat32(), min); + assert.equal(bsr.readFloat32(), max); + }); + + test('Min / max float64 (normal values)', function () { + var scratch = new DataView(new ArrayBuffer(16)); + + scratch.setUint32(0, 0x00100000); + scratch.setUint32(4, 0x00000000); + scratch.setUint32(8, 0x7fefffff); + scratch.setUint32(12, 0xffffffff); + + var min = scratch.getFloat64(0); + var max = scratch.getFloat64(8); + + bsw.writeFloat64(min); + bsw.writeFloat64(max); + + assert.equal(bsr.readFloat64(), min); + assert.equal(bsr.readFloat64(), max); + }); + + test('Overwrite previous value with 0', function () { + bv.setUint8(0, 13); + bv.setUint8(0, 0); + + assert.equal(bv.getUint8(0), 0); + }); + + test('Read / write ASCII string, fixed length', function () { + var str = 'foobar'; + var len = 16; + + bsw.writeASCIIString(str, len); + assert.equal(bsw.byteIndex, len); + + assert.equal(bsr.readASCIIString(len), str); + assert.equal(bsr.byteIndex, len); + }); + + test('Read / write ASCII string, unknown length', function () { + var str = 'foobar'; + + bsw.writeASCIIString(str); + assert.equal(bsw.byteIndex, str.length + 1); // +1 for 0x00 + + assert.equal(bsr.readASCIIString(), str); + assert.equal(bsr.byteIndex, str.length + 1); + }); + + test('Read ASCII string, 0 length', function () { + var str = 'foobar'; + + bsw.writeASCIIString(str); + assert.equal(bsw.byteIndex, str.length + 1); // +1 for 0x00 + + assert.equal(bsr.readASCIIString(0), ''); + assert.equal(bsr.byteIndex, 0); + }); + + test('Read overflow', function () { + var exception = false; + + try { + bsr.readASCIIString(128); + } catch (e) { + exception = true; + } + + assert(exception); + }); + + test('Write overflow', function () { + var exception = false; + + try { + bsw.writeASCIIString('foobar', 128); + } catch (e) { + exception = true; + } + + assert(exception); + }); + + test('Get boolean', function () { + bv.setUint8(0, 1); + + assert(bv.getBoolean(0)); + + bv.setUint8(0, 0); + assert(!bv.getBoolean(0)); + }); + + test('Set boolean', function () { + bv.setBoolean(0, true); + + assert(bv.getBoolean(0)); + + bv.setBoolean(0, false); + + assert(!bv.getBoolean(0)); + }); + + test('Read boolean', function () { + bv.setBits(0, 1, 1); + bv.setBits(1, 0, 1); + + assert(bsr.readBoolean()); + assert(!bsr.readBoolean()); + }); + + test('Write boolean', function () { + bsr.writeBoolean(true); + assert.equal(bv.getBits(0, 1, false), 1); + bsr.writeBoolean(false); + assert.equal(bv.getBits(1, 1, false), 0); + }); + + test('Read / write UTF8 string, only ASCII characters', function () { + var str = 'foobar'; + + bsw.writeUTF8String(str); + assert(bsw.byteIndex === str.length + 1); // +1 for 0x00 + + assert.equal(bsr.readUTF8String(), str); + assert.equal(bsr.byteIndex, str.length + 1); + }); + + test('Read / write UTF8 string, non ASCII characters', function () { + var str = '日本語'; + + var bytes = [ + 0xE6, + 0x97, + 0xA5, + 0xE6, + 0x9C, + 0xAC, + 0xE8, + 0xAA, + 0x9E + ]; + + bsw.writeUTF8String(str); + + for (var i = 0; i < bytes.length; i++) { + assert.equal(bytes[i], bv.getBits(i * 8, 8)); + } + + assert.equal(bsw.byteIndex, bytes.length + 1); // +1 for 0x00 + + assert.equal(str, bsr.readUTF8String()); + assert.equal(bsr.byteIndex, bytes.length + 1); + }); + + test('readBitStream', function () { + bsw.writeBits(0xF0, 8); //0b11110000 + bsw.writeBits(0xF1, 8); //0b11110001 + bsr.readBits(3); //offset + var slice = bsr.readBitStream(8); + assert.equal(slice.readBits(6), 0x3E); //0b111110 + assert.equal(9, slice._index); + assert.equal(6, slice.index); + assert.equal(8, slice.length); + assert.equal(2, slice.bitsLeft); + + assert.equal(bsr._index, 11); + assert.equal((64 * 8) - 11, bsr.bitsLeft); + }); + + test('readBitStream overflow', function () { + bsw.writeBits(0xF0, 8); //0b11110000 + bsw.writeBits(0xF1, 8); //0b11110001 + bsr.readBits(3); //offset + var slice = bsr.readBitStream(4); + + var exception = false; + + try { + slice.readUint8(); + } catch (e) { + exception = true; + } + + assert(exception); + }); + + test('writeBitStream', function () { + var buf = new ArrayBuffer(64); + var sourceStream = new BitStream(buf); + + sourceStream.writeBits(0xF0, 8); //0b11110000 + sourceStream.writeBits(0xF1, 8); //0b11110001 + sourceStream.index = 0; + sourceStream.readBits(3); //offset + bsr.writeBitStream(sourceStream, 8); + assert.equal(8, bsr.index); + bsr.index = 0; + assert.equal(bsr.readBits(6), 0x3E); //0b00111110 + assert.equal(11, sourceStream.index); + + var bin = new Uint8Array(buf); + assert.equal(bin[0], 0xF0); + assert.equal(bin[1], 0xF1); + }); + + test('writeBitStream Buffer', function () { + var buf = Buffer.alloc(64); + var sourceStream = new BitStream(buf); + + sourceStream.writeBits(0xF0, 8); //0b11110000 + sourceStream.writeBits(0xF1, 8); //0b11110001 + sourceStream.index = 0; + sourceStream.readBits(3); //offset + bsr.writeBitStream(sourceStream, 8); + assert.equal(8, bsr.index); + bsr.index = 0; + assert.equal(bsr.readBits(6), 0x3E); //0b00111110 + assert.equal(11, sourceStream.index); + + var bin = new Uint8Array(buf.buffer); + assert.equal(bin[0], 0xF0); + assert.equal(bin[1], 0xF1); + }); + + test('writeBitStream long', function () { + var sourceStream = new BitStream(new ArrayBuffer(64)); + + sourceStream.writeBits(0xF0, 8); + sourceStream.writeBits(0xF1, 8); + sourceStream.writeBits(0xF1, 8); + sourceStream.writeBits(0xF1, 8); + sourceStream.writeBits(0xF1, 8); + sourceStream.index = 0; + sourceStream.readBits(3); //offset + bsr.index = 3; + bsr.writeBitStream(sourceStream, 35); + assert.equal(38, bsr.index); + bsr.index = 3; + assert.equal(bsr.readBits(35), 1044266558); + assert.equal(38, sourceStream.index); + }); + + test('readArrayBuffer', function () { + bsw.writeBits(0xF0, 8); //0b11110000 + bsw.writeBits(0xF1, 8); //0b11110001 + bsw.writeBits(0xF0, 8); //0b11110000 + bsr.readBits(3); //offset + + var buffer = bsr.readArrayBuffer(2); + + assert.equal(0x3E, buffer[0]); //0b00111110 + assert.equal(0x1E, buffer[1]); //0b00011110 + + assert.equal(3 + (2 * 8), bsr._index); + }); + + test('writeArrayBuffer', function () { + var source = new Uint8Array(4); + source[0] = 0xF0; + source[1] = 0xF1; + source[2] = 0xF1; + bsr.readBits(3); //offset + + bsr.writeArrayBuffer(source.buffer, 2); + assert.equal(19, bsr.index); + + bsr.index = 0; + + assert.equal(bsr.readBits(8), 128); + }); + + test('Get buffer from view', function () { + bv.setBits(0, 0xFFFFFFFF, 32); + var buffer = bv.buffer; + + assert.equal(64, buffer.length); + assert.equal(0xFFFF, buffer.readUInt16LE(0)); + }); + + test('Get buffer from stream', function () { + bsw.writeBits(0xFFFFFFFF, 32); + var buffer = bsr.buffer; + + assert.equal(64, buffer.length); + assert.equal(0xFFFF, buffer.readUInt16LE(0)); + }); +}); + +suite('Reading big/little endian', function () { + var array, u8, bv, bsw, bsr; + + setup(function () { + array = new ArrayBuffer(64); + u8 = new Uint8Array(array); + u8[0] = 0x01; + u8[1] = 0x02; + // Test initializing straight from the array. + bsr = new BitStream(array); + }); + + test('4b, little-endian', function () { + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(4)); + result.push(bsr.readBits(4)); + result.push(bsr.readBits(4)); + result.push(bsr.readBits(4)); + + // 0000 0001 0000 0010 [01 02] + // [#2] [#1] [#4] [#3] + assert.deepEqual(result, [1, 0, 2, 0]); + }); + + test('8b, little-endian', function () { + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(8)); + result.push(bsr.readBits(8)); + + // 0000 0001 0000 0010 [01 02] + // [ #1] [ #2] + assert.deepEqual(result, [1, 2]); + }); + + test('10b, little-endian', function () { + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(10)); + + // 0000 0001 0000 0010 [01 02] + // ... #1] [ #2][#1... + assert.deepEqual(result, [513]); + }); + + test('16b, little-endian', function () { + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(16)); + + // 0000 0001 0000 0010 [01 02] + // [ #1] + assert.deepEqual(result, [0x201]); + }); + + test('24b, little-endian', function () { + u8[2] = 0x03; + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(24)); + + // 0000 0001 0000 0010 0000 0011 [01 02 03] + // [ #1] + assert.deepEqual(result, [0x30201]); + }); + + test('4b, big-endian', function () { + bsr.bigEndian = true; + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(4)); + result.push(bsr.readBits(4)); + result.push(bsr.readBits(4)); + result.push(bsr.readBits(4)); + + // 0000 0001 0000 0010 [01 02] + // [#1] [#2] [#3] [#4] + assert.deepEqual(result, [0, 1, 0, 2]); + }); + + test('8b, big-endian', function () { + bsr.bigEndian = true; + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(8)); + result.push(bsr.readBits(8)); + + // 0000 0001 0000 0010 [01 02] + // [ #1] [ #2] + assert.deepEqual(result, [1, 2]); + }); + + test('10b, big-endian', function () { + bsr.bigEndian = true; + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(10)); + result.push(bsr.readBits(6)); + + // 0000 0001 0000 0010 [01 02] + // [ #1][ #2] + assert.deepEqual(result, [4, 2]); + }); + + test('16b, big-endian', function () { + bsr.bigEndian = true; + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(16)); + + // 0000 0001 0000 0010 [01 02] + // [ #1] + assert.deepEqual(result, [0x102]); + }); + + test('24b, big-endian', function () { + u8[2] = 0x03; + bsr.bigEndian = true; + assert.equal(bsr.index, 0, 'BitStream didn\'t init at offset 0'); + + var result = []; + result.push(bsr.readBits(24)); + + // 0000 0001 0000 0010 0000 0011 [01 02 03] + // [ #1] + assert.deepEqual(result, [0x10203]); + }); +}); + +suite('Writing big/little endian', function () { + var array, u8, bv, bsw, bsr; + + setup(function () { + array = new ArrayBuffer(2); + u8 = new Uint8Array(array); + bv = new BitView(array); + bsw = new BitStream(bv); + }); + + test('4b, little-endian', function () { + // 0000 0001 0000 0010 [01 02] + // [#2] [#1] [#4] [#3] + bsw.writeBits(1, 4); + bsw.writeBits(0, 4); + bsw.writeBits(2, 4); + bsw.writeBits(0, 4); + + assert.deepEqual(u8, new Uint8Array([0x01, 0x02])); + }); + + test('8b, little-endian', function () { + // 0000 0001 0000 0010 [01 02] + // [ #1] [ #2] + bsw.writeBits(1, 8); + bsw.writeBits(2, 8); + + assert.deepEqual(u8, new Uint8Array([0x01, 0x02])); + }); + + test('10b, little-endian', function () { + // 0000 0001 0000 0010 [01 02] + // ... #1] [ #2][#1... + bsw.writeBits(513, 10); + + assert.deepEqual(u8, new Uint8Array([0x01, 0x02])); + }); + + test('16b, little-endian', function () { + // 0000 0001 0000 0010 [01 02] + // [ #1] + bsw.writeBits(0x201, 16); + + assert.deepEqual(u8, new Uint8Array([0x01, 0x02])); + }); + + test('4b, big-endian', function () { + bsw.bigEndian = true; + + // 0000 0001 0000 0010 [01 02] + // [#1] [#2] [#3] [#4] + bsw.writeBits(0, 4); + bsw.writeBits(1, 4); + bsw.writeBits(0, 4); + bsw.writeBits(2, 4); + + assert.deepEqual(u8, new Uint8Array([0x01, 0x02])); + }); + + test('8b, big-endian', function () { + bsw.bigEndian = true; + + // 0000 0001 0000 0010 [01 02] + // [ #1] [ #2] + bsw.writeBits(1, 8); + bsw.writeBits(2, 8); + + assert.deepEqual(u8, new Uint8Array([0x01, 0x02])); + }); + + test('10b, big-endian', function () { + bsw.bigEndian = true; + + // 0000 0001 0000 0010 [01 02] + // [ #1][ #2] + bsw.writeBits(4, 10); + bsw.writeBits(2, 6); + + assert.deepEqual(u8, new Uint8Array([0x01, 0x02])); + }); + + test('16b, big-endian', function () { + bsw.bigEndian = true; + + // 0000 0001 0000 0010 [01 02] + // [ #1] + bsw.writeBits(0x102, 16); + + assert.deepEqual(u8, new Uint8Array([0x01, 0x02])); + }); +}); diff --git a/node_modules/lv_font_conv/node_modules/debug/LICENSE b/node_modules/lv_font_conv/node_modules/debug/LICENSE new file mode 100644 index 00000000..658c933d --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/lv_font_conv/node_modules/debug/README.md b/node_modules/lv_font_conv/node_modules/debug/README.md new file mode 100644 index 00000000..88dae35d --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/debug/README.md @@ -0,0 +1,455 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example [_worker.js_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows command prompt notes + +##### CMD + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Example: + +```cmd +set DEBUG=* & node app.js +``` + +##### PowerShell (VS Code default) + +PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Example: + +```cmd +$env:DEBUG='app';node app.js +``` + +Then, run the program to be debugged as usual. + +npm script example: +```js + "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", +``` + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/stdout.js): + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +## Extend +You can simply extend debugger +```js +const log = require('debug')('auth'); + +//creates new debug instance with extended namespace +const logSign = log.extend('sign'); +const logLogin = log.extend('login'); + +log('hello'); // auth hello +logSign('hello'); //auth:sign hello +logLogin('hello'); //auth:login hello +``` + +## Set dynamically + +You can also enable debug dynamically by calling the `enable()` method : + +```js +let debug = require('debug'); + +console.log(1, debug.enabled('test')); + +debug.enable('test'); +console.log(2, debug.enabled('test')); + +debug.disable(); +console.log(3, debug.enabled('test')); + +``` + +print : +``` +1 false +2 true +3 false +``` + +Usage : +`enable(namespaces)` +`namespaces` can include modes separated by a colon and wildcards. + +Note that calling `enable()` completely overrides previously set DEBUG variable : + +``` +$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' +=> false +``` + +`disable()` + +Will disable all namespaces. The functions returns the namespaces currently +enabled (and skipped). This can be useful if you want to disable debugging +temporarily without knowing what was enabled to begin with. + +For example: + +```js +let debug = require('debug'); +debug.enable('foo:*,-foo:bar'); +let namespaces = debug.disable(); +debug.enable(namespaces); +``` + +Note: There is no guarantee that the string will be identical to the initial +enable string, but semantically they will be identical. + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/debug/package.json b/node_modules/lv_font_conv/node_modules/debug/package.json new file mode 100644 index 00000000..c9f15f8c --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/debug/package.json @@ -0,0 +1,111 @@ +{ + "_args": [ + [ + "debug@4.3.1", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "debug@4.3.1", + "_id": "debug@4.3.1", + "_inBundle": false, + "_integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", + "_location": "/debug", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "debug@4.3.1", + "name": "debug", + "escapedName": "debug", + "rawSpec": "4.3.1", + "saveSpec": null, + "fetchSpec": "4.3.1" + }, + "_requiredBy": [ + "/", + "/@babel/core", + "/@babel/helper-define-polyfill-provider", + "/@babel/traverse", + "/@eslint/eslintrc", + "/eslint", + "/istanbul-lib-source-maps", + "/mocha" + ], + "_resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", + "_spec": "4.3.1", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./src/browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + }, + { + "name": "Andrew Rhyne", + "email": "rhyneandrew@gmail.com" + }, + { + "name": "Josh Junon", + "email": "josh@junon.me" + } + ], + "dependencies": { + "ms": "2.1.2" + }, + "description": "small debugging utility", + "devDependencies": { + "brfs": "^2.0.1", + "browserify": "^16.2.3", + "coveralls": "^3.0.2", + "istanbul": "^0.4.5", + "karma": "^3.1.4", + "karma-browserify": "^6.0.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "xo": "^0.23.0" + }, + "engines": { + "node": ">=6.0" + }, + "files": [ + "src", + "LICENSE", + "README.md" + ], + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "license": "MIT", + "main": "./src/index.js", + "name": "debug", + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + }, + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "scripts": { + "lint": "xo", + "test": "npm run test:node && npm run test:browser && npm run lint", + "test:browser": "karma start --single-run", + "test:coverage": "cat ./coverage/lcov.info | coveralls", + "test:node": "istanbul cover _mocha -- test.js" + }, + "version": "4.3.1" +} diff --git a/node_modules/lv_font_conv/node_modules/debug/src/browser.js b/node_modules/lv_font_conv/node_modules/debug/src/browser.js new file mode 100644 index 00000000..cd0fc35d --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/debug/src/browser.js @@ -0,0 +1,269 @@ +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ +exports.log = console.debug || console.log || (() => {}); + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; diff --git a/node_modules/lv_font_conv/node_modules/debug/src/common.js b/node_modules/lv_font_conv/node_modules/debug/src/common.js new file mode 100644 index 00000000..392a8e00 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/debug/src/common.js @@ -0,0 +1,261 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; diff --git a/node_modules/lv_font_conv/node_modules/debug/src/index.js b/node_modules/lv_font_conv/node_modules/debug/src/index.js new file mode 100644 index 00000000..bf4c57f2 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/lv_font_conv/node_modules/debug/src/node.js b/node_modules/lv_font_conv/node_modules/debug/src/node.js new file mode 100644 index 00000000..79bc085c --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/debug/src/node.js @@ -0,0 +1,263 @@ +/** + * Module dependencies. + */ + +const tty = require('tty'); +const util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; diff --git a/node_modules/lv_font_conv/node_modules/make-error/LICENSE b/node_modules/lv_font_conv/node_modules/make-error/LICENSE new file mode 100644 index 00000000..9dcf797e --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/make-error/LICENSE @@ -0,0 +1,5 @@ +Copyright 2014 Julien Fontanet + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/make-error/README.md b/node_modules/lv_font_conv/node_modules/make-error/README.md new file mode 100644 index 00000000..5c089a26 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/make-error/README.md @@ -0,0 +1,112 @@ +# make-error + +[![Package Version](https://badgen.net/npm/v/make-error)](https://npmjs.org/package/make-error) [![Build Status](https://travis-ci.org/JsCommunity/make-error.png?branch=master)](https://travis-ci.org/JsCommunity/make-error) [![PackagePhobia](https://badgen.net/packagephobia/install/make-error)](https://packagephobia.now.sh/result?p=make-error) [![Latest Commit](https://badgen.net/github/last-commit/JsCommunity/make-error)](https://github.com/JsCommunity/make-error/commits/master) + +> Make your own error types! + +## Features + +- Compatible Node & browsers +- `instanceof` support +- `error.name` & `error.stack` support +- compatible with [CSP](https://en.wikipedia.org/wiki/Content_Security_Policy) (i.e. no `eval()`) + +## Installation + +### Node & [Browserify](http://browserify.org/)/[Webpack](https://webpack.js.org/) + +Installation of the [npm package](https://npmjs.org/package/make-error): + +``` +> npm install --save make-error +``` + +Then require the package: + +```javascript +var makeError = require("make-error"); +``` + +### Browser + +You can directly use the build provided at [unpkg.com](https://unpkg.com): + +```html + +``` + +## Usage + +### Basic named error + +```javascript +var CustomError = makeError("CustomError"); + +// Parameters are forwarded to the super class (here Error). +throw new CustomError("a message"); +``` + +### Advanced error class + +```javascript +function CustomError(customValue) { + CustomError.super.call(this, "custom error message"); + + this.customValue = customValue; +} +makeError(CustomError); + +// Feel free to extend the prototype. +CustomError.prototype.myMethod = function CustomError$myMethod() { + console.log("CustomError.myMethod (%s, %s)", this.code, this.message); +}; + +//----- + +try { + throw new CustomError(42); +} catch (error) { + error.myMethod(); +} +``` + +### Specialized error + +```javascript +var SpecializedError = makeError("SpecializedError", CustomError); + +throw new SpecializedError(42); +``` + +### Inheritance + +> Best for ES2015+. + +```javascript +import { BaseError } from "make-error"; + +class CustomError extends BaseError { + constructor() { + super("custom error message"); + } +} +``` + +## Related + +- [make-error-cause](https://www.npmjs.com/package/make-error-cause): Make your own error types, with a cause! + +## Contributions + +Contributions are _very_ welcomed, either on the documentation or on +the code. + +You may: + +- report any [issue](https://github.com/JsCommunity/make-error/issues) + you've encountered; +- fork and create a pull request. + +## License + +ISC © [Julien Fontanet](http://julien.isonoe.net) diff --git a/node_modules/lv_font_conv/node_modules/make-error/dist/make-error.js b/node_modules/lv_font_conv/node_modules/make-error/dist/make-error.js new file mode 100644 index 00000000..32444c69 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/make-error/dist/make-error.js @@ -0,0 +1 @@ +!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).makeError=f()}}(function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){return o(e[i][1][r]||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i; + +/** + * Set the constructor prototype to `BaseError`. + */ +declare function makeError(super_: { + new (...args: any[]): T; +}): makeError.Constructor; + +/** + * Create a specialized error instance. + */ +declare function makeError( + name: string | Function, + super_: K +): K & makeError.SpecializedConstructor; + +declare namespace makeError { + /** + * Use with ES2015+ inheritance. + */ + export class BaseError extends Error { + message: string; + name: string; + stack: string; + + constructor(message?: string); + } + + export interface Constructor { + new (message?: string): T; + super_: any; + prototype: T; + } + + export interface SpecializedConstructor { + super_: any; + prototype: T; + } +} + +export = makeError; diff --git a/node_modules/lv_font_conv/node_modules/make-error/index.js b/node_modules/lv_font_conv/node_modules/make-error/index.js new file mode 100644 index 00000000..fab60407 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/make-error/index.js @@ -0,0 +1,151 @@ +// ISC @ Julien Fontanet + +"use strict"; + +// =================================================================== + +var construct = typeof Reflect !== "undefined" ? Reflect.construct : undefined; +var defineProperty = Object.defineProperty; + +// ------------------------------------------------------------------- + +var captureStackTrace = Error.captureStackTrace; +if (captureStackTrace === undefined) { + captureStackTrace = function captureStackTrace(error) { + var container = new Error(); + + defineProperty(error, "stack", { + configurable: true, + get: function getStack() { + var stack = container.stack; + + // Replace property with value for faster future accesses. + defineProperty(this, "stack", { + configurable: true, + value: stack, + writable: true, + }); + + return stack; + }, + set: function setStack(stack) { + defineProperty(error, "stack", { + configurable: true, + value: stack, + writable: true, + }); + }, + }); + }; +} + +// ------------------------------------------------------------------- + +function BaseError(message) { + if (message !== undefined) { + defineProperty(this, "message", { + configurable: true, + value: message, + writable: true, + }); + } + + var cname = this.constructor.name; + if (cname !== undefined && cname !== this.name) { + defineProperty(this, "name", { + configurable: true, + value: cname, + writable: true, + }); + } + + captureStackTrace(this, this.constructor); +} + +BaseError.prototype = Object.create(Error.prototype, { + // See: https://github.com/JsCommunity/make-error/issues/4 + constructor: { + configurable: true, + value: BaseError, + writable: true, + }, +}); + +// ------------------------------------------------------------------- + +// Sets the name of a function if possible (depends of the JS engine). +var setFunctionName = (function() { + function setFunctionName(fn, name) { + return defineProperty(fn, "name", { + configurable: true, + value: name, + }); + } + try { + var f = function() {}; + setFunctionName(f, "foo"); + if (f.name === "foo") { + return setFunctionName; + } + } catch (_) {} +})(); + +// ------------------------------------------------------------------- + +function makeError(constructor, super_) { + if (super_ == null || super_ === Error) { + super_ = BaseError; + } else if (typeof super_ !== "function") { + throw new TypeError("super_ should be a function"); + } + + var name; + if (typeof constructor === "string") { + name = constructor; + constructor = + construct !== undefined + ? function() { + return construct(super_, arguments, this.constructor); + } + : function() { + super_.apply(this, arguments); + }; + + // If the name can be set, do it once and for all. + if (setFunctionName !== undefined) { + setFunctionName(constructor, name); + name = undefined; + } + } else if (typeof constructor !== "function") { + throw new TypeError("constructor should be either a string or a function"); + } + + // Also register the super constructor also as `constructor.super_` just + // like Node's `util.inherits()`. + // + // eslint-disable-next-line dot-notation + constructor.super_ = constructor["super"] = super_; + + var properties = { + constructor: { + configurable: true, + value: constructor, + writable: true, + }, + }; + + // If the name could not be set on the constructor, set it on the + // prototype. + if (name !== undefined) { + properties.name = { + configurable: true, + value: name, + writable: true, + }; + } + constructor.prototype = Object.create(super_.prototype, properties); + + return constructor; +} +exports = module.exports = makeError; +exports.BaseError = BaseError; diff --git a/node_modules/lv_font_conv/node_modules/make-error/package.json b/node_modules/lv_font_conv/node_modules/make-error/package.json new file mode 100644 index 00000000..e5f69904 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/make-error/package.json @@ -0,0 +1,95 @@ +{ + "_args": [ + [ + "make-error@1.3.6", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "make-error@1.3.6", + "_id": "make-error@1.3.6", + "_inBundle": false, + "_integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "_location": "/make-error", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "make-error@1.3.6", + "name": "make-error", + "escapedName": "make-error", + "rawSpec": "1.3.6", + "saveSpec": null, + "fetchSpec": "1.3.6" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "_spec": "1.3.6", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "author": { + "name": "Julien Fontanet", + "email": "julien.fontanet@isonoe.net" + }, + "bugs": { + "url": "https://github.com/JsCommunity/make-error/issues" + }, + "description": "Make your own error types!", + "devDependencies": { + "browserify": "^16.2.3", + "eslint": "^6.5.1", + "eslint-config-prettier": "^6.4.0", + "eslint-config-standard": "^14.1.0", + "eslint-plugin-import": "^2.14.0", + "eslint-plugin-node": "^10.0.0", + "eslint-plugin-promise": "^4.0.1", + "eslint-plugin-standard": "^4.0.0", + "husky": "^3.0.9", + "jest": "^24", + "prettier": "^1.14.3", + "uglify-js": "^3.3.2" + }, + "files": [ + "dist/", + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/JsCommunity/make-error", + "husky": { + "hooks": { + "commit-msg": "npm run test" + } + }, + "jest": { + "testEnvironment": "node" + }, + "keywords": [ + "create", + "custom", + "derive", + "error", + "errors", + "extend", + "extending", + "extension", + "factory", + "inherit", + "make", + "subclass" + ], + "license": "ISC", + "main": "index.js", + "name": "make-error", + "repository": { + "type": "git", + "url": "git://github.com/JsCommunity/make-error.git" + }, + "scripts": { + "dev-test": "jest --watch", + "format": "prettier --write '**'", + "prepublishOnly": "mkdir -p dist && browserify -s makeError index.js | uglifyjs -c > dist/make-error.js", + "pretest": "eslint --ignore-path .gitignore .", + "test": "jest" + }, + "version": "1.3.6" +} diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/CHANGELOG.md b/node_modules/lv_font_conv/node_modules/mkdirp/CHANGELOG.md new file mode 100644 index 00000000..81458380 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changers Lorgs! + +## 1.0 + +Full rewrite. Essentially a brand new module. + +- Return a promise instead of taking a callback. +- Use native `fs.mkdir(path, { recursive: true })` when available. +- Drop support for outdated Node.js versions. (Technically still works on + Node.js v8, but only 10 and above are officially supported.) + +## 0.x + +Original and most widely used recursive directory creation implementation +in JavaScript, dating back to 2010. diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/LICENSE b/node_modules/lv_font_conv/node_modules/mkdirp/LICENSE new file mode 100644 index 00000000..13fcd15f --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +Copyright James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me) + +This project is free software released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/bin/cmd.js b/node_modules/lv_font_conv/node_modules/mkdirp/bin/cmd.js new file mode 100755 index 00000000..6e0aa8dc --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/bin/cmd.js @@ -0,0 +1,68 @@ +#!/usr/bin/env node + +const usage = () => ` +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories + that don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m If a directory needs to be created, set the mode as an octal + --mode= permission string. + + -v --version Print the mkdirp version number + + -h --help Print this helpful banner + + -p --print Print the first directories created for each path provided + + --manual Use manual implementation, even if native is available +` + +const dirs = [] +const opts = {} +let print = false +let dashdash = false +let manual = false +for (const arg of process.argv.slice(2)) { + if (dashdash) + dirs.push(arg) + else if (arg === '--') + dashdash = true + else if (arg === '--manual') + manual = true + else if (/^-h/.test(arg) || /^--help/.test(arg)) { + console.log(usage()) + process.exit(0) + } else if (arg === '-v' || arg === '--version') { + console.log(require('../package.json').version) + process.exit(0) + } else if (arg === '-p' || arg === '--print') { + print = true + } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) { + const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8) + if (isNaN(mode)) { + console.error(`invalid mode argument: ${arg}\nMust be an octal number.`) + process.exit(1) + } + opts.mode = mode + } else + dirs.push(arg) +} + +const mkdirp = require('../') +const impl = manual ? mkdirp.manual : mkdirp +if (dirs.length === 0) + console.error(usage()) + +Promise.all(dirs.map(dir => impl(dir, opts))) + .then(made => print ? made.forEach(m => m && console.log(m)) : null) + .catch(er => { + console.error(er.message) + if (er.code) + console.error(' code: ' + er.code) + process.exit(1) + }) diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/index.js b/node_modules/lv_font_conv/node_modules/mkdirp/index.js new file mode 100644 index 00000000..ad7a16c9 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/index.js @@ -0,0 +1,31 @@ +const optsArg = require('./lib/opts-arg.js') +const pathArg = require('./lib/path-arg.js') + +const {mkdirpNative, mkdirpNativeSync} = require('./lib/mkdirp-native.js') +const {mkdirpManual, mkdirpManualSync} = require('./lib/mkdirp-manual.js') +const {useNative, useNativeSync} = require('./lib/use-native.js') + + +const mkdirp = (path, opts) => { + path = pathArg(path) + opts = optsArg(opts) + return useNative(opts) + ? mkdirpNative(path, opts) + : mkdirpManual(path, opts) +} + +const mkdirpSync = (path, opts) => { + path = pathArg(path) + opts = optsArg(opts) + return useNativeSync(opts) + ? mkdirpNativeSync(path, opts) + : mkdirpManualSync(path, opts) +} + +mkdirp.sync = mkdirpSync +mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts)) +mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts)) +mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts)) +mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts)) + +module.exports = mkdirp diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/lib/find-made.js b/node_modules/lv_font_conv/node_modules/mkdirp/lib/find-made.js new file mode 100644 index 00000000..022e492c --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/lib/find-made.js @@ -0,0 +1,29 @@ +const {dirname} = require('path') + +const findMade = (opts, parent, path = undefined) => { + // we never want the 'made' return value to be a root directory + if (path === parent) + return Promise.resolve() + + return opts.statAsync(parent).then( + st => st.isDirectory() ? path : undefined, // will fail later + er => er.code === 'ENOENT' + ? findMade(opts, dirname(parent), parent) + : undefined + ) +} + +const findMadeSync = (opts, parent, path = undefined) => { + if (path === parent) + return undefined + + try { + return opts.statSync(parent).isDirectory() ? path : undefined + } catch (er) { + return er.code === 'ENOENT' + ? findMadeSync(opts, dirname(parent), parent) + : undefined + } +} + +module.exports = {findMade, findMadeSync} diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/lib/mkdirp-manual.js b/node_modules/lv_font_conv/node_modules/mkdirp/lib/mkdirp-manual.js new file mode 100644 index 00000000..2eb18cd6 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/lib/mkdirp-manual.js @@ -0,0 +1,64 @@ +const {dirname} = require('path') + +const mkdirpManual = (path, opts, made) => { + opts.recursive = false + const parent = dirname(path) + if (parent === path) { + return opts.mkdirAsync(path, opts).catch(er => { + // swallowed by recursive implementation on posix systems + // any other error is a failure + if (er.code !== 'EISDIR') + throw er + }) + } + + return opts.mkdirAsync(path, opts).then(() => made || path, er => { + if (er.code === 'ENOENT') + return mkdirpManual(parent, opts) + .then(made => mkdirpManual(path, opts, made)) + if (er.code !== 'EEXIST' && er.code !== 'EROFS') + throw er + return opts.statAsync(path).then(st => { + if (st.isDirectory()) + return made + else + throw er + }, () => { throw er }) + }) +} + +const mkdirpManualSync = (path, opts, made) => { + const parent = dirname(path) + opts.recursive = false + + if (parent === path) { + try { + return opts.mkdirSync(path, opts) + } catch (er) { + // swallowed by recursive implementation on posix systems + // any other error is a failure + if (er.code !== 'EISDIR') + throw er + else + return + } + } + + try { + opts.mkdirSync(path, opts) + return made || path + } catch (er) { + if (er.code === 'ENOENT') + return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made)) + if (er.code !== 'EEXIST' && er.code !== 'EROFS') + throw er + try { + if (!opts.statSync(path).isDirectory()) + throw er + } catch (_) { + throw er + } + } +} + +module.exports = {mkdirpManual, mkdirpManualSync} diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/lib/mkdirp-native.js b/node_modules/lv_font_conv/node_modules/mkdirp/lib/mkdirp-native.js new file mode 100644 index 00000000..c7a6b698 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/lib/mkdirp-native.js @@ -0,0 +1,39 @@ +const {dirname} = require('path') +const {findMade, findMadeSync} = require('./find-made.js') +const {mkdirpManual, mkdirpManualSync} = require('./mkdirp-manual.js') + +const mkdirpNative = (path, opts) => { + opts.recursive = true + const parent = dirname(path) + if (parent === path) + return opts.mkdirAsync(path, opts) + + return findMade(opts, path).then(made => + opts.mkdirAsync(path, opts).then(() => made) + .catch(er => { + if (er.code === 'ENOENT') + return mkdirpManual(path, opts) + else + throw er + })) +} + +const mkdirpNativeSync = (path, opts) => { + opts.recursive = true + const parent = dirname(path) + if (parent === path) + return opts.mkdirSync(path, opts) + + const made = findMadeSync(opts, path) + try { + opts.mkdirSync(path, opts) + return made + } catch (er) { + if (er.code === 'ENOENT') + return mkdirpManualSync(path, opts) + else + throw er + } +} + +module.exports = {mkdirpNative, mkdirpNativeSync} diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/lib/opts-arg.js b/node_modules/lv_font_conv/node_modules/mkdirp/lib/opts-arg.js new file mode 100644 index 00000000..2fa4833f --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/lib/opts-arg.js @@ -0,0 +1,23 @@ +const { promisify } = require('util') +const fs = require('fs') +const optsArg = opts => { + if (!opts) + opts = { mode: 0o777, fs } + else if (typeof opts === 'object') + opts = { mode: 0o777, fs, ...opts } + else if (typeof opts === 'number') + opts = { mode: opts, fs } + else if (typeof opts === 'string') + opts = { mode: parseInt(opts, 8), fs } + else + throw new TypeError('invalid options argument') + + opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir + opts.mkdirAsync = promisify(opts.mkdir) + opts.stat = opts.stat || opts.fs.stat || fs.stat + opts.statAsync = promisify(opts.stat) + opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync + opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync + return opts +} +module.exports = optsArg diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/lib/path-arg.js b/node_modules/lv_font_conv/node_modules/mkdirp/lib/path-arg.js new file mode 100644 index 00000000..cc07de5a --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/lib/path-arg.js @@ -0,0 +1,29 @@ +const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform +const { resolve, parse } = require('path') +const pathArg = path => { + if (/\0/.test(path)) { + // simulate same failure that node raises + throw Object.assign( + new TypeError('path must be a string without null bytes'), + { + path, + code: 'ERR_INVALID_ARG_VALUE', + } + ) + } + + path = resolve(path) + if (platform === 'win32') { + const badWinChars = /[*|"<>?:]/ + const {root} = parse(path) + if (badWinChars.test(path.substr(root.length))) { + throw Object.assign(new Error('Illegal characters in path.'), { + path, + code: 'EINVAL', + }) + } + } + + return path +} +module.exports = pathArg diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/lib/use-native.js b/node_modules/lv_font_conv/node_modules/mkdirp/lib/use-native.js new file mode 100644 index 00000000..079361de --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/lib/use-native.js @@ -0,0 +1,10 @@ +const fs = require('fs') + +const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version +const versArr = version.replace(/^v/, '').split('.') +const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12 + +const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir +const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync + +module.exports = {useNative, useNativeSync} diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/package.json b/node_modules/lv_font_conv/node_modules/mkdirp/package.json new file mode 100644 index 00000000..1fb2e3d9 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/package.json @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "mkdirp@1.0.4", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "mkdirp@1.0.4", + "_id": "mkdirp@1.0.4", + "_inBundle": false, + "_integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "_location": "/mkdirp", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mkdirp@1.0.4", + "name": "mkdirp", + "escapedName": "mkdirp", + "rawSpec": "1.0.4", + "saveSpec": null, + "fetchSpec": "1.0.4" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "_spec": "1.0.4", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "bugs": { + "url": "https://github.com/isaacs/node-mkdirp/issues" + }, + "description": "Recursively mkdir, like `mkdir -p`", + "devDependencies": { + "require-inject": "^1.4.4", + "tap": "^14.10.7" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "bin", + "lib", + "index.js" + ], + "homepage": "https://github.com/isaacs/node-mkdirp#readme", + "keywords": [ + "mkdir", + "directory", + "make dir", + "make", + "dir", + "recursive", + "native" + ], + "license": "MIT", + "main": "index.js", + "name": "mkdirp", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/node-mkdirp.git" + }, + "scripts": { + "postpublish": "git push origin --follow-tags", + "postversion": "npm publish", + "preversion": "npm test", + "snap": "tap", + "test": "tap" + }, + "tap": { + "check-coverage": true, + "coverage-map": "map.js" + }, + "version": "1.0.4" +} diff --git a/node_modules/lv_font_conv/node_modules/mkdirp/readme.markdown b/node_modules/lv_font_conv/node_modules/mkdirp/readme.markdown new file mode 100644 index 00000000..827de590 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/mkdirp/readme.markdown @@ -0,0 +1,266 @@ +# mkdirp + +Like `mkdir -p`, but in Node.js! + +Now with a modern API and no\* bugs! + +\* may contain some bugs + +# example + +## pow.js + +```js +const mkdirp = require('mkdirp') + +// return value is a Promise resolving to the first directory created +mkdirp('/tmp/foo/bar/baz').then(made => + console.log(`made directories, starting with ${made}`)) +``` + +Output (where `/tmp/foo` already exists) + +``` +made directories, starting with /tmp/foo/bar +``` + +Or, if you don't have time to wait around for promises: + +```js +const mkdirp = require('mkdirp') + +// return value is the first directory created +const made = mkdirp.sync('/tmp/foo/bar/baz') +console.log(`made directories, starting with ${made}`) +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +const mkdirp = require('mkdirp') +``` + +## mkdirp(dir, [opts]) -> Promise + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `opts.mode`. If `opts` is a string or number, it will be +treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0o777 & +(~process.umask())`. + +Promise resolves to first directory `made` that had to be created, or +`undefined` if everything already exists. Promise rejects if any errors +are encountered. Note that, in the case of promise rejection, some +directories _may_ have been created, as recursive directory creation is not +an atomic operation. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)` +and `opts.fs.stat(path, cb)`. + +You can also override just one or the other of `mkdir` and `stat` by +passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that +only overrides one of these. + +## mkdirp.sync(dir, opts) -> String|null + +Synchronously create a new directory and any necessary subdirectories at +`dir` with octal permission string `opts.mode`. If `opts` is a string or +number, it will be treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0o777 & +(~process.umask())`. + +Returns the first directory that had to be created, or undefined if +everything already exists. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` +and `opts.fs.statSync(path)`. + +You can also override just one or the other of `mkdirSync` and `statSync` +by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs` +option that only overrides one of these. + +## mkdirp.manual, mkdirp.manualSync + +Use the manual implementation (not the native one). This is the default +when the native implementation is not available or the stat/mkdir +implementation is overridden. + +## mkdirp.native, mkdirp.nativeSync + +Use the native implementation (not the manual one). This is the default +when the native implementation is available and stat/mkdir are not +overridden. + +# implementation + +On Node.js v10.12.0 and above, use the native `fs.mkdir(p, +{recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been +overridden by an option. + +## native implementation + +- If the path is a root directory, then pass it to the underlying + implementation and return the result/error. (In this case, it'll either + succeed or fail, but we aren't actually creating any dirs.) +- Walk up the path statting each directory, to find the first path that + will be created, `made`. +- Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`) +- If error, raise it to the caller. +- Return `made`. + +## manual implementation + +- Call underlying `fs.mkdir` implementation, with `recursive: false` +- If error: + - If path is a root directory, raise to the caller and do not handle it + - If ENOENT, mkdirp parent dir, store result as `made` + - stat(path) + - If error, raise original `mkdir` error + - If directory, return `made` + - Else, raise original `mkdir` error +- else + - return `undefined` if a root dir, or `made` if set, or `path` + +## windows vs unix caveat + +On Windows file systems, attempts to create a root directory (ie, a drive +letter or root UNC path) will fail. If the root directory exists, then it +will fail with `EPERM`. If the root directory does not exist, then it will +fail with `ENOENT`. + +On posix file systems, attempts to create a root directory (in recursive +mode) will succeed silently, as it is treated like just another directory +that already exists. (In non-recursive mode, of course, it fails with +`EEXIST`.) + +In order to preserve this system-specific behavior (and because it's not as +if we can create the parent of a root directory anyway), attempts to create +a root directory are passed directly to the `fs` implementation, and any +errors encountered are not handled. + +## native error caveat + +The native implementation (as of at least Node.js v13.4.0) does not provide +appropriate errors in some cases (see +[nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and +[nodejs/node#28015](https://github.com/nodejs/node/issues/28015)). + +In order to work around this issue, the native implementation will fall +back to the manual implementation if an `ENOENT` error is encountered. + +# choosing a recursive mkdir implementation + +There are a few to choose from! Use the one that suits your needs best :D + +## use `fs.mkdir(path, {recursive: true}, cb)` if: + +- You wish to optimize performance even at the expense of other factors. +- You don't need to know the first dir created. +- You are ok with getting `ENOENT` as the error when some other problem is + the actual cause. +- You can limit your platforms to Node.js v10.12 and above. +- You're ok with using callbacks instead of promises. +- You don't need/want a CLI. +- You don't need to override the `fs` methods in use. + +## use this module (mkdirp 1.x) if: + +- You need to know the first directory that was created. +- You wish to use the native implementation if available, but fall back + when it's not. +- You prefer promise-returning APIs to callback-taking APIs. +- You want more useful error messages than the native recursive mkdir + provides (at least as of Node.js v13.4), and are ok with re-trying on + `ENOENT` to achieve this. +- You need (or at least, are ok with) a CLI. +- You need to override the `fs` methods in use. + +## use [`make-dir`](http://npm.im/make-dir) if: + +- You do not need to know the first dir created (and wish to save a few + `stat` calls when using the native implementation for this reason). +- You wish to use the native implementation if available, but fall back + when it's not. +- You prefer promise-returning APIs to callback-taking APIs. +- You are ok with occasionally getting `ENOENT` errors for failures that + are actually related to something other than a missing file system entry. +- You don't need/want a CLI. +- You need to override the `fs` methods in use. + +## use mkdirp 0.x if: + +- You need to know the first directory that was created. +- You need (or at least, are ok with) a CLI. +- You need to override the `fs` methods in use. +- You're ok with using callbacks instead of promises. +- You are not running on Windows, where the root-level ENOENT errors can + lead to infinite regress. +- You think vinyl just sounds warmer and richer for some weird reason. +- You are supporting truly ancient Node.js versions, before even the advent + of a `Promise` language primitive. (Please don't. You deserve better.) + +# cli + +This package also ships with a `mkdirp` command. + +``` +$ mkdirp -h + +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories + that don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m If a directory needs to be created, set the mode as an octal + --mode= permission string. + + -v --version Print the mkdirp version number + + -h --help Print this helpful banner + + -p --print Print the first directories created for each path provided + + --manual Use manual implementation, even if native is available +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +to get the library locally, or + +``` +npm install -g mkdirp +``` + +to get the command everywhere, or + +``` +npx mkdirp ... +``` + +to run the command without installing it globally. + +# platform support + +This module works on node v8, but only v10 and above are officially +supported, as Node v8 reached its LTS end of life 2020-01-01, which is in +the past, as of this writing. + +# license + +MIT diff --git a/node_modules/lv_font_conv/node_modules/ms/index.js b/node_modules/lv_font_conv/node_modules/ms/index.js new file mode 100644 index 00000000..c4498bcc --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/lv_font_conv/node_modules/ms/license.md b/node_modules/lv_font_conv/node_modules/ms/license.md new file mode 100644 index 00000000..69b61253 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/ms/package.json b/node_modules/lv_font_conv/node_modules/ms/package.json new file mode 100644 index 00000000..6d514e71 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/ms/package.json @@ -0,0 +1,72 @@ +{ + "_args": [ + [ + "ms@2.1.2", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "ms@2.1.2", + "_id": "ms@2.1.2", + "_inBundle": false, + "_integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "_location": "/ms", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@2.1.2", + "name": "ms", + "escapedName": "ms", + "rawSpec": "2.1.2", + "saveSpec": null, + "fetchSpec": "2.1.2" + }, + "_requiredBy": [ + "/debug" + ], + "_resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "_spec": "2.1.2", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "bugs": { + "url": "https://github.com/zeit/ms/issues" + }, + "description": "Tiny millisecond conversion utility", + "devDependencies": { + "eslint": "4.12.1", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/zeit/ms#readme", + "license": "MIT", + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "main": "./index", + "name": "ms", + "repository": { + "type": "git", + "url": "git+https://github.com/zeit/ms.git" + }, + "scripts": { + "lint": "eslint lib/* bin/*", + "precommit": "lint-staged", + "test": "mocha tests.js" + }, + "version": "2.1.2" +} diff --git a/node_modules/lv_font_conv/node_modules/ms/readme.md b/node_modules/lv_font_conv/node_modules/ms/readme.md new file mode 100644 index 00000000..9a1996b1 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/ms/readme.md @@ -0,0 +1,60 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/zeit) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/lv_font_conv/node_modules/opentype.js/LICENSE b/node_modules/lv_font_conv/node_modules/opentype.js/LICENSE new file mode 100644 index 00000000..c9b39953 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/opentype.js/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2017 Frederik De Bleser + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/opentype.js/README.md b/node_modules/lv_font_conv/node_modules/opentype.js/README.md new file mode 100644 index 00000000..bcb557e8 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/opentype.js/README.md @@ -0,0 +1,313 @@ + +# opentype.js · [![Build Status](https://img.shields.io/travis/opentypejs/opentype.js.svg?style=flat-square)](https://travis-ci.org/opentypejs/opentype.js) [![npm](https://img.shields.io/npm/v/opentype.js.svg?style=flat-square)](https://www.npmjs.com/package/opentype.js) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://github.com/opentypejs/opentype.js/blob/master/LICENSE) [![david-dm](https://david-dm.org/opentypejs/opentype.js.svg)](https://david-dm.org/opentypejs/opentype.js) [![Gitter](https://badges.gitter.im/opentypejs/opentype.js.svg)](https://gitter.im/opentypejs/opentype.js) + +opentype.js is a JavaScript parser and writer for TrueType and OpenType fonts. + +It gives you access to the letterforms of text from the browser or Node.js. +See [https://opentype.js.org/](https://opentype.js.org/) for a live demo. + +Features +======== + +* Create a bézier path out of a piece of text. +* Support for composite glyphs (accented letters). +* Support for WOFF, OTF, TTF (both with TrueType `glyf` and PostScript `cff` outlines) +* Support for kerning (Using GPOS or the kern table). +* Support for ligatures. +* Support for TrueType font hinting. +* Support arabic text rendering (See issue #364 & PR #359 #361) +* A low memory mode is available as an option (see #329) +* Runs in the browser and Node.js. + +Installation +============ + +### Using [npm](http://npmjs.org/) package manager + + npm install opentype.js + + const opentype = require('opentype.js'); + + import opentype from 'opentype.js' + + import { load } from 'opentype.js' + +Using TypeScript? [See this example](examples/typescript) + +Note: OpenType.js uses ES6-style imports, so if you want to edit it and debug it in Node.js run `npm run build` first and use `npm run watch` to automatically rebuild when files change. + +### Directly + +[Download the latest ZIP](https://github.com/opentypejs/opentype.js/archive/master.zip) and grab the files in the `dist` +folder. These are compiled. + +### Using via a CDN + +To use via a CDN, include the following code in your html: + + + +### Using Bower (Deprecated [see official post](https://bower.io/blog/2017/how-to-migrate-away-from-bower/)) + +To install using [Bower](https://bower.io/), enter the following command in your project directory: + + bower install opentype.js + +You can then include them in your scripts using: + + + + +API +=== +### Loading a font +![OpenType.js example Hello World](https://raw.github.com/opentypejs/opentype.js/master/g/hello-world.png) + +Use `opentype.load(url, callback)` to load a font from a URL. Since this method goes out the network, it is asynchronous. +The callback gets `(err, font)` where `font` is a `Font` object. Check if the `err` is null before using the font. +```javascript +opentype.load('fonts/Roboto-Black.ttf', function(err, font) { + if (err) { + alert('Font could not be loaded: ' + err); + } else { + // Now let's display it on a canvas with id "canvas" + const ctx = document.getElementById('canvas').getContext('2d'); + + // Construct a Path object containing the letter shapes of the given text. + // The other parameters are x, y and fontSize. + // Note that y is the position of the baseline. + const path = font.getPath('Hello, World!', 0, 150, 72); + + // If you just want to draw the text you can also use font.draw(ctx, text, x, y, fontSize). + path.draw(ctx); + } +}); +``` + +You can also use `es6 async/await` syntax to load your fonts + +```javascript +async function make(){ + const font = await opentype.load('fonts/Roboto-Black.ttf'); + const path = font.getPath('Hello, World!', 0, 150, 72); + console.log(path); +} +``` + +If you already have an `ArrayBuffer`, you can use `opentype.parse(buffer)` to parse the buffer. This method always +returns a Font, but check `font.supported` to see if the font is in a supported format. (Fonts can be marked unsupported +if they have encoding tables we can't read). + + const font = opentype.parse(myBuffer); + +### Loading a font synchronously (Node.js) +Use `opentype.loadSync(url)` to load a font from a file and return a `Font` object. +Throws an error if the font could not be parsed. This only works in Node.js. + + const font = opentype.loadSync('fonts/Roboto-Black.ttf'); + +### Writing a font +Once you have a `Font` object (either by using `opentype.load` or by creating a new one from scratch) you can write it +back out as a binary file. + +In the browser, you can use `Font.download()` to instruct the browser to download a binary .OTF file. The name is based +on the font name. +```javascript +// Create the bézier paths for each of the glyphs. +// Note that the .notdef glyph is required. +const notdefGlyph = new opentype.Glyph({ + name: '.notdef', + unicode: 0, + advanceWidth: 650, + path: new opentype.Path() +}); + +const aPath = new opentype.Path(); +aPath.moveTo(100, 0); +aPath.lineTo(100, 700); +// more drawing instructions... +const aGlyph = new opentype.Glyph({ + name: 'A', + unicode: 65, + advanceWidth: 650, + path: aPath +}); + +const glyphs = [notdefGlyph, aGlyph]; +const font = new opentype.Font({ + familyName: 'OpenTypeSans', + styleName: 'Medium', + unitsPerEm: 1000, + ascender: 800, + descender: -200, + glyphs: glyphs}); +font.download(); +``` + +If you want to inspect the font, use `font.toTables()` to generate an object showing the data structures that map +directly to binary values. If you want to get an `ArrayBuffer`, use `font.toArrayBuffer()`. + + +### The Font object +A Font represents a loaded OpenType font file. It contains a set of glyphs and methods to draw text on a drawing context, or to get a path representing the text. + +* `glyphs`: an indexed list of Glyph objects. +* `unitsPerEm`: X/Y coordinates in fonts are stored as integers. This value determines the size of the grid. Common values are 2048 and 4096. +* `ascender`: Distance from baseline of highest ascender. In font units, not pixels. +* `descender`: Distance from baseline of lowest descender. In font units, not pixels. + +#### `Font.getPath(text, x, y, fontSize, options)` +Create a Path that represents the given text. +* `x`: Horizontal position of the beginning of the text. (default: 0) +* `y`: Vertical position of the *baseline* of the text. (default: 0) +* `fontSize`: Size of the text in pixels (default: 72). + +Options is an optional object containing: +* `kerning`: if true takes kerning information into account (default: true) +* `features`: an object with [OpenType feature tags](https://docs.microsoft.com/en-us/typography/opentype/spec/featuretags) as keys, and a boolean value to enable each feature. +Currently only ligature features "liga" and "rlig" are supported (default: true). +* `hinting`: if true uses TrueType font hinting if available (default: false). + +_Note: there is also `Font.getPaths` with the same arguments which returns a list of Paths._ + +#### `Font.draw(ctx, text, x, y, fontSize, options)` +Create a Path that represents the given text. +* `ctx`: A 2D drawing context, like Canvas. +* `x`: Horizontal position of the beginning of the text. (default: 0) +* `y`: Vertical position of the *baseline* of the text. (default: 0) +* `fontSize`: Size of the text in pixels (default: 72). + +Options is an optional object containing: +* `kerning`: if true takes kerning information into account (default: true) +* `features`: an object with [OpenType feature tags](https://docs.microsoft.com/en-us/typography/opentype/spec/featuretags) as keys, and a boolean value to enable each feature. +Currently only ligature features "liga" and "rlig" are supported (default: true). +* `hinting`: if true uses TrueType font hinting if available (default: false). + +#### `Font.drawPoints(ctx, text, x, y, fontSize, options)` +Draw the points of all glyphs in the text. On-curve points will be drawn in blue, off-curve points will be drawn in red. The arguments are the same as `Font.draw`. + +#### `Font.drawMetrics(ctx, text, x, y, fontSize, options)` +Draw lines indicating important font measurements for all glyphs in the text. +Black lines indicate the origin of the coordinate system (point 0,0). +Blue lines indicate the glyph bounding box. +Green line indicates the advance width of the glyph. + +#### `Font.stringToGlyphs(string)` +Convert the string to a list of glyph objects. +Note that there is no strict 1-to-1 correspondence between the string and glyph list due to +possible substitutions such as ligatures. The list of returned glyphs can be larger or smaller than the length of the given string. + +#### `Font.charToGlyph(char)` +Convert the character to a `Glyph` object. Returns null if the glyph could not be found. Note that this function assumes that there is a one-to-one mapping between the given character and a glyph; for complex scripts this might not be the case. + +#### `Font.getKerningValue(leftGlyph, rightGlyph)` +Retrieve the value of the [kerning pair](https://en.wikipedia.org/wiki/Kerning) between the left glyph (or its index) and the right glyph (or its index). If no kerning pair is found, return 0. The kerning value gets added to the advance width when calculating the spacing between glyphs. + +#### `Font.getAdvanceWidth(text, fontSize, options)` +Returns the advance width of a text. + +This is something different than Path.getBoundingBox() as for example a +suffixed whitespace increases the advancewidth but not the bounding box +or an overhanging letter like a calligraphic 'f' might have a quite larger +bounding box than its advance width. + +This corresponds to canvas2dContext.measureText(text).width +* `fontSize`: Size of the text in pixels (default: 72). +* `options`: See Font.getPath + +#### The Glyph object +A Glyph is an individual mark that often corresponds to a character. Some glyphs, such as ligatures, are a combination of many characters. Glyphs are the basic building blocks of a font. + +* `font`: A reference to the `Font` object. +* `name`: The glyph name (e.g. "Aring", "five") +* `unicode`: The primary unicode value of this glyph (can be `undefined`). +* `unicodes`: The list of unicode values for this glyph (most of the time this will be 1, can also be empty). +* `index`: The index number of the glyph. +* `advanceWidth`: The width to advance the pen when drawing this glyph. +* `xMin`, `yMin`, `xMax`, `yMax`: The bounding box of the glyph. +* `path`: The raw, unscaled path of the glyph. + +##### `Glyph.getPath(x, y, fontSize)` +Get a scaled glyph Path object we can draw on a drawing context. +* `x`: Horizontal position of the glyph. (default: 0) +* `y`: Vertical position of the *baseline* of the glyph. (default: 0) +* `fontSize`: Font size in pixels (default: 72). + +##### `Glyph.getBoundingBox()` +Calculate the minimum bounding box for the unscaled path of the given glyph. Returns an `opentype.BoundingBox` object that contains x1/y1/x2/y2. +If the glyph has no points (e.g. a space character), all coordinates will be zero. + +##### `Glyph.draw(ctx, x, y, fontSize)` +Draw the glyph on the given context. +* `ctx`: The drawing context. +* `x`: Horizontal position of the glyph. (default: 0) +* `y`: Vertical position of the *baseline* of the glyph. (default: 0) +* `fontSize`: Font size, in pixels (default: 72). + +##### `Glyph.drawPoints(ctx, x, y, fontSize)` +Draw the points of the glyph on the given context. +On-curve points will be drawn in blue, off-curve points will be drawn in red. +The arguments are the same as `Glyph.draw`. + +##### `Glyph.drawMetrics(ctx, x, y, fontSize)` +Draw lines indicating important font measurements for all glyphs in the text. +Black lines indicate the origin of the coordinate system (point 0,0). +Blue lines indicate the glyph bounding box. +Green line indicates the advance width of the glyph. +The arguments are the same as `Glyph.draw`. + +### The Path object +Once you have a path through `Font.getPath` or `Glyph.getPath`, you can use it. + +* `commands`: The path commands. Each command is a dictionary containing a type and coordinates. See below for examples. +* `fill`: The fill color of the `Path`. Color is a string representing a [CSS color](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). (default: 'black') +* `stroke`: The stroke color of the `Path`. Color is a string representing a [CSS color](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). (default: `null`: the path will not be stroked) +* `strokeWidth`: The line thickness of the `Path`. (default: 1, but since the `stroke` is null no stroke will be drawn) + +##### `Path.draw(ctx)` +Draw the path on the given 2D context. This uses the `fill`, `stroke` and `strokeWidth` properties of the `Path` object. +* `ctx`: The drawing context. + +##### `Path.getBoundingBox()` +Calculate the minimum bounding box for the given path. Returns an `opentype.BoundingBox` object that contains x1/y1/x2/y2. +If the path is empty (e.g. a space character), all coordinates will be zero. + +##### `Path.toPathData(decimalPlaces)` +Convert the Path to a string of path data instructions. +See https://www.w3.org/TR/SVG/paths.html#PathData +* `decimalPlaces`: The amount of decimal places for floating-point values. (default: 2) + +##### `Path.toSVG(decimalPlaces)` +Convert the path to a SVG <path> element, as a string. +* `decimalPlaces`: The amount of decimal places for floating-point values. (default: 2) + +#### Path commands +* **Move To**: Move to a new position. This creates a new contour. Example: `{type: 'M', x: 100, y: 200}` +* **Line To**: Draw a line from the previous position to the given coordinate. Example: `{type: 'L', x: 100, y: 200}` +* **Curve To**: Draw a bézier curve from the current position to the given coordinate. Example: `{type: 'C', x1: 0, y1: 50, x2: 100, y2: 200, x: 100, y: 200}` +* **Quad To**: Draw a quadratic bézier curve from the current position to the given coordinate. Example: `{type: 'Q', x1: 0, y1: 50, x: 100, y: 200}` +* **Close**: Close the path. If stroked, this will draw a line from the first to the last point of the contour. Example: `{type: 'Z'}` + + +## Versioning + +We use [SemVer](https://semver.org/) for versioning. + + +## License + +MIT + + +Thanks +====== +I would like to acknowledge the work of others without which opentype.js wouldn't be possible: + +* [pdf.js](https://mozilla.github.io/pdf.js/): for an awesome implementation of font parsing in the browser. +* [FreeType](https://www.freetype.org/): for the nitty-gritty details and filling in the gaps when the spec was incomplete. +* [ttf.js](https://ynakajima.github.io/ttf.js/demo/glyflist/): for hints about the TrueType parsing code. +* [CFF-glyphlet-fonts](https://pomax.github.io/CFF-glyphlet-fonts/): for a great explanation/implementation of CFF font writing. +* [tiny-inflate](https://github.com/foliojs/tiny-inflate): for WOFF decompression. +* [Microsoft Typography](https://docs.microsoft.com/en-us/typography/opentype/spec/otff): the go-to reference for all things OpenType. +* [Adobe Compact Font Format spec](http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/cff.pdf) and the [Adobe Type 2 Charstring spec](http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/type2.pdf): explains the data structures and commands for the CFF glyph format. +* All contributing authors mentioned in the [AUTHORS](https://github.com/opentypejs/opentype.js/blob/master/AUTHORS.md) file. diff --git a/node_modules/lv_font_conv/node_modules/opentype.js/RELEASES.md b/node_modules/lv_font_conv/node_modules/opentype.js/RELEASES.md new file mode 100644 index 00000000..e1c698b1 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/opentype.js/RELEASES.md @@ -0,0 +1,267 @@ +1.3.3 (April 20, 2020) +===================== +* fix GlyphOptions with falsy values (#430) + +1.3.2 (April 20, 2020) +===================== +* Re-export named exports with a default export and add a TypeScript import example + +* 1.3.1 (April 13, 2020) +===================== +* Revert Fix Path.toPathData and Path.toSVG - X Axis is flipped (#369) + +1.3.0 (April 13, 2020) +===================== +* Forward os2 Table attributs during font construction (#422) +* Add default export + +1.2.1 (April 13, 2020) +===================== +* Fix Path.toPathData and Path.toSVG - X Axis is flipped (#369) +* Fix use of Promise / async/await in the load function (#427) +* Fix a bug for unsupported SUBSTITUTIONS #403 + +1.2.0 (April 13, 2020) +===================== +* Fix issue #385, merge default options with user options (#386) +* Adds support for browser Async/Await for .load() (#389) +* Introduce ES6 module build (#391) +* Fix test in featureQuery +* Remove Node 4 from Travis (#392) +* Update dependencies & build dist files + +1.1.0 (May 1, 2019) +===================== +* Support reading GSUB Single substitution format 1 (PR #382) (thanks @solomancode!) + +1.0.1 (April 19, 2019) +===================== +* Fix error if defaultLangSys is undefined (Issue #378) + +1.0.0 (April 17, 2019) +===================== +* Render arabic rtl text properly (PR #361, partial fix of #364) (thanks @solomancode!) +* #361 introduced a breaking change to `Font.prototype.defaultRenderOptions` +Before +```js +Font.prototype.defaultRenderOptions = { + kerning: true, + features: { + liga: true, + rlig: true + } +}; +``` + +Now +```js +Font.prototype.defaultRenderOptions = { + kerning: true, + features: [ + /** + * these 4 features are required to render Arabic text properly + * and shouldn't be turned off when rendering arabic text. + */ + { script: 'arab', tags: ['init', 'medi', 'fina', 'rlig'] }, + { script: 'latn', tags: ['liga', 'rlig'] } + ] +}; +``` + +Also as this project is now using SemVer, the breaking change required a new major version, 1.0.0! + +0.12.0 (April 17, 2019) +===================== +* Fix Glyph.getPath() issue (PR #362, fixes #363) (thanks @solomancode!) +* Add lowMemory mode (PR #329) (thanks @debussy2k!) +* Update README (PR #377) (thanks @jolg42!) + +0.11.0 (October 22, 2018) +===================== +* Support Arabic text rendering (PR #359, fixes #46) (thanks @solomancode!) + +0.10.0 (August 14, 2018) +===================== +* font.download(): use window.URL instead of window.requestFileSystem, which works on a larger set of browsers : Chrome (32+), Opera (19+), Firefox (26+), Safari (7.1+), and all of Edge. + +0.9.0 (June 21, 2018) +===================== +* Update/Migrate rollup, update all dependencies, add package-lock.json and fix circular dependency (thanks @jolg42!) +* Parse cmap table with platform id 0 as well (PR #350, fixes #348) (thanks @moyogo!) +* Prevent auto-generated postScriptName from containing whitespace (#339) (thanks @mqudsi!) +* Support non-Basic-Multilingual-Plane (BMP) characters (#338) (thanks @antonytse!) +* GPOS: display correct error message in some cases of malformed data (#336) (thanks @fpirsch!) +* Restore simple GPOS kerning in font.getKerningValue (#335) (thanks @fpirsch!) +* Fix duplicated lineTo when using `getPath` (#328) (thanks @jolg42!) +* Change example generate-font-node.js to be compatible with any Node.js version (thanks @jolg42!) + +0.8.0 (March 6, 2018) +===================== +* Fix loading font file on Android devices (thanks @maoamid!). +* Fix loading fonts from a local source (file://data/... for Android for example (thanks @IntuilabGit!). +* Fixing 2 issues when hinting "mutlu.ttf" (thanks @axkibe!). +* Add some support for OpenType font variations (thanks @taylorb-monotype!). +* Make cmap table format 12 if needed (thanks @Jolg42!). +* Enable uglify's mangle and compress optimizations for a ~30% smaller minified file. (thanks @lojjic & @Jolg42!). +* Better parsing of NULL pointers (thanks @fpirsch!). +* Fix bad path init (empty glyphs) (thanks @fpirsch!). +* Rewrite GPOS parsing (thanks @fpirsch!). +* Roboto-Black.ttf updated (thanks @Jolg42!). + +0.7.3 (July 18, 2017) +===================== +* Fix "Object x already has key" error in Safari (thanks @neiltron!). +* Fixed a bug where Font.getPaths() didn't pass options (thanks @keeslinp!). + +0.7.2 (June 7, 2017) +==================== +* WOFF fonts with cvt tables now parse correctly. +* Migrated to ES6 modules and let/const. +* Use Rollup to bundle the JavaScript. + +0.7.1 (Apr 25, 2017) +==================== +* Auto-generated glyph IDs (CID-keyed fonts) are now prefixed with "gid", e.g. "gid42". +* Fix ligature substitution for fonts with coverage table format 2. +* Better error messages when no valid cmap is found. + +0.7.0 (Apr 25, 2017) +==================== +* Add font hinting (thanks @axkibe!) +* Add support for CID-keyed fonts, thanks to @tshinnic. +* TrueType fonts with signature 'true' or 'typ1' are also supported. +* Fixing rounding issues. +* Add GSUB and kern output in font-inspector. +* Add font loading error callback. +* Dev server turns browser caching off. +* Add encoding support for variation adjustment deltas (thanks @brawer!). + +0.6.9 (Jan 17, 2017) +==================== +* Add ligature rendering (thanks @fpirsch!) + +0.6.8 (Jan 9, 2017) +========================= +* Add a `getBoundingBox` method to the `Path` and `Glyph` objects. + +0.6.7 (Jan 5, 2017) +========================= +* Add basic support for Mac OS X format kern tables. + +0.6.6 (October 25, 2016) +========================= +* Add support for letter-spacing and tracking (thanks @lachmanski!). +* Fixed a bug in the nameToGlyph function. + +0.6.5 (September 9, 2016) +========================= +* GSUB reading and writing by @fpirsch. This is still missing a user-friendly API. +* Add support for cmap table format 12, which enables support for Unicode characters outside of the 0x0 - 0xFFFF range. +* Better API documentation using [JSDoc](http://usejsdoc.org/). +* Accessing xMin/... metrics works before path load.
 + +0.6.4 (June 30, 2016) +========================= +* Add X/Y scale options to compute a streched path of a glyph. +* Correct reading/writing of font timestamps. +* examples/generate-font-node.js now generates "full" Latin font. +* Add OS/2 value options for weight, width and fsSelection. + +0.6.3 (May 10, 2016) +========================= +* Wrapped parseBuffer in a try/catch so it doesn't throw exceptions. Thanks @rBurgett! +* Fix a leaking global variable. Thanks @cuixiping! + +0.6.2 (March 11, 2016) +========================= +* Improve table writing to support nested subtables. Thanks @fpirsch! + +0.6.1 (February 20, 2016) +========================= +* Left side bearing is now correctly reported. +* Simplified code for including ascender / descender values. + +0.6.0 (December 1, 2015) +======================== +* Improvements to font writing: generated fonts now work properly on OS X. +* When creating a new font, ascender and descender are now required. + +0.5.1 (October 26, 2015) +======================== +* Add `Font.getPaths()` which returns a list of paths. + +0.5.0 (October 6, 2015) +======================= +* Read support for WOFF. + +0.4.11 (September 27, 2015) +=========================== +* Fix issue with loading of TrueType composite glyphs. +* Fix issue with missing hmtx values. +* Sensible getMetrics() values for empty glyphs (e.g. space). + +0.4.10 (July 30, 2015) +====================== +* Add loadSync method for Node.js. +* Unit tests for basic types and tables. +* Implement MACSTRING codec. +* Support multilingual names. +* Handle names of font variation axes and instances. + +0.4.9 (June 23, 2015) +===================== +* Improve memory usage by deferring glyph / path loading. Thanks @Pomax! +* Put examples in the "examples" directory. Use the local web server to see them. + +0.4.8 (June 3, 2015) +==================== +* Fix an issue with writing out fonts that have an UPM != 1000. + +0.4.6 (March 26, 2015) +====================== +* Fix issues with exporting/subsetting TrueType fonts. +* Improve validness of exported fonts. +* Empty paths (think: space) no longer contain a single closePath command. +* Fix issues with exporting fonts with TrueType half-point values. +* Expose the internal byte parsing algorithms as opentype._parse. + +0.4.5 (March 10, 2015) +====================== +* Add support for writing quad curves. +* Add support for CFF flex operators. +* Close CFF subpaths. + +0.4.4 (Dec 8, 2014) +=================== +* Solve issues with Browserify. + +0.4.3 (Nov 26, 2014) +==================== +* Un-break node.js support. + +0.4.2 (Nov 24, 2014) +==================== +* 2x speedup when writing fonts, thanks @louisremi! + +0.4.1 (Nov 10, 2014) +==================== +* Fix bug that prevented `npm install`. + +0.4.0 (Nov 10, 2014) +==================== +* Add support for font writing. + +0.3.0 (Jun 10, 2014) +==================== +* Support for GPOS kerning, which works in both PostScript and OpenType. +* Big performance improvements. +* The font and glyph inspector can visually debug a font. + +0.2.0 (Feb 7, 2014) +=================== +* Support for reading PostScript fonts. + +0.1.0 (Sep 27, 2013) +==================== +* Initial release. +* Supports reading TrueType CFF fonts. diff --git a/node_modules/lv_font_conv/node_modules/opentype.js/bin/ot b/node_modules/lv_font_conv/node_modules/opentype.js/bin/ot new file mode 100755 index 00000000..af990cd2 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/opentype.js/bin/ot @@ -0,0 +1,84 @@ +#!/usr/bin/env node +/* eslint no-console: off */ + +import fs from 'fs'; +import path from 'path'; +import { load } from '../src/opentype'; + +// Print out information about the font on the console. +function printFontInfo(font) { + console.log(' glyphs:', font.glyphs.length); + console.log(' kerning pairs (kern table):', Object.keys(font.kerningPairs).length); + console.log(' kerning pairs (GPOS table):', (font.getGposKerningValue) ? 'yes' : 'no'); +} + +// Recursively walk a directory and execute the function for every file. +function walk(dir, fn) { + var files, i, file; + files = fs.readdirSync(dir); + for (i = 0; i < files.length; i += 1) { + file = files[i]; + var fullName = path.join(dir, file); + var stat = fs.statSync(fullName); + if (stat.isFile()) { + fn(fullName); + } else if (stat.isDirectory()) { + walk(fullName, fn); + } + } +} + +// Print out usage information. +function printUsage() { + console.log('Usage: ot command [dir|file]'); + console.log(); + console.log('Commands:'); + console.log(); + console.log(' info Get information of specified font or fonts in the specified directory.'); + console.log(); +} + +function fileInfo(file) { + load(file, function(err, font) { + console.log(path.basename(file)); + if (err) { + console.log(' (Error: ' + err + ')'); + } else if (!font.supported) { + console.log(' (Unsupported)'); + } else { + printFontInfo(font); + } + }); +} + +function recursiveInfo(fontDirectory) { + walk(fontDirectory, function(file) { + var ext = path.extname(file).toLowerCase(); + if (ext === '.ttf' || ext === '.otf') { + fileInfo(file); + } + }); +} + +if (process.argv.length < 3) { + printUsage(); +} else { + var command = process.argv[2]; + if (command === 'info') { + var fontpath = process.argv.length === 3 ? '.' : process.argv[3]; + if (fs.existsSync(fontpath)) { + var ext = path.extname(fontpath).toLowerCase(); + if (fs.statSync(fontpath).isDirectory()) { + recursiveInfo(fontpath); + } else if (ext === '.ttf' || ext === '.otf') { + fileInfo(fontpath); + } else { + printUsage(); + } + } else { + console.log('Path not found'); + } + } else { + printUsage(); + } +} diff --git a/node_modules/lv_font_conv/node_modules/opentype.js/bin/server.js b/node_modules/lv_font_conv/node_modules/opentype.js/bin/server.js new file mode 100755 index 00000000..f6f450a4 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/opentype.js/bin/server.js @@ -0,0 +1,64 @@ +#!/usr/bin/env node + +var fs = require('fs'); +var http = require('http'); +var path = require('path'); +var rollup = require('rollup'); +var rollupConfig = require('../rollup.config'); + +var CONTENT_TYPES = { + '.html': 'text/html', + '.css': 'text/css', + '.png': 'image/png', + '.js': 'text/javascript', + '.ttf': 'font/otf', + '.otf': 'font/otf', + '.woff': 'font/woff', + '.woff2': 'font/woff2', +}; + +http.createServer(function(req, res) { + var rewrite = ''; + var url = req.url.substring(1); + if (url.length === 0) { + url = 'index.html'; + rewrite = ' -> ' + url; + } + + console.log('HTTP', req.url, rewrite); + var filePath = './' + url; + fs.readFile(filePath, function(err, data) { + if (err) { + res.writeHead(404, {'Content-Type': 'text/plain'}); + res.end('Error: ' + err); + } else { + var contentType = CONTENT_TYPES[path.extname(filePath)] || 'text/plain'; + res.writeHead(200, { + 'Content-Type': contentType, + 'Cache-Control': 'max-age=0' + }); + res.end(data); + } + }); +}).listen(8080); +console.log('Server running at http://localhost:8080/'); + +// Watch changes and rebundle +var watcher = rollup.watch(rollupConfig); +watcher.on('event', e => { + // event.code can be one of: + // START — the watcher is (re)starting + // BUNDLE_START — building an individual bundle + // BUNDLE_END — finished building a bundle + // END — finished building all bundles + // ERROR — encountered an error while bundling + // FATAL — encountered an unrecoverable error + + if (e.code === 'BUNDLE_START') { + console.log('Bundling...'); + } else if (e.code === 'BUNDLE_END') { + console.log('Bundled in ' + e.duration + 'ms.'); + } else if (e.code === 'ERROR' || e.code === 'FATAL') { + console.error(e.error); + } +}); diff --git a/node_modules/lv_font_conv/node_modules/opentype.js/bin/test-render b/node_modules/lv_font_conv/node_modules/opentype.js/bin/test-render new file mode 100755 index 00000000..4bfc31e6 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/opentype.js/bin/test-render @@ -0,0 +1,96 @@ +#!/usr/bin/env node +// This is a command to test the text rendering compliance of OpenType.js. +// It is designed to operate with https://github.com/unicode-org/text-rendering-tests. +// +// Call it like this: +// +// ./bin/test-render --font=fonts/FiraSansOT-Medium.otf --testcase=TEST-1 --render=BALL +// +// The output will look like this: +// +// +// +// +// +// +// +// +// +// +// +// +// When viewing the SVG, it will be upside-down (since glyphs are designed Y-up). + +var opentype = require('../dist/opentype.js'); + +const SVG_FOOTER = ``; + +function printUsage() { + console.log('Usage: test-render --font=filename.otf --testcase=TEST_NAME --render=TEXT_TO_RENDER'); + console.log('This commands output the text to render as an SVG file.'); + console.log(); +} + +let filename; +let testcase; +let textToRender; +for (let i = 0; i < process.argv.length; i++) { + const arg = process.argv[i]; + if (arg.startsWith('--font=')) { + filename = arg.substring('--font='.length); + } else if (arg.startsWith('--testcase=')) { + testcase = arg.substring('--testcase='.length); + } else if (arg.startsWith('--render=')) { + textToRender = arg.substring('--render='.length); + } +} + +if (filename === undefined || testcase === undefined || textToRender === undefined) { + printUsage(); + process.exit(1); +} + +function renderSVG() { + var font = opentype.loadSync(filename); + + let svgSymbols = []; + let svgBody = []; + + var glyphSet = new Set(); + let x = 0; + const glyphs = font.stringToGlyphs(textToRender); + for (let i = 0; i < glyphs.length; i++) { + const glyph = glyphs[i]; + const symbolId = testcase + '.' + glyph.name; + if (!glyphSet.has(glyph)) { + glyphSet.add(glyph); + const svgPath = glyph.path.toSVG(); + svgSymbols.push(` ${svgPath}`); + } + svgBody.push(` `); + x += glyph.advanceWidth; + } + + let minX = 0; + let minY = Math.round(font.descender); + let width = Math.round(x); + let height = Math.round(font.ascender - font.descender); + let svgHeader = ` +`; + + return svgHeader + svgSymbols.join('\n') + svgBody.join('\n') + SVG_FOOTER; +} + +try { + var svg = renderSVG(); + console.log(svg); +} catch(e) { + console.error(e.stack); + process.exit(1); +} diff --git a/node_modules/lv_font_conv/node_modules/opentype.js/dist/opentype.js b/node_modules/lv_font_conv/node_modules/opentype.js/dist/opentype.js new file mode 100644 index 00000000..11b0a548 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/opentype.js/dist/opentype.js @@ -0,0 +1,14254 @@ +/** + * https://opentype.js.org v1.3.3 | (c) Frederik De Bleser and other contributors | MIT License | Uses tiny-inflate by Devon Govett and string.prototype.codepointat polyfill by Mathias Bynens + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = global || self, factory(global.opentype = {})); +}(this, (function (exports) { 'use strict'; + + /*! https://mths.be/codepointat v0.2.0 by @mathias */ + if (!String.prototype.codePointAt) { + (function() { + var defineProperty = (function() { + // IE 8 only supports `Object.defineProperty` on DOM elements + try { + var object = {}; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch(error) {} + return result; + }()); + var codePointAt = function(position) { + if (this == null) { + throw TypeError(); + } + var string = String(this); + var size = string.length; + // `ToInteger` + var index = position ? Number(position) : 0; + if (index != index) { // better `isNaN` + index = 0; + } + // Account for out-of-bounds indices: + if (index < 0 || index >= size) { + return undefined; + } + // Get the first code unit + var first = string.charCodeAt(index); + var second; + if ( // check if it’s the start of a surrogate pair + first >= 0xD800 && first <= 0xDBFF && // high surrogate + size > index + 1 // there is a next code unit + ) { + second = string.charCodeAt(index + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; + }; + if (defineProperty) { + defineProperty(String.prototype, 'codePointAt', { + 'value': codePointAt, + 'configurable': true, + 'writable': true + }); + } else { + String.prototype.codePointAt = codePointAt; + } + }()); + } + + var TINF_OK = 0; + var TINF_DATA_ERROR = -3; + + function Tree() { + this.table = new Uint16Array(16); /* table of code length counts */ + this.trans = new Uint16Array(288); /* code -> symbol translation table */ + } + + function Data(source, dest) { + this.source = source; + this.sourceIndex = 0; + this.tag = 0; + this.bitcount = 0; + + this.dest = dest; + this.destLen = 0; + + this.ltree = new Tree(); /* dynamic length/symbol tree */ + this.dtree = new Tree(); /* dynamic distance tree */ + } + + /* --------------------------------------------------- * + * -- uninitialized global data (static structures) -- * + * --------------------------------------------------- */ + + var sltree = new Tree(); + var sdtree = new Tree(); + + /* extra bits and base tables for length codes */ + var length_bits = new Uint8Array(30); + var length_base = new Uint16Array(30); + + /* extra bits and base tables for distance codes */ + var dist_bits = new Uint8Array(30); + var dist_base = new Uint16Array(30); + + /* special ordering of code length codes */ + var clcidx = new Uint8Array([ + 16, 17, 18, 0, 8, 7, 9, 6, + 10, 5, 11, 4, 12, 3, 13, 2, + 14, 1, 15 + ]); + + /* used by tinf_decode_trees, avoids allocations every call */ + var code_tree = new Tree(); + var lengths = new Uint8Array(288 + 32); + + /* ----------------------- * + * -- utility functions -- * + * ----------------------- */ + + /* build extra bits and base tables */ + function tinf_build_bits_base(bits, base, delta, first) { + var i, sum; + + /* build bits table */ + for (i = 0; i < delta; ++i) { bits[i] = 0; } + for (i = 0; i < 30 - delta; ++i) { bits[i + delta] = i / delta | 0; } + + /* build base table */ + for (sum = first, i = 0; i < 30; ++i) { + base[i] = sum; + sum += 1 << bits[i]; + } + } + + /* build the fixed huffman trees */ + function tinf_build_fixed_trees(lt, dt) { + var i; + + /* build fixed length tree */ + for (i = 0; i < 7; ++i) { lt.table[i] = 0; } + + lt.table[7] = 24; + lt.table[8] = 152; + lt.table[9] = 112; + + for (i = 0; i < 24; ++i) { lt.trans[i] = 256 + i; } + for (i = 0; i < 144; ++i) { lt.trans[24 + i] = i; } + for (i = 0; i < 8; ++i) { lt.trans[24 + 144 + i] = 280 + i; } + for (i = 0; i < 112; ++i) { lt.trans[24 + 144 + 8 + i] = 144 + i; } + + /* build fixed distance tree */ + for (i = 0; i < 5; ++i) { dt.table[i] = 0; } + + dt.table[5] = 32; + + for (i = 0; i < 32; ++i) { dt.trans[i] = i; } + } + + /* given an array of code lengths, build a tree */ + var offs = new Uint16Array(16); + + function tinf_build_tree(t, lengths, off, num) { + var i, sum; + + /* clear code length count table */ + for (i = 0; i < 16; ++i) { t.table[i] = 0; } + + /* scan symbol lengths, and sum code length counts */ + for (i = 0; i < num; ++i) { t.table[lengths[off + i]]++; } + + t.table[0] = 0; + + /* compute offset table for distribution sort */ + for (sum = 0, i = 0; i < 16; ++i) { + offs[i] = sum; + sum += t.table[i]; + } + + /* create code->symbol translation table (symbols sorted by code) */ + for (i = 0; i < num; ++i) { + if (lengths[off + i]) { t.trans[offs[lengths[off + i]]++] = i; } + } + } + + /* ---------------------- * + * -- decode functions -- * + * ---------------------- */ + + /* get one bit from source stream */ + function tinf_getbit(d) { + /* check if tag is empty */ + if (!d.bitcount--) { + /* load next tag */ + d.tag = d.source[d.sourceIndex++]; + d.bitcount = 7; + } + + /* shift bit out of tag */ + var bit = d.tag & 1; + d.tag >>>= 1; + + return bit; + } + + /* read a num bit value from a stream and add base */ + function tinf_read_bits(d, num, base) { + if (!num) + { return base; } + + while (d.bitcount < 24) { + d.tag |= d.source[d.sourceIndex++] << d.bitcount; + d.bitcount += 8; + } + + var val = d.tag & (0xffff >>> (16 - num)); + d.tag >>>= num; + d.bitcount -= num; + return val + base; + } + + /* given a data stream and a tree, decode a symbol */ + function tinf_decode_symbol(d, t) { + while (d.bitcount < 24) { + d.tag |= d.source[d.sourceIndex++] << d.bitcount; + d.bitcount += 8; + } + + var sum = 0, cur = 0, len = 0; + var tag = d.tag; + + /* get more bits while code value is above sum */ + do { + cur = 2 * cur + (tag & 1); + tag >>>= 1; + ++len; + + sum += t.table[len]; + cur -= t.table[len]; + } while (cur >= 0); + + d.tag = tag; + d.bitcount -= len; + + return t.trans[sum + cur]; + } + + /* given a data stream, decode dynamic trees from it */ + function tinf_decode_trees(d, lt, dt) { + var hlit, hdist, hclen; + var i, num, length; + + /* get 5 bits HLIT (257-286) */ + hlit = tinf_read_bits(d, 5, 257); + + /* get 5 bits HDIST (1-32) */ + hdist = tinf_read_bits(d, 5, 1); + + /* get 4 bits HCLEN (4-19) */ + hclen = tinf_read_bits(d, 4, 4); + + for (i = 0; i < 19; ++i) { lengths[i] = 0; } + + /* read code lengths for code length alphabet */ + for (i = 0; i < hclen; ++i) { + /* get 3 bits code length (0-7) */ + var clen = tinf_read_bits(d, 3, 0); + lengths[clcidx[i]] = clen; + } + + /* build code length tree */ + tinf_build_tree(code_tree, lengths, 0, 19); + + /* decode code lengths for the dynamic trees */ + for (num = 0; num < hlit + hdist;) { + var sym = tinf_decode_symbol(d, code_tree); + + switch (sym) { + case 16: + /* copy previous code length 3-6 times (read 2 bits) */ + var prev = lengths[num - 1]; + for (length = tinf_read_bits(d, 2, 3); length; --length) { + lengths[num++] = prev; + } + break; + case 17: + /* repeat code length 0 for 3-10 times (read 3 bits) */ + for (length = tinf_read_bits(d, 3, 3); length; --length) { + lengths[num++] = 0; + } + break; + case 18: + /* repeat code length 0 for 11-138 times (read 7 bits) */ + for (length = tinf_read_bits(d, 7, 11); length; --length) { + lengths[num++] = 0; + } + break; + default: + /* values 0-15 represent the actual code lengths */ + lengths[num++] = sym; + break; + } + } + + /* build dynamic trees */ + tinf_build_tree(lt, lengths, 0, hlit); + tinf_build_tree(dt, lengths, hlit, hdist); + } + + /* ----------------------------- * + * -- block inflate functions -- * + * ----------------------------- */ + + /* given a stream and two trees, inflate a block of data */ + function tinf_inflate_block_data(d, lt, dt) { + while (1) { + var sym = tinf_decode_symbol(d, lt); + + /* check for end of block */ + if (sym === 256) { + return TINF_OK; + } + + if (sym < 256) { + d.dest[d.destLen++] = sym; + } else { + var length, dist, offs; + var i; + + sym -= 257; + + /* possibly get more bits from length code */ + length = tinf_read_bits(d, length_bits[sym], length_base[sym]); + + dist = tinf_decode_symbol(d, dt); + + /* possibly get more bits from distance code */ + offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]); + + /* copy match */ + for (i = offs; i < offs + length; ++i) { + d.dest[d.destLen++] = d.dest[i]; + } + } + } + } + + /* inflate an uncompressed block of data */ + function tinf_inflate_uncompressed_block(d) { + var length, invlength; + var i; + + /* unread from bitbuffer */ + while (d.bitcount > 8) { + d.sourceIndex--; + d.bitcount -= 8; + } + + /* get length */ + length = d.source[d.sourceIndex + 1]; + length = 256 * length + d.source[d.sourceIndex]; + + /* get one's complement of length */ + invlength = d.source[d.sourceIndex + 3]; + invlength = 256 * invlength + d.source[d.sourceIndex + 2]; + + /* check length */ + if (length !== (~invlength & 0x0000ffff)) + { return TINF_DATA_ERROR; } + + d.sourceIndex += 4; + + /* copy block */ + for (i = length; i; --i) + { d.dest[d.destLen++] = d.source[d.sourceIndex++]; } + + /* make sure we start next block on a byte boundary */ + d.bitcount = 0; + + return TINF_OK; + } + + /* inflate stream from source to dest */ + function tinf_uncompress(source, dest) { + var d = new Data(source, dest); + var bfinal, btype, res; + + do { + /* read final block flag */ + bfinal = tinf_getbit(d); + + /* read block type (2 bits) */ + btype = tinf_read_bits(d, 2, 0); + + /* decompress block */ + switch (btype) { + case 0: + /* decompress uncompressed block */ + res = tinf_inflate_uncompressed_block(d); + break; + case 1: + /* decompress block with fixed huffman trees */ + res = tinf_inflate_block_data(d, sltree, sdtree); + break; + case 2: + /* decompress block with dynamic huffman trees */ + tinf_decode_trees(d, d.ltree, d.dtree); + res = tinf_inflate_block_data(d, d.ltree, d.dtree); + break; + default: + res = TINF_DATA_ERROR; + } + + if (res !== TINF_OK) + { throw new Error('Data error'); } + + } while (!bfinal); + + if (d.destLen < d.dest.length) { + if (typeof d.dest.slice === 'function') + { return d.dest.slice(0, d.destLen); } + else + { return d.dest.subarray(0, d.destLen); } + } + + return d.dest; + } + + /* -------------------- * + * -- initialization -- * + * -------------------- */ + + /* build fixed huffman trees */ + tinf_build_fixed_trees(sltree, sdtree); + + /* build extra bits and base tables */ + tinf_build_bits_base(length_bits, length_base, 4, 3); + tinf_build_bits_base(dist_bits, dist_base, 2, 1); + + /* fix a special case */ + length_bits[28] = 0; + length_base[28] = 258; + + var tinyInflate = tinf_uncompress; + + // The Bounding Box object + + function derive(v0, v1, v2, v3, t) { + return Math.pow(1 - t, 3) * v0 + + 3 * Math.pow(1 - t, 2) * t * v1 + + 3 * (1 - t) * Math.pow(t, 2) * v2 + + Math.pow(t, 3) * v3; + } + /** + * A bounding box is an enclosing box that describes the smallest measure within which all the points lie. + * It is used to calculate the bounding box of a glyph or text path. + * + * On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`. + * + * @exports opentype.BoundingBox + * @class + * @constructor + */ + function BoundingBox() { + this.x1 = Number.NaN; + this.y1 = Number.NaN; + this.x2 = Number.NaN; + this.y2 = Number.NaN; + } + + /** + * Returns true if the bounding box is empty, that is, no points have been added to the box yet. + */ + BoundingBox.prototype.isEmpty = function() { + return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2); + }; + + /** + * Add the point to the bounding box. + * The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point. + * @param {number} x - The X coordinate of the point. + * @param {number} y - The Y coordinate of the point. + */ + BoundingBox.prototype.addPoint = function(x, y) { + if (typeof x === 'number') { + if (isNaN(this.x1) || isNaN(this.x2)) { + this.x1 = x; + this.x2 = x; + } + if (x < this.x1) { + this.x1 = x; + } + if (x > this.x2) { + this.x2 = x; + } + } + if (typeof y === 'number') { + if (isNaN(this.y1) || isNaN(this.y2)) { + this.y1 = y; + this.y2 = y; + } + if (y < this.y1) { + this.y1 = y; + } + if (y > this.y2) { + this.y2 = y; + } + } + }; + + /** + * Add a X coordinate to the bounding box. + * This extends the bounding box to include the X coordinate. + * This function is used internally inside of addBezier. + * @param {number} x - The X coordinate of the point. + */ + BoundingBox.prototype.addX = function(x) { + this.addPoint(x, null); + }; + + /** + * Add a Y coordinate to the bounding box. + * This extends the bounding box to include the Y coordinate. + * This function is used internally inside of addBezier. + * @param {number} y - The Y coordinate of the point. + */ + BoundingBox.prototype.addY = function(y) { + this.addPoint(null, y); + }; + + /** + * Add a Bézier curve to the bounding box. + * This extends the bounding box to include the entire Bézier. + * @param {number} x0 - The starting X coordinate. + * @param {number} y0 - The starting Y coordinate. + * @param {number} x1 - The X coordinate of the first control point. + * @param {number} y1 - The Y coordinate of the first control point. + * @param {number} x2 - The X coordinate of the second control point. + * @param {number} y2 - The Y coordinate of the second control point. + * @param {number} x - The ending X coordinate. + * @param {number} y - The ending Y coordinate. + */ + BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x, y) { + // This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html + // and https://github.com/icons8/svg-path-bounding-box + + var p0 = [x0, y0]; + var p1 = [x1, y1]; + var p2 = [x2, y2]; + var p3 = [x, y]; + + this.addPoint(x0, y0); + this.addPoint(x, y); + + for (var i = 0; i <= 1; i++) { + var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; + var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; + var c = 3 * p1[i] - 3 * p0[i]; + + if (a === 0) { + if (b === 0) { continue; } + var t = -c / b; + if (0 < t && t < 1) { + if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t)); } + if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t)); } + } + continue; + } + + var b2ac = Math.pow(b, 2) - 4 * c * a; + if (b2ac < 0) { continue; } + var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); + if (0 < t1 && t1 < 1) { + if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); } + if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); } + } + var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); + if (0 < t2 && t2 < 1) { + if (i === 0) { this.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); } + if (i === 1) { this.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); } + } + } + }; + + /** + * Add a quadratic curve to the bounding box. + * This extends the bounding box to include the entire quadratic curve. + * @param {number} x0 - The starting X coordinate. + * @param {number} y0 - The starting Y coordinate. + * @param {number} x1 - The X coordinate of the control point. + * @param {number} y1 - The Y coordinate of the control point. + * @param {number} x - The ending X coordinate. + * @param {number} y - The ending Y coordinate. + */ + BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x, y) { + var cp1x = x0 + 2 / 3 * (x1 - x0); + var cp1y = y0 + 2 / 3 * (y1 - y0); + var cp2x = cp1x + 1 / 3 * (x - x0); + var cp2y = cp1y + 1 / 3 * (y - y0); + this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y); + }; + + // Geometric objects + + /** + * A bézier path containing a set of path commands similar to a SVG path. + * Paths can be drawn on a context using `draw`. + * @exports opentype.Path + * @class + * @constructor + */ + function Path() { + this.commands = []; + this.fill = 'black'; + this.stroke = null; + this.strokeWidth = 1; + } + + /** + * @param {number} x + * @param {number} y + */ + Path.prototype.moveTo = function(x, y) { + this.commands.push({ + type: 'M', + x: x, + y: y + }); + }; + + /** + * @param {number} x + * @param {number} y + */ + Path.prototype.lineTo = function(x, y) { + this.commands.push({ + type: 'L', + x: x, + y: y + }); + }; + + /** + * Draws cubic curve + * @function + * curveTo + * @memberof opentype.Path.prototype + * @param {number} x1 - x of control 1 + * @param {number} y1 - y of control 1 + * @param {number} x2 - x of control 2 + * @param {number} y2 - y of control 2 + * @param {number} x - x of path point + * @param {number} y - y of path point + */ + + /** + * Draws cubic curve + * @function + * bezierCurveTo + * @memberof opentype.Path.prototype + * @param {number} x1 - x of control 1 + * @param {number} y1 - y of control 1 + * @param {number} x2 - x of control 2 + * @param {number} y2 - y of control 2 + * @param {number} x - x of path point + * @param {number} y - y of path point + * @see curveTo + */ + Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) { + this.commands.push({ + type: 'C', + x1: x1, + y1: y1, + x2: x2, + y2: y2, + x: x, + y: y + }); + }; + + /** + * Draws quadratic curve + * @function + * quadraticCurveTo + * @memberof opentype.Path.prototype + * @param {number} x1 - x of control + * @param {number} y1 - y of control + * @param {number} x - x of path point + * @param {number} y - y of path point + */ + + /** + * Draws quadratic curve + * @function + * quadTo + * @memberof opentype.Path.prototype + * @param {number} x1 - x of control + * @param {number} y1 - y of control + * @param {number} x - x of path point + * @param {number} y - y of path point + */ + Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) { + this.commands.push({ + type: 'Q', + x1: x1, + y1: y1, + x: x, + y: y + }); + }; + + /** + * Closes the path + * @function closePath + * @memberof opentype.Path.prototype + */ + + /** + * Close the path + * @function close + * @memberof opentype.Path.prototype + */ + Path.prototype.close = Path.prototype.closePath = function() { + this.commands.push({ + type: 'Z' + }); + }; + + /** + * Add the given path or list of commands to the commands of this path. + * @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands. + */ + Path.prototype.extend = function(pathOrCommands) { + if (pathOrCommands.commands) { + pathOrCommands = pathOrCommands.commands; + } else if (pathOrCommands instanceof BoundingBox) { + var box = pathOrCommands; + this.moveTo(box.x1, box.y1); + this.lineTo(box.x2, box.y1); + this.lineTo(box.x2, box.y2); + this.lineTo(box.x1, box.y2); + this.close(); + return; + } + + Array.prototype.push.apply(this.commands, pathOrCommands); + }; + + /** + * Calculate the bounding box of the path. + * @returns {opentype.BoundingBox} + */ + Path.prototype.getBoundingBox = function() { + var box = new BoundingBox(); + + var startX = 0; + var startY = 0; + var prevX = 0; + var prevY = 0; + for (var i = 0; i < this.commands.length; i++) { + var cmd = this.commands[i]; + switch (cmd.type) { + case 'M': + box.addPoint(cmd.x, cmd.y); + startX = prevX = cmd.x; + startY = prevY = cmd.y; + break; + case 'L': + box.addPoint(cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case 'Q': + box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case 'C': + box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case 'Z': + prevX = startX; + prevY = startY; + break; + default: + throw new Error('Unexpected path command ' + cmd.type); + } + } + if (box.isEmpty()) { + box.addPoint(0, 0); + } + return box; + }; + + /** + * Draw the path to a 2D context. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context. + */ + Path.prototype.draw = function(ctx) { + ctx.beginPath(); + for (var i = 0; i < this.commands.length; i += 1) { + var cmd = this.commands[i]; + if (cmd.type === 'M') { + ctx.moveTo(cmd.x, cmd.y); + } else if (cmd.type === 'L') { + ctx.lineTo(cmd.x, cmd.y); + } else if (cmd.type === 'C') { + ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === 'Q') { + ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === 'Z') { + ctx.closePath(); + } + } + + if (this.fill) { + ctx.fillStyle = this.fill; + ctx.fill(); + } + + if (this.stroke) { + ctx.strokeStyle = this.stroke; + ctx.lineWidth = this.strokeWidth; + ctx.stroke(); + } + }; + + /** + * Convert the Path to a string of path data instructions + * See http://www.w3.org/TR/SVG/paths.html#PathData + * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values + * @return {string} + */ + Path.prototype.toPathData = function(decimalPlaces) { + decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; + + function floatToString(v) { + if (Math.round(v) === v) { + return '' + Math.round(v); + } else { + return v.toFixed(decimalPlaces); + } + } + + function packValues() { + var arguments$1 = arguments; + + var s = ''; + for (var i = 0; i < arguments.length; i += 1) { + var v = arguments$1[i]; + if (v >= 0 && i > 0) { + s += ' '; + } + + s += floatToString(v); + } + + return s; + } + + var d = ''; + for (var i = 0; i < this.commands.length; i += 1) { + var cmd = this.commands[i]; + if (cmd.type === 'M') { + d += 'M' + packValues(cmd.x, cmd.y); + } else if (cmd.type === 'L') { + d += 'L' + packValues(cmd.x, cmd.y); + } else if (cmd.type === 'C') { + d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === 'Q') { + d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === 'Z') { + d += 'Z'; + } + } + + return d; + }; + + /** + * Convert the path to an SVG element, as a string. + * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values + * @return {string} + */ + Path.prototype.toSVG = function(decimalPlaces) { + var svg = '= 0 && v <= 255, 'Byte value should be between 0 and 255.'); + return [v]; + }; + /** + * @constant + * @type {number} + */ + sizeOf.BYTE = constant(1); + + /** + * Convert a 8-bit signed integer to a list of 1 byte. + * @param {string} + * @returns {Array} + */ + encode.CHAR = function(v) { + return [v.charCodeAt(0)]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.CHAR = constant(1); + + /** + * Convert an ASCII string to a list of bytes. + * @param {string} + * @returns {Array} + */ + encode.CHARARRAY = function(v) { + var b = []; + for (var i = 0; i < v.length; i += 1) { + b[i] = v.charCodeAt(i); + } + + return b; + }; + + /** + * @param {Array} + * @returns {number} + */ + sizeOf.CHARARRAY = function(v) { + return v.length; + }; + + /** + * Convert a 16-bit unsigned integer to a list of 2 bytes. + * @param {number} + * @returns {Array} + */ + encode.USHORT = function(v) { + return [(v >> 8) & 0xFF, v & 0xFF]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.USHORT = constant(2); + + /** + * Convert a 16-bit signed integer to a list of 2 bytes. + * @param {number} + * @returns {Array} + */ + encode.SHORT = function(v) { + // Two's complement + if (v >= LIMIT16) { + v = -(2 * LIMIT16 - v); + } + + return [(v >> 8) & 0xFF, v & 0xFF]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.SHORT = constant(2); + + /** + * Convert a 24-bit unsigned integer to a list of 3 bytes. + * @param {number} + * @returns {Array} + */ + encode.UINT24 = function(v) { + return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.UINT24 = constant(3); + + /** + * Convert a 32-bit unsigned integer to a list of 4 bytes. + * @param {number} + * @returns {Array} + */ + encode.ULONG = function(v) { + return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.ULONG = constant(4); + + /** + * Convert a 32-bit unsigned integer to a list of 4 bytes. + * @param {number} + * @returns {Array} + */ + encode.LONG = function(v) { + // Two's complement + if (v >= LIMIT32) { + v = -(2 * LIMIT32 - v); + } + + return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.LONG = constant(4); + + encode.FIXED = encode.ULONG; + sizeOf.FIXED = sizeOf.ULONG; + + encode.FWORD = encode.SHORT; + sizeOf.FWORD = sizeOf.SHORT; + + encode.UFWORD = encode.USHORT; + sizeOf.UFWORD = sizeOf.USHORT; + + /** + * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp. + * @param {number} + * @returns {Array} + */ + encode.LONGDATETIME = function(v) { + return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.LONGDATETIME = constant(8); + + /** + * Convert a 4-char tag to a list of 4 bytes. + * @param {string} + * @returns {Array} + */ + encode.TAG = function(v) { + check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.'); + return [v.charCodeAt(0), + v.charCodeAt(1), + v.charCodeAt(2), + v.charCodeAt(3)]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.TAG = constant(4); + + // CFF data types /////////////////////////////////////////////////////////// + + encode.Card8 = encode.BYTE; + sizeOf.Card8 = sizeOf.BYTE; + + encode.Card16 = encode.USHORT; + sizeOf.Card16 = sizeOf.USHORT; + + encode.OffSize = encode.BYTE; + sizeOf.OffSize = sizeOf.BYTE; + + encode.SID = encode.USHORT; + sizeOf.SID = sizeOf.USHORT; + + // Convert a numeric operand or charstring number to a variable-size list of bytes. + /** + * Convert a numeric operand or charstring number to a variable-size list of bytes. + * @param {number} + * @returns {Array} + */ + encode.NUMBER = function(v) { + if (v >= -107 && v <= 107) { + return [v + 139]; + } else if (v >= 108 && v <= 1131) { + v = v - 108; + return [(v >> 8) + 247, v & 0xFF]; + } else if (v >= -1131 && v <= -108) { + v = -v - 108; + return [(v >> 8) + 251, v & 0xFF]; + } else if (v >= -32768 && v <= 32767) { + return encode.NUMBER16(v); + } else { + return encode.NUMBER32(v); + } + }; + + /** + * @param {number} + * @returns {number} + */ + sizeOf.NUMBER = function(v) { + return encode.NUMBER(v).length; + }; + + /** + * Convert a signed number between -32768 and +32767 to a three-byte value. + * This ensures we always use three bytes, but is not the most compact format. + * @param {number} + * @returns {Array} + */ + encode.NUMBER16 = function(v) { + return [28, (v >> 8) & 0xFF, v & 0xFF]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.NUMBER16 = constant(3); + + /** + * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value. + * This is useful if you want to be sure you always use four bytes, + * at the expense of wasting a few bytes for smaller numbers. + * @param {number} + * @returns {Array} + */ + encode.NUMBER32 = function(v) { + return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; + }; + + /** + * @constant + * @type {number} + */ + sizeOf.NUMBER32 = constant(5); + + /** + * @param {number} + * @returns {Array} + */ + encode.REAL = function(v) { + var value = v.toString(); + + // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7) + // This code converts it back to a number without the epsilon. + var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); + if (m) { + var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length)); + value = (Math.round(v * epsilon) / epsilon).toString(); + } + + var nibbles = ''; + for (var i = 0, ii = value.length; i < ii; i += 1) { + var c = value[i]; + if (c === 'e') { + nibbles += value[++i] === '-' ? 'c' : 'b'; + } else if (c === '.') { + nibbles += 'a'; + } else if (c === '-') { + nibbles += 'e'; + } else { + nibbles += c; + } + } + + nibbles += (nibbles.length & 1) ? 'f' : 'ff'; + var out = [30]; + for (var i$1 = 0, ii$1 = nibbles.length; i$1 < ii$1; i$1 += 2) { + out.push(parseInt(nibbles.substr(i$1, 2), 16)); + } + + return out; + }; + + /** + * @param {number} + * @returns {number} + */ + sizeOf.REAL = function(v) { + return encode.REAL(v).length; + }; + + encode.NAME = encode.CHARARRAY; + sizeOf.NAME = sizeOf.CHARARRAY; + + encode.STRING = encode.CHARARRAY; + sizeOf.STRING = sizeOf.CHARARRAY; + + /** + * @param {DataView} data + * @param {number} offset + * @param {number} numBytes + * @returns {string} + */ + decode.UTF8 = function(data, offset, numBytes) { + var codePoints = []; + var numChars = numBytes; + for (var j = 0; j < numChars; j++, offset += 1) { + codePoints[j] = data.getUint8(offset); + } + + return String.fromCharCode.apply(null, codePoints); + }; + + /** + * @param {DataView} data + * @param {number} offset + * @param {number} numBytes + * @returns {string} + */ + decode.UTF16 = function(data, offset, numBytes) { + var codePoints = []; + var numChars = numBytes / 2; + for (var j = 0; j < numChars; j++, offset += 2) { + codePoints[j] = data.getUint16(offset); + } + + return String.fromCharCode.apply(null, codePoints); + }; + + /** + * Convert a JavaScript string to UTF16-BE. + * @param {string} + * @returns {Array} + */ + encode.UTF16 = function(v) { + var b = []; + for (var i = 0; i < v.length; i += 1) { + var codepoint = v.charCodeAt(i); + b[b.length] = (codepoint >> 8) & 0xFF; + b[b.length] = codepoint & 0xFF; + } + + return b; + }; + + /** + * @param {string} + * @returns {number} + */ + sizeOf.UTF16 = function(v) { + return v.length * 2; + }; + + // Data for converting old eight-bit Macintosh encodings to Unicode. + // This representation is optimized for decoding; encoding is slower + // and needs more memory. The assumption is that all opentype.js users + // want to open fonts, but saving a font will be comparatively rare + // so it can be more expensive. Keyed by IANA character set name. + // + // Python script for generating these strings: + // + // s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)]) + // print(s.encode('utf-8')) + /** + * @private + */ + var eightBitMacEncodings = { + 'x-mac-croatian': // Python: 'mac_croatian' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' + + '¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', + 'x-mac-cyrillic': // Python: 'mac_cyrillic' + 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' + + 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю', + 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' + + 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', + 'x-mac-greek': // Python: 'mac_greek' + 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' + + 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD', + 'x-mac-icelandic': // Python: 'mac_iceland' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', + 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT + 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' + + 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', + 'x-mac-ce': // Python: 'mac_latin2' + 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' + + 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', + macintosh: // Python: 'mac_roman' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', + 'x-mac-romanian': // Python: 'mac_romanian' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' + + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', + 'x-mac-turkish': // Python: 'mac_turkish' + 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' + }; + + /** + * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript + * string, or 'undefined' if the encoding is unsupported. For example, we do + * not support Chinese, Japanese or Korean because these would need large + * mapping tables. + * @param {DataView} dataView + * @param {number} offset + * @param {number} dataLength + * @param {string} encoding + * @returns {string} + */ + decode.MACSTRING = function(dataView, offset, dataLength, encoding) { + var table = eightBitMacEncodings[encoding]; + if (table === undefined) { + return undefined; + } + + var result = ''; + for (var i = 0; i < dataLength; i++) { + var c = dataView.getUint8(offset + i); + // In all eight-bit Mac encodings, the characters 0x00..0x7F are + // mapped to U+0000..U+007F; we only need to look up the others. + if (c <= 0x7F) { + result += String.fromCharCode(c); + } else { + result += table[c & 0x7F]; + } + } + + return result; + }; + + // Helper function for encode.MACSTRING. Returns a dictionary for mapping + // Unicode character codes to their 8-bit MacOS equivalent. This table + // is not exactly a super cheap data structure, but we do not care because + // encoding Macintosh strings is only rarely needed in typical applications. + var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap(); + var macEncodingCacheKeys; + var getMacEncodingTable = function (encoding) { + // Since we use encoding as a cache key for WeakMap, it has to be + // a String object and not a literal. And at least on NodeJS 2.10.1, + // WeakMap requires that the same String instance is passed for cache hits. + if (!macEncodingCacheKeys) { + macEncodingCacheKeys = {}; + for (var e in eightBitMacEncodings) { + /*jshint -W053 */ // Suppress "Do not use String as a constructor." + macEncodingCacheKeys[e] = new String(e); + } + } + + var cacheKey = macEncodingCacheKeys[encoding]; + if (cacheKey === undefined) { + return undefined; + } + + // We can't do "if (cache.has(key)) {return cache.get(key)}" here: + // since garbage collection may run at any time, it could also kick in + // between the calls to cache.has() and cache.get(). In that case, + // we would return 'undefined' even though we do support the encoding. + if (macEncodingTableCache) { + var cachedTable = macEncodingTableCache.get(cacheKey); + if (cachedTable !== undefined) { + return cachedTable; + } + } + + var decodingTable = eightBitMacEncodings[encoding]; + if (decodingTable === undefined) { + return undefined; + } + + var encodingTable = {}; + for (var i = 0; i < decodingTable.length; i++) { + encodingTable[decodingTable.charCodeAt(i)] = i + 0x80; + } + + if (macEncodingTableCache) { + macEncodingTableCache.set(cacheKey, encodingTable); + } + + return encodingTable; + }; + + /** + * Encodes an old-style Macintosh string. Returns a byte array upon success. + * If the requested encoding is unsupported, or if the input string contains + * a character that cannot be expressed in the encoding, the function returns + * 'undefined'. + * @param {string} str + * @param {string} encoding + * @returns {Array} + */ + encode.MACSTRING = function(str, encoding) { + var table = getMacEncodingTable(encoding); + if (table === undefined) { + return undefined; + } + + var result = []; + for (var i = 0; i < str.length; i++) { + var c = str.charCodeAt(i); + + // In all eight-bit Mac encodings, the characters 0x00..0x7F are + // mapped to U+0000..U+007F; we only need to look up the others. + if (c >= 0x80) { + c = table[c]; + if (c === undefined) { + // str contains a Unicode character that cannot be encoded + // in the requested encoding. + return undefined; + } + } + result[i] = c; + // result.push(c); + } + + return result; + }; + + /** + * @param {string} str + * @param {string} encoding + * @returns {number} + */ + sizeOf.MACSTRING = function(str, encoding) { + var b = encode.MACSTRING(str, encoding); + if (b !== undefined) { + return b.length; + } else { + return 0; + } + }; + + // Helper for encode.VARDELTAS + function isByteEncodable(value) { + return value >= -128 && value <= 127; + } + + // Helper for encode.VARDELTAS + function encodeVarDeltaRunAsZeroes(deltas, pos, result) { + var runLength = 0; + var numDeltas = deltas.length; + while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) { + ++pos; + ++runLength; + } + result.push(0x80 | (runLength - 1)); + return pos; + } + + // Helper for encode.VARDELTAS + function encodeVarDeltaRunAsBytes(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value = deltas[pos]; + if (!isByteEncodable(value)) { + break; + } + + // Within a byte-encoded run of deltas, a single zero is best + // stored literally as 0x00 value. However, if we have two or + // more zeroes in a sequence, it is better to start a new run. + // Fore example, the sequence of deltas [15, 15, 0, 15, 15] + // becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero + // within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F) + // when starting a new run. + if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { + break; + } + + ++pos; + ++runLength; + } + result.push(runLength - 1); + for (var i = offset; i < pos; ++i) { + result.push((deltas[i] + 256) & 0xff); + } + return pos; + } + + // Helper for encode.VARDELTAS + function encodeVarDeltaRunAsWords(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value = deltas[pos]; + + // Within a word-encoded run of deltas, it is easiest to start + // a new run (with a different encoding) whenever we encounter + // a zero value. For example, the sequence [0x6666, 0, 0x7777] + // needs 7 bytes when storing the zero inside the current run + // (42 66 66 00 00 77 77), and equally 7 bytes when starting a + // new run (40 66 66 80 40 77 77). + if (value === 0) { + break; + } + + // Within a word-encoded run of deltas, a single value in the + // range (-128..127) should be encoded within the current run + // because it is more compact. For example, the sequence + // [0x6666, 2, 0x7777] becomes 7 bytes when storing the value + // literally (42 66 66 00 02 77 77), but 8 bytes when starting + // a new run (40 66 66 00 02 40 77 77). + if (isByteEncodable(value) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { + break; + } + + ++pos; + ++runLength; + } + result.push(0x40 | (runLength - 1)); + for (var i = offset; i < pos; ++i) { + var val = deltas[i]; + result.push(((val + 0x10000) >> 8) & 0xff, (val + 0x100) & 0xff); + } + return pos; + } + + /** + * Encode a list of variation adjustment deltas. + * + * Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables. + * They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted + * when generating instances of variation fonts. + * + * @see https://www.microsoft.com/typography/otspec/gvar.htm + * @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html + * @param {Array} + * @return {Array} + */ + encode.VARDELTAS = function(deltas) { + var pos = 0; + var result = []; + while (pos < deltas.length) { + var value = deltas[pos]; + if (value === 0) { + pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); + } else if (value >= -128 && value <= 127) { + pos = encodeVarDeltaRunAsBytes(deltas, pos, result); + } else { + pos = encodeVarDeltaRunAsWords(deltas, pos, result); + } + } + return result; + }; + + // Convert a list of values to a CFF INDEX structure. + // The values should be objects containing name / type / value. + /** + * @param {Array} l + * @returns {Array} + */ + encode.INDEX = function(l) { + //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data, + // i, v; + // Because we have to know which data type to use to encode the offsets, + // we have to go through the values twice: once to encode the data and + // calculate the offsets, then again to encode the offsets using the fitting data type. + var offset = 1; // First offset is always 1. + var offsets = [offset]; + var data = []; + for (var i = 0; i < l.length; i += 1) { + var v = encode.OBJECT(l[i]); + Array.prototype.push.apply(data, v); + offset += v.length; + offsets.push(offset); + } + + if (data.length === 0) { + return [0, 0]; + } + + var encodedOffsets = []; + var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0; + var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; + for (var i$1 = 0; i$1 < offsets.length; i$1 += 1) { + var encodedOffset = offsetEncoder(offsets[i$1]); + Array.prototype.push.apply(encodedOffsets, encodedOffset); + } + + return Array.prototype.concat(encode.Card16(l.length), + encode.OffSize(offSize), + encodedOffsets, + data); + }; + + /** + * @param {Array} + * @returns {number} + */ + sizeOf.INDEX = function(v) { + return encode.INDEX(v).length; + }; + + /** + * Convert an object to a CFF DICT structure. + * The keys should be numeric. + * The values should be objects containing name / type / value. + * @param {Object} m + * @returns {Array} + */ + encode.DICT = function(m) { + var d = []; + var keys = Object.keys(m); + var length = keys.length; + + for (var i = 0; i < length; i += 1) { + // Object.keys() return string keys, but our keys are always numeric. + var k = parseInt(keys[i], 0); + var v = m[k]; + // Value comes before the key. + d = d.concat(encode.OPERAND(v.value, v.type)); + d = d.concat(encode.OPERATOR(k)); + } + + return d; + }; + + /** + * @param {Object} + * @returns {number} + */ + sizeOf.DICT = function(m) { + return encode.DICT(m).length; + }; + + /** + * @param {number} + * @returns {Array} + */ + encode.OPERATOR = function(v) { + if (v < 1200) { + return [v]; + } else { + return [12, v - 1200]; + } + }; + + /** + * @param {Array} v + * @param {string} + * @returns {Array} + */ + encode.OPERAND = function(v, type) { + var d = []; + if (Array.isArray(type)) { + for (var i = 0; i < type.length; i += 1) { + check.argument(v.length === type.length, 'Not enough arguments given for type' + type); + d = d.concat(encode.OPERAND(v[i], type[i])); + } + } else { + if (type === 'SID') { + d = d.concat(encode.NUMBER(v)); + } else if (type === 'offset') { + // We make it easy for ourselves and always encode offsets as + // 4 bytes. This makes offset calculation for the top dict easier. + d = d.concat(encode.NUMBER32(v)); + } else if (type === 'number') { + d = d.concat(encode.NUMBER(v)); + } else if (type === 'real') { + d = d.concat(encode.REAL(v)); + } else { + throw new Error('Unknown operand type ' + type); + // FIXME Add support for booleans + } + } + + return d; + }; + + encode.OP = encode.BYTE; + sizeOf.OP = sizeOf.BYTE; + + // memoize charstring encoding using WeakMap if available + var wmm = typeof WeakMap === 'function' && new WeakMap(); + + /** + * Convert a list of CharString operations to bytes. + * @param {Array} + * @returns {Array} + */ + encode.CHARSTRING = function(ops) { + // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))". + if (wmm) { + var cachedValue = wmm.get(ops); + if (cachedValue !== undefined) { + return cachedValue; + } + } + + var d = []; + var length = ops.length; + + for (var i = 0; i < length; i += 1) { + var op = ops[i]; + d = d.concat(encode[op.type](op.value)); + } + + if (wmm) { + wmm.set(ops, d); + } + + return d; + }; + + /** + * @param {Array} + * @returns {number} + */ + sizeOf.CHARSTRING = function(ops) { + return encode.CHARSTRING(ops).length; + }; + + // Utility functions //////////////////////////////////////////////////////// + + /** + * Convert an object containing name / type / value to bytes. + * @param {Object} + * @returns {Array} + */ + encode.OBJECT = function(v) { + var encodingFunction = encode[v.type]; + check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type); + return encodingFunction(v.value); + }; + + /** + * @param {Object} + * @returns {number} + */ + sizeOf.OBJECT = function(v) { + var sizeOfFunction = sizeOf[v.type]; + check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type); + return sizeOfFunction(v.value); + }; + + /** + * Convert a table object to bytes. + * A table contains a list of fields containing the metadata (name, type and default value). + * The table itself has the field values set as attributes. + * @param {opentype.Table} + * @returns {Array} + */ + encode.TABLE = function(table) { + var d = []; + var length = table.fields.length; + var subtables = []; + var subtableOffsets = []; + + for (var i = 0; i < length; i += 1) { + var field = table.fields[i]; + var encodingFunction = encode[field.type]; + check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')'); + var value = table[field.name]; + if (value === undefined) { + value = field.value; + } + + var bytes = encodingFunction(value); + + if (field.type === 'TABLE') { + subtableOffsets.push(d.length); + d = d.concat([0, 0]); + subtables.push(bytes); + } else { + d = d.concat(bytes); + } + } + + for (var i$1 = 0; i$1 < subtables.length; i$1 += 1) { + var o = subtableOffsets[i$1]; + var offset = d.length; + check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.'); + d[o] = offset >> 8; + d[o + 1] = offset & 0xff; + d = d.concat(subtables[i$1]); + } + + return d; + }; + + /** + * @param {opentype.Table} + * @returns {number} + */ + sizeOf.TABLE = function(table) { + var numBytes = 0; + var length = table.fields.length; + + for (var i = 0; i < length; i += 1) { + var field = table.fields[i]; + var sizeOfFunction = sizeOf[field.type]; + check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')'); + var value = table[field.name]; + if (value === undefined) { + value = field.value; + } + + numBytes += sizeOfFunction(value); + + // Subtables take 2 more bytes for offsets. + if (field.type === 'TABLE') { + numBytes += 2; + } + } + + return numBytes; + }; + + encode.RECORD = encode.TABLE; + sizeOf.RECORD = sizeOf.TABLE; + + // Merge in a list of bytes. + encode.LITERAL = function(v) { + return v; + }; + + sizeOf.LITERAL = function(v) { + return v.length; + }; + + // Table metadata + + /** + * @exports opentype.Table + * @class + * @param {string} tableName + * @param {Array} fields + * @param {Object} options + * @constructor + */ + function Table(tableName, fields, options) { + for (var i = 0; i < fields.length; i += 1) { + var field = fields[i]; + this[field.name] = field.value; + } + + this.tableName = tableName; + this.fields = fields; + if (options) { + var optionKeys = Object.keys(options); + for (var i$1 = 0; i$1 < optionKeys.length; i$1 += 1) { + var k = optionKeys[i$1]; + var v = options[k]; + if (this[k] !== undefined) { + this[k] = v; + } + } + } + } + + /** + * Encodes the table and returns an array of bytes + * @return {Array} + */ + Table.prototype.encode = function() { + return encode.TABLE(this); + }; + + /** + * Get the size of the table. + * @return {number} + */ + Table.prototype.sizeOf = function() { + return sizeOf.TABLE(this); + }; + + /** + * @private + */ + function ushortList(itemName, list, count) { + if (count === undefined) { + count = list.length; + } + var fields = new Array(list.length + 1); + fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; + for (var i = 0; i < list.length; i++) { + fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]}; + } + return fields; + } + + /** + * @private + */ + function tableList(itemName, records, itemCallback) { + var count = records.length; + var fields = new Array(count + 1); + fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; + for (var i = 0; i < count; i++) { + fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)}; + } + return fields; + } + + /** + * @private + */ + function recordList(itemName, records, itemCallback) { + var count = records.length; + var fields = []; + fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; + for (var i = 0; i < count; i++) { + fields = fields.concat(itemCallback(records[i], i)); + } + return fields; + } + + // Common Layout Tables + + /** + * @exports opentype.Coverage + * @class + * @param {opentype.Table} + * @constructor + * @extends opentype.Table + */ + function Coverage(coverageTable) { + if (coverageTable.format === 1) { + Table.call(this, 'coverageTable', + [{name: 'coverageFormat', type: 'USHORT', value: 1}] + .concat(ushortList('glyph', coverageTable.glyphs)) + ); + } else { + check.assert(false, 'Can\'t create coverage table format 2 yet.'); + } + } + Coverage.prototype = Object.create(Table.prototype); + Coverage.prototype.constructor = Coverage; + + function ScriptList(scriptListTable) { + Table.call(this, 'scriptListTable', + recordList('scriptRecord', scriptListTable, function(scriptRecord, i) { + var script = scriptRecord.script; + var defaultLangSys = script.defaultLangSys; + check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.'); + return [ + {name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag}, + {name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [ + {name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [ + {name: 'lookupOrder', type: 'USHORT', value: 0}, + {name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}] + .concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))} + ].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) { + var langSys = langSysRecord.langSys; + return [ + {name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag}, + {name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [ + {name: 'lookupOrder', type: 'USHORT', value: 0}, + {name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex} + ].concat(ushortList('featureIndex', langSys.featureIndexes)))} + ]; + })))} + ]; + }) + ); + } + ScriptList.prototype = Object.create(Table.prototype); + ScriptList.prototype.constructor = ScriptList; + + /** + * @exports opentype.FeatureList + * @class + * @param {opentype.Table} + * @constructor + * @extends opentype.Table + */ + function FeatureList(featureListTable) { + Table.call(this, 'featureListTable', + recordList('featureRecord', featureListTable, function(featureRecord, i) { + var feature = featureRecord.feature; + return [ + {name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag}, + {name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [ + {name: 'featureParams', type: 'USHORT', value: feature.featureParams} ].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))} + ]; + }) + ); + } + FeatureList.prototype = Object.create(Table.prototype); + FeatureList.prototype.constructor = FeatureList; + + /** + * @exports opentype.LookupList + * @class + * @param {opentype.Table} + * @param {Object} + * @constructor + * @extends opentype.Table + */ + function LookupList(lookupListTable, subtableMakers) { + Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) { + var subtableCallback = subtableMakers[lookupTable.lookupType]; + check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.'); + return new Table('lookupTable', [ + {name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType}, + {name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag} + ].concat(tableList('subtable', lookupTable.subtables, subtableCallback))); + })); + } + LookupList.prototype = Object.create(Table.prototype); + LookupList.prototype.constructor = LookupList; + + // Record = same as Table, but inlined (a Table has an offset and its data is further in the stream) + // Don't use offsets inside Records (probable bug), only in Tables. + var table = { + Table: Table, + Record: Table, + Coverage: Coverage, + ScriptList: ScriptList, + FeatureList: FeatureList, + LookupList: LookupList, + ushortList: ushortList, + tableList: tableList, + recordList: recordList, + }; + + // Parsing utility functions + + // Retrieve an unsigned byte from the DataView. + function getByte(dataView, offset) { + return dataView.getUint8(offset); + } + + // Retrieve an unsigned 16-bit short from the DataView. + // The value is stored in big endian. + function getUShort(dataView, offset) { + return dataView.getUint16(offset, false); + } + + // Retrieve a signed 16-bit short from the DataView. + // The value is stored in big endian. + function getShort(dataView, offset) { + return dataView.getInt16(offset, false); + } + + // Retrieve an unsigned 32-bit long from the DataView. + // The value is stored in big endian. + function getULong(dataView, offset) { + return dataView.getUint32(offset, false); + } + + // Retrieve a 32-bit signed fixed-point number (16.16) from the DataView. + // The value is stored in big endian. + function getFixed(dataView, offset) { + var decimal = dataView.getInt16(offset, false); + var fraction = dataView.getUint16(offset + 2, false); + return decimal + fraction / 65535; + } + + // Retrieve a 4-character tag from the DataView. + // Tags are used to identify tables. + function getTag(dataView, offset) { + var tag = ''; + for (var i = offset; i < offset + 4; i += 1) { + tag += String.fromCharCode(dataView.getInt8(i)); + } + + return tag; + } + + // Retrieve an offset from the DataView. + // Offsets are 1 to 4 bytes in length, depending on the offSize argument. + function getOffset(dataView, offset, offSize) { + var v = 0; + for (var i = 0; i < offSize; i += 1) { + v <<= 8; + v += dataView.getUint8(offset + i); + } + + return v; + } + + // Retrieve a number of bytes from start offset to the end offset from the DataView. + function getBytes(dataView, startOffset, endOffset) { + var bytes = []; + for (var i = startOffset; i < endOffset; i += 1) { + bytes.push(dataView.getUint8(i)); + } + + return bytes; + } + + // Convert the list of bytes to a string. + function bytesToString(bytes) { + var s = ''; + for (var i = 0; i < bytes.length; i += 1) { + s += String.fromCharCode(bytes[i]); + } + + return s; + } + + var typeOffsets = { + byte: 1, + uShort: 2, + short: 2, + uLong: 4, + fixed: 4, + longDateTime: 8, + tag: 4 + }; + + // A stateful parser that changes the offset whenever a value is retrieved. + // The data is a DataView. + function Parser(data, offset) { + this.data = data; + this.offset = offset; + this.relativeOffset = 0; + } + + Parser.prototype.parseByte = function() { + var v = this.data.getUint8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; + }; + + Parser.prototype.parseChar = function() { + var v = this.data.getInt8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; + }; + + Parser.prototype.parseCard8 = Parser.prototype.parseByte; + + Parser.prototype.parseUShort = function() { + var v = this.data.getUint16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; + }; + + Parser.prototype.parseCard16 = Parser.prototype.parseUShort; + Parser.prototype.parseSID = Parser.prototype.parseUShort; + Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; + + Parser.prototype.parseShort = function() { + var v = this.data.getInt16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; + }; + + Parser.prototype.parseF2Dot14 = function() { + var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; + this.relativeOffset += 2; + return v; + }; + + Parser.prototype.parseULong = function() { + var v = getULong(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; + }; + + Parser.prototype.parseOffset32 = Parser.prototype.parseULong; + + Parser.prototype.parseFixed = function() { + var v = getFixed(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; + }; + + Parser.prototype.parseString = function(length) { + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + var string = ''; + this.relativeOffset += length; + for (var i = 0; i < length; i++) { + string += String.fromCharCode(dataView.getUint8(offset + i)); + } + + return string; + }; + + Parser.prototype.parseTag = function() { + return this.parseString(4); + }; + + // LONGDATETIME is a 64-bit integer. + // JavaScript and unix timestamps traditionally use 32 bits, so we + // only take the last 32 bits. + // + Since until 2038 those bits will be filled by zeros we can ignore them. + Parser.prototype.parseLongDateTime = function() { + var v = getULong(this.data, this.offset + this.relativeOffset + 4); + // Subtract seconds between 01/01/1904 and 01/01/1970 + // to convert Apple Mac timestamp to Standard Unix timestamp + v -= 2082844800; + this.relativeOffset += 8; + return v; + }; + + Parser.prototype.parseVersion = function(minorBase) { + var major = getUShort(this.data, this.offset + this.relativeOffset); + + // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1 + // Default returns the correct number if minor = 0xN000 where N is 0-9 + // Set minorBase to 1 for tables that use minor = N where N is 0-9 + var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); + this.relativeOffset += 4; + if (minorBase === undefined) { minorBase = 0x1000; } + return major + minor / minorBase / 10; + }; + + Parser.prototype.skip = function(type, amount) { + if (amount === undefined) { + amount = 1; + } + + this.relativeOffset += typeOffsets[type] * amount; + }; + + ///// Parsing lists and records /////////////////////////////// + + // Parse a list of 32 bit unsigned integers. + Parser.prototype.parseULongList = function(count) { + if (count === undefined) { count = this.parseULong(); } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0; i < count; i++) { + offsets[i] = dataView.getUint32(offset); + offset += 4; + } + + this.relativeOffset += count * 4; + return offsets; + }; + + // Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream + // or provided as an argument. + Parser.prototype.parseOffset16List = + Parser.prototype.parseUShortList = function(count) { + if (count === undefined) { count = this.parseUShort(); } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0; i < count; i++) { + offsets[i] = dataView.getUint16(offset); + offset += 2; + } + + this.relativeOffset += count * 2; + return offsets; + }; + + // Parses a list of 16 bit signed integers. + Parser.prototype.parseShortList = function(count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0; i < count; i++) { + list[i] = dataView.getInt16(offset); + offset += 2; + } + + this.relativeOffset += count * 2; + return list; + }; + + // Parses a list of bytes. + Parser.prototype.parseByteList = function(count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0; i < count; i++) { + list[i] = dataView.getUint8(offset++); + } + + this.relativeOffset += count; + return list; + }; + + /** + * Parse a list of items. + * Record count is optional, if omitted it is read from the stream. + * itemCallback is one of the Parser methods. + */ + Parser.prototype.parseList = function(count, itemCallback) { + if (!itemCallback) { + itemCallback = count; + count = this.parseUShort(); + } + var list = new Array(count); + for (var i = 0; i < count; i++) { + list[i] = itemCallback.call(this); + } + return list; + }; + + Parser.prototype.parseList32 = function(count, itemCallback) { + if (!itemCallback) { + itemCallback = count; + count = this.parseULong(); + } + var list = new Array(count); + for (var i = 0; i < count; i++) { + list[i] = itemCallback.call(this); + } + return list; + }; + + /** + * Parse a list of records. + * Record count is optional, if omitted it is read from the stream. + * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } + */ + Parser.prototype.parseRecordList = function(count, recordDescription) { + // If the count argument is absent, read it in the stream. + if (!recordDescription) { + recordDescription = count; + count = this.parseUShort(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0; i < count; i++) { + var rec = {}; + for (var j = 0; j < fields.length; j++) { + var fieldName = fields[j]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this); + } + records[i] = rec; + } + return records; + }; + + Parser.prototype.parseRecordList32 = function(count, recordDescription) { + // If the count argument is absent, read it in the stream. + if (!recordDescription) { + recordDescription = count; + count = this.parseULong(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0; i < count; i++) { + var rec = {}; + for (var j = 0; j < fields.length; j++) { + var fieldName = fields[j]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this); + } + records[i] = rec; + } + return records; + }; + + // Parse a data structure into an object + // Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } + Parser.prototype.parseStruct = function(description) { + if (typeof description === 'function') { + return description.call(this); + } else { + var fields = Object.keys(description); + var struct = {}; + for (var j = 0; j < fields.length; j++) { + var fieldName = fields[j]; + var fieldType = description[fieldName]; + struct[fieldName] = fieldType.call(this); + } + return struct; + } + }; + + /** + * Parse a GPOS valueRecord + * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record + * valueFormat is optional, if omitted it is read from the stream. + */ + Parser.prototype.parseValueRecord = function(valueFormat) { + if (valueFormat === undefined) { + valueFormat = this.parseUShort(); + } + if (valueFormat === 0) { + // valueFormat2 in kerning pairs is most often 0 + // in this case return undefined instead of an empty object, to save space + return; + } + var valueRecord = {}; + + if (valueFormat & 0x0001) { valueRecord.xPlacement = this.parseShort(); } + if (valueFormat & 0x0002) { valueRecord.yPlacement = this.parseShort(); } + if (valueFormat & 0x0004) { valueRecord.xAdvance = this.parseShort(); } + if (valueFormat & 0x0008) { valueRecord.yAdvance = this.parseShort(); } + + // Device table (non-variable font) / VariationIndex table (variable font) not supported + // https://docs.microsoft.com/fr-fr/typography/opentype/spec/chapter2#devVarIdxTbls + if (valueFormat & 0x0010) { valueRecord.xPlaDevice = undefined; this.parseShort(); } + if (valueFormat & 0x0020) { valueRecord.yPlaDevice = undefined; this.parseShort(); } + if (valueFormat & 0x0040) { valueRecord.xAdvDevice = undefined; this.parseShort(); } + if (valueFormat & 0x0080) { valueRecord.yAdvDevice = undefined; this.parseShort(); } + + return valueRecord; + }; + + /** + * Parse a list of GPOS valueRecords + * https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#value-record + * valueFormat and valueCount are read from the stream. + */ + Parser.prototype.parseValueRecordList = function() { + var valueFormat = this.parseUShort(); + var valueCount = this.parseUShort(); + var values = new Array(valueCount); + for (var i = 0; i < valueCount; i++) { + values[i] = this.parseValueRecord(valueFormat); + } + return values; + }; + + Parser.prototype.parsePointer = function(description) { + var structOffset = this.parseOffset16(); + if (structOffset > 0) { + // NULL offset => return undefined + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return undefined; + }; + + Parser.prototype.parsePointer32 = function(description) { + var structOffset = this.parseOffset32(); + if (structOffset > 0) { + // NULL offset => return undefined + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return undefined; + }; + + /** + * Parse a list of offsets to lists of 16-bit integers, + * or a list of offsets to lists of offsets to any kind of items. + * If itemCallback is not provided, a list of list of UShort is assumed. + * If provided, itemCallback is called on each item and must parse the item. + * See examples in tables/gsub.js + */ + Parser.prototype.parseListOfLists = function(itemCallback) { + var offsets = this.parseOffset16List(); + var count = offsets.length; + var relativeOffset = this.relativeOffset; + var list = new Array(count); + for (var i = 0; i < count; i++) { + var start = offsets[i]; + if (start === 0) { + // NULL offset + // Add i as owned property to list. Convenient with assert. + list[i] = undefined; + continue; + } + this.relativeOffset = start; + if (itemCallback) { + var subOffsets = this.parseOffset16List(); + var subList = new Array(subOffsets.length); + for (var j = 0; j < subOffsets.length; j++) { + this.relativeOffset = start + subOffsets[j]; + subList[j] = itemCallback.call(this); + } + list[i] = subList; + } else { + list[i] = this.parseUShortList(); + } + } + this.relativeOffset = relativeOffset; + return list; + }; + + ///// Complex tables parsing ////////////////////////////////// + + // Parse a coverage table in a GSUB, GPOS or GDEF table. + // https://www.microsoft.com/typography/OTSPEC/chapter2.htm + // parser.offset must point to the start of the table containing the coverage. + Parser.prototype.parseCoverage = function() { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + var count = this.parseUShort(); + if (format === 1) { + return { + format: 1, + glyphs: this.parseUShortList(count) + }; + } else if (format === 2) { + var ranges = new Array(count); + for (var i = 0; i < count; i++) { + ranges[i] = { + start: this.parseUShort(), + end: this.parseUShort(), + index: this.parseUShort() + }; + } + return { + format: 2, + ranges: ranges + }; + } + throw new Error('0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.'); + }; + + // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. + // https://www.microsoft.com/typography/OTSPEC/chapter2.htm + Parser.prototype.parseClassDef = function() { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + if (format === 1) { + return { + format: 1, + startGlyph: this.parseUShort(), + classes: this.parseUShortList() + }; + } else if (format === 2) { + return { + format: 2, + ranges: this.parseRecordList({ + start: Parser.uShort, + end: Parser.uShort, + classId: Parser.uShort + }) + }; + } + throw new Error('0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'); + }; + + ///// Static methods /////////////////////////////////// + // These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance. + + Parser.list = function(count, itemCallback) { + return function() { + return this.parseList(count, itemCallback); + }; + }; + + Parser.list32 = function(count, itemCallback) { + return function() { + return this.parseList32(count, itemCallback); + }; + }; + + Parser.recordList = function(count, recordDescription) { + return function() { + return this.parseRecordList(count, recordDescription); + }; + }; + + Parser.recordList32 = function(count, recordDescription) { + return function() { + return this.parseRecordList32(count, recordDescription); + }; + }; + + Parser.pointer = function(description) { + return function() { + return this.parsePointer(description); + }; + }; + + Parser.pointer32 = function(description) { + return function() { + return this.parsePointer32(description); + }; + }; + + Parser.tag = Parser.prototype.parseTag; + Parser.byte = Parser.prototype.parseByte; + Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; + Parser.uShortList = Parser.prototype.parseUShortList; + Parser.uLong = Parser.offset32 = Parser.prototype.parseULong; + Parser.uLongList = Parser.prototype.parseULongList; + Parser.struct = Parser.prototype.parseStruct; + Parser.coverage = Parser.prototype.parseCoverage; + Parser.classDef = Parser.prototype.parseClassDef; + + ///// Script, Feature, Lookup lists /////////////////////////////////////////////// + // https://www.microsoft.com/typography/OTSPEC/chapter2.htm + + var langSysTable = { + reserved: Parser.uShort, + reqFeatureIndex: Parser.uShort, + featureIndexes: Parser.uShortList + }; + + Parser.prototype.parseScriptList = function() { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + script: Parser.pointer({ + defaultLangSys: Parser.pointer(langSysTable), + langSysRecords: Parser.recordList({ + tag: Parser.tag, + langSys: Parser.pointer(langSysTable) + }) + }) + })) || []; + }; + + Parser.prototype.parseFeatureList = function() { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + feature: Parser.pointer({ + featureParams: Parser.offset16, + lookupListIndexes: Parser.uShortList + }) + })) || []; + }; + + Parser.prototype.parseLookupList = function(lookupTableParsers) { + return this.parsePointer(Parser.list(Parser.pointer(function() { + var lookupType = this.parseUShort(); + check.argument(1 <= lookupType && lookupType <= 9, 'GPOS/GSUB lookup type ' + lookupType + ' unknown.'); + var lookupFlag = this.parseUShort(); + var useMarkFilteringSet = lookupFlag & 0x10; + return { + lookupType: lookupType, + lookupFlag: lookupFlag, + subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), + markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined + }; + }))) || []; + }; + + Parser.prototype.parseFeatureVariationsList = function() { + return this.parsePointer32(function() { + var majorVersion = this.parseUShort(); + var minorVersion = this.parseUShort(); + check.argument(majorVersion === 1 && minorVersion < 1, 'GPOS/GSUB feature variations table unknown.'); + var featureVariations = this.parseRecordList32({ + conditionSetOffset: Parser.offset32, + featureTableSubstitutionOffset: Parser.offset32 + }); + return featureVariations; + }) || []; + }; + + var parse = { + getByte: getByte, + getCard8: getByte, + getUShort: getUShort, + getCard16: getUShort, + getShort: getShort, + getULong: getULong, + getFixed: getFixed, + getTag: getTag, + getOffset: getOffset, + getBytes: getBytes, + bytesToString: bytesToString, + Parser: Parser, + }; + + // The `cmap` table stores the mappings from characters to glyphs. + + function parseCmapTableFormat12(cmap, p) { + //Skip reserved. + p.parseUShort(); + + // Length in bytes of the sub-tables. + cmap.length = p.parseULong(); + cmap.language = p.parseULong(); + + var groupCount; + cmap.groupCount = groupCount = p.parseULong(); + cmap.glyphIndexMap = {}; + + for (var i = 0; i < groupCount; i += 1) { + var startCharCode = p.parseULong(); + var endCharCode = p.parseULong(); + var startGlyphId = p.parseULong(); + + for (var c = startCharCode; c <= endCharCode; c += 1) { + cmap.glyphIndexMap[c] = startGlyphId; + startGlyphId++; + } + } + } + + function parseCmapTableFormat4(cmap, p, data, start, offset) { + // Length in bytes of the sub-tables. + cmap.length = p.parseUShort(); + cmap.language = p.parseUShort(); + + // segCount is stored x 2. + var segCount; + cmap.segCount = segCount = p.parseUShort() >> 1; + + // Skip searchRange, entrySelector, rangeShift. + p.skip('uShort', 3); + + // The "unrolled" mapping from character codes to glyph indices. + cmap.glyphIndexMap = {}; + var endCountParser = new parse.Parser(data, start + offset + 14); + var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2); + var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4); + var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6); + var glyphIndexOffset = start + offset + 16 + segCount * 8; + for (var i = 0; i < segCount - 1; i += 1) { + var glyphIndex = (void 0); + var endCount = endCountParser.parseUShort(); + var startCount = startCountParser.parseUShort(); + var idDelta = idDeltaParser.parseShort(); + var idRangeOffset = idRangeOffsetParser.parseUShort(); + for (var c = startCount; c <= endCount; c += 1) { + if (idRangeOffset !== 0) { + // The idRangeOffset is relative to the current position in the idRangeOffset array. + // Take the current offset in the idRangeOffset array. + glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2); + + // Add the value of the idRangeOffset, which will move us into the glyphIndex array. + glyphIndexOffset += idRangeOffset; + + // Then add the character index of the current segment, multiplied by 2 for USHORTs. + glyphIndexOffset += (c - startCount) * 2; + glyphIndex = parse.getUShort(data, glyphIndexOffset); + if (glyphIndex !== 0) { + glyphIndex = (glyphIndex + idDelta) & 0xFFFF; + } + } else { + glyphIndex = (c + idDelta) & 0xFFFF; + } + + cmap.glyphIndexMap[c] = glyphIndex; + } + } + } + + // Parse the `cmap` table. This table stores the mappings from characters to glyphs. + // There are many available formats, but we only support the Windows format 4 and 12. + // This function returns a `CmapEncoding` object or null if no supported format could be found. + function parseCmapTable(data, start) { + var cmap = {}; + cmap.version = parse.getUShort(data, start); + check.argument(cmap.version === 0, 'cmap table version should be 0.'); + + // The cmap table can contain many sub-tables, each with their own format. + // We're only interested in a "platform 0" (Unicode format) and "platform 3" (Windows format) table. + cmap.numTables = parse.getUShort(data, start + 2); + var offset = -1; + for (var i = cmap.numTables - 1; i >= 0; i -= 1) { + var platformId = parse.getUShort(data, start + 4 + (i * 8)); + var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2); + if ((platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) || + (platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4))) { + offset = parse.getULong(data, start + 4 + (i * 8) + 4); + break; + } + } + + if (offset === -1) { + // There is no cmap table in the font that we support. + throw new Error('No valid cmap sub-tables found.'); + } + + var p = new parse.Parser(data, start + offset); + cmap.format = p.parseUShort(); + + if (cmap.format === 12) { + parseCmapTableFormat12(cmap, p); + } else if (cmap.format === 4) { + parseCmapTableFormat4(cmap, p, data, start, offset); + } else { + throw new Error('Only format 4 and 12 cmap tables are supported (found format ' + cmap.format + ').'); + } + + return cmap; + } + + function addSegment(t, code, glyphIndex) { + t.segments.push({ + end: code, + start: code, + delta: -(code - glyphIndex), + offset: 0, + glyphIndex: glyphIndex + }); + } + + function addTerminatorSegment(t) { + t.segments.push({ + end: 0xFFFF, + start: 0xFFFF, + delta: 1, + offset: 0 + }); + } + + // Make cmap table, format 4 by default, 12 if needed only + function makeCmapTable(glyphs) { + // Plan 0 is the base Unicode Plan but emojis, for example are on another plan, and needs cmap 12 format (with 32bit) + var isPlan0Only = true; + var i; + + // Check if we need to add cmap format 12 or if format 4 only is fine + for (i = glyphs.length - 1; i > 0; i -= 1) { + var g = glyphs.get(i); + if (g.unicode > 65535) { + console.log('Adding CMAP format 12 (needed!)'); + isPlan0Only = false; + break; + } + } + + var cmapTable = [ + {name: 'version', type: 'USHORT', value: 0}, + {name: 'numTables', type: 'USHORT', value: isPlan0Only ? 1 : 2}, + + // CMAP 4 header + {name: 'platformID', type: 'USHORT', value: 3}, + {name: 'encodingID', type: 'USHORT', value: 1}, + {name: 'offset', type: 'ULONG', value: isPlan0Only ? 12 : (12 + 8)} + ]; + + if (!isPlan0Only) + { cmapTable = cmapTable.concat([ + // CMAP 12 header + {name: 'cmap12PlatformID', type: 'USHORT', value: 3}, // We encode only for PlatformID = 3 (Windows) because it is supported everywhere + {name: 'cmap12EncodingID', type: 'USHORT', value: 10}, + {name: 'cmap12Offset', type: 'ULONG', value: 0} + ]); } + + cmapTable = cmapTable.concat([ + // CMAP 4 Subtable + {name: 'format', type: 'USHORT', value: 4}, + {name: 'cmap4Length', type: 'USHORT', value: 0}, + {name: 'language', type: 'USHORT', value: 0}, + {name: 'segCountX2', type: 'USHORT', value: 0}, + {name: 'searchRange', type: 'USHORT', value: 0}, + {name: 'entrySelector', type: 'USHORT', value: 0}, + {name: 'rangeShift', type: 'USHORT', value: 0} + ]); + + var t = new table.Table('cmap', cmapTable); + + t.segments = []; + for (i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j = 0; j < glyph.unicodes.length; j += 1) { + addSegment(t, glyph.unicodes[j], i); + } + + t.segments = t.segments.sort(function (a, b) { + return a.start - b.start; + }); + } + + addTerminatorSegment(t); + + var segCount = t.segments.length; + var segCountToRemove = 0; + + // CMAP 4 + // Set up parallel segment arrays. + var endCounts = []; + var startCounts = []; + var idDeltas = []; + var idRangeOffsets = []; + var glyphIds = []; + + // CMAP 12 + var cmap12Groups = []; + + // Reminder this loop is not following the specification at 100% + // The specification -> find suites of characters and make a group + // Here we're doing one group for each letter + // Doing as the spec can save 8 times (or more) space + for (i = 0; i < segCount; i += 1) { + var segment = t.segments[i]; + + // CMAP 4 + if (segment.end <= 65535 && segment.start <= 65535) { + endCounts = endCounts.concat({name: 'end_' + i, type: 'USHORT', value: segment.end}); + startCounts = startCounts.concat({name: 'start_' + i, type: 'USHORT', value: segment.start}); + idDeltas = idDeltas.concat({name: 'idDelta_' + i, type: 'SHORT', value: segment.delta}); + idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i, type: 'USHORT', value: segment.offset}); + if (segment.glyphId !== undefined) { + glyphIds = glyphIds.concat({name: 'glyph_' + i, type: 'USHORT', value: segment.glyphId}); + } + } else { + // Skip Unicode > 65535 (16bit unsigned max) for CMAP 4, will be added in CMAP 12 + segCountToRemove += 1; + } + + // CMAP 12 + // Skip Terminator Segment + if (!isPlan0Only && segment.glyphIndex !== undefined) { + cmap12Groups = cmap12Groups.concat({name: 'cmap12Start_' + i, type: 'ULONG', value: segment.start}); + cmap12Groups = cmap12Groups.concat({name: 'cmap12End_' + i, type: 'ULONG', value: segment.end}); + cmap12Groups = cmap12Groups.concat({name: 'cmap12Glyph_' + i, type: 'ULONG', value: segment.glyphIndex}); + } + } + + // CMAP 4 Subtable + t.segCountX2 = (segCount - segCountToRemove) * 2; + t.searchRange = Math.pow(2, Math.floor(Math.log((segCount - segCountToRemove)) / Math.log(2))) * 2; + t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2); + t.rangeShift = t.segCountX2 - t.searchRange; + + t.fields = t.fields.concat(endCounts); + t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0}); + t.fields = t.fields.concat(startCounts); + t.fields = t.fields.concat(idDeltas); + t.fields = t.fields.concat(idRangeOffsets); + t.fields = t.fields.concat(glyphIds); + + t.cmap4Length = 14 + // Subtable header + endCounts.length * 2 + + 2 + // reservedPad + startCounts.length * 2 + + idDeltas.length * 2 + + idRangeOffsets.length * 2 + + glyphIds.length * 2; + + if (!isPlan0Only) { + // CMAP 12 Subtable + var cmap12Length = 16 + // Subtable header + cmap12Groups.length * 4; + + t.cmap12Offset = 12 + (2 * 2) + 4 + t.cmap4Length; + t.fields = t.fields.concat([ + {name: 'cmap12Format', type: 'USHORT', value: 12}, + {name: 'cmap12Reserved', type: 'USHORT', value: 0}, + {name: 'cmap12Length', type: 'ULONG', value: cmap12Length}, + {name: 'cmap12Language', type: 'ULONG', value: 0}, + {name: 'cmap12nGroups', type: 'ULONG', value: cmap12Groups.length / 3} + ]); + + t.fields = t.fields.concat(cmap12Groups); + } + + return t; + } + + var cmap = { parse: parseCmapTable, make: makeCmapTable }; + + // Glyph encoding + + var cffStandardStrings = [ + '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', + 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', + 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', + 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', + 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', + 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', + 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', + 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', + 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', + 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', + 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', + 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', + 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', + 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', + 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', + 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', + 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', + 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', + 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', + 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', + 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', + 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader', + 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', + 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', + 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', + 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', + 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', + 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', + 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', + 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', + 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', + 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', + 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', + 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', + 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', + 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', + 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', + 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', + 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', + 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', + 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', + '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold']; + + var cffStandardEncoding = [ + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', + 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', + 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', + 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', + 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', + 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', + 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', + 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', + 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', + 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde', + 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron', + 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '', + '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '', + 'lslash', 'oslash', 'oe', 'germandbls']; + + var cffExpertEncoding = [ + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', + 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', + 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', + 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', + 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', + 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', + 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', + 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', + 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', + 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', + 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', + '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', + 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', + 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', + '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', + 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', + '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', + 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', + 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', + 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', + 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', + 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', + 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', + 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', + 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall']; + + var standardNames = [ + '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', + 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', + 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', + 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', + 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', + 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', + 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', + 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', + 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', + 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', + 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', + 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', + 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', + 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', + 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', + 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', + 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', + 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', + 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', + 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', + 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', + 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', + 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat']; + + /** + * This is the encoding used for fonts created from scratch. + * It loops through all glyphs and finds the appropriate unicode value. + * Since it's linear time, other encodings will be faster. + * @exports opentype.DefaultEncoding + * @class + * @constructor + * @param {opentype.Font} + */ + function DefaultEncoding(font) { + this.font = font; + } + + DefaultEncoding.prototype.charToGlyphIndex = function(c) { + var code = c.codePointAt(0); + var glyphs = this.font.glyphs; + if (glyphs) { + for (var i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j = 0; j < glyph.unicodes.length; j += 1) { + if (glyph.unicodes[j] === code) { + return i; + } + } + } + } + return null; + }; + + /** + * @exports opentype.CmapEncoding + * @class + * @constructor + * @param {Object} cmap - a object with the cmap encoded data + */ + function CmapEncoding(cmap) { + this.cmap = cmap; + } + + /** + * @param {string} c - the character + * @return {number} The glyph index. + */ + CmapEncoding.prototype.charToGlyphIndex = function(c) { + return this.cmap.glyphIndexMap[c.codePointAt(0)] || 0; + }; + + /** + * @exports opentype.CffEncoding + * @class + * @constructor + * @param {string} encoding - The encoding + * @param {Array} charset - The character set. + */ + function CffEncoding(encoding, charset) { + this.encoding = encoding; + this.charset = charset; + } + + /** + * @param {string} s - The character + * @return {number} The index. + */ + CffEncoding.prototype.charToGlyphIndex = function(s) { + var code = s.codePointAt(0); + var charName = this.encoding[code]; + return this.charset.indexOf(charName); + }; + + /** + * @exports opentype.GlyphNames + * @class + * @constructor + * @param {Object} post + */ + function GlyphNames(post) { + switch (post.version) { + case 1: + this.names = standardNames.slice(); + break; + case 2: + this.names = new Array(post.numberOfGlyphs); + for (var i = 0; i < post.numberOfGlyphs; i++) { + if (post.glyphNameIndex[i] < standardNames.length) { + this.names[i] = standardNames[post.glyphNameIndex[i]]; + } else { + this.names[i] = post.names[post.glyphNameIndex[i] - standardNames.length]; + } + } + + break; + case 2.5: + this.names = new Array(post.numberOfGlyphs); + for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) { + this.names[i$1] = standardNames[i$1 + post.glyphNameIndex[i$1]]; + } + + break; + case 3: + this.names = []; + break; + default: + this.names = []; + break; + } + } + + /** + * Gets the index of a glyph by name. + * @param {string} name - The glyph name + * @return {number} The index + */ + GlyphNames.prototype.nameToGlyphIndex = function(name) { + return this.names.indexOf(name); + }; + + /** + * @param {number} gid + * @return {string} + */ + GlyphNames.prototype.glyphIndexToName = function(gid) { + return this.names[gid]; + }; + + function addGlyphNamesAll(font) { + var glyph; + var glyphIndexMap = font.tables.cmap.glyphIndexMap; + var charCodes = Object.keys(glyphIndexMap); + + for (var i = 0; i < charCodes.length; i += 1) { + var c = charCodes[i]; + var glyphIndex = glyphIndexMap[c]; + glyph = font.glyphs.get(glyphIndex); + glyph.addUnicode(parseInt(c)); + } + + for (var i$1 = 0; i$1 < font.glyphs.length; i$1 += 1) { + glyph = font.glyphs.get(i$1); + if (font.cffEncoding) { + if (font.isCIDFont) { + glyph.name = 'gid' + i$1; + } else { + glyph.name = font.cffEncoding.charset[i$1]; + } + } else if (font.glyphNames.names) { + glyph.name = font.glyphNames.glyphIndexToName(i$1); + } + } + } + + function addGlyphNamesToUnicodeMap(font) { + font._IndexToUnicodeMap = {}; + + var glyphIndexMap = font.tables.cmap.glyphIndexMap; + var charCodes = Object.keys(glyphIndexMap); + + for (var i = 0; i < charCodes.length; i += 1) { + var c = charCodes[i]; + var glyphIndex = glyphIndexMap[c]; + if (font._IndexToUnicodeMap[glyphIndex] === undefined) { + font._IndexToUnicodeMap[glyphIndex] = { + unicodes: [parseInt(c)] + }; + } else { + font._IndexToUnicodeMap[glyphIndex].unicodes.push(parseInt(c)); + } + } + } + + /** + * @alias opentype.addGlyphNames + * @param {opentype.Font} + * @param {Object} + */ + function addGlyphNames(font, opt) { + if (opt.lowMemory) { + addGlyphNamesToUnicodeMap(font); + } else { + addGlyphNamesAll(font); + } + } + + // Drawing utility functions. + + // Draw a line on the given context from point `x1,y1` to point `x2,y2`. + function line(ctx, x1, y1, x2, y2) { + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); + } + + var draw = { line: line }; + + // The Glyph object + // import glyf from './tables/glyf' Can't be imported here, because it's a circular dependency + + function getPathDefinition(glyph, path) { + var _path = path || new Path(); + return { + configurable: true, + + get: function() { + if (typeof _path === 'function') { + _path = _path(); + } + + return _path; + }, + + set: function(p) { + _path = p; + } + }; + } + /** + * @typedef GlyphOptions + * @type Object + * @property {string} [name] - The glyph name + * @property {number} [unicode] + * @property {Array} [unicodes] + * @property {number} [xMin] + * @property {number} [yMin] + * @property {number} [xMax] + * @property {number} [yMax] + * @property {number} [advanceWidth] + */ + + // A Glyph is an individual mark that often corresponds to a character. + // Some glyphs, such as ligatures, are a combination of many characters. + // Glyphs are the basic building blocks of a font. + // + // The `Glyph` class contains utility methods for drawing the path and its points. + /** + * @exports opentype.Glyph + * @class + * @param {GlyphOptions} + * @constructor + */ + function Glyph(options) { + // By putting all the code on a prototype function (which is only declared once) + // we reduce the memory requirements for larger fonts by some 2% + this.bindConstructorValues(options); + } + + /** + * @param {GlyphOptions} + */ + Glyph.prototype.bindConstructorValues = function(options) { + this.index = options.index || 0; + + // These three values cannot be deferred for memory optimization: + this.name = options.name || null; + this.unicode = options.unicode || undefined; + this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; + + // But by binding these values only when necessary, we reduce can + // the memory requirements by almost 3% for larger fonts. + if ('xMin' in options) { + this.xMin = options.xMin; + } + + if ('yMin' in options) { + this.yMin = options.yMin; + } + + if ('xMax' in options) { + this.xMax = options.xMax; + } + + if ('yMax' in options) { + this.yMax = options.yMax; + } + + if ('advanceWidth' in options) { + this.advanceWidth = options.advanceWidth; + } + + // The path for a glyph is the most memory intensive, and is bound as a value + // with a getter/setter to ensure we actually do path parsing only once the + // path is actually needed by anything. + Object.defineProperty(this, 'path', getPathDefinition(this, options.path)); + }; + + /** + * @param {number} + */ + Glyph.prototype.addUnicode = function(unicode) { + if (this.unicodes.length === 0) { + this.unicode = unicode; + } + + this.unicodes.push(unicode); + }; + + /** + * Calculate the minimum bounding box for this glyph. + * @return {opentype.BoundingBox} + */ + Glyph.prototype.getBoundingBox = function() { + return this.path.getBoundingBox(); + }; + + /** + * Convert the glyph to a Path we can draw on a drawing context. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {Object=} options - xScale, yScale to stretch the glyph. + * @param {opentype.Font} if hinting is to be used, the font + * @return {opentype.Path} + */ + Glyph.prototype.getPath = function(x, y, fontSize, options, font) { + x = x !== undefined ? x : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + var commands; + var hPoints; + if (!options) { options = { }; } + var xScale = options.xScale; + var yScale = options.yScale; + + if (options.hinting && font && font.hinting) { + // in case of hinting, the hinting engine takes care + // of scaling the points (not the path) before hinting. + hPoints = this.path && font.hinting.exec(this, fontSize); + // in case the hinting engine failed hPoints is undefined + // and thus reverts to plain rending + } + + if (hPoints) { + // Call font.hinting.getCommands instead of `glyf.getPath(hPoints).commands` to avoid a circular dependency + commands = font.hinting.getCommands(hPoints); + x = Math.round(x); + y = Math.round(y); + // TODO in case of hinting xyScaling is not yet supported + xScale = yScale = 1; + } else { + commands = this.path.commands; + var scale = 1 / (this.path.unitsPerEm || 1000) * fontSize; + if (xScale === undefined) { xScale = scale; } + if (yScale === undefined) { yScale = scale; } + } + + var p = new Path(); + for (var i = 0; i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type === 'M') { + p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); + } else if (cmd.type === 'L') { + p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); + } else if (cmd.type === 'Q') { + p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), + x + (cmd.x * xScale), y + (-cmd.y * yScale)); + } else if (cmd.type === 'C') { + p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), + x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale), + x + (cmd.x * xScale), y + (-cmd.y * yScale)); + } else if (cmd.type === 'Z') { + p.closePath(); + } + } + + return p; + }; + + /** + * Split the glyph into contours. + * This function is here for backwards compatibility, and to + * provide raw access to the TrueType glyph outlines. + * @return {Array} + */ + Glyph.prototype.getContours = function() { + if (this.points === undefined) { + return []; + } + + var contours = []; + var currentContour = []; + for (var i = 0; i < this.points.length; i += 1) { + var pt = this.points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = []; + } + } + + check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); + return contours; + }; + + /** + * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph. + * @return {Object} + */ + Glyph.prototype.getMetrics = function() { + var commands = this.path.commands; + var xCoords = []; + var yCoords = []; + for (var i = 0; i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type !== 'Z') { + xCoords.push(cmd.x); + yCoords.push(cmd.y); + } + + if (cmd.type === 'Q' || cmd.type === 'C') { + xCoords.push(cmd.x1); + yCoords.push(cmd.y1); + } + + if (cmd.type === 'C') { + xCoords.push(cmd.x2); + yCoords.push(cmd.y2); + } + } + + var metrics = { + xMin: Math.min.apply(null, xCoords), + yMin: Math.min.apply(null, yCoords), + xMax: Math.max.apply(null, xCoords), + yMax: Math.max.apply(null, yCoords), + leftSideBearing: this.leftSideBearing + }; + + if (!isFinite(metrics.xMin)) { + metrics.xMin = 0; + } + + if (!isFinite(metrics.xMax)) { + metrics.xMax = this.advanceWidth; + } + + if (!isFinite(metrics.yMin)) { + metrics.yMin = 0; + } + + if (!isFinite(metrics.yMax)) { + metrics.yMax = 0; + } + + metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); + return metrics; + }; + + /** + * Draw the glyph on the given context. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {Object=} options - xScale, yScale to stretch the glyph. + */ + Glyph.prototype.draw = function(ctx, x, y, fontSize, options) { + this.getPath(x, y, fontSize, options).draw(ctx); + }; + + /** + * Draw the points of the glyph. + * On-curve points will be drawn in blue, off-curve points will be drawn in red. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + */ + Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) { + function drawCircles(l, x, y, scale) { + ctx.beginPath(); + for (var j = 0; j < l.length; j += 1) { + ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale)); + ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, Math.PI * 2, false); + } + + ctx.closePath(); + ctx.fill(); + } + + x = x !== undefined ? x : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + var scale = 1 / this.path.unitsPerEm * fontSize; + + var blueCircles = []; + var redCircles = []; + var path = this.path; + for (var i = 0; i < path.commands.length; i += 1) { + var cmd = path.commands[i]; + if (cmd.x !== undefined) { + blueCircles.push({x: cmd.x, y: -cmd.y}); + } + + if (cmd.x1 !== undefined) { + redCircles.push({x: cmd.x1, y: -cmd.y1}); + } + + if (cmd.x2 !== undefined) { + redCircles.push({x: cmd.x2, y: -cmd.y2}); + } + } + + ctx.fillStyle = 'blue'; + drawCircles(blueCircles, x, y, scale); + ctx.fillStyle = 'red'; + drawCircles(redCircles, x, y, scale); + }; + + /** + * Draw lines indicating important font measurements. + * Black lines indicate the origin of the coordinate system (point 0,0). + * Blue lines indicate the glyph bounding box. + * Green line indicates the advance width of the glyph. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + */ + Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) { + var scale; + x = x !== undefined ? x : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + scale = 1 / this.path.unitsPerEm * fontSize; + ctx.lineWidth = 1; + + // Draw the origin + ctx.strokeStyle = 'black'; + draw.line(ctx, x, -10000, x, 10000); + draw.line(ctx, -10000, y, 10000, y); + + // This code is here due to memory optimization: by not using + // defaults in the constructor, we save a notable amount of memory. + var xMin = this.xMin || 0; + var yMin = this.yMin || 0; + var xMax = this.xMax || 0; + var yMax = this.yMax || 0; + var advanceWidth = this.advanceWidth || 0; + + // Draw the glyph box + ctx.strokeStyle = 'blue'; + draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000); + draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000); + draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale)); + draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale)); + + // Draw the advance width + ctx.strokeStyle = 'green'; + draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000); + }; + + // The GlyphSet object + + // Define a property on the glyph that depends on the path being loaded. + function defineDependentProperty(glyph, externalName, internalName) { + Object.defineProperty(glyph, externalName, { + get: function() { + // Request the path property to make sure the path is loaded. + glyph.path; // jshint ignore:line + return glyph[internalName]; + }, + set: function(newValue) { + glyph[internalName] = newValue; + }, + enumerable: true, + configurable: true + }); + } + + /** + * A GlyphSet represents all glyphs available in the font, but modelled using + * a deferred glyph loader, for retrieving glyphs only once they are absolutely + * necessary, to keep the memory footprint down. + * @exports opentype.GlyphSet + * @class + * @param {opentype.Font} + * @param {Array} + */ + function GlyphSet(font, glyphs) { + this.font = font; + this.glyphs = {}; + if (Array.isArray(glyphs)) { + for (var i = 0; i < glyphs.length; i++) { + var glyph = glyphs[i]; + glyph.path.unitsPerEm = font.unitsPerEm; + this.glyphs[i] = glyph; + } + } + + this.length = (glyphs && glyphs.length) || 0; + } + + /** + * @param {number} index + * @return {opentype.Glyph} + */ + GlyphSet.prototype.get = function(index) { + // this.glyphs[index] is 'undefined' when low memory mode is on. glyph is pushed on request only. + if (this.glyphs[index] === undefined) { + this.font._push(index); + if (typeof this.glyphs[index] === 'function') { + this.glyphs[index] = this.glyphs[index](); + } + + var glyph = this.glyphs[index]; + var unicodeObj = this.font._IndexToUnicodeMap[index]; + + if (unicodeObj) { + for (var j = 0; j < unicodeObj.unicodes.length; j++) + { glyph.addUnicode(unicodeObj.unicodes[j]); } + } + + if (this.font.cffEncoding) { + if (this.font.isCIDFont) { + glyph.name = 'gid' + index; + } else { + glyph.name = this.font.cffEncoding.charset[index]; + } + } else if (this.font.glyphNames.names) { + glyph.name = this.font.glyphNames.glyphIndexToName(index); + } + + this.glyphs[index].advanceWidth = this.font._hmtxTableData[index].advanceWidth; + this.glyphs[index].leftSideBearing = this.font._hmtxTableData[index].leftSideBearing; + } else { + if (typeof this.glyphs[index] === 'function') { + this.glyphs[index] = this.glyphs[index](); + } + } + + return this.glyphs[index]; + }; + + /** + * @param {number} index + * @param {Object} + */ + GlyphSet.prototype.push = function(index, loader) { + this.glyphs[index] = loader; + this.length++; + }; + + /** + * @alias opentype.glyphLoader + * @param {opentype.Font} font + * @param {number} index + * @return {opentype.Glyph} + */ + function glyphLoader(font, index) { + return new Glyph({index: index, font: font}); + } + + /** + * Generate a stub glyph that can be filled with all metadata *except* + * the "points" and "path" properties, which must be loaded only once + * the glyph's path is actually requested for text shaping. + * @alias opentype.ttfGlyphLoader + * @param {opentype.Font} font + * @param {number} index + * @param {Function} parseGlyph + * @param {Object} data + * @param {number} position + * @param {Function} buildPath + * @return {opentype.Glyph} + */ + function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) { + return function() { + var glyph = new Glyph({index: index, font: font}); + + glyph.path = function() { + parseGlyph(glyph, data, position); + var path = buildPath(font.glyphs, glyph); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + + defineDependentProperty(glyph, 'xMin', '_xMin'); + defineDependentProperty(glyph, 'xMax', '_xMax'); + defineDependentProperty(glyph, 'yMin', '_yMin'); + defineDependentProperty(glyph, 'yMax', '_yMax'); + + return glyph; + }; + } + /** + * @alias opentype.cffGlyphLoader + * @param {opentype.Font} font + * @param {number} index + * @param {Function} parseCFFCharstring + * @param {string} charstring + * @return {opentype.Glyph} + */ + function cffGlyphLoader(font, index, parseCFFCharstring, charstring) { + return function() { + var glyph = new Glyph({index: index, font: font}); + + glyph.path = function() { + var path = parseCFFCharstring(font, glyph, charstring); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + + return glyph; + }; + } + + var glyphset = { GlyphSet: GlyphSet, glyphLoader: glyphLoader, ttfGlyphLoader: ttfGlyphLoader, cffGlyphLoader: cffGlyphLoader }; + + // The `CFF` table contains the glyph outlines in PostScript format. + + // Custom equals function that can also check lists. + function equals(a, b) { + if (a === b) { + return true; + } else if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return false; + } + + for (var i = 0; i < a.length; i += 1) { + if (!equals(a[i], b[i])) { + return false; + } + } + + return true; + } else { + return false; + } + } + + // Subroutines are encoded using the negative half of the number space. + // See type 2 chapter 4.7 "Subroutine operators". + function calcCFFSubroutineBias(subrs) { + var bias; + if (subrs.length < 1240) { + bias = 107; + } else if (subrs.length < 33900) { + bias = 1131; + } else { + bias = 32768; + } + + return bias; + } + + // Parse a `CFF` INDEX array. + // An index array consists of a list of offsets, then a list of objects at those offsets. + function parseCFFIndex(data, start, conversionFn) { + var offsets = []; + var objects = []; + var count = parse.getCard16(data, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data, start + 2); + objectOffset = start + ((count + 1) * offsetSize) + 2; + var pos = start + 3; + for (var i = 0; i < count + 1; i += 1) { + offsets.push(parse.getOffset(data, pos, offsetSize)); + pos += offsetSize; + } + + // The total size of the index array is 4 header bytes + the value of the last offset. + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + + for (var i$1 = 0; i$1 < offsets.length - 1; i$1 += 1) { + var value = parse.getBytes(data, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]); + if (conversionFn) { + value = conversionFn(value); + } + + objects.push(value); + } + + return {objects: objects, startOffset: start, endOffset: endOffset}; + } + + function parseCFFIndexLowMemory(data, start) { + var offsets = []; + var count = parse.getCard16(data, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data, start + 2); + objectOffset = start + ((count + 1) * offsetSize) + 2; + var pos = start + 3; + for (var i = 0; i < count + 1; i += 1) { + offsets.push(parse.getOffset(data, pos, offsetSize)); + pos += offsetSize; + } + + // The total size of the index array is 4 header bytes + the value of the last offset. + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + + return {offsets: offsets, startOffset: start, endOffset: endOffset}; + } + function getCffIndexObject(i, offsets, data, start, conversionFn) { + var count = parse.getCard16(data, start); + var objectOffset = 0; + if (count !== 0) { + var offsetSize = parse.getByte(data, start + 2); + objectOffset = start + ((count + 1) * offsetSize) + 2; + } + + var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]); + if (conversionFn) { + value = conversionFn(value); + } + return value; + } + + // Parse a `CFF` DICT real value. + function parseFloatOperand(parser) { + var s = ''; + var eof = 15; + var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-']; + while (true) { + var b = parser.parseByte(); + var n1 = b >> 4; + var n2 = b & 15; + + if (n1 === eof) { + break; + } + + s += lookup[n1]; + + if (n2 === eof) { + break; + } + + s += lookup[n2]; + } + + return parseFloat(s); + } + + // Parse a `CFF` DICT operand. + function parseOperand(parser, b0) { + var b1; + var b2; + var b3; + var b4; + if (b0 === 28) { + b1 = parser.parseByte(); + b2 = parser.parseByte(); + return b1 << 8 | b2; + } + + if (b0 === 29) { + b1 = parser.parseByte(); + b2 = parser.parseByte(); + b3 = parser.parseByte(); + b4 = parser.parseByte(); + return b1 << 24 | b2 << 16 | b3 << 8 | b4; + } + + if (b0 === 30) { + return parseFloatOperand(parser); + } + + if (b0 >= 32 && b0 <= 246) { + return b0 - 139; + } + + if (b0 >= 247 && b0 <= 250) { + b1 = parser.parseByte(); + return (b0 - 247) * 256 + b1 + 108; + } + + if (b0 >= 251 && b0 <= 254) { + b1 = parser.parseByte(); + return -(b0 - 251) * 256 - b1 - 108; + } + + throw new Error('Invalid b0 ' + b0); + } + + // Convert the entries returned by `parseDict` to a proper dictionary. + // If a value is a list of one, it is unpacked. + function entriesToObject(entries) { + var o = {}; + for (var i = 0; i < entries.length; i += 1) { + var key = entries[i][0]; + var values = entries[i][1]; + var value = (void 0); + if (values.length === 1) { + value = values[0]; + } else { + value = values; + } + + if (o.hasOwnProperty(key) && !isNaN(o[key])) { + throw new Error('Object ' + o + ' already has key ' + key); + } + + o[key] = value; + } + + return o; + } + + // Parse a `CFF` DICT object. + // A dictionary contains key-value pairs in a compact tokenized format. + function parseCFFDict(data, start, size) { + start = start !== undefined ? start : 0; + var parser = new parse.Parser(data, start); + var entries = []; + var operands = []; + size = size !== undefined ? size : data.length; + + while (parser.relativeOffset < size) { + var op = parser.parseByte(); + + // The first byte for each dict item distinguishes between operator (key) and operand (value). + // Values <= 21 are operators. + if (op <= 21) { + // Two-byte operators have an initial escape byte of 12. + if (op === 12) { + op = 1200 + parser.parseByte(); + } + + entries.push([op, operands]); + operands = []; + } else { + // Since the operands (values) come before the operators (keys), we store all operands in a list + // until we encounter an operator. + operands.push(parseOperand(parser, op)); + } + } + + return entriesToObject(entries); + } + + // Given a String Index (SID), return the value of the string. + // Strings below index 392 are standard CFF strings and are not encoded in the font. + function getCFFString(strings, index) { + if (index <= 390) { + index = cffStandardStrings[index]; + } else { + index = strings[index - 391]; + } + + return index; + } + + // Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. + // This function takes `meta` which is a list of objects containing `operand`, `name` and `default`. + function interpretDict(dict, meta, strings) { + var newDict = {}; + var value; + + // Because we also want to include missing values, we start out from the meta list + // and lookup values in the dict. + for (var i = 0; i < meta.length; i += 1) { + var m = meta[i]; + + if (Array.isArray(m.type)) { + var values = []; + values.length = m.type.length; + for (var j = 0; j < m.type.length; j++) { + value = dict[m.op] !== undefined ? dict[m.op][j] : undefined; + if (value === undefined) { + value = m.value !== undefined && m.value[j] !== undefined ? m.value[j] : null; + } + if (m.type[j] === 'SID') { + value = getCFFString(strings, value); + } + values[j] = value; + } + newDict[m.name] = values; + } else { + value = dict[m.op]; + if (value === undefined) { + value = m.value !== undefined ? m.value : null; + } + + if (m.type === 'SID') { + value = getCFFString(strings, value); + } + newDict[m.name] = value; + } + } + + return newDict; + } + + // Parse the CFF header. + function parseCFFHeader(data, start) { + var header = {}; + header.formatMajor = parse.getCard8(data, start); + header.formatMinor = parse.getCard8(data, start + 1); + header.size = parse.getCard8(data, start + 2); + header.offsetSize = parse.getCard8(data, start + 3); + header.startOffset = start; + header.endOffset = start + 4; + return header; + } + + var TOP_DICT_META = [ + {name: 'version', op: 0, type: 'SID'}, + {name: 'notice', op: 1, type: 'SID'}, + {name: 'copyright', op: 1200, type: 'SID'}, + {name: 'fullName', op: 2, type: 'SID'}, + {name: 'familyName', op: 3, type: 'SID'}, + {name: 'weight', op: 4, type: 'SID'}, + {name: 'isFixedPitch', op: 1201, type: 'number', value: 0}, + {name: 'italicAngle', op: 1202, type: 'number', value: 0}, + {name: 'underlinePosition', op: 1203, type: 'number', value: -100}, + {name: 'underlineThickness', op: 1204, type: 'number', value: 50}, + {name: 'paintType', op: 1205, type: 'number', value: 0}, + {name: 'charstringType', op: 1206, type: 'number', value: 2}, + { + name: 'fontMatrix', + op: 1207, + type: ['real', 'real', 'real', 'real', 'real', 'real'], + value: [0.001, 0, 0, 0.001, 0, 0] + }, + {name: 'uniqueId', op: 13, type: 'number'}, + {name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]}, + {name: 'strokeWidth', op: 1208, type: 'number', value: 0}, + {name: 'xuid', op: 14, type: [], value: null}, + {name: 'charset', op: 15, type: 'offset', value: 0}, + {name: 'encoding', op: 16, type: 'offset', value: 0}, + {name: 'charStrings', op: 17, type: 'offset', value: 0}, + {name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]}, + {name: 'ros', op: 1230, type: ['SID', 'SID', 'number']}, + {name: 'cidFontVersion', op: 1231, type: 'number', value: 0}, + {name: 'cidFontRevision', op: 1232, type: 'number', value: 0}, + {name: 'cidFontType', op: 1233, type: 'number', value: 0}, + {name: 'cidCount', op: 1234, type: 'number', value: 8720}, + {name: 'uidBase', op: 1235, type: 'number'}, + {name: 'fdArray', op: 1236, type: 'offset'}, + {name: 'fdSelect', op: 1237, type: 'offset'}, + {name: 'fontName', op: 1238, type: 'SID'} + ]; + + var PRIVATE_DICT_META = [ + {name: 'subrs', op: 19, type: 'offset', value: 0}, + {name: 'defaultWidthX', op: 20, type: 'number', value: 0}, + {name: 'nominalWidthX', op: 21, type: 'number', value: 0} + ]; + + // Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. + // The top dictionary contains the essential metadata for the font, together with the private dictionary. + function parseCFFTopDict(data, strings) { + var dict = parseCFFDict(data, 0, data.byteLength); + return interpretDict(dict, TOP_DICT_META, strings); + } + + // Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need. + function parseCFFPrivateDict(data, start, size, strings) { + var dict = parseCFFDict(data, start, size); + return interpretDict(dict, PRIVATE_DICT_META, strings); + } + + // Returns a list of "Top DICT"s found using an INDEX list. + // Used to read both the usual high-level Top DICTs and also the FDArray + // discovered inside CID-keyed fonts. When a Top DICT has a reference to + // a Private DICT that is read and saved into the Top DICT. + // + // In addition to the expected/optional values as outlined in TOP_DICT_META + // the following values might be saved into the Top DICT. + // + // _subrs [] array of local CFF subroutines from Private DICT + // _subrsBias bias value computed from number of subroutines + // (see calcCFFSubroutineBias() and parseCFFCharstring()) + // _defaultWidthX default widths for CFF characters + // _nominalWidthX bias added to width embedded within glyph description + // + // _privateDict saved copy of parsed Private DICT from Top DICT + function gatherCFFTopDicts(data, start, cffIndex, strings) { + var topDictArray = []; + for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) { + var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer); + var topDict = parseCFFTopDict(topDictData, strings); + topDict._subrs = []; + topDict._subrsBias = 0; + var privateSize = topDict.private[0]; + var privateOffset = topDict.private[1]; + if (privateSize !== 0 && privateOffset !== 0) { + var privateDict = parseCFFPrivateDict(data, privateOffset + start, privateSize, strings); + topDict._defaultWidthX = privateDict.defaultWidthX; + topDict._nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data, subrOffset + start); + topDict._subrs = subrIndex.objects; + topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); + } + topDict._privateDict = privateDict; + } + topDictArray.push(topDict); + } + return topDictArray; + } + + // Parse the CFF charset table, which contains internal names for all the glyphs. + // This function will return a list of glyph names. + // See Adobe TN #5176 chapter 13, "Charsets". + function parseCFFCharset(data, start, nGlyphs, strings) { + var sid; + var count; + var parser = new parse.Parser(data, start); + + // The .notdef glyph is not included, so subtract 1. + nGlyphs -= 1; + var charset = ['.notdef']; + + var format = parser.parseCard8(); + if (format === 0) { + for (var i = 0; i < nGlyphs; i += 1) { + sid = parser.parseSID(); + charset.push(getCFFString(strings, sid)); + } + } else if (format === 1) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard8(); + for (var i$1 = 0; i$1 <= count; i$1 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else if (format === 2) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard16(); + for (var i$2 = 0; i$2 <= count; i$2 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else { + throw new Error('Unknown charset format ' + format); + } + + return charset; + } + + // Parse the CFF encoding data. Only one encoding can be specified per font. + // See Adobe TN #5176 chapter 12, "Encodings". + function parseCFFEncoding(data, start, charset) { + var code; + var enc = {}; + var parser = new parse.Parser(data, start); + var format = parser.parseCard8(); + if (format === 0) { + var nCodes = parser.parseCard8(); + for (var i = 0; i < nCodes; i += 1) { + code = parser.parseCard8(); + enc[code] = i; + } + } else if (format === 1) { + var nRanges = parser.parseCard8(); + code = 1; + for (var i$1 = 0; i$1 < nRanges; i$1 += 1) { + var first = parser.parseCard8(); + var nLeft = parser.parseCard8(); + for (var j = first; j <= first + nLeft; j += 1) { + enc[j] = code; + code += 1; + } + } + } else { + throw new Error('Unknown encoding format ' + format); + } + + return new CffEncoding(enc, charset); + } + + // Take in charstring code and return a Glyph object. + // The encoding is described in the Type 2 Charstring Format + // https://www.microsoft.com/typography/OTSPEC/charstr2.htm + function parseCFFCharstring(font, glyph, code) { + var c1x; + var c1y; + var c2x; + var c2y; + var p = new Path(); + var stack = []; + var nStems = 0; + var haveWidth = false; + var open = false; + var x = 0; + var y = 0; + var subrs; + var subrsBias; + var defaultWidthX; + var nominalWidthX; + if (font.isCIDFont) { + var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index]; + var fdDict = font.tables.cff.topDict._fdArray[fdIndex]; + subrs = fdDict._subrs; + subrsBias = fdDict._subrsBias; + defaultWidthX = fdDict._defaultWidthX; + nominalWidthX = fdDict._nominalWidthX; + } else { + subrs = font.tables.cff.topDict._subrs; + subrsBias = font.tables.cff.topDict._subrsBias; + defaultWidthX = font.tables.cff.topDict._defaultWidthX; + nominalWidthX = font.tables.cff.topDict._nominalWidthX; + } + var width = defaultWidthX; + + function newContour(x, y) { + if (open) { + p.closePath(); + } + + p.moveTo(x, y); + open = true; + } + + function parseStems() { + var hasWidthArg; + + // The number of stem operators on the stack is always even. + // If the value is uneven, that means a width is specified. + hasWidthArg = stack.length % 2 !== 0; + if (hasWidthArg && !haveWidth) { + width = stack.shift() + nominalWidthX; + } + + nStems += stack.length >> 1; + stack.length = 0; + haveWidth = true; + } + + function parse(code) { + var b1; + var b2; + var b3; + var b4; + var codeIndex; + var subrCode; + var jpx; + var jpy; + var c3x; + var c3y; + var c4x; + var c4y; + + var i = 0; + while (i < code.length) { + var v = code[i]; + i += 1; + switch (v) { + case 1: // hstem + parseStems(); + break; + case 3: // vstem + parseStems(); + break; + case 4: // vmoveto + if (stack.length > 1 && !haveWidth) { + width = stack.shift() + nominalWidthX; + haveWidth = true; + } + + y += stack.pop(); + newContour(x, y); + break; + case 5: // rlineto + while (stack.length > 0) { + x += stack.shift(); + y += stack.shift(); + p.lineTo(x, y); + } + + break; + case 6: // hlineto + while (stack.length > 0) { + x += stack.shift(); + p.lineTo(x, y); + if (stack.length === 0) { + break; + } + + y += stack.shift(); + p.lineTo(x, y); + } + + break; + case 7: // vlineto + while (stack.length > 0) { + y += stack.shift(); + p.lineTo(x, y); + if (stack.length === 0) { + break; + } + + x += stack.shift(); + p.lineTo(x, y); + } + + break; + case 8: // rrcurveto + while (stack.length > 0) { + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + + break; + case 10: // callsubr + codeIndex = stack.pop() + subrsBias; + subrCode = subrs[codeIndex]; + if (subrCode) { + parse(subrCode); + } + + break; + case 11: // return + return; + case 12: // flex operators + v = code[i]; + i += 1; + switch (v) { + case 35: // flex + // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- + c1x = x + stack.shift(); // dx1 + c1y = y + stack.shift(); // dy1 + c2x = c1x + stack.shift(); // dx2 + c2y = c1y + stack.shift(); // dy2 + jpx = c2x + stack.shift(); // dx3 + jpy = c2y + stack.shift(); // dy3 + c3x = jpx + stack.shift(); // dx4 + c3y = jpy + stack.shift(); // dy4 + c4x = c3x + stack.shift(); // dx5 + c4y = c3y + stack.shift(); // dy5 + x = c4x + stack.shift(); // dx6 + y = c4y + stack.shift(); // dy6 + stack.shift(); // flex depth + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x, y); + break; + case 34: // hflex + // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- + c1x = x + stack.shift(); // dx1 + c1y = y; // dy1 + c2x = c1x + stack.shift(); // dx2 + c2y = c1y + stack.shift(); // dy2 + jpx = c2x + stack.shift(); // dx3 + jpy = c2y; // dy3 + c3x = jpx + stack.shift(); // dx4 + c3y = c2y; // dy4 + c4x = c3x + stack.shift(); // dx5 + c4y = y; // dy5 + x = c4x + stack.shift(); // dx6 + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x, y); + break; + case 36: // hflex1 + // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- + c1x = x + stack.shift(); // dx1 + c1y = y + stack.shift(); // dy1 + c2x = c1x + stack.shift(); // dx2 + c2y = c1y + stack.shift(); // dy2 + jpx = c2x + stack.shift(); // dx3 + jpy = c2y; // dy3 + c3x = jpx + stack.shift(); // dx4 + c3y = c2y; // dy4 + c4x = c3x + stack.shift(); // dx5 + c4y = c3y + stack.shift(); // dy5 + x = c4x + stack.shift(); // dx6 + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x, y); + break; + case 37: // flex1 + // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- + c1x = x + stack.shift(); // dx1 + c1y = y + stack.shift(); // dy1 + c2x = c1x + stack.shift(); // dx2 + c2y = c1y + stack.shift(); // dy2 + jpx = c2x + stack.shift(); // dx3 + jpy = c2y + stack.shift(); // dy3 + c3x = jpx + stack.shift(); // dx4 + c3y = jpy + stack.shift(); // dy4 + c4x = c3x + stack.shift(); // dx5 + c4y = c3y + stack.shift(); // dy5 + if (Math.abs(c4x - x) > Math.abs(c4y - y)) { + x = c4x + stack.shift(); + } else { + y = c4y + stack.shift(); + } + + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x, y); + break; + default: + console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v); + stack.length = 0; + } + break; + case 14: // endchar + if (stack.length > 0 && !haveWidth) { + width = stack.shift() + nominalWidthX; + haveWidth = true; + } + + if (open) { + p.closePath(); + open = false; + } + + break; + case 18: // hstemhm + parseStems(); + break; + case 19: // hintmask + case 20: // cntrmask + parseStems(); + i += (nStems + 7) >> 3; + break; + case 21: // rmoveto + if (stack.length > 2 && !haveWidth) { + width = stack.shift() + nominalWidthX; + haveWidth = true; + } + + y += stack.pop(); + x += stack.pop(); + newContour(x, y); + break; + case 22: // hmoveto + if (stack.length > 1 && !haveWidth) { + width = stack.shift() + nominalWidthX; + haveWidth = true; + } + + x += stack.pop(); + newContour(x, y); + break; + case 23: // vstemhm + parseStems(); + break; + case 24: // rcurveline + while (stack.length > 2) { + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + + x += stack.shift(); + y += stack.shift(); + p.lineTo(x, y); + break; + case 25: // rlinecurve + while (stack.length > 6) { + x += stack.shift(); + y += stack.shift(); + p.lineTo(x, y); + } + + c1x = x + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + break; + case 26: // vvcurveto + if (stack.length % 2) { + x += stack.shift(); + } + + while (stack.length > 0) { + c1x = x; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x; + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + + break; + case 27: // hhcurveto + if (stack.length % 2) { + y += stack.shift(); + } + + while (stack.length > 0) { + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y; + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + + break; + case 28: // shortint + b1 = code[i]; + b2 = code[i + 1]; + stack.push(((b1 << 24) | (b2 << 16)) >> 16); + i += 2; + break; + case 29: // callgsubr + codeIndex = stack.pop() + font.gsubrsBias; + subrCode = font.gsubrs[codeIndex]; + if (subrCode) { + parse(subrCode); + } + + break; + case 30: // vhcurveto + while (stack.length > 0) { + c1x = x; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + if (stack.length === 0) { + break; + } + + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + + break; + case 31: // hvcurveto + while (stack.length > 0) { + c1x = x + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + if (stack.length === 0) { + break; + } + + c1x = x; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x, y); + } + + break; + default: + if (v < 32) { + console.log('Glyph ' + glyph.index + ': unknown operator ' + v); + } else if (v < 247) { + stack.push(v - 139); + } else if (v < 251) { + b1 = code[i]; + i += 1; + stack.push((v - 247) * 256 + b1 + 108); + } else if (v < 255) { + b1 = code[i]; + i += 1; + stack.push(-(v - 251) * 256 - b1 - 108); + } else { + b1 = code[i]; + b2 = code[i + 1]; + b3 = code[i + 2]; + b4 = code[i + 3]; + i += 4; + stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536); + } + } + } + } + + parse(code); + + glyph.advanceWidth = width; + return p; + } + + function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) { + var fdSelect = []; + var fdIndex; + var parser = new parse.Parser(data, start); + var format = parser.parseCard8(); + if (format === 0) { + // Simple list of nGlyphs elements + for (var iGid = 0; iGid < nGlyphs; iGid++) { + fdIndex = parser.parseCard8(); + if (fdIndex >= fdArrayCount) { + throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); + } + fdSelect.push(fdIndex); + } + } else if (format === 3) { + // Ranges + var nRanges = parser.parseCard16(); + var first = parser.parseCard16(); + if (first !== 0) { + throw new Error('CFF Table CID Font FDSelect format 3 range has bad initial GID ' + first); + } + var next; + for (var iRange = 0; iRange < nRanges; iRange++) { + fdIndex = parser.parseCard8(); + next = parser.parseCard16(); + if (fdIndex >= fdArrayCount) { + throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); + } + if (next > nGlyphs) { + throw new Error('CFF Table CID Font FDSelect format 3 range has bad GID ' + next); + } + for (; first < next; first++) { + fdSelect.push(fdIndex); + } + first = next; + } + if (next !== nGlyphs) { + throw new Error('CFF Table CID Font FDSelect format 3 range has bad final GID ' + next); + } + } else { + throw new Error('CFF Table CID Font FDSelect table has unsupported format ' + format); + } + return fdSelect; + } + + // Parse the `CFF` table, which contains the glyph outlines in PostScript format. + function parseCFFTable(data, start, font, opt) { + font.tables.cff = {}; + var header = parseCFFHeader(data, start); + var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString); + var topDictIndex = parseCFFIndex(data, nameIndex.endOffset); + var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString); + var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset); + font.gsubrs = globalSubrIndex.objects; + font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); + + var topDictArray = gatherCFFTopDicts(data, start, topDictIndex.objects, stringIndex.objects); + if (topDictArray.length !== 1) { + throw new Error('CFF table has too many fonts in \'FontSet\' - count of fonts NameIndex.length = ' + topDictArray.length); + } + + var topDict = topDictArray[0]; + font.tables.cff.topDict = topDict; + + if (topDict._privateDict) { + font.defaultWidthX = topDict._privateDict.defaultWidthX; + font.nominalWidthX = topDict._privateDict.nominalWidthX; + } + + if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) { + font.isCIDFont = true; + } + + if (font.isCIDFont) { + var fdArrayOffset = topDict.fdArray; + var fdSelectOffset = topDict.fdSelect; + if (fdArrayOffset === 0 || fdSelectOffset === 0) { + throw new Error('Font is marked as a CID font, but FDArray and/or FDSelect information is missing'); + } + fdArrayOffset += start; + var fdArrayIndex = parseCFFIndex(data, fdArrayOffset); + var fdArray = gatherCFFTopDicts(data, start, fdArrayIndex.objects, stringIndex.objects); + topDict._fdArray = fdArray; + fdSelectOffset += start; + topDict._fdSelect = parseCFFFDSelect(data, fdSelectOffset, font.numGlyphs, fdArray.length); + } + + var privateDictOffset = start + topDict.private[1]; + var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict.private[0], stringIndex.objects); + font.defaultWidthX = privateDict.defaultWidthX; + font.nominalWidthX = privateDict.nominalWidthX; + + if (privateDict.subrs !== 0) { + var subrOffset = privateDictOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data, subrOffset); + font.subrs = subrIndex.objects; + font.subrsBias = calcCFFSubroutineBias(font.subrs); + } else { + font.subrs = []; + font.subrsBias = 0; + } + + // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset. + var charStringsIndex; + if (opt.lowMemory) { + charStringsIndex = parseCFFIndexLowMemory(data, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.offsets.length; + } else { + charStringsIndex = parseCFFIndex(data, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.objects.length; + } + + var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects); + if (topDict.encoding === 0) { + // Standard encoding + font.cffEncoding = new CffEncoding(cffStandardEncoding, charset); + } else if (topDict.encoding === 1) { + // Expert encoding + font.cffEncoding = new CffEncoding(cffExpertEncoding, charset); + } else { + font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset); + } + + // Prefer the CMAP encoding to the CFF encoding. + font.encoding = font.encoding || font.cffEncoding; + + font.glyphs = new glyphset.GlyphSet(font); + if (opt.lowMemory) { + font._push = function(i) { + var charString = getCffIndexObject(i, charStringsIndex.offsets, data, start + topDict.charStrings); + font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); + }; + } else { + for (var i = 0; i < font.nGlyphs; i += 1) { + var charString = charStringsIndex.objects[i]; + font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); + } + } + } + + // Convert a string to a String ID (SID). + // The list of strings is modified in place. + function encodeString(s, strings) { + var sid; + + // Is the string in the CFF standard strings? + var i = cffStandardStrings.indexOf(s); + if (i >= 0) { + sid = i; + } + + // Is the string already in the string index? + i = strings.indexOf(s); + if (i >= 0) { + sid = i + cffStandardStrings.length; + } else { + sid = cffStandardStrings.length + strings.length; + strings.push(s); + } + + return sid; + } + + function makeHeader() { + return new table.Record('Header', [ + {name: 'major', type: 'Card8', value: 1}, + {name: 'minor', type: 'Card8', value: 0}, + {name: 'hdrSize', type: 'Card8', value: 4}, + {name: 'major', type: 'Card8', value: 1} + ]); + } + + function makeNameIndex(fontNames) { + var t = new table.Record('Name INDEX', [ + {name: 'names', type: 'INDEX', value: []} + ]); + t.names = []; + for (var i = 0; i < fontNames.length; i += 1) { + t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]}); + } + + return t; + } + + // Given a dictionary's metadata, create a DICT structure. + function makeDict(meta, attrs, strings) { + var m = {}; + for (var i = 0; i < meta.length; i += 1) { + var entry = meta[i]; + var value = attrs[entry.name]; + if (value !== undefined && !equals(value, entry.value)) { + if (entry.type === 'SID') { + value = encodeString(value, strings); + } + + m[entry.op] = {name: entry.name, type: entry.type, value: value}; + } + } + + return m; + } + + // The Top DICT houses the global font attributes. + function makeTopDict(attrs, strings) { + var t = new table.Record('Top DICT', [ + {name: 'dict', type: 'DICT', value: {}} + ]); + t.dict = makeDict(TOP_DICT_META, attrs, strings); + return t; + } + + function makeTopDictIndex(topDict) { + var t = new table.Record('Top DICT INDEX', [ + {name: 'topDicts', type: 'INDEX', value: []} + ]); + t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}]; + return t; + } + + function makeStringIndex(strings) { + var t = new table.Record('String INDEX', [ + {name: 'strings', type: 'INDEX', value: []} + ]); + t.strings = []; + for (var i = 0; i < strings.length; i += 1) { + t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]}); + } + + return t; + } + + function makeGlobalSubrIndex() { + // Currently we don't use subroutines. + return new table.Record('Global Subr INDEX', [ + {name: 'subrs', type: 'INDEX', value: []} + ]); + } + + function makeCharsets(glyphNames, strings) { + var t = new table.Record('Charsets', [ + {name: 'format', type: 'Card8', value: 0} + ]); + for (var i = 0; i < glyphNames.length; i += 1) { + var glyphName = glyphNames[i]; + var glyphSID = encodeString(glyphName, strings); + t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID}); + } + + return t; + } + + function glyphToOps(glyph) { + var ops = []; + var path = glyph.path; + ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth}); + var x = 0; + var y = 0; + for (var i = 0; i < path.commands.length; i += 1) { + var dx = (void 0); + var dy = (void 0); + var cmd = path.commands[i]; + if (cmd.type === 'Q') { + // CFF only supports bézier curves, so convert the quad to a bézier. + var _13 = 1 / 3; + var _23 = 2 / 3; + + // We're going to create a new command so we don't change the original path. + cmd = { + type: 'C', + x: cmd.x, + y: cmd.y, + x1: _13 * x + _23 * cmd.x1, + y1: _13 * y + _23 * cmd.y1, + x2: _13 * cmd.x + _23 * cmd.x1, + y2: _13 * cmd.y + _23 * cmd.y1 + }; + } + + if (cmd.type === 'M') { + dx = Math.round(cmd.x - x); + dy = Math.round(cmd.y - y); + ops.push({name: 'dx', type: 'NUMBER', value: dx}); + ops.push({name: 'dy', type: 'NUMBER', value: dy}); + ops.push({name: 'rmoveto', type: 'OP', value: 21}); + x = Math.round(cmd.x); + y = Math.round(cmd.y); + } else if (cmd.type === 'L') { + dx = Math.round(cmd.x - x); + dy = Math.round(cmd.y - y); + ops.push({name: 'dx', type: 'NUMBER', value: dx}); + ops.push({name: 'dy', type: 'NUMBER', value: dy}); + ops.push({name: 'rlineto', type: 'OP', value: 5}); + x = Math.round(cmd.x); + y = Math.round(cmd.y); + } else if (cmd.type === 'C') { + var dx1 = Math.round(cmd.x1 - x); + var dy1 = Math.round(cmd.y1 - y); + var dx2 = Math.round(cmd.x2 - cmd.x1); + var dy2 = Math.round(cmd.y2 - cmd.y1); + dx = Math.round(cmd.x - cmd.x2); + dy = Math.round(cmd.y - cmd.y2); + ops.push({name: 'dx1', type: 'NUMBER', value: dx1}); + ops.push({name: 'dy1', type: 'NUMBER', value: dy1}); + ops.push({name: 'dx2', type: 'NUMBER', value: dx2}); + ops.push({name: 'dy2', type: 'NUMBER', value: dy2}); + ops.push({name: 'dx', type: 'NUMBER', value: dx}); + ops.push({name: 'dy', type: 'NUMBER', value: dy}); + ops.push({name: 'rrcurveto', type: 'OP', value: 8}); + x = Math.round(cmd.x); + y = Math.round(cmd.y); + } + + // Contours are closed automatically. + } + + ops.push({name: 'endchar', type: 'OP', value: 14}); + return ops; + } + + function makeCharStringsIndex(glyphs) { + var t = new table.Record('CharStrings INDEX', [ + {name: 'charStrings', type: 'INDEX', value: []} + ]); + + for (var i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var ops = glyphToOps(glyph); + t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops}); + } + + return t; + } + + function makePrivateDict(attrs, strings) { + var t = new table.Record('Private DICT', [ + {name: 'dict', type: 'DICT', value: {}} + ]); + t.dict = makeDict(PRIVATE_DICT_META, attrs, strings); + return t; + } + + function makeCFFTable(glyphs, options) { + var t = new table.Table('CFF ', [ + {name: 'header', type: 'RECORD'}, + {name: 'nameIndex', type: 'RECORD'}, + {name: 'topDictIndex', type: 'RECORD'}, + {name: 'stringIndex', type: 'RECORD'}, + {name: 'globalSubrIndex', type: 'RECORD'}, + {name: 'charsets', type: 'RECORD'}, + {name: 'charStringsIndex', type: 'RECORD'}, + {name: 'privateDict', type: 'RECORD'} + ]); + + var fontScale = 1 / options.unitsPerEm; + // We use non-zero values for the offsets so that the DICT encodes them. + // This is important because the size of the Top DICT plays a role in offset calculation, + // and the size shouldn't change after we've written correct offsets. + var attrs = { + version: options.version, + fullName: options.fullName, + familyName: options.familyName, + weight: options.weightName, + fontBBox: options.fontBBox || [0, 0, 0, 0], + fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], + charset: 999, + encoding: 0, + charStrings: 999, + private: [0, 999] + }; + + var privateAttrs = {}; + + var glyphNames = []; + var glyph; + + // Skip first glyph (.notdef) + for (var i = 1; i < glyphs.length; i += 1) { + glyph = glyphs.get(i); + glyphNames.push(glyph.name); + } + + var strings = []; + + t.header = makeHeader(); + t.nameIndex = makeNameIndex([options.postScriptName]); + var topDict = makeTopDict(attrs, strings); + t.topDictIndex = makeTopDictIndex(topDict); + t.globalSubrIndex = makeGlobalSubrIndex(); + t.charsets = makeCharsets(glyphNames, strings); + t.charStringsIndex = makeCharStringsIndex(glyphs); + t.privateDict = makePrivateDict(privateAttrs, strings); + + // Needs to come at the end, to encode all custom strings used in the font. + t.stringIndex = makeStringIndex(strings); + + var startOffset = t.header.sizeOf() + + t.nameIndex.sizeOf() + + t.topDictIndex.sizeOf() + + t.stringIndex.sizeOf() + + t.globalSubrIndex.sizeOf(); + attrs.charset = startOffset; + + // We use the CFF standard encoding; proper encoding will be handled in cmap. + attrs.encoding = 0; + attrs.charStrings = attrs.charset + t.charsets.sizeOf(); + attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf(); + + // Recreate the Top DICT INDEX with the correct offsets. + topDict = makeTopDict(attrs, strings); + t.topDictIndex = makeTopDictIndex(topDict); + + return t; + } + + var cff = { parse: parseCFFTable, make: makeCFFTable }; + + // The `head` table contains global information about the font. + + // Parse the header `head` table + function parseHeadTable(data, start) { + var head = {}; + var p = new parse.Parser(data, start); + head.version = p.parseVersion(); + head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; + head.checkSumAdjustment = p.parseULong(); + head.magicNumber = p.parseULong(); + check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.'); + head.flags = p.parseUShort(); + head.unitsPerEm = p.parseUShort(); + head.created = p.parseLongDateTime(); + head.modified = p.parseLongDateTime(); + head.xMin = p.parseShort(); + head.yMin = p.parseShort(); + head.xMax = p.parseShort(); + head.yMax = p.parseShort(); + head.macStyle = p.parseUShort(); + head.lowestRecPPEM = p.parseUShort(); + head.fontDirectionHint = p.parseShort(); + head.indexToLocFormat = p.parseShort(); + head.glyphDataFormat = p.parseShort(); + return head; + } + + function makeHeadTable(options) { + // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970 + var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; + var createdTimestamp = timestamp; + + if (options.createdTimestamp) { + createdTimestamp = options.createdTimestamp + 2082844800; + } + + return new table.Table('head', [ + {name: 'version', type: 'FIXED', value: 0x00010000}, + {name: 'fontRevision', type: 'FIXED', value: 0x00010000}, + {name: 'checkSumAdjustment', type: 'ULONG', value: 0}, + {name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5}, + {name: 'flags', type: 'USHORT', value: 0}, + {name: 'unitsPerEm', type: 'USHORT', value: 1000}, + {name: 'created', type: 'LONGDATETIME', value: createdTimestamp}, + {name: 'modified', type: 'LONGDATETIME', value: timestamp}, + {name: 'xMin', type: 'SHORT', value: 0}, + {name: 'yMin', type: 'SHORT', value: 0}, + {name: 'xMax', type: 'SHORT', value: 0}, + {name: 'yMax', type: 'SHORT', value: 0}, + {name: 'macStyle', type: 'USHORT', value: 0}, + {name: 'lowestRecPPEM', type: 'USHORT', value: 0}, + {name: 'fontDirectionHint', type: 'SHORT', value: 2}, + {name: 'indexToLocFormat', type: 'SHORT', value: 0}, + {name: 'glyphDataFormat', type: 'SHORT', value: 0} + ], options); + } + + var head = { parse: parseHeadTable, make: makeHeadTable }; + + // The `hhea` table contains information for horizontal layout. + + // Parse the horizontal header `hhea` table + function parseHheaTable(data, start) { + var hhea = {}; + var p = new parse.Parser(data, start); + hhea.version = p.parseVersion(); + hhea.ascender = p.parseShort(); + hhea.descender = p.parseShort(); + hhea.lineGap = p.parseShort(); + hhea.advanceWidthMax = p.parseUShort(); + hhea.minLeftSideBearing = p.parseShort(); + hhea.minRightSideBearing = p.parseShort(); + hhea.xMaxExtent = p.parseShort(); + hhea.caretSlopeRise = p.parseShort(); + hhea.caretSlopeRun = p.parseShort(); + hhea.caretOffset = p.parseShort(); + p.relativeOffset += 8; + hhea.metricDataFormat = p.parseShort(); + hhea.numberOfHMetrics = p.parseUShort(); + return hhea; + } + + function makeHheaTable(options) { + return new table.Table('hhea', [ + {name: 'version', type: 'FIXED', value: 0x00010000}, + {name: 'ascender', type: 'FWORD', value: 0}, + {name: 'descender', type: 'FWORD', value: 0}, + {name: 'lineGap', type: 'FWORD', value: 0}, + {name: 'advanceWidthMax', type: 'UFWORD', value: 0}, + {name: 'minLeftSideBearing', type: 'FWORD', value: 0}, + {name: 'minRightSideBearing', type: 'FWORD', value: 0}, + {name: 'xMaxExtent', type: 'FWORD', value: 0}, + {name: 'caretSlopeRise', type: 'SHORT', value: 1}, + {name: 'caretSlopeRun', type: 'SHORT', value: 0}, + {name: 'caretOffset', type: 'SHORT', value: 0}, + {name: 'reserved1', type: 'SHORT', value: 0}, + {name: 'reserved2', type: 'SHORT', value: 0}, + {name: 'reserved3', type: 'SHORT', value: 0}, + {name: 'reserved4', type: 'SHORT', value: 0}, + {name: 'metricDataFormat', type: 'SHORT', value: 0}, + {name: 'numberOfHMetrics', type: 'USHORT', value: 0} + ], options); + } + + var hhea = { parse: parseHheaTable, make: makeHheaTable }; + + // The `hmtx` table contains the horizontal metrics for all glyphs. + + function parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs) { + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data, start); + for (var i = 0; i < numGlyphs; i += 1) { + // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + + var glyph = glyphs.get(i); + glyph.advanceWidth = advanceWidth; + glyph.leftSideBearing = leftSideBearing; + } + } + + function parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs) { + font._hmtxTableData = {}; + + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data, start); + for (var i = 0; i < numGlyphs; i += 1) { + // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + + font._hmtxTableData[i] = { + advanceWidth: advanceWidth, + leftSideBearing: leftSideBearing + }; + } + } + + // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. + // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. + function parseHmtxTable(font, data, start, numMetrics, numGlyphs, glyphs, opt) { + if (opt.lowMemory) + { parseHmtxTableOnLowMemory(font, data, start, numMetrics, numGlyphs); } + else + { parseHmtxTableAll(data, start, numMetrics, numGlyphs, glyphs); } + } + + function makeHmtxTable(glyphs) { + var t = new table.Table('hmtx', []); + for (var i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var advanceWidth = glyph.advanceWidth || 0; + var leftSideBearing = glyph.leftSideBearing || 0; + t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth}); + t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing}); + } + + return t; + } + + var hmtx = { parse: parseHmtxTable, make: makeHmtxTable }; + + // The `ltag` table stores IETF BCP-47 language tags. It allows supporting + + function makeLtagTable(tags) { + var result = new table.Table('ltag', [ + {name: 'version', type: 'ULONG', value: 1}, + {name: 'flags', type: 'ULONG', value: 0}, + {name: 'numTags', type: 'ULONG', value: tags.length} + ]); + + var stringPool = ''; + var stringPoolOffset = 12 + tags.length * 4; + for (var i = 0; i < tags.length; ++i) { + var pos = stringPool.indexOf(tags[i]); + if (pos < 0) { + pos = stringPool.length; + stringPool += tags[i]; + } + + result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos}); + result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length}); + } + + result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); + return result; + } + + function parseLtagTable(data, start) { + var p = new parse.Parser(data, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, 'Unsupported ltag table version.'); + // The 'ltag' specification does not define any flags; skip the field. + p.skip('uLong', 1); + var numTags = p.parseULong(); + + var tags = []; + for (var i = 0; i < numTags; i++) { + var tag = ''; + var offset = start + p.parseUShort(); + var length = p.parseUShort(); + for (var j = offset; j < offset + length; ++j) { + tag += String.fromCharCode(data.getInt8(j)); + } + + tags.push(tag); + } + + return tags; + } + + var ltag = { make: makeLtagTable, parse: parseLtagTable }; + + // The `maxp` table establishes the memory requirements for the font. + + // Parse the maximum profile `maxp` table. + function parseMaxpTable(data, start) { + var maxp = {}; + var p = new parse.Parser(data, start); + maxp.version = p.parseVersion(); + maxp.numGlyphs = p.parseUShort(); + if (maxp.version === 1.0) { + maxp.maxPoints = p.parseUShort(); + maxp.maxContours = p.parseUShort(); + maxp.maxCompositePoints = p.parseUShort(); + maxp.maxCompositeContours = p.parseUShort(); + maxp.maxZones = p.parseUShort(); + maxp.maxTwilightPoints = p.parseUShort(); + maxp.maxStorage = p.parseUShort(); + maxp.maxFunctionDefs = p.parseUShort(); + maxp.maxInstructionDefs = p.parseUShort(); + maxp.maxStackElements = p.parseUShort(); + maxp.maxSizeOfInstructions = p.parseUShort(); + maxp.maxComponentElements = p.parseUShort(); + maxp.maxComponentDepth = p.parseUShort(); + } + + return maxp; + } + + function makeMaxpTable(numGlyphs) { + return new table.Table('maxp', [ + {name: 'version', type: 'FIXED', value: 0x00005000}, + {name: 'numGlyphs', type: 'USHORT', value: numGlyphs} + ]); + } + + var maxp = { parse: parseMaxpTable, make: makeMaxpTable }; + + // The `name` naming table. + + // NameIDs for the name table. + var nameTableNames = [ + 'copyright', // 0 + 'fontFamily', // 1 + 'fontSubfamily', // 2 + 'uniqueID', // 3 + 'fullName', // 4 + 'version', // 5 + 'postScriptName', // 6 + 'trademark', // 7 + 'manufacturer', // 8 + 'designer', // 9 + 'description', // 10 + 'manufacturerURL', // 11 + 'designerURL', // 12 + 'license', // 13 + 'licenseURL', // 14 + 'reserved', // 15 + 'preferredFamily', // 16 + 'preferredSubfamily', // 17 + 'compatibleFullName', // 18 + 'sampleText', // 19 + 'postScriptFindFontName', // 20 + 'wwsFamily', // 21 + 'wwsSubfamily' // 22 + ]; + + var macLanguages = { + 0: 'en', + 1: 'fr', + 2: 'de', + 3: 'it', + 4: 'nl', + 5: 'sv', + 6: 'es', + 7: 'da', + 8: 'pt', + 9: 'no', + 10: 'he', + 11: 'ja', + 12: 'ar', + 13: 'fi', + 14: 'el', + 15: 'is', + 16: 'mt', + 17: 'tr', + 18: 'hr', + 19: 'zh-Hant', + 20: 'ur', + 21: 'hi', + 22: 'th', + 23: 'ko', + 24: 'lt', + 25: 'pl', + 26: 'hu', + 27: 'es', + 28: 'lv', + 29: 'se', + 30: 'fo', + 31: 'fa', + 32: 'ru', + 33: 'zh', + 34: 'nl-BE', + 35: 'ga', + 36: 'sq', + 37: 'ro', + 38: 'cz', + 39: 'sk', + 40: 'si', + 41: 'yi', + 42: 'sr', + 43: 'mk', + 44: 'bg', + 45: 'uk', + 46: 'be', + 47: 'uz', + 48: 'kk', + 49: 'az-Cyrl', + 50: 'az-Arab', + 51: 'hy', + 52: 'ka', + 53: 'mo', + 54: 'ky', + 55: 'tg', + 56: 'tk', + 57: 'mn-CN', + 58: 'mn', + 59: 'ps', + 60: 'ks', + 61: 'ku', + 62: 'sd', + 63: 'bo', + 64: 'ne', + 65: 'sa', + 66: 'mr', + 67: 'bn', + 68: 'as', + 69: 'gu', + 70: 'pa', + 71: 'or', + 72: 'ml', + 73: 'kn', + 74: 'ta', + 75: 'te', + 76: 'si', + 77: 'my', + 78: 'km', + 79: 'lo', + 80: 'vi', + 81: 'id', + 82: 'tl', + 83: 'ms', + 84: 'ms-Arab', + 85: 'am', + 86: 'ti', + 87: 'om', + 88: 'so', + 89: 'sw', + 90: 'rw', + 91: 'rn', + 92: 'ny', + 93: 'mg', + 94: 'eo', + 128: 'cy', + 129: 'eu', + 130: 'ca', + 131: 'la', + 132: 'qu', + 133: 'gn', + 134: 'ay', + 135: 'tt', + 136: 'ug', + 137: 'dz', + 138: 'jv', + 139: 'su', + 140: 'gl', + 141: 'af', + 142: 'br', + 143: 'iu', + 144: 'gd', + 145: 'gv', + 146: 'ga', + 147: 'to', + 148: 'el-polyton', + 149: 'kl', + 150: 'az', + 151: 'nn' + }; + + // MacOS language ID → MacOS script ID + // + // Note that the script ID is not sufficient to determine what encoding + // to use in TrueType files. For some languages, MacOS used a modification + // of a mainstream script. For example, an Icelandic name would be stored + // with smRoman in the TrueType naming table, but the actual encoding + // is a special Icelandic version of the normal Macintosh Roman encoding. + // As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal + // Syllables but MacOS had run out of available script codes, so this was + // done as a (pretty radical) "modification" of Ethiopic. + // + // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt + var macLanguageToScript = { + 0: 0, // langEnglish → smRoman + 1: 0, // langFrench → smRoman + 2: 0, // langGerman → smRoman + 3: 0, // langItalian → smRoman + 4: 0, // langDutch → smRoman + 5: 0, // langSwedish → smRoman + 6: 0, // langSpanish → smRoman + 7: 0, // langDanish → smRoman + 8: 0, // langPortuguese → smRoman + 9: 0, // langNorwegian → smRoman + 10: 5, // langHebrew → smHebrew + 11: 1, // langJapanese → smJapanese + 12: 4, // langArabic → smArabic + 13: 0, // langFinnish → smRoman + 14: 6, // langGreek → smGreek + 15: 0, // langIcelandic → smRoman (modified) + 16: 0, // langMaltese → smRoman + 17: 0, // langTurkish → smRoman (modified) + 18: 0, // langCroatian → smRoman (modified) + 19: 2, // langTradChinese → smTradChinese + 20: 4, // langUrdu → smArabic + 21: 9, // langHindi → smDevanagari + 22: 21, // langThai → smThai + 23: 3, // langKorean → smKorean + 24: 29, // langLithuanian → smCentralEuroRoman + 25: 29, // langPolish → smCentralEuroRoman + 26: 29, // langHungarian → smCentralEuroRoman + 27: 29, // langEstonian → smCentralEuroRoman + 28: 29, // langLatvian → smCentralEuroRoman + 29: 0, // langSami → smRoman + 30: 0, // langFaroese → smRoman (modified) + 31: 4, // langFarsi → smArabic (modified) + 32: 7, // langRussian → smCyrillic + 33: 25, // langSimpChinese → smSimpChinese + 34: 0, // langFlemish → smRoman + 35: 0, // langIrishGaelic → smRoman (modified) + 36: 0, // langAlbanian → smRoman + 37: 0, // langRomanian → smRoman (modified) + 38: 29, // langCzech → smCentralEuroRoman + 39: 29, // langSlovak → smCentralEuroRoman + 40: 0, // langSlovenian → smRoman (modified) + 41: 5, // langYiddish → smHebrew + 42: 7, // langSerbian → smCyrillic + 43: 7, // langMacedonian → smCyrillic + 44: 7, // langBulgarian → smCyrillic + 45: 7, // langUkrainian → smCyrillic (modified) + 46: 7, // langByelorussian → smCyrillic + 47: 7, // langUzbek → smCyrillic + 48: 7, // langKazakh → smCyrillic + 49: 7, // langAzerbaijani → smCyrillic + 50: 4, // langAzerbaijanAr → smArabic + 51: 24, // langArmenian → smArmenian + 52: 23, // langGeorgian → smGeorgian + 53: 7, // langMoldavian → smCyrillic + 54: 7, // langKirghiz → smCyrillic + 55: 7, // langTajiki → smCyrillic + 56: 7, // langTurkmen → smCyrillic + 57: 27, // langMongolian → smMongolian + 58: 7, // langMongolianCyr → smCyrillic + 59: 4, // langPashto → smArabic + 60: 4, // langKurdish → smArabic + 61: 4, // langKashmiri → smArabic + 62: 4, // langSindhi → smArabic + 63: 26, // langTibetan → smTibetan + 64: 9, // langNepali → smDevanagari + 65: 9, // langSanskrit → smDevanagari + 66: 9, // langMarathi → smDevanagari + 67: 13, // langBengali → smBengali + 68: 13, // langAssamese → smBengali + 69: 11, // langGujarati → smGujarati + 70: 10, // langPunjabi → smGurmukhi + 71: 12, // langOriya → smOriya + 72: 17, // langMalayalam → smMalayalam + 73: 16, // langKannada → smKannada + 74: 14, // langTamil → smTamil + 75: 15, // langTelugu → smTelugu + 76: 18, // langSinhalese → smSinhalese + 77: 19, // langBurmese → smBurmese + 78: 20, // langKhmer → smKhmer + 79: 22, // langLao → smLao + 80: 30, // langVietnamese → smVietnamese + 81: 0, // langIndonesian → smRoman + 82: 0, // langTagalog → smRoman + 83: 0, // langMalayRoman → smRoman + 84: 4, // langMalayArabic → smArabic + 85: 28, // langAmharic → smEthiopic + 86: 28, // langTigrinya → smEthiopic + 87: 28, // langOromo → smEthiopic + 88: 0, // langSomali → smRoman + 89: 0, // langSwahili → smRoman + 90: 0, // langKinyarwanda → smRoman + 91: 0, // langRundi → smRoman + 92: 0, // langNyanja → smRoman + 93: 0, // langMalagasy → smRoman + 94: 0, // langEsperanto → smRoman + 128: 0, // langWelsh → smRoman (modified) + 129: 0, // langBasque → smRoman + 130: 0, // langCatalan → smRoman + 131: 0, // langLatin → smRoman + 132: 0, // langQuechua → smRoman + 133: 0, // langGuarani → smRoman + 134: 0, // langAymara → smRoman + 135: 7, // langTatar → smCyrillic + 136: 4, // langUighur → smArabic + 137: 26, // langDzongkha → smTibetan + 138: 0, // langJavaneseRom → smRoman + 139: 0, // langSundaneseRom → smRoman + 140: 0, // langGalician → smRoman + 141: 0, // langAfrikaans → smRoman + 142: 0, // langBreton → smRoman (modified) + 143: 28, // langInuktitut → smEthiopic (modified) + 144: 0, // langScottishGaelic → smRoman (modified) + 145: 0, // langManxGaelic → smRoman (modified) + 146: 0, // langIrishGaelicScript → smRoman (modified) + 147: 0, // langTongan → smRoman + 148: 6, // langGreekAncient → smRoman + 149: 0, // langGreenlandic → smRoman + 150: 0, // langAzerbaijanRoman → smRoman + 151: 0 // langNynorsk → smRoman + }; + + // While Microsoft indicates a region/country for all its language + // IDs, we omit the region code if it's equal to the "most likely + // region subtag" according to Unicode CLDR. For scripts, we omit + // the subtag if it is equal to the Suppress-Script entry in the + // IANA language subtag registry for IETF BCP 47. + // + // For example, Microsoft states that its language code 0x041A is + // Croatian in Croatia. We transform this to the BCP 47 language code 'hr' + // and not 'hr-HR' because Croatia is the default country for Croatian, + // according to Unicode CLDR. As another example, Microsoft states + // that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform + // this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script + // for the Croatian language, according to IANA. + // + // http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html + // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry + var windowsLanguages = { + 0x0436: 'af', + 0x041C: 'sq', + 0x0484: 'gsw', + 0x045E: 'am', + 0x1401: 'ar-DZ', + 0x3C01: 'ar-BH', + 0x0C01: 'ar', + 0x0801: 'ar-IQ', + 0x2C01: 'ar-JO', + 0x3401: 'ar-KW', + 0x3001: 'ar-LB', + 0x1001: 'ar-LY', + 0x1801: 'ary', + 0x2001: 'ar-OM', + 0x4001: 'ar-QA', + 0x0401: 'ar-SA', + 0x2801: 'ar-SY', + 0x1C01: 'aeb', + 0x3801: 'ar-AE', + 0x2401: 'ar-YE', + 0x042B: 'hy', + 0x044D: 'as', + 0x082C: 'az-Cyrl', + 0x042C: 'az', + 0x046D: 'ba', + 0x042D: 'eu', + 0x0423: 'be', + 0x0845: 'bn', + 0x0445: 'bn-IN', + 0x201A: 'bs-Cyrl', + 0x141A: 'bs', + 0x047E: 'br', + 0x0402: 'bg', + 0x0403: 'ca', + 0x0C04: 'zh-HK', + 0x1404: 'zh-MO', + 0x0804: 'zh', + 0x1004: 'zh-SG', + 0x0404: 'zh-TW', + 0x0483: 'co', + 0x041A: 'hr', + 0x101A: 'hr-BA', + 0x0405: 'cs', + 0x0406: 'da', + 0x048C: 'prs', + 0x0465: 'dv', + 0x0813: 'nl-BE', + 0x0413: 'nl', + 0x0C09: 'en-AU', + 0x2809: 'en-BZ', + 0x1009: 'en-CA', + 0x2409: 'en-029', + 0x4009: 'en-IN', + 0x1809: 'en-IE', + 0x2009: 'en-JM', + 0x4409: 'en-MY', + 0x1409: 'en-NZ', + 0x3409: 'en-PH', + 0x4809: 'en-SG', + 0x1C09: 'en-ZA', + 0x2C09: 'en-TT', + 0x0809: 'en-GB', + 0x0409: 'en', + 0x3009: 'en-ZW', + 0x0425: 'et', + 0x0438: 'fo', + 0x0464: 'fil', + 0x040B: 'fi', + 0x080C: 'fr-BE', + 0x0C0C: 'fr-CA', + 0x040C: 'fr', + 0x140C: 'fr-LU', + 0x180C: 'fr-MC', + 0x100C: 'fr-CH', + 0x0462: 'fy', + 0x0456: 'gl', + 0x0437: 'ka', + 0x0C07: 'de-AT', + 0x0407: 'de', + 0x1407: 'de-LI', + 0x1007: 'de-LU', + 0x0807: 'de-CH', + 0x0408: 'el', + 0x046F: 'kl', + 0x0447: 'gu', + 0x0468: 'ha', + 0x040D: 'he', + 0x0439: 'hi', + 0x040E: 'hu', + 0x040F: 'is', + 0x0470: 'ig', + 0x0421: 'id', + 0x045D: 'iu', + 0x085D: 'iu-Latn', + 0x083C: 'ga', + 0x0434: 'xh', + 0x0435: 'zu', + 0x0410: 'it', + 0x0810: 'it-CH', + 0x0411: 'ja', + 0x044B: 'kn', + 0x043F: 'kk', + 0x0453: 'km', + 0x0486: 'quc', + 0x0487: 'rw', + 0x0441: 'sw', + 0x0457: 'kok', + 0x0412: 'ko', + 0x0440: 'ky', + 0x0454: 'lo', + 0x0426: 'lv', + 0x0427: 'lt', + 0x082E: 'dsb', + 0x046E: 'lb', + 0x042F: 'mk', + 0x083E: 'ms-BN', + 0x043E: 'ms', + 0x044C: 'ml', + 0x043A: 'mt', + 0x0481: 'mi', + 0x047A: 'arn', + 0x044E: 'mr', + 0x047C: 'moh', + 0x0450: 'mn', + 0x0850: 'mn-CN', + 0x0461: 'ne', + 0x0414: 'nb', + 0x0814: 'nn', + 0x0482: 'oc', + 0x0448: 'or', + 0x0463: 'ps', + 0x0415: 'pl', + 0x0416: 'pt', + 0x0816: 'pt-PT', + 0x0446: 'pa', + 0x046B: 'qu-BO', + 0x086B: 'qu-EC', + 0x0C6B: 'qu', + 0x0418: 'ro', + 0x0417: 'rm', + 0x0419: 'ru', + 0x243B: 'smn', + 0x103B: 'smj-NO', + 0x143B: 'smj', + 0x0C3B: 'se-FI', + 0x043B: 'se', + 0x083B: 'se-SE', + 0x203B: 'sms', + 0x183B: 'sma-NO', + 0x1C3B: 'sms', + 0x044F: 'sa', + 0x1C1A: 'sr-Cyrl-BA', + 0x0C1A: 'sr', + 0x181A: 'sr-Latn-BA', + 0x081A: 'sr-Latn', + 0x046C: 'nso', + 0x0432: 'tn', + 0x045B: 'si', + 0x041B: 'sk', + 0x0424: 'sl', + 0x2C0A: 'es-AR', + 0x400A: 'es-BO', + 0x340A: 'es-CL', + 0x240A: 'es-CO', + 0x140A: 'es-CR', + 0x1C0A: 'es-DO', + 0x300A: 'es-EC', + 0x440A: 'es-SV', + 0x100A: 'es-GT', + 0x480A: 'es-HN', + 0x080A: 'es-MX', + 0x4C0A: 'es-NI', + 0x180A: 'es-PA', + 0x3C0A: 'es-PY', + 0x280A: 'es-PE', + 0x500A: 'es-PR', + + // Microsoft has defined two different language codes for + // “Spanish with modern sorting” and “Spanish with traditional + // sorting”. This makes sense for collation APIs, and it would be + // possible to express this in BCP 47 language tags via Unicode + // extensions (eg., es-u-co-trad is Spanish with traditional + // sorting). However, for storing names in fonts, the distinction + // does not make sense, so we give “es” in both cases. + 0x0C0A: 'es', + 0x040A: 'es', + + 0x540A: 'es-US', + 0x380A: 'es-UY', + 0x200A: 'es-VE', + 0x081D: 'sv-FI', + 0x041D: 'sv', + 0x045A: 'syr', + 0x0428: 'tg', + 0x085F: 'tzm', + 0x0449: 'ta', + 0x0444: 'tt', + 0x044A: 'te', + 0x041E: 'th', + 0x0451: 'bo', + 0x041F: 'tr', + 0x0442: 'tk', + 0x0480: 'ug', + 0x0422: 'uk', + 0x042E: 'hsb', + 0x0420: 'ur', + 0x0843: 'uz-Cyrl', + 0x0443: 'uz', + 0x042A: 'vi', + 0x0452: 'cy', + 0x0488: 'wo', + 0x0485: 'sah', + 0x0478: 'ii', + 0x046A: 'yo' + }; + + // Returns a IETF BCP 47 language code, for example 'zh-Hant' + // for 'Chinese in the traditional script'. + function getLanguageCode(platformID, languageID, ltag) { + switch (platformID) { + case 0: // Unicode + if (languageID === 0xFFFF) { + return 'und'; + } else if (ltag) { + return ltag[languageID]; + } + + break; + + case 1: // Macintosh + return macLanguages[languageID]; + + case 3: // Windows + return windowsLanguages[languageID]; + } + + return undefined; + } + + var utf16 = 'utf-16'; + + // MacOS script ID → encoding. This table stores the default case, + // which can be overridden by macLanguageEncodings. + var macScriptEncodings = { + 0: 'macintosh', // smRoman + 1: 'x-mac-japanese', // smJapanese + 2: 'x-mac-chinesetrad', // smTradChinese + 3: 'x-mac-korean', // smKorean + 6: 'x-mac-greek', // smGreek + 7: 'x-mac-cyrillic', // smCyrillic + 9: 'x-mac-devanagai', // smDevanagari + 10: 'x-mac-gurmukhi', // smGurmukhi + 11: 'x-mac-gujarati', // smGujarati + 12: 'x-mac-oriya', // smOriya + 13: 'x-mac-bengali', // smBengali + 14: 'x-mac-tamil', // smTamil + 15: 'x-mac-telugu', // smTelugu + 16: 'x-mac-kannada', // smKannada + 17: 'x-mac-malayalam', // smMalayalam + 18: 'x-mac-sinhalese', // smSinhalese + 19: 'x-mac-burmese', // smBurmese + 20: 'x-mac-khmer', // smKhmer + 21: 'x-mac-thai', // smThai + 22: 'x-mac-lao', // smLao + 23: 'x-mac-georgian', // smGeorgian + 24: 'x-mac-armenian', // smArmenian + 25: 'x-mac-chinesesimp', // smSimpChinese + 26: 'x-mac-tibetan', // smTibetan + 27: 'x-mac-mongolian', // smMongolian + 28: 'x-mac-ethiopic', // smEthiopic + 29: 'x-mac-ce', // smCentralEuroRoman + 30: 'x-mac-vietnamese', // smVietnamese + 31: 'x-mac-extarabic' // smExtArabic + }; + + // MacOS language ID → encoding. This table stores the exceptional + // cases, which override macScriptEncodings. For writing MacOS naming + // tables, we need to emit a MacOS script ID. Therefore, we cannot + // merge macScriptEncodings into macLanguageEncodings. + // + // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt + var macLanguageEncodings = { + 15: 'x-mac-icelandic', // langIcelandic + 17: 'x-mac-turkish', // langTurkish + 18: 'x-mac-croatian', // langCroatian + 24: 'x-mac-ce', // langLithuanian + 25: 'x-mac-ce', // langPolish + 26: 'x-mac-ce', // langHungarian + 27: 'x-mac-ce', // langEstonian + 28: 'x-mac-ce', // langLatvian + 30: 'x-mac-icelandic', // langFaroese + 37: 'x-mac-romanian', // langRomanian + 38: 'x-mac-ce', // langCzech + 39: 'x-mac-ce', // langSlovak + 40: 'x-mac-ce', // langSlovenian + 143: 'x-mac-inuit', // langInuktitut + 146: 'x-mac-gaelic' // langIrishGaelicScript + }; + + function getEncoding(platformID, encodingID, languageID) { + switch (platformID) { + case 0: // Unicode + return utf16; + + case 1: // Apple Macintosh + return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; + + case 3: // Microsoft Windows + if (encodingID === 1 || encodingID === 10) { + return utf16; + } + + break; + } + + return undefined; + } + + // Parse the naming `name` table. + // FIXME: Format 1 additional fields are not supported yet. + // ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904']. + function parseNameTable(data, start, ltag) { + var name = {}; + var p = new parse.Parser(data, start); + var format = p.parseUShort(); + var count = p.parseUShort(); + var stringOffset = p.offset + p.parseUShort(); + for (var i = 0; i < count; i++) { + var platformID = p.parseUShort(); + var encodingID = p.parseUShort(); + var languageID = p.parseUShort(); + var nameID = p.parseUShort(); + var property = nameTableNames[nameID] || nameID; + var byteLength = p.parseUShort(); + var offset = p.parseUShort(); + var language = getLanguageCode(platformID, languageID, ltag); + var encoding = getEncoding(platformID, encodingID, languageID); + if (encoding !== undefined && language !== undefined) { + var text = (void 0); + if (encoding === utf16) { + text = decode.UTF16(data, stringOffset + offset, byteLength); + } else { + text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding); + } + + if (text) { + var translations = name[property]; + if (translations === undefined) { + translations = name[property] = {}; + } + + translations[language] = text; + } + } + } + + var langTagCount = 0; + if (format === 1) { + // FIXME: Also handle Microsoft's 'name' table 1. + langTagCount = p.parseUShort(); + } + + return name; + } + + // {23: 'foo'} → {'foo': 23} + // ['bar', 'baz'] → {'bar': 0, 'baz': 1} + function reverseDict(dict) { + var result = {}; + for (var key in dict) { + result[dict[key]] = parseInt(key); + } + + return result; + } + + function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) { + return new table.Record('NameRecord', [ + {name: 'platformID', type: 'USHORT', value: platformID}, + {name: 'encodingID', type: 'USHORT', value: encodingID}, + {name: 'languageID', type: 'USHORT', value: languageID}, + {name: 'nameID', type: 'USHORT', value: nameID}, + {name: 'length', type: 'USHORT', value: length}, + {name: 'offset', type: 'USHORT', value: offset} + ]); + } + + // Finds the position of needle in haystack, or -1 if not there. + // Like String.indexOf(), but for arrays. + function findSubArray(needle, haystack) { + var needleLength = needle.length; + var limit = haystack.length - needleLength + 1; + + loop: + for (var pos = 0; pos < limit; pos++) { + for (; pos < limit; pos++) { + for (var k = 0; k < needleLength; k++) { + if (haystack[pos + k] !== needle[k]) { + continue loop; + } + } + + return pos; + } + } + + return -1; + } + + function addStringToPool(s, pool) { + var offset = findSubArray(s, pool); + if (offset < 0) { + offset = pool.length; + var i = 0; + var len = s.length; + for (; i < len; ++i) { + pool.push(s[i]); + } + + } + + return offset; + } + + function makeNameTable(names, ltag) { + var nameID; + var nameIDs = []; + + var namesWithNumericKeys = {}; + var nameTableIds = reverseDict(nameTableNames); + for (var key in names) { + var id = nameTableIds[key]; + if (id === undefined) { + id = key; + } + + nameID = parseInt(id); + + if (isNaN(nameID)) { + throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.'); + } + + namesWithNumericKeys[nameID] = names[key]; + nameIDs.push(nameID); + } + + var macLanguageIds = reverseDict(macLanguages); + var windowsLanguageIds = reverseDict(windowsLanguages); + + var nameRecords = []; + var stringPool = []; + + for (var i = 0; i < nameIDs.length; i++) { + nameID = nameIDs[i]; + var translations = namesWithNumericKeys[nameID]; + for (var lang in translations) { + var text = translations[lang]; + + // For MacOS, we try to emit the name in the form that was introduced + // in the initial version of the TrueType spec (in the late 1980s). + // However, this can fail for various reasons: the requested BCP 47 + // language code might not have an old-style Mac equivalent; + // we might not have a codec for the needed character encoding; + // or the name might contain characters that cannot be expressed + // in the old-style Macintosh encoding. In case of failure, we emit + // the name in a more modern fashion (Unicode encoding with BCP 47 + // language tags) that is recognized by MacOS 10.5, released in 2009. + // If fonts were only read by operating systems, we could simply + // emit all names in the modern form; this would be much easier. + // However, there are many applications and libraries that read + // 'name' tables directly, and these will usually only recognize + // the ancient form (silently skipping the unrecognized names). + var macPlatform = 1; // Macintosh + var macLanguage = macLanguageIds[lang]; + var macScript = macLanguageToScript[macLanguage]; + var macEncoding = getEncoding(macPlatform, macScript, macLanguage); + var macName = encode.MACSTRING(text, macEncoding); + if (macName === undefined) { + macPlatform = 0; // Unicode + macLanguage = ltag.indexOf(lang); + if (macLanguage < 0) { + macLanguage = ltag.length; + ltag.push(lang); + } + + macScript = 4; // Unicode 2.0 and later + macName = encode.UTF16(text); + } + + var macNameOffset = addStringToPool(macName, stringPool); + nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, + nameID, macName.length, macNameOffset)); + + var winLanguage = windowsLanguageIds[lang]; + if (winLanguage !== undefined) { + var winName = encode.UTF16(text); + var winNameOffset = addStringToPool(winName, stringPool); + nameRecords.push(makeNameRecord(3, 1, winLanguage, + nameID, winName.length, winNameOffset)); + } + } + } + + nameRecords.sort(function(a, b) { + return ((a.platformID - b.platformID) || + (a.encodingID - b.encodingID) || + (a.languageID - b.languageID) || + (a.nameID - b.nameID)); + }); + + var t = new table.Table('name', [ + {name: 'format', type: 'USHORT', value: 0}, + {name: 'count', type: 'USHORT', value: nameRecords.length}, + {name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12} + ]); + + for (var r = 0; r < nameRecords.length; r++) { + t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]}); + } + + t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool}); + return t; + } + + var _name = { parse: parseNameTable, make: makeNameTable }; + + // The `OS/2` table contains metrics required in OpenType fonts. + + var unicodeRanges = [ + {begin: 0x0000, end: 0x007F}, // Basic Latin + {begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement + {begin: 0x0100, end: 0x017F}, // Latin Extended-A + {begin: 0x0180, end: 0x024F}, // Latin Extended-B + {begin: 0x0250, end: 0x02AF}, // IPA Extensions + {begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters + {begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks + {begin: 0x0370, end: 0x03FF}, // Greek and Coptic + {begin: 0x2C80, end: 0x2CFF}, // Coptic + {begin: 0x0400, end: 0x04FF}, // Cyrillic + {begin: 0x0530, end: 0x058F}, // Armenian + {begin: 0x0590, end: 0x05FF}, // Hebrew + {begin: 0xA500, end: 0xA63F}, // Vai + {begin: 0x0600, end: 0x06FF}, // Arabic + {begin: 0x07C0, end: 0x07FF}, // NKo + {begin: 0x0900, end: 0x097F}, // Devanagari + {begin: 0x0980, end: 0x09FF}, // Bengali + {begin: 0x0A00, end: 0x0A7F}, // Gurmukhi + {begin: 0x0A80, end: 0x0AFF}, // Gujarati + {begin: 0x0B00, end: 0x0B7F}, // Oriya + {begin: 0x0B80, end: 0x0BFF}, // Tamil + {begin: 0x0C00, end: 0x0C7F}, // Telugu + {begin: 0x0C80, end: 0x0CFF}, // Kannada + {begin: 0x0D00, end: 0x0D7F}, // Malayalam + {begin: 0x0E00, end: 0x0E7F}, // Thai + {begin: 0x0E80, end: 0x0EFF}, // Lao + {begin: 0x10A0, end: 0x10FF}, // Georgian + {begin: 0x1B00, end: 0x1B7F}, // Balinese + {begin: 0x1100, end: 0x11FF}, // Hangul Jamo + {begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional + {begin: 0x1F00, end: 0x1FFF}, // Greek Extended + {begin: 0x2000, end: 0x206F}, // General Punctuation + {begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts + {begin: 0x20A0, end: 0x20CF}, // Currency Symbol + {begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols + {begin: 0x2100, end: 0x214F}, // Letterlike Symbols + {begin: 0x2150, end: 0x218F}, // Number Forms + {begin: 0x2190, end: 0x21FF}, // Arrows + {begin: 0x2200, end: 0x22FF}, // Mathematical Operators + {begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical + {begin: 0x2400, end: 0x243F}, // Control Pictures + {begin: 0x2440, end: 0x245F}, // Optical Character Recognition + {begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics + {begin: 0x2500, end: 0x257F}, // Box Drawing + {begin: 0x2580, end: 0x259F}, // Block Elements + {begin: 0x25A0, end: 0x25FF}, // Geometric Shapes + {begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols + {begin: 0x2700, end: 0x27BF}, // Dingbats + {begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation + {begin: 0x3040, end: 0x309F}, // Hiragana + {begin: 0x30A0, end: 0x30FF}, // Katakana + {begin: 0x3100, end: 0x312F}, // Bopomofo + {begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo + {begin: 0xA840, end: 0xA87F}, // Phags-pa + {begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months + {begin: 0x3300, end: 0x33FF}, // CJK Compatibility + {begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables + {begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 * + {begin: 0x10900, end: 0x1091F}, // Phoenicia + {begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs + {begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0) + {begin: 0x31C0, end: 0x31EF}, // CJK Strokes + {begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms + {begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A + {begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks + {begin: 0xFE10, end: 0xFE1F}, // Vertical Forms + {begin: 0xFE50, end: 0xFE6F}, // Small Form Variants + {begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B + {begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms + {begin: 0xFFF0, end: 0xFFFF}, // Specials + {begin: 0x0F00, end: 0x0FFF}, // Tibetan + {begin: 0x0700, end: 0x074F}, // Syriac + {begin: 0x0780, end: 0x07BF}, // Thaana + {begin: 0x0D80, end: 0x0DFF}, // Sinhala + {begin: 0x1000, end: 0x109F}, // Myanmar + {begin: 0x1200, end: 0x137F}, // Ethiopic + {begin: 0x13A0, end: 0x13FF}, // Cherokee + {begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics + {begin: 0x1680, end: 0x169F}, // Ogham + {begin: 0x16A0, end: 0x16FF}, // Runic + {begin: 0x1780, end: 0x17FF}, // Khmer + {begin: 0x1800, end: 0x18AF}, // Mongolian + {begin: 0x2800, end: 0x28FF}, // Braille Patterns + {begin: 0xA000, end: 0xA48F}, // Yi Syllables + {begin: 0x1700, end: 0x171F}, // Tagalog + {begin: 0x10300, end: 0x1032F}, // Old Italic + {begin: 0x10330, end: 0x1034F}, // Gothic + {begin: 0x10400, end: 0x1044F}, // Deseret + {begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols + {begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols + {begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15) + {begin: 0xFE00, end: 0xFE0F}, // Variation Selectors + {begin: 0xE0000, end: 0xE007F}, // Tags + {begin: 0x1900, end: 0x194F}, // Limbu + {begin: 0x1950, end: 0x197F}, // Tai Le + {begin: 0x1980, end: 0x19DF}, // New Tai Lue + {begin: 0x1A00, end: 0x1A1F}, // Buginese + {begin: 0x2C00, end: 0x2C5F}, // Glagolitic + {begin: 0x2D30, end: 0x2D7F}, // Tifinagh + {begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols + {begin: 0xA800, end: 0xA82F}, // Syloti Nagri + {begin: 0x10000, end: 0x1007F}, // Linear B Syllabary + {begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers + {begin: 0x10380, end: 0x1039F}, // Ugaritic + {begin: 0x103A0, end: 0x103DF}, // Old Persian + {begin: 0x10450, end: 0x1047F}, // Shavian + {begin: 0x10480, end: 0x104AF}, // Osmanya + {begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary + {begin: 0x10A00, end: 0x10A5F}, // Kharoshthi + {begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols + {begin: 0x12000, end: 0x123FF}, // Cuneiform + {begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals + {begin: 0x1B80, end: 0x1BBF}, // Sundanese + {begin: 0x1C00, end: 0x1C4F}, // Lepcha + {begin: 0x1C50, end: 0x1C7F}, // Ol Chiki + {begin: 0xA880, end: 0xA8DF}, // Saurashtra + {begin: 0xA900, end: 0xA92F}, // Kayah Li + {begin: 0xA930, end: 0xA95F}, // Rejang + {begin: 0xAA00, end: 0xAA5F}, // Cham + {begin: 0x10190, end: 0x101CF}, // Ancient Symbols + {begin: 0x101D0, end: 0x101FF}, // Phaistos Disc + {begin: 0x102A0, end: 0x102DF}, // Carian + {begin: 0x1F030, end: 0x1F09F} // Domino Tiles + ]; + + function getUnicodeRange(unicode) { + for (var i = 0; i < unicodeRanges.length; i += 1) { + var range = unicodeRanges[i]; + if (unicode >= range.begin && unicode < range.end) { + return i; + } + } + + return -1; + } + + // Parse the OS/2 and Windows metrics `OS/2` table + function parseOS2Table(data, start) { + var os2 = {}; + var p = new parse.Parser(data, start); + os2.version = p.parseUShort(); + os2.xAvgCharWidth = p.parseShort(); + os2.usWeightClass = p.parseUShort(); + os2.usWidthClass = p.parseUShort(); + os2.fsType = p.parseUShort(); + os2.ySubscriptXSize = p.parseShort(); + os2.ySubscriptYSize = p.parseShort(); + os2.ySubscriptXOffset = p.parseShort(); + os2.ySubscriptYOffset = p.parseShort(); + os2.ySuperscriptXSize = p.parseShort(); + os2.ySuperscriptYSize = p.parseShort(); + os2.ySuperscriptXOffset = p.parseShort(); + os2.ySuperscriptYOffset = p.parseShort(); + os2.yStrikeoutSize = p.parseShort(); + os2.yStrikeoutPosition = p.parseShort(); + os2.sFamilyClass = p.parseShort(); + os2.panose = []; + for (var i = 0; i < 10; i++) { + os2.panose[i] = p.parseByte(); + } + + os2.ulUnicodeRange1 = p.parseULong(); + os2.ulUnicodeRange2 = p.parseULong(); + os2.ulUnicodeRange3 = p.parseULong(); + os2.ulUnicodeRange4 = p.parseULong(); + os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); + os2.fsSelection = p.parseUShort(); + os2.usFirstCharIndex = p.parseUShort(); + os2.usLastCharIndex = p.parseUShort(); + os2.sTypoAscender = p.parseShort(); + os2.sTypoDescender = p.parseShort(); + os2.sTypoLineGap = p.parseShort(); + os2.usWinAscent = p.parseUShort(); + os2.usWinDescent = p.parseUShort(); + if (os2.version >= 1) { + os2.ulCodePageRange1 = p.parseULong(); + os2.ulCodePageRange2 = p.parseULong(); + } + + if (os2.version >= 2) { + os2.sxHeight = p.parseShort(); + os2.sCapHeight = p.parseShort(); + os2.usDefaultChar = p.parseUShort(); + os2.usBreakChar = p.parseUShort(); + os2.usMaxContent = p.parseUShort(); + } + + return os2; + } + + function makeOS2Table(options) { + return new table.Table('OS/2', [ + {name: 'version', type: 'USHORT', value: 0x0003}, + {name: 'xAvgCharWidth', type: 'SHORT', value: 0}, + {name: 'usWeightClass', type: 'USHORT', value: 0}, + {name: 'usWidthClass', type: 'USHORT', value: 0}, + {name: 'fsType', type: 'USHORT', value: 0}, + {name: 'ySubscriptXSize', type: 'SHORT', value: 650}, + {name: 'ySubscriptYSize', type: 'SHORT', value: 699}, + {name: 'ySubscriptXOffset', type: 'SHORT', value: 0}, + {name: 'ySubscriptYOffset', type: 'SHORT', value: 140}, + {name: 'ySuperscriptXSize', type: 'SHORT', value: 650}, + {name: 'ySuperscriptYSize', type: 'SHORT', value: 699}, + {name: 'ySuperscriptXOffset', type: 'SHORT', value: 0}, + {name: 'ySuperscriptYOffset', type: 'SHORT', value: 479}, + {name: 'yStrikeoutSize', type: 'SHORT', value: 49}, + {name: 'yStrikeoutPosition', type: 'SHORT', value: 258}, + {name: 'sFamilyClass', type: 'SHORT', value: 0}, + {name: 'bFamilyType', type: 'BYTE', value: 0}, + {name: 'bSerifStyle', type: 'BYTE', value: 0}, + {name: 'bWeight', type: 'BYTE', value: 0}, + {name: 'bProportion', type: 'BYTE', value: 0}, + {name: 'bContrast', type: 'BYTE', value: 0}, + {name: 'bStrokeVariation', type: 'BYTE', value: 0}, + {name: 'bArmStyle', type: 'BYTE', value: 0}, + {name: 'bLetterform', type: 'BYTE', value: 0}, + {name: 'bMidline', type: 'BYTE', value: 0}, + {name: 'bXHeight', type: 'BYTE', value: 0}, + {name: 'ulUnicodeRange1', type: 'ULONG', value: 0}, + {name: 'ulUnicodeRange2', type: 'ULONG', value: 0}, + {name: 'ulUnicodeRange3', type: 'ULONG', value: 0}, + {name: 'ulUnicodeRange4', type: 'ULONG', value: 0}, + {name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'}, + {name: 'fsSelection', type: 'USHORT', value: 0}, + {name: 'usFirstCharIndex', type: 'USHORT', value: 0}, + {name: 'usLastCharIndex', type: 'USHORT', value: 0}, + {name: 'sTypoAscender', type: 'SHORT', value: 0}, + {name: 'sTypoDescender', type: 'SHORT', value: 0}, + {name: 'sTypoLineGap', type: 'SHORT', value: 0}, + {name: 'usWinAscent', type: 'USHORT', value: 0}, + {name: 'usWinDescent', type: 'USHORT', value: 0}, + {name: 'ulCodePageRange1', type: 'ULONG', value: 0}, + {name: 'ulCodePageRange2', type: 'ULONG', value: 0}, + {name: 'sxHeight', type: 'SHORT', value: 0}, + {name: 'sCapHeight', type: 'SHORT', value: 0}, + {name: 'usDefaultChar', type: 'USHORT', value: 0}, + {name: 'usBreakChar', type: 'USHORT', value: 0}, + {name: 'usMaxContext', type: 'USHORT', value: 0} + ], options); + } + + var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges: unicodeRanges, getUnicodeRange: getUnicodeRange }; + + // The `post` table stores additional PostScript information, such as glyph names. + + // Parse the PostScript `post` table + function parsePostTable(data, start) { + var post = {}; + var p = new parse.Parser(data, start); + post.version = p.parseVersion(); + post.italicAngle = p.parseFixed(); + post.underlinePosition = p.parseShort(); + post.underlineThickness = p.parseShort(); + post.isFixedPitch = p.parseULong(); + post.minMemType42 = p.parseULong(); + post.maxMemType42 = p.parseULong(); + post.minMemType1 = p.parseULong(); + post.maxMemType1 = p.parseULong(); + switch (post.version) { + case 1: + post.names = standardNames.slice(); + break; + case 2: + post.numberOfGlyphs = p.parseUShort(); + post.glyphNameIndex = new Array(post.numberOfGlyphs); + for (var i = 0; i < post.numberOfGlyphs; i++) { + post.glyphNameIndex[i] = p.parseUShort(); + } + + post.names = []; + for (var i$1 = 0; i$1 < post.numberOfGlyphs; i$1++) { + if (post.glyphNameIndex[i$1] >= standardNames.length) { + var nameLength = p.parseChar(); + post.names.push(p.parseString(nameLength)); + } + } + + break; + case 2.5: + post.numberOfGlyphs = p.parseUShort(); + post.offset = new Array(post.numberOfGlyphs); + for (var i$2 = 0; i$2 < post.numberOfGlyphs; i$2++) { + post.offset[i$2] = p.parseChar(); + } + + break; + } + return post; + } + + function makePostTable() { + return new table.Table('post', [ + {name: 'version', type: 'FIXED', value: 0x00030000}, + {name: 'italicAngle', type: 'FIXED', value: 0}, + {name: 'underlinePosition', type: 'FWORD', value: 0}, + {name: 'underlineThickness', type: 'FWORD', value: 0}, + {name: 'isFixedPitch', type: 'ULONG', value: 0}, + {name: 'minMemType42', type: 'ULONG', value: 0}, + {name: 'maxMemType42', type: 'ULONG', value: 0}, + {name: 'minMemType1', type: 'ULONG', value: 0}, + {name: 'maxMemType1', type: 'ULONG', value: 0} + ]); + } + + var post = { parse: parsePostTable, make: makePostTable }; + + // The `GSUB` table contains ligatures, among other things. + + var subtableParsers = new Array(9); // subtableParsers[0] is unused + + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS + subtableParsers[1] = function parseLookup1() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + deltaGlyphId: this.parseUShort() + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + substitute: this.parseOffset16List() + }; + } + check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.'); + }; + + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS + subtableParsers[2] = function parseLookup2() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1'); + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + sequences: this.parseListOfLists() + }; + }; + + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS + subtableParsers[3] = function parseLookup3() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1'); + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + alternateSets: this.parseListOfLists() + }; + }; + + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS + subtableParsers[4] = function parseLookup4() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1'); + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + ligatureSets: this.parseListOfLists(function() { + return { + ligGlyph: this.parseUShort(), + components: this.parseUShortList(this.parseUShort() - 1) + }; + }) + }; + }; + + var lookupRecordDesc = { + sequenceIndex: Parser.uShort, + lookupListIndex: Parser.uShort + }; + + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF + subtableParsers[5] = function parseLookup5() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + + if (substFormat === 1) { + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + ruleSets: this.parseListOfLists(function() { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + input: this.parseUShortList(glyphCount - 1), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + classDef: this.parsePointer(Parser.classDef), + classSets: this.parseListOfLists(function() { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + classes: this.parseUShortList(glyphCount - 1), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + substFormat: substFormat, + coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + } + check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.'); + }; + + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC + subtableParsers[6] = function parseLookup6() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + chainRuleSets: this.parseListOfLists(function() { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + backtrackClassDef: this.parsePointer(Parser.classDef), + inputClassDef: this.parsePointer(Parser.classDef), + lookaheadClassDef: this.parsePointer(Parser.classDef), + chainClassSet: this.parseListOfLists(function() { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + return { + substFormat: 3, + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + } + check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.'); + }; + + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES + subtableParsers[7] = function parseLookup7() { + // Extension Substitution subtable + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1'); + var extensionLookupType = this.parseUShort(); + var extensionParser = new Parser(this.data, this.offset + this.parseULong()); + return { + substFormat: 1, + lookupType: extensionLookupType, + extension: subtableParsers[extensionLookupType].call(extensionParser) + }; + }; + + // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS + subtableParsers[8] = function parseLookup8() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1'); + return { + substFormat: substFormat, + coverage: this.parsePointer(Parser.coverage), + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + substitutes: this.parseUShortList() + }; + }; + + // https://www.microsoft.com/typography/OTSPEC/gsub.htm + function parseGsubTable(data, start) { + start = start || 0; + var p = new Parser(data, start); + var tableVersion = p.parseVersion(1); + check.argument(tableVersion === 1 || tableVersion === 1.1, 'Unsupported GSUB table version.'); + if (tableVersion === 1) { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers) + }; + } else { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers), + variations: p.parseFeatureVariationsList() + }; + } + + } + + // GSUB Writing ////////////////////////////////////////////// + var subtableMakers = new Array(9); + + subtableMakers[1] = function makeLookup1(subtable) { + if (subtable.substFormat === 1) { + return new table.Table('substitutionTable', [ + {name: 'substFormat', type: 'USHORT', value: 1}, + {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}, + {name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId} + ]); + } else { + return new table.Table('substitutionTable', [ + {name: 'substFormat', type: 'USHORT', value: 2}, + {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} + ].concat(table.ushortList('substitute', subtable.substitute))); + } + }; + + subtableMakers[3] = function makeLookup3(subtable) { + check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.'); + return new table.Table('substitutionTable', [ + {name: 'substFormat', type: 'USHORT', value: 1}, + {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} + ].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) { + return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet)); + }))); + }; + + subtableMakers[4] = function makeLookup4(subtable) { + check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.'); + return new table.Table('substitutionTable', [ + {name: 'substFormat', type: 'USHORT', value: 1}, + {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} + ].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) { + return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) { + return new table.Table('ligatureTable', + [{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}] + .concat(table.ushortList('component', ligature.components, ligature.components.length + 1)) + ); + })); + }))); + }; + + function makeGsubTable(gsub) { + return new table.Table('GSUB', [ + {name: 'version', type: 'ULONG', value: 0x10000}, + {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)}, + {name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)}, + {name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)} + ]); + } + + var gsub = { parse: parseGsubTable, make: makeGsubTable }; + + // The `GPOS` table contains kerning pairs, among other things. + + // Parse the metadata `meta` table. + // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html + function parseMetaTable(data, start) { + var p = new parse.Parser(data, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, 'Unsupported META table version.'); + p.parseULong(); // flags - currently unused and set to 0 + p.parseULong(); // tableOffset + var numDataMaps = p.parseULong(); + + var tags = {}; + for (var i = 0; i < numDataMaps; i++) { + var tag = p.parseTag(); + var dataOffset = p.parseULong(); + var dataLength = p.parseULong(); + var text = decode.UTF8(data, start + dataOffset, dataLength); + + tags[tag] = text; + } + return tags; + } + + function makeMetaTable(tags) { + var numTags = Object.keys(tags).length; + var stringPool = ''; + var stringPoolOffset = 16 + numTags * 12; + + var result = new table.Table('meta', [ + {name: 'version', type: 'ULONG', value: 1}, + {name: 'flags', type: 'ULONG', value: 0}, + {name: 'offset', type: 'ULONG', value: stringPoolOffset}, + {name: 'numTags', type: 'ULONG', value: numTags} + ]); + + for (var tag in tags) { + var pos = stringPool.length; + stringPool += tags[tag]; + + result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag}); + result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos}); + result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length}); + } + + result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); + + return result; + } + + var meta = { parse: parseMetaTable, make: makeMetaTable }; + + // The `sfnt` wrapper provides organization for the tables in the font. + + function log2(v) { + return Math.log(v) / Math.log(2) | 0; + } + + function computeCheckSum(bytes) { + while (bytes.length % 4 !== 0) { + bytes.push(0); + } + + var sum = 0; + for (var i = 0; i < bytes.length; i += 4) { + sum += (bytes[i] << 24) + + (bytes[i + 1] << 16) + + (bytes[i + 2] << 8) + + (bytes[i + 3]); + } + + sum %= Math.pow(2, 32); + return sum; + } + + function makeTableRecord(tag, checkSum, offset, length) { + return new table.Record('Table Record', [ + {name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''}, + {name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0}, + {name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0}, + {name: 'length', type: 'ULONG', value: length !== undefined ? length : 0} + ]); + } + + function makeSfntTable(tables) { + var sfnt = new table.Table('sfnt', [ + {name: 'version', type: 'TAG', value: 'OTTO'}, + {name: 'numTables', type: 'USHORT', value: 0}, + {name: 'searchRange', type: 'USHORT', value: 0}, + {name: 'entrySelector', type: 'USHORT', value: 0}, + {name: 'rangeShift', type: 'USHORT', value: 0} + ]); + sfnt.tables = tables; + sfnt.numTables = tables.length; + var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); + sfnt.searchRange = 16 * highestPowerOf2; + sfnt.entrySelector = log2(highestPowerOf2); + sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; + + var recordFields = []; + var tableFields = []; + + var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables); + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({name: 'padding', type: 'BYTE', value: 0}); + } + + for (var i = 0; i < tables.length; i += 1) { + var t = tables[i]; + check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.'); + var tableLength = t.sizeOf(); + var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength); + recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord}); + tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t}); + offset += tableLength; + check.argument(!isNaN(offset), 'Something went wrong calculating the offset.'); + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({name: 'padding', type: 'BYTE', value: 0}); + } + } + + // Table records need to be sorted alphabetically. + recordFields.sort(function(r1, r2) { + if (r1.value.tag > r2.value.tag) { + return 1; + } else { + return -1; + } + }); + + sfnt.fields = sfnt.fields.concat(recordFields); + sfnt.fields = sfnt.fields.concat(tableFields); + return sfnt; + } + + // Get the metrics for a character. If the string has more than one character + // this function returns metrics for the first available character. + // You can provide optional fallback metrics if no characters are available. + function metricsForChar(font, chars, notFoundMetrics) { + for (var i = 0; i < chars.length; i += 1) { + var glyphIndex = font.charToGlyphIndex(chars[i]); + if (glyphIndex > 0) { + var glyph = font.glyphs.get(glyphIndex); + return glyph.getMetrics(); + } + } + + return notFoundMetrics; + } + + function average(vs) { + var sum = 0; + for (var i = 0; i < vs.length; i += 1) { + sum += vs[i]; + } + + return sum / vs.length; + } + + // Convert the font object to a SFNT data structure. + // This structure contains all the necessary tables and metadata to create a binary OTF file. + function fontToSfntTable(font) { + var xMins = []; + var yMins = []; + var xMaxs = []; + var yMaxs = []; + var advanceWidths = []; + var leftSideBearings = []; + var rightSideBearings = []; + var firstCharIndex; + var lastCharIndex = 0; + var ulUnicodeRange1 = 0; + var ulUnicodeRange2 = 0; + var ulUnicodeRange3 = 0; + var ulUnicodeRange4 = 0; + + for (var i = 0; i < font.glyphs.length; i += 1) { + var glyph = font.glyphs.get(i); + var unicode = glyph.unicode | 0; + + if (isNaN(glyph.advanceWidth)) { + throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'); + } + + if (firstCharIndex > unicode || firstCharIndex === undefined) { + // ignore .notdef char + if (unicode > 0) { + firstCharIndex = unicode; + } + } + + if (lastCharIndex < unicode) { + lastCharIndex = unicode; + } + + var position = os2.getUnicodeRange(unicode); + if (position < 32) { + ulUnicodeRange1 |= 1 << position; + } else if (position < 64) { + ulUnicodeRange2 |= 1 << position - 32; + } else if (position < 96) { + ulUnicodeRange3 |= 1 << position - 64; + } else if (position < 123) { + ulUnicodeRange4 |= 1 << position - 96; + } else { + throw new Error('Unicode ranges bits > 123 are reserved for internal usage'); + } + // Skip non-important characters. + if (glyph.name === '.notdef') { continue; } + var metrics = glyph.getMetrics(); + xMins.push(metrics.xMin); + yMins.push(metrics.yMin); + xMaxs.push(metrics.xMax); + yMaxs.push(metrics.yMax); + leftSideBearings.push(metrics.leftSideBearing); + rightSideBearings.push(metrics.rightSideBearing); + advanceWidths.push(glyph.advanceWidth); + } + + var globals = { + xMin: Math.min.apply(null, xMins), + yMin: Math.min.apply(null, yMins), + xMax: Math.max.apply(null, xMaxs), + yMax: Math.max.apply(null, yMaxs), + advanceWidthMax: Math.max.apply(null, advanceWidths), + advanceWidthAvg: average(advanceWidths), + minLeftSideBearing: Math.min.apply(null, leftSideBearings), + maxLeftSideBearing: Math.max.apply(null, leftSideBearings), + minRightSideBearing: Math.min.apply(null, rightSideBearings) + }; + globals.ascender = font.ascender; + globals.descender = font.descender; + + var headTable = head.make({ + flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0) + unitsPerEm: font.unitsPerEm, + xMin: globals.xMin, + yMin: globals.yMin, + xMax: globals.xMax, + yMax: globals.yMax, + lowestRecPPEM: 3, + createdTimestamp: font.createdTimestamp + }); + + var hheaTable = hhea.make({ + ascender: globals.ascender, + descender: globals.descender, + advanceWidthMax: globals.advanceWidthMax, + minLeftSideBearing: globals.minLeftSideBearing, + minRightSideBearing: globals.minRightSideBearing, + xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), + numberOfHMetrics: font.glyphs.length + }); + + var maxpTable = maxp.make(font.glyphs.length); + + var os2Table = os2.make(Object.assign({ + xAvgCharWidth: Math.round(globals.advanceWidthAvg), + usFirstCharIndex: firstCharIndex, + usLastCharIndex: lastCharIndex, + ulUnicodeRange1: ulUnicodeRange1, + ulUnicodeRange2: ulUnicodeRange2, + ulUnicodeRange3: ulUnicodeRange3, + ulUnicodeRange4: ulUnicodeRange4, + // See http://typophile.com/node/13081 for more info on vertical metrics. + // We get metrics for typical characters (such as "x" for xHeight). + // We provide some fallback characters if characters are unavailable: their + // ordering was chosen experimentally. + sTypoAscender: globals.ascender, + sTypoDescender: globals.descender, + sTypoLineGap: 0, + usWinAscent: globals.yMax, + usWinDescent: Math.abs(globals.yMin), + ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now + sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax, + sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax, + usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available. + usBreakChar: font.hasChar(' ') ? 32 : 0, // Use space as the break character, if available. + }, font.tables.os2)); + + var hmtxTable = hmtx.make(font.glyphs); + var cmapTable = cmap.make(font.glyphs); + + var englishFamilyName = font.getEnglishName('fontFamily'); + var englishStyleName = font.getEnglishName('fontSubfamily'); + var englishFullName = englishFamilyName + ' ' + englishStyleName; + var postScriptName = font.getEnglishName('postScriptName'); + if (!postScriptName) { + postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName; + } + + var names = {}; + for (var n in font.names) { + names[n] = font.names[n]; + } + + if (!names.uniqueID) { + names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName}; + } + + if (!names.postScriptName) { + names.postScriptName = {en: postScriptName}; + } + + if (!names.preferredFamily) { + names.preferredFamily = font.names.fontFamily; + } + + if (!names.preferredSubfamily) { + names.preferredSubfamily = font.names.fontSubfamily; + } + + var languageTags = []; + var nameTable = _name.make(names, languageTags); + var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined); + + var postTable = post.make(); + var cffTable = cff.make(font.glyphs, { + version: font.getEnglishName('version'), + fullName: englishFullName, + familyName: englishFamilyName, + weightName: englishStyleName, + postScriptName: postScriptName, + unitsPerEm: font.unitsPerEm, + fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] + }); + + var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined; + + // The order does not matter because makeSfntTable() will sort them. + var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; + if (ltagTable) { + tables.push(ltagTable); + } + // Optional tables + if (font.tables.gsub) { + tables.push(gsub.make(font.tables.gsub)); + } + if (metaTable) { + tables.push(metaTable); + } + + var sfntTable = makeSfntTable(tables); + + // Compute the font's checkSum and store it in head.checkSumAdjustment. + var bytes = sfntTable.encode(); + var checkSum = computeCheckSum(bytes); + var tableFields = sfntTable.fields; + var checkSumAdjusted = false; + for (var i$1 = 0; i$1 < tableFields.length; i$1 += 1) { + if (tableFields[i$1].name === 'head table') { + tableFields[i$1].value.checkSumAdjustment = 0xB1B0AFBA - checkSum; + checkSumAdjusted = true; + break; + } + } + + if (!checkSumAdjusted) { + throw new Error('Could not find head table with checkSum to adjust.'); + } + + return sfntTable; + } + + var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum: computeCheckSum }; + + // The Layout object is the prototype of Substitution objects, and provides + + function searchTag(arr, tag) { + /* jshint bitwise: false */ + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = (imin + imax) >>> 1; + var val = arr[imid].tag; + if (val === tag) { + return imid; + } else if (val < tag) { + imin = imid + 1; + } else { imax = imid - 1; } + } + // Not found: return -1-insertion point + return -imin - 1; + } + + function binSearch(arr, value) { + /* jshint bitwise: false */ + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = (imin + imax) >>> 1; + var val = arr[imid]; + if (val === value) { + return imid; + } else if (val < value) { + imin = imid + 1; + } else { imax = imid - 1; } + } + // Not found: return -1-insertion point + return -imin - 1; + } + + // binary search in a list of ranges (coverage, class definition) + function searchRange(ranges, value) { + // jshint bitwise: false + var range; + var imin = 0; + var imax = ranges.length - 1; + while (imin <= imax) { + var imid = (imin + imax) >>> 1; + range = ranges[imid]; + var start = range.start; + if (start === value) { + return range; + } else if (start < value) { + imin = imid + 1; + } else { imax = imid - 1; } + } + if (imin > 0) { + range = ranges[imin - 1]; + if (value > range.end) { return 0; } + return range; + } + } + + /** + * @exports opentype.Layout + * @class + */ + function Layout(font, tableName) { + this.font = font; + this.tableName = tableName; + } + + Layout.prototype = { + + /** + * Binary search an object by "tag" property + * @instance + * @function searchTag + * @memberof opentype.Layout + * @param {Array} arr + * @param {string} tag + * @return {number} + */ + searchTag: searchTag, + + /** + * Binary search in a list of numbers + * @instance + * @function binSearch + * @memberof opentype.Layout + * @param {Array} arr + * @param {number} value + * @return {number} + */ + binSearch: binSearch, + + /** + * Get or create the Layout table (GSUB, GPOS etc). + * @param {boolean} create - Whether to create a new one. + * @return {Object} The GSUB or GPOS table. + */ + getTable: function(create) { + var layout = this.font.tables[this.tableName]; + if (!layout && create) { + layout = this.font.tables[this.tableName] = this.createDefaultTable(); + } + return layout; + }, + + /** + * Returns all scripts in the substitution table. + * @instance + * @return {Array} + */ + getScriptNames: function() { + var layout = this.getTable(); + if (!layout) { return []; } + return layout.scripts.map(function(script) { + return script.tag; + }); + }, + + /** + * Returns the best bet for a script name. + * Returns 'DFLT' if it exists. + * If not, returns 'latn' if it exists. + * If neither exist, returns undefined. + */ + getDefaultScriptName: function() { + var layout = this.getTable(); + if (!layout) { return; } + var hasLatn = false; + for (var i = 0; i < layout.scripts.length; i++) { + var name = layout.scripts[i].tag; + if (name === 'DFLT') { return name; } + if (name === 'latn') { hasLatn = true; } + } + if (hasLatn) { return 'latn'; } + }, + + /** + * Returns all LangSysRecords in the given script. + * @instance + * @param {string} [script='DFLT'] + * @param {boolean} create - forces the creation of this script table if it doesn't exist. + * @return {Object} An object with tag and script properties. + */ + getScriptTable: function(script, create) { + var layout = this.getTable(create); + if (layout) { + script = script || 'DFLT'; + var scripts = layout.scripts; + var pos = searchTag(layout.scripts, script); + if (pos >= 0) { + return scripts[pos].script; + } else if (create) { + var scr = { + tag: script, + script: { + defaultLangSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []}, + langSysRecords: [] + } + }; + scripts.splice(-1 - pos, 0, scr); + return scr.script; + } + } + }, + + /** + * Returns a language system table + * @instance + * @param {string} [script='DFLT'] + * @param {string} [language='dlft'] + * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. + * @return {Object} + */ + getLangSysTable: function(script, language, create) { + var scriptTable = this.getScriptTable(script, create); + if (scriptTable) { + if (!language || language === 'dflt' || language === 'DFLT') { + return scriptTable.defaultLangSys; + } + var pos = searchTag(scriptTable.langSysRecords, language); + if (pos >= 0) { + return scriptTable.langSysRecords[pos].langSys; + } else if (create) { + var langSysRecord = { + tag: language, + langSys: {reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: []} + }; + scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); + return langSysRecord.langSys; + } + } + }, + + /** + * Get a specific feature table. + * @instance + * @param {string} [script='DFLT'] + * @param {string} [language='dlft'] + * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm + * @param {boolean} create - forces the creation of the feature table if it doesn't exist. + * @return {Object} + */ + getFeatureTable: function(script, language, feature, create) { + var langSysTable = this.getLangSysTable(script, language, create); + if (langSysTable) { + var featureRecord; + var featIndexes = langSysTable.featureIndexes; + var allFeatures = this.font.tables[this.tableName].features; + // The FeatureIndex array of indices is in arbitrary order, + // even if allFeatures is sorted alphabetically by feature tag. + for (var i = 0; i < featIndexes.length; i++) { + featureRecord = allFeatures[featIndexes[i]]; + if (featureRecord.tag === feature) { + return featureRecord.feature; + } + } + if (create) { + var index = allFeatures.length; + // Automatic ordering of features would require to shift feature indexes in the script list. + check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.'); + featureRecord = { + tag: feature, + feature: { params: 0, lookupListIndexes: [] } + }; + allFeatures.push(featureRecord); + featIndexes.push(index); + return featureRecord.feature; + } + } + }, + + /** + * Get the lookup tables of a given type for a script/language/feature. + * @instance + * @param {string} [script='DFLT'] + * @param {string} [language='dlft'] + * @param {string} feature - 4-letter feature code + * @param {number} lookupType - 1 to 9 + * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. + * @return {Object[]} + */ + getLookupTables: function(script, language, feature, lookupType, create) { + var featureTable = this.getFeatureTable(script, language, feature, create); + var tables = []; + if (featureTable) { + var lookupTable; + var lookupListIndexes = featureTable.lookupListIndexes; + var allLookups = this.font.tables[this.tableName].lookups; + // lookupListIndexes are in no particular order, so use naive search. + for (var i = 0; i < lookupListIndexes.length; i++) { + lookupTable = allLookups[lookupListIndexes[i]]; + if (lookupTable.lookupType === lookupType) { + tables.push(lookupTable); + } + } + if (tables.length === 0 && create) { + lookupTable = { + lookupType: lookupType, + lookupFlag: 0, + subtables: [], + markFilteringSet: undefined + }; + var index = allLookups.length; + allLookups.push(lookupTable); + lookupListIndexes.push(index); + return [lookupTable]; + } + } + return tables; + }, + + /** + * Find a glyph in a class definition table + * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table + * @param {object} classDefTable - an OpenType Layout class definition table + * @param {number} glyphIndex - the index of the glyph to find + * @returns {number} -1 if not found + */ + getGlyphClass: function(classDefTable, glyphIndex) { + switch (classDefTable.format) { + case 1: + if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) { + return classDefTable.classes[glyphIndex - classDefTable.startGlyph]; + } + return 0; + case 2: + var range = searchRange(classDefTable.ranges, glyphIndex); + return range ? range.classId : 0; + } + }, + + /** + * Find a glyph in a coverage table + * https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-table + * @param {object} coverageTable - an OpenType Layout coverage table + * @param {number} glyphIndex - the index of the glyph to find + * @returns {number} -1 if not found + */ + getCoverageIndex: function(coverageTable, glyphIndex) { + switch (coverageTable.format) { + case 1: + var index = binSearch(coverageTable.glyphs, glyphIndex); + return index >= 0 ? index : -1; + case 2: + var range = searchRange(coverageTable.ranges, glyphIndex); + return range ? range.index + glyphIndex - range.start : -1; + } + }, + + /** + * Returns the list of glyph indexes of a coverage table. + * Format 1: the list is stored raw + * Format 2: compact list as range records. + * @instance + * @param {Object} coverageTable + * @return {Array} + */ + expandCoverage: function(coverageTable) { + if (coverageTable.format === 1) { + return coverageTable.glyphs; + } else { + var glyphs = []; + var ranges = coverageTable.ranges; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + var start = range.start; + var end = range.end; + for (var j = start; j <= end; j++) { + glyphs.push(j); + } + } + return glyphs; + } + } + + }; + + // The Position object provides utility methods to manipulate + + /** + * @exports opentype.Position + * @class + * @extends opentype.Layout + * @param {opentype.Font} + * @constructor + */ + function Position(font) { + Layout.call(this, font, 'gpos'); + } + + Position.prototype = Layout.prototype; + + /** + * Init some data for faster and easier access later. + */ + Position.prototype.init = function() { + var script = this.getDefaultScriptName(); + this.defaultKerningTables = this.getKerningTables(script); + }; + + /** + * Find a glyph pair in a list of lookup tables of type 2 and retrieve the xAdvance kerning value. + * + * @param {integer} leftIndex - left glyph index + * @param {integer} rightIndex - right glyph index + * @returns {integer} + */ + Position.prototype.getKerningValue = function(kerningLookups, leftIndex, rightIndex) { + for (var i = 0; i < kerningLookups.length; i++) { + var subtables = kerningLookups[i].subtables; + for (var j = 0; j < subtables.length; j++) { + var subtable = subtables[j]; + var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex); + if (covIndex < 0) { continue; } + switch (subtable.posFormat) { + case 1: + // Search Pair Adjustment Positioning Format 1 + var pairSet = subtable.pairSets[covIndex]; + for (var k = 0; k < pairSet.length; k++) { + var pair = pairSet[k]; + if (pair.secondGlyph === rightIndex) { + return pair.value1 && pair.value1.xAdvance || 0; + } + } + break; // left glyph found, not right glyph - try next subtable + case 2: + // Search Pair Adjustment Positioning Format 2 + var class1 = this.getGlyphClass(subtable.classDef1, leftIndex); + var class2 = this.getGlyphClass(subtable.classDef2, rightIndex); + var pair$1 = subtable.classRecords[class1][class2]; + return pair$1.value1 && pair$1.value1.xAdvance || 0; + } + } + } + return 0; + }; + + /** + * List all kerning lookup tables. + * + * @param {string} [script='DFLT'] - use font.position.getDefaultScriptName() for a better default value + * @param {string} [language='dflt'] + * @return {object[]} The list of kerning lookup tables (may be empty), or undefined if there is no GPOS table (and we should use the kern table) + */ + Position.prototype.getKerningTables = function(script, language) { + if (this.font.tables.gpos) { + return this.getLookupTables(script, language, 'kern', 2); + } + }; + + // The Substitution object provides utility methods to manipulate + + /** + * @exports opentype.Substitution + * @class + * @extends opentype.Layout + * @param {opentype.Font} + * @constructor + */ + function Substitution(font) { + Layout.call(this, font, 'gsub'); + } + + // Check if 2 arrays of primitives are equal. + function arraysEqual(ar1, ar2) { + var n = ar1.length; + if (n !== ar2.length) { return false; } + for (var i = 0; i < n; i++) { + if (ar1[i] !== ar2[i]) { return false; } + } + return true; + } + + // Find the first subtable of a lookup table in a particular format. + function getSubstFormat(lookupTable, format, defaultSubtable) { + var subtables = lookupTable.subtables; + for (var i = 0; i < subtables.length; i++) { + var subtable = subtables[i]; + if (subtable.substFormat === format) { + return subtable; + } + } + if (defaultSubtable) { + subtables.push(defaultSubtable); + return defaultSubtable; + } + return undefined; + } + + Substitution.prototype = Layout.prototype; + + /** + * Create a default GSUB table. + * @return {Object} gsub - The GSUB table. + */ + Substitution.prototype.createDefaultTable = function() { + // Generate a default empty GSUB table with just a DFLT script and dflt lang sys. + return { + version: 1, + scripts: [{ + tag: 'DFLT', + script: { + defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }, + langSysRecords: [] + } + }], + features: [], + lookups: [] + }; + }; + + /** + * List all single substitutions (lookup type 1) for a given script, language, and feature. + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + * @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...) + * @return {Array} substitutions - The list of substitutions. + */ + Substitution.prototype.getSingle = function(feature, script, language) { + var substitutions = []; + var lookupTables = this.getLookupTables(script, language, feature, 1); + for (var idx = 0; idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0; i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var j = (void 0); + if (subtable.substFormat === 1) { + var delta = subtable.deltaGlyphId; + for (j = 0; j < glyphs.length; j++) { + var glyph = glyphs[j]; + substitutions.push({ sub: glyph, by: glyph + delta }); + } + } else { + var substitute = subtable.substitute; + for (j = 0; j < glyphs.length; j++) { + substitutions.push({ sub: glyphs[j], by: substitute[j] }); + } + } + } + } + return substitutions; + }; + + /** + * List all alternates (lookup type 3) for a given script, language, and feature. + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + * @param {string} feature - 4-character feature name ('aalt', 'salt'...) + * @return {Array} alternates - The list of alternates + */ + Substitution.prototype.getAlternates = function(feature, script, language) { + var alternates = []; + var lookupTables = this.getLookupTables(script, language, feature, 3); + for (var idx = 0; idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0; i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var alternateSets = subtable.alternateSets; + for (var j = 0; j < glyphs.length; j++) { + alternates.push({ sub: glyphs[j], by: alternateSets[j] }); + } + } + } + return alternates; + }; + + /** + * List all ligatures (lookup type 4) for a given script, language, and feature. + * The result is an array of ligature objects like { sub: [ids], by: id } + * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + * @return {Array} ligatures - The list of ligatures. + */ + Substitution.prototype.getLigatures = function(feature, script, language) { + var ligatures = []; + var lookupTables = this.getLookupTables(script, language, feature, 4); + for (var idx = 0; idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0; i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var ligatureSets = subtable.ligatureSets; + for (var j = 0; j < glyphs.length; j++) { + var startGlyph = glyphs[j]; + var ligSet = ligatureSets[j]; + for (var k = 0; k < ligSet.length; k++) { + var lig = ligSet[k]; + ligatures.push({ + sub: [startGlyph].concat(lig.components), + by: lig.ligGlyph + }); + } + } + } + } + return ligatures; + }; + + /** + * Add or modify a single substitution (lookup type 1) + * Format 2, more flexible, is always used. + * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) + * @param {Object} substitution - { sub: id, delta: number } for format 1 or { sub: id, by: id } for format 2. + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + */ + Substitution.prototype.addSingle = function(feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0]; + var subtable = getSubstFormat(lookupTable, 2, { // lookup type 1 subtable, format 2, coverage format 1 + substFormat: 2, + coverage: {format: 1, glyphs: []}, + substitute: [] + }); + check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.substitute.splice(pos, 0, 0); + } + subtable.substitute[pos] = substitution.by; + }; + + /** + * Add or modify an alternate substitution (lookup type 1) + * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) + * @param {Object} substitution - { sub: id, by: [ids] } + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + */ + Substitution.prototype.addAlternate = function(feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0]; + var subtable = getSubstFormat(lookupTable, 1, { // lookup type 3 subtable, format 1, coverage format 1 + substFormat: 1, + coverage: {format: 1, glyphs: []}, + alternateSets: [] + }); + check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.alternateSets.splice(pos, 0, 0); + } + subtable.alternateSets[pos] = substitution.by; + }; + + /** + * Add a ligature (lookup type 4) + * Ligatures with more components must be stored ahead of those with fewer components in order to be found + * @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...) + * @param {Object} ligature - { sub: [ids], by: id } + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + */ + Substitution.prototype.addLigature = function(feature, ligature, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0]; + var subtable = lookupTable.subtables[0]; + if (!subtable) { + subtable = { // lookup type 4 subtable, format 1, coverage format 1 + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + ligatureSets: [] + }; + lookupTable.subtables[0] = subtable; + } + check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format); + var coverageGlyph = ligature.sub[0]; + var ligComponents = ligature.sub.slice(1); + var ligatureTable = { + ligGlyph: ligature.by, + components: ligComponents + }; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos >= 0) { + // ligatureSet already exists + var ligatureSet = subtable.ligatureSets[pos]; + for (var i = 0; i < ligatureSet.length; i++) { + // If ligature already exists, return. + if (arraysEqual(ligatureSet[i].components, ligComponents)) { + return; + } + } + // ligature does not exist: add it. + ligatureSet.push(ligatureTable); + } else { + // Create a new ligatureSet and add coverage for the first glyph. + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.ligatureSets.splice(pos, 0, [ligatureTable]); + } + }; + + /** + * List all feature data for a given script and language. + * @param {string} feature - 4-letter feature name + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + * @return {Array} substitutions - The list of substitutions. + */ + Substitution.prototype.getFeature = function(feature, script, language) { + if (/ss\d\d/.test(feature)) { + // ss01 - ss20 + return this.getSingle(feature, script, language); + } + switch (feature) { + case 'aalt': + case 'salt': + return this.getSingle(feature, script, language) + .concat(this.getAlternates(feature, script, language)); + case 'dlig': + case 'liga': + case 'rlig': return this.getLigatures(feature, script, language); + } + return undefined; + }; + + /** + * Add a substitution to a feature for a given script and language. + * @param {string} feature - 4-letter feature name + * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] }) + * @param {string} [script='DFLT'] + * @param {string} [language='dflt'] + */ + Substitution.prototype.add = function(feature, sub, script, language) { + if (/ss\d\d/.test(feature)) { + // ss01 - ss20 + return this.addSingle(feature, sub, script, language); + } + switch (feature) { + case 'aalt': + case 'salt': + if (typeof sub.by === 'number') { + return this.addSingle(feature, sub, script, language); + } + return this.addAlternate(feature, sub, script, language); + case 'dlig': + case 'liga': + case 'rlig': + return this.addLigature(feature, sub, script, language); + } + return undefined; + }; + + function isBrowser() { + return typeof window !== 'undefined'; + } + + function nodeBufferToArrayBuffer(buffer) { + var ab = new ArrayBuffer(buffer.length); + var view = new Uint8Array(ab); + for (var i = 0; i < buffer.length; ++i) { + view[i] = buffer[i]; + } + + return ab; + } + + function arrayBufferToNodeBuffer(ab) { + var buffer = new Buffer(ab.byteLength); + var view = new Uint8Array(ab); + for (var i = 0; i < buffer.length; ++i) { + buffer[i] = view[i]; + } + + return buffer; + } + + function checkArgument(expression, message) { + if (!expression) { + throw message; + } + } + + // The `glyf` table describes the glyphs in TrueType outline format. + + // Parse the coordinate data for a glyph. + function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { + var v; + if ((flag & shortVectorBitMask) > 0) { + // The coordinate is 1 byte long. + v = p.parseByte(); + // The `same` bit is re-used for short values to signify the sign of the value. + if ((flag & sameBitMask) === 0) { + v = -v; + } + + v = previousValue + v; + } else { + // The coordinate is 2 bytes long. + // If the `same` bit is set, the coordinate is the same as the previous coordinate. + if ((flag & sameBitMask) > 0) { + v = previousValue; + } else { + // Parse the coordinate as a signed 16-bit delta value. + v = previousValue + p.parseShort(); + } + } + + return v; + } + + // Parse a TrueType glyph. + function parseGlyph(glyph, data, start) { + var p = new parse.Parser(data, start); + glyph.numberOfContours = p.parseShort(); + glyph._xMin = p.parseShort(); + glyph._yMin = p.parseShort(); + glyph._xMax = p.parseShort(); + glyph._yMax = p.parseShort(); + var flags; + var flag; + + if (glyph.numberOfContours > 0) { + // This glyph is not a composite. + var endPointIndices = glyph.endPointIndices = []; + for (var i = 0; i < glyph.numberOfContours; i += 1) { + endPointIndices.push(p.parseUShort()); + } + + glyph.instructionLength = p.parseUShort(); + glyph.instructions = []; + for (var i$1 = 0; i$1 < glyph.instructionLength; i$1 += 1) { + glyph.instructions.push(p.parseByte()); + } + + var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; + flags = []; + for (var i$2 = 0; i$2 < numberOfCoordinates; i$2 += 1) { + flag = p.parseByte(); + flags.push(flag); + // If bit 3 is set, we repeat this flag n times, where n is the next byte. + if ((flag & 8) > 0) { + var repeatCount = p.parseByte(); + for (var j = 0; j < repeatCount; j += 1) { + flags.push(flag); + i$2 += 1; + } + } + } + + check.argument(flags.length === numberOfCoordinates, 'Bad flags.'); + + if (endPointIndices.length > 0) { + var points = []; + var point; + // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. + if (numberOfCoordinates > 0) { + for (var i$3 = 0; i$3 < numberOfCoordinates; i$3 += 1) { + flag = flags[i$3]; + point = {}; + point.onCurve = !!(flag & 1); + point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0; + points.push(point); + } + + var px = 0; + for (var i$4 = 0; i$4 < numberOfCoordinates; i$4 += 1) { + flag = flags[i$4]; + point = points[i$4]; + point.x = parseGlyphCoordinate(p, flag, px, 2, 16); + px = point.x; + } + + var py = 0; + for (var i$5 = 0; i$5 < numberOfCoordinates; i$5 += 1) { + flag = flags[i$5]; + point = points[i$5]; + point.y = parseGlyphCoordinate(p, flag, py, 4, 32); + py = point.y; + } + } + + glyph.points = points; + } else { + glyph.points = []; + } + } else if (glyph.numberOfContours === 0) { + glyph.points = []; + } else { + glyph.isComposite = true; + glyph.points = []; + glyph.components = []; + var moreComponents = true; + while (moreComponents) { + flags = p.parseUShort(); + var component = { + glyphIndex: p.parseUShort(), + xScale: 1, + scale01: 0, + scale10: 0, + yScale: 1, + dx: 0, + dy: 0 + }; + if ((flags & 1) > 0) { + // The arguments are words + if ((flags & 2) > 0) { + // values are offset + component.dx = p.parseShort(); + component.dy = p.parseShort(); + } else { + // values are matched points + component.matchedPoints = [p.parseUShort(), p.parseUShort()]; + } + + } else { + // The arguments are bytes + if ((flags & 2) > 0) { + // values are offset + component.dx = p.parseChar(); + component.dy = p.parseChar(); + } else { + // values are matched points + component.matchedPoints = [p.parseByte(), p.parseByte()]; + } + } + + if ((flags & 8) > 0) { + // We have a scale + component.xScale = component.yScale = p.parseF2Dot14(); + } else if ((flags & 64) > 0) { + // We have an X / Y scale + component.xScale = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } else if ((flags & 128) > 0) { + // We have a 2x2 transformation + component.xScale = p.parseF2Dot14(); + component.scale01 = p.parseF2Dot14(); + component.scale10 = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } + + glyph.components.push(component); + moreComponents = !!(flags & 32); + } + if (flags & 0x100) { + // We have instructions + glyph.instructionLength = p.parseUShort(); + glyph.instructions = []; + for (var i$6 = 0; i$6 < glyph.instructionLength; i$6 += 1) { + glyph.instructions.push(p.parseByte()); + } + } + } + } + + // Transform an array of points and return a new array. + function transformPoints(points, transform) { + var newPoints = []; + for (var i = 0; i < points.length; i += 1) { + var pt = points[i]; + var newPt = { + x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, + y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, + onCurve: pt.onCurve, + lastPointOfContour: pt.lastPointOfContour + }; + newPoints.push(newPt); + } + + return newPoints; + } + + function getContours(points) { + var contours = []; + var currentContour = []; + for (var i = 0; i < points.length; i += 1) { + var pt = points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = []; + } + } + + check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); + return contours; + } + + // Convert the TrueType glyph outline to a Path. + function getPath(points) { + var p = new Path(); + if (!points) { + return p; + } + + var contours = getContours(points); + + for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) { + var contour = contours[contourIndex]; + + var prev = null; + var curr = contour[contour.length - 1]; + var next = contour[0]; + + if (curr.onCurve) { + p.moveTo(curr.x, curr.y); + } else { + if (next.onCurve) { + p.moveTo(next.x, next.y); + } else { + // If both first and last points are off-curve, start at their middle. + var start = {x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5}; + p.moveTo(start.x, start.y); + } + } + + for (var i = 0; i < contour.length; ++i) { + prev = curr; + curr = next; + next = contour[(i + 1) % contour.length]; + + if (curr.onCurve) { + // This is a straight line. + p.lineTo(curr.x, curr.y); + } else { + var prev2 = prev; + var next2 = next; + + if (!prev.onCurve) { + prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 }; + } + + if (!next.onCurve) { + next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; + } + + p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); + } + } + + p.closePath(); + } + return p; + } + + function buildPath(glyphs, glyph) { + if (glyph.isComposite) { + for (var j = 0; j < glyph.components.length; j += 1) { + var component = glyph.components[j]; + var componentGlyph = glyphs.get(component.glyphIndex); + // Force the ttfGlyphLoader to parse the glyph. + componentGlyph.getPath(); + if (componentGlyph.points) { + var transformedPoints = (void 0); + if (component.matchedPoints === undefined) { + // component positioned by offset + transformedPoints = transformPoints(componentGlyph.points, component); + } else { + // component positioned by matched points + if ((component.matchedPoints[0] > glyph.points.length - 1) || + (component.matchedPoints[1] > componentGlyph.points.length - 1)) { + throw Error('Matched points out of range in ' + glyph.name); + } + var firstPt = glyph.points[component.matchedPoints[0]]; + var secondPt = componentGlyph.points[component.matchedPoints[1]]; + var transform = { + xScale: component.xScale, scale01: component.scale01, + scale10: component.scale10, yScale: component.yScale, + dx: 0, dy: 0 + }; + secondPt = transformPoints([secondPt], transform)[0]; + transform.dx = firstPt.x - secondPt.x; + transform.dy = firstPt.y - secondPt.y; + transformedPoints = transformPoints(componentGlyph.points, transform); + } + glyph.points = glyph.points.concat(transformedPoints); + } + } + } + + return getPath(glyph.points); + } + + function parseGlyfTableAll(data, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + + // The last element of the loca table is invalid. + for (var i = 0; i < loca.length - 1; i += 1) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + } + + return glyphs; + } + + function parseGlyfTableOnLowMemory(data, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + + font._push = function(i) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + }; + + return glyphs; + } + + // Parse all the glyphs according to the offsets from the `loca` table. + function parseGlyfTable(data, start, loca, font, opt) { + if (opt.lowMemory) + { return parseGlyfTableOnLowMemory(data, start, loca, font); } + else + { return parseGlyfTableAll(data, start, loca, font); } + } + + var glyf = { getPath: getPath, parse: parseGlyfTable}; + + /* A TrueType font hinting interpreter. + * + * (c) 2017 Axel Kittenberger + * + * This interpreter has been implemented according to this documentation: + * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html + * + * According to the documentation F24DOT6 values are used for pixels. + * That means calculation is 1/64 pixel accurate and uses integer operations. + * However, Javascript has floating point operations by default and only + * those are available. One could make a case to simulate the 1/64 accuracy + * exactly by truncating after every division operation + * (for example with << 0) to get pixel exactly results as other TrueType + * implementations. It may make sense since some fonts are pixel optimized + * by hand using DELTAP instructions. The current implementation doesn't + * and rather uses full floating point precision. + * + * xScale, yScale and rotation is currently ignored. + * + * A few non-trivial instructions are missing as I didn't encounter yet + * a font that used them to test a possible implementation. + * + * Some fonts seem to use undocumented features regarding the twilight zone. + * Only some of them are implemented as they were encountered. + * + * The exports.DEBUG statements are removed on the minified distribution file. + */ + + var instructionTable; + var exec; + var execGlyph; + var execComponent; + + /* + * Creates a hinting object. + * + * There ought to be exactly one + * for each truetype font that is used for hinting. + */ + function Hinting(font) { + // the font this hinting object is for + this.font = font; + + this.getCommands = function (hPoints) { + return glyf.getPath(hPoints).commands; + }; + + // cached states + this._fpgmState = + this._prepState = + undefined; + + // errorState + // 0 ... all okay + // 1 ... had an error in a glyf, + // continue working but stop spamming + // the console + // 2 ... error at prep, stop hinting at this ppem + // 3 ... error at fpeg, stop hinting for this font at all + this._errorState = 0; + } + + /* + * Not rounding. + */ + function roundOff(v) { + return v; + } + + /* + * Rounding to grid. + */ + function roundToGrid(v) { + //Rounding in TT is supposed to "symmetrical around zero" + return Math.sign(v) * Math.round(Math.abs(v)); + } + + /* + * Rounding to double grid. + */ + function roundToDoubleGrid(v) { + return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; + } + + /* + * Rounding to half grid. + */ + function roundToHalfGrid(v) { + return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5); + } + + /* + * Rounding to up to grid. + */ + function roundUpToGrid(v) { + return Math.sign(v) * Math.ceil(Math.abs(v)); + } + + /* + * Rounding to down to grid. + */ + function roundDownToGrid(v) { + return Math.sign(v) * Math.floor(Math.abs(v)); + } + + /* + * Super rounding. + */ + var roundSuper = function (v) { + var period = this.srPeriod; + var phase = this.srPhase; + var threshold = this.srThreshold; + var sign = 1; + + if (v < 0) { + v = -v; + sign = -1; + } + + v += threshold - phase; + + v = Math.trunc(v / period) * period; + + v += phase; + + // according to http://xgridfit.sourceforge.net/round.html + if (v < 0) { return phase * sign; } + + return v * sign; + }; + + /* + * Unit vector of x-axis. + */ + var xUnitVector = { + x: 1, + + y: 0, + + axis: 'x', + + // Gets the projected distance between two points. + // o1/o2 ... if true, respective original position is used. + distance: function (p1, p2, o1, o2) { + return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); + }, + + // Moves point p so the moved position has the same relative + // position to the moved positions of rp1 and rp2 than the + // original positions had. + // + // See APPENDIX on INTERPOLATE at the bottom of this file. + interpolate: function (p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + + if (!pv || pv === this) { + do1 = p.xo - rp1.xo; + do2 = p.xo - rp2.xo; + dm1 = rp1.x - rp1.xo; + dm2 = rp2.x - rp2.xo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + + if (dt === 0) { + p.x = p.xo + (dm1 + dm2) / 2; + return; + } + + p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + + if (dt === 0) { + xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + + xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + + // Slope of line normal to this + normalSlope: Number.NEGATIVE_INFINITY, + + // Sets the point 'p' relative to point 'rp' + // by the distance 'd'. + // + // See APPENDIX on SETRELATIVE at the bottom of this file. + // + // p ... point to set + // rp ... reference point + // d ... distance on projection vector + // pv ... projection vector (undefined = this) + // org ... if true, uses the original position of rp as reference. + setRelative: function (p, rp, d, pv, org) { + if (!pv || pv === this) { + p.x = (org ? rp.xo : rp.x) + d; + return; + } + + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + + p.x = rpdx + (p.y - rpdy) / pv.normalSlope; + }, + + // Slope of vector line. + slope: 0, + + // Touches the point p. + touch: function (p) { + p.xTouched = true; + }, + + // Tests if a point p is touched. + touched: function (p) { + return p.xTouched; + }, + + // Untouches the point p. + untouch: function (p) { + p.xTouched = false; + } + }; + + /* + * Unit vector of y-axis. + */ + var yUnitVector = { + x: 0, + + y: 1, + + axis: 'y', + + // Gets the projected distance between two points. + // o1/o2 ... if true, respective original position is used. + distance: function (p1, p2, o1, o2) { + return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); + }, + + // Moves point p so the moved position has the same relative + // position to the moved positions of rp1 and rp2 than the + // original positions had. + // + // See APPENDIX on INTERPOLATE at the bottom of this file. + interpolate: function (p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + + if (!pv || pv === this) { + do1 = p.yo - rp1.yo; + do2 = p.yo - rp2.yo; + dm1 = rp1.y - rp1.yo; + dm2 = rp2.y - rp2.yo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + + if (dt === 0) { + p.y = p.yo + (dm1 + dm2) / 2; + return; + } + + p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + + if (dt === 0) { + yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + + yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + + // Slope of line normal to this. + normalSlope: 0, + + // Sets the point 'p' relative to point 'rp' + // by the distance 'd' + // + // See APPENDIX on SETRELATIVE at the bottom of this file. + // + // p ... point to set + // rp ... reference point + // d ... distance on projection vector + // pv ... projection vector (undefined = this) + // org ... if true, uses the original position of rp as reference. + setRelative: function (p, rp, d, pv, org) { + if (!pv || pv === this) { + p.y = (org ? rp.yo : rp.y) + d; + return; + } + + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + + p.y = rpdy + pv.normalSlope * (p.x - rpdx); + }, + + // Slope of vector line. + slope: Number.POSITIVE_INFINITY, + + // Touches the point p. + touch: function (p) { + p.yTouched = true; + }, + + // Tests if a point p is touched. + touched: function (p) { + return p.yTouched; + }, + + // Untouches the point p. + untouch: function (p) { + p.yTouched = false; + } + }; + + Object.freeze(xUnitVector); + Object.freeze(yUnitVector); + + /* + * Creates a unit vector that is not x- or y-axis. + */ + function UnitVector(x, y) { + this.x = x; + this.y = y; + this.axis = undefined; + this.slope = y / x; + this.normalSlope = -x / y; + Object.freeze(this); + } + + /* + * Gets the projected distance between two points. + * o1/o2 ... if true, respective original position is used. + */ + UnitVector.prototype.distance = function(p1, p2, o1, o2) { + return ( + this.x * xUnitVector.distance(p1, p2, o1, o2) + + this.y * yUnitVector.distance(p1, p2, o1, o2) + ); + }; + + /* + * Moves point p so the moved position has the same relative + * position to the moved positions of rp1 and rp2 than the + * original positions had. + * + * See APPENDIX on INTERPOLATE at the bottom of this file. + */ + UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) { + var dm1; + var dm2; + var do1; + var do2; + var doa1; + var doa2; + var dt; + + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + + if (dt === 0) { + this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + + this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }; + + /* + * Sets the point 'p' relative to point 'rp' + * by the distance 'd' + * + * See APPENDIX on SETRELATIVE at the bottom of this file. + * + * p ... point to set + * rp ... reference point + * d ... distance on projection vector + * pv ... projection vector (undefined = this) + * org ... if true, uses the original position of rp as reference. + */ + UnitVector.prototype.setRelative = function(p, rp, d, pv, org) { + pv = pv || this; + + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + + var pvns = pv.normalSlope; + var fvs = this.slope; + + var px = p.x; + var py = p.y; + + p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns); + p.y = fvs * (p.x - px) + py; + }; + + /* + * Touches the point p. + */ + UnitVector.prototype.touch = function(p) { + p.xTouched = true; + p.yTouched = true; + }; + + /* + * Returns a unit vector with x/y coordinates. + */ + function getUnitVector(x, y) { + var d = Math.sqrt(x * x + y * y); + + x /= d; + y /= d; + + if (x === 1 && y === 0) { return xUnitVector; } + else if (x === 0 && y === 1) { return yUnitVector; } + else { return new UnitVector(x, y); } + } + + /* + * Creates a point in the hinting engine. + */ + function HPoint( + x, + y, + lastPointOfContour, + onCurve + ) { + this.x = this.xo = Math.round(x * 64) / 64; // hinted x value and original x-value + this.y = this.yo = Math.round(y * 64) / 64; // hinted y value and original y-value + + this.lastPointOfContour = lastPointOfContour; + this.onCurve = onCurve; + this.prevPointOnContour = undefined; + this.nextPointOnContour = undefined; + this.xTouched = false; + this.yTouched = false; + + Object.preventExtensions(this); + } + + /* + * Returns the next touched point on the contour. + * + * v ... unit vector to test touch axis. + */ + HPoint.prototype.nextTouched = function(v) { + var p = this.nextPointOnContour; + + while (!v.touched(p) && p !== this) { p = p.nextPointOnContour; } + + return p; + }; + + /* + * Returns the previous touched point on the contour + * + * v ... unit vector to test touch axis. + */ + HPoint.prototype.prevTouched = function(v) { + var p = this.prevPointOnContour; + + while (!v.touched(p) && p !== this) { p = p.prevPointOnContour; } + + return p; + }; + + /* + * The zero point. + */ + var HPZero = Object.freeze(new HPoint(0, 0)); + + /* + * The default state of the interpreter. + * + * Note: Freezing the defaultState and then deriving from it + * makes the V8 Javascript engine going awkward, + * so this is avoided, albeit the defaultState shouldn't + * ever change. + */ + var defaultState = { + cvCutIn: 17 / 16, // control value cut in + deltaBase: 9, + deltaShift: 0.125, + loop: 1, // loops some instructions + minDis: 1, // minimum distance + autoFlip: true + }; + + /* + * The current state of the interpreter. + * + * env ... 'fpgm' or 'prep' or 'glyf' + * prog ... the program + */ + function State(env, prog) { + this.env = env; + this.stack = []; + this.prog = prog; + + switch (env) { + case 'glyf' : + this.zp0 = this.zp1 = this.zp2 = 1; + this.rp0 = this.rp1 = this.rp2 = 0; + /* fall through */ + case 'prep' : + this.fv = this.pv = this.dpv = xUnitVector; + this.round = roundToGrid; + } + } + + /* + * Executes a glyph program. + * + * This does the hinting for each glyph. + * + * Returns an array of moved points. + * + * glyph: the glyph to hint + * ppem: the size the glyph is rendered for + */ + Hinting.prototype.exec = function(glyph, ppem) { + if (typeof ppem !== 'number') { + throw new Error('Point size is not a number!'); + } + + // Received a fatal error, don't do any hinting anymore. + if (this._errorState > 2) { return; } + + var font = this.font; + var prepState = this._prepState; + + if (!prepState || prepState.ppem !== ppem) { + var fpgmState = this._fpgmState; + + if (!fpgmState) { + // Executes the fpgm state. + // This is used by fonts to define functions. + State.prototype = defaultState; + + fpgmState = + this._fpgmState = + new State('fpgm', font.tables.fpgm); + + fpgmState.funcs = [ ]; + fpgmState.font = font; + + if (exports.DEBUG) { + console.log('---EXEC FPGM---'); + fpgmState.step = -1; + } + + try { + exec(fpgmState); + } catch (e) { + console.log('Hinting error in FPGM:' + e); + this._errorState = 3; + return; + } + } + + // Executes the prep program for this ppem setting. + // This is used by fonts to set cvt values + // depending on to be rendered font size. + + State.prototype = fpgmState; + prepState = + this._prepState = + new State('prep', font.tables.prep); + + prepState.ppem = ppem; + + // Creates a copy of the cvt table + // and scales it to the current ppem setting. + var oCvt = font.tables.cvt; + if (oCvt) { + var cvt = prepState.cvt = new Array(oCvt.length); + var scale = ppem / font.unitsPerEm; + for (var c = 0; c < oCvt.length; c++) { + cvt[c] = oCvt[c] * scale; + } + } else { + prepState.cvt = []; + } + + if (exports.DEBUG) { + console.log('---EXEC PREP---'); + prepState.step = -1; + } + + try { + exec(prepState); + } catch (e) { + if (this._errorState < 2) { + console.log('Hinting error in PREP:' + e); + } + this._errorState = 2; + } + } + + if (this._errorState > 1) { return; } + + try { + return execGlyph(glyph, prepState); + } catch (e) { + if (this._errorState < 1) { + console.log('Hinting error:' + e); + console.log('Note: further hinting errors are silenced'); + } + this._errorState = 1; + return undefined; + } + }; + + /* + * Executes the hinting program for a glyph. + */ + execGlyph = function(glyph, prepState) { + // original point positions + var xScale = prepState.ppem / prepState.font.unitsPerEm; + var yScale = xScale; + var components = glyph.components; + var contours; + var gZone; + var state; + + State.prototype = prepState; + if (!components) { + state = new State('glyf', glyph.instructions); + if (exports.DEBUG) { + console.log('---EXEC GLYPH---'); + state.step = -1; + } + execComponent(glyph, state, xScale, yScale); + gZone = state.gZone; + } else { + var font = prepState.font; + gZone = []; + contours = []; + for (var i = 0; i < components.length; i++) { + var c = components[i]; + var cg = font.glyphs.get(c.glyphIndex); + + state = new State('glyf', cg.instructions); + + if (exports.DEBUG) { + console.log('---EXEC COMP ' + i + '---'); + state.step = -1; + } + + execComponent(cg, state, xScale, yScale); + // appends the computed points to the result array + // post processes the component points + var dx = Math.round(c.dx * xScale); + var dy = Math.round(c.dy * yScale); + var gz = state.gZone; + var cc = state.contours; + for (var pi = 0; pi < gz.length; pi++) { + var p = gz[pi]; + p.xTouched = p.yTouched = false; + p.xo = p.x = p.x + dx; + p.yo = p.y = p.y + dy; + } + + var gLen = gZone.length; + gZone.push.apply(gZone, gz); + for (var j = 0; j < cc.length; j++) { + contours.push(cc[j] + gLen); + } + } + + if (glyph.instructions && !state.inhibitGridFit) { + // the composite has instructions on its own + state = new State('glyf', glyph.instructions); + + state.gZone = state.z0 = state.z1 = state.z2 = gZone; + + state.contours = contours; + + // note: HPZero cannot be used here, since + // the point might be modified + gZone.push( + new HPoint(0, 0), + new HPoint(Math.round(glyph.advanceWidth * xScale), 0) + ); + + if (exports.DEBUG) { + console.log('---EXEC COMPOSITE---'); + state.step = -1; + } + + exec(state); + + gZone.length -= 2; + } + } + + return gZone; + }; + + /* + * Executes the hinting program for a component of a multi-component glyph + * or of the glyph itself for a non-component glyph. + */ + execComponent = function(glyph, state, xScale, yScale) + { + var points = glyph.points || []; + var pLen = points.length; + var gZone = state.gZone = state.z0 = state.z1 = state.z2 = []; + var contours = state.contours = []; + + // Scales the original points and + // makes copies for the hinted points. + var cp; // current point + for (var i = 0; i < pLen; i++) { + cp = points[i]; + + gZone[i] = new HPoint( + cp.x * xScale, + cp.y * yScale, + cp.lastPointOfContour, + cp.onCurve + ); + } + + // Chain links the contours. + var sp; // start point + var np; // next point + + for (var i$1 = 0; i$1 < pLen; i$1++) { + cp = gZone[i$1]; + + if (!sp) { + sp = cp; + contours.push(i$1); + } + + if (cp.lastPointOfContour) { + cp.nextPointOnContour = sp; + sp.prevPointOnContour = cp; + sp = undefined; + } else { + np = gZone[i$1 + 1]; + cp.nextPointOnContour = np; + np.prevPointOnContour = cp; + } + } + + if (state.inhibitGridFit) { return; } + + if (exports.DEBUG) { + console.log('PROCESSING GLYPH', state.stack); + for (var i$2 = 0; i$2 < pLen; i$2++) { + console.log(i$2, gZone[i$2].x, gZone[i$2].y); + } + } + + gZone.push( + new HPoint(0, 0), + new HPoint(Math.round(glyph.advanceWidth * xScale), 0) + ); + + exec(state); + + // Removes the extra points. + gZone.length -= 2; + + if (exports.DEBUG) { + console.log('FINISHED GLYPH', state.stack); + for (var i$3 = 0; i$3 < pLen; i$3++) { + console.log(i$3, gZone[i$3].x, gZone[i$3].y); + } + } + }; + + /* + * Executes the program loaded in state. + */ + exec = function(state) { + var prog = state.prog; + + if (!prog) { return; } + + var pLen = prog.length; + var ins; + + for (state.ip = 0; state.ip < pLen; state.ip++) { + if (exports.DEBUG) { state.step++; } + ins = instructionTable[prog[state.ip]]; + + if (!ins) { + throw new Error( + 'unknown instruction: 0x' + + Number(prog[state.ip]).toString(16) + ); + } + + ins(state); + + // very extensive debugging for each step + /* + if (exports.DEBUG) { + var da; + if (state.gZone) { + da = []; + for (let i = 0; i < state.gZone.length; i++) + { + da.push(i + ' ' + + state.gZone[i].x * 64 + ' ' + + state.gZone[i].y * 64 + ' ' + + (state.gZone[i].xTouched ? 'x' : '') + + (state.gZone[i].yTouched ? 'y' : '') + ); + } + console.log('GZ', da); + } + + if (state.tZone) { + da = []; + for (let i = 0; i < state.tZone.length; i++) { + da.push(i + ' ' + + state.tZone[i].x * 64 + ' ' + + state.tZone[i].y * 64 + ' ' + + (state.tZone[i].xTouched ? 'x' : '') + + (state.tZone[i].yTouched ? 'y' : '') + ); + } + console.log('TZ', da); + } + + if (state.stack.length > 10) { + console.log( + state.stack.length, + '...', state.stack.slice(state.stack.length - 10) + ); + } else { + console.log(state.stack.length, state.stack); + } + } + */ + } + }; + + /* + * Initializes the twilight zone. + * + * This is only done if a SZPx instruction + * refers to the twilight zone. + */ + function initTZone(state) + { + var tZone = state.tZone = new Array(state.gZone.length); + + // no idea if this is actually correct... + for (var i = 0; i < tZone.length; i++) + { + tZone[i] = new HPoint(0, 0); + } + } + + /* + * Skips the instruction pointer ahead over an IF/ELSE block. + * handleElse .. if true breaks on matching ELSE + */ + function skip(state, handleElse) + { + var prog = state.prog; + var ip = state.ip; + var nesting = 1; + var ins; + + do { + ins = prog[++ip]; + if (ins === 0x58) // IF + { nesting++; } + else if (ins === 0x59) // EIF + { nesting--; } + else if (ins === 0x40) // NPUSHB + { ip += prog[ip + 1] + 1; } + else if (ins === 0x41) // NPUSHW + { ip += 2 * prog[ip + 1] + 1; } + else if (ins >= 0xB0 && ins <= 0xB7) // PUSHB + { ip += ins - 0xB0 + 1; } + else if (ins >= 0xB8 && ins <= 0xBF) // PUSHW + { ip += (ins - 0xB8 + 1) * 2; } + else if (handleElse && nesting === 1 && ins === 0x1B) // ELSE + { break; } + } while (nesting > 0); + + state.ip = ip; + } + + /*----------------------------------------------------------* + * And then a lot of instructions... * + *----------------------------------------------------------*/ + + // SVTCA[a] Set freedom and projection Vectors To Coordinate Axis + // 0x00-0x01 + function SVTCA(v, state) { + if (exports.DEBUG) { console.log(state.step, 'SVTCA[' + v.axis + ']'); } + + state.fv = state.pv = state.dpv = v; + } + + // SPVTCA[a] Set Projection Vector to Coordinate Axis + // 0x02-0x03 + function SPVTCA(v, state) { + if (exports.DEBUG) { console.log(state.step, 'SPVTCA[' + v.axis + ']'); } + + state.pv = state.dpv = v; + } + + // SFVTCA[a] Set Freedom Vector to Coordinate Axis + // 0x04-0x05 + function SFVTCA(v, state) { + if (exports.DEBUG) { console.log(state.step, 'SFVTCA[' + v.axis + ']'); } + + state.fv = v; + } + + // SPVTL[a] Set Projection Vector To Line + // 0x06-0x07 + function SPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + + if (exports.DEBUG) { console.log('SPVTL[' + a + ']', p2i, p1i); } + + var dx; + var dy; + + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + + state.pv = state.dpv = getUnitVector(dx, dy); + } + + // SFVTL[a] Set Freedom Vector To Line + // 0x08-0x09 + function SFVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + + if (exports.DEBUG) { console.log('SFVTL[' + a + ']', p2i, p1i); } + + var dx; + var dy; + + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + + state.fv = getUnitVector(dx, dy); + } + + // SPVFS[] Set Projection Vector From Stack + // 0x0A + function SPVFS(state) { + var stack = state.stack; + var y = stack.pop(); + var x = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); } + + state.pv = state.dpv = getUnitVector(x, y); + } + + // SFVFS[] Set Freedom Vector From Stack + // 0x0B + function SFVFS(state) { + var stack = state.stack; + var y = stack.pop(); + var x = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SPVFS[]', y, x); } + + state.fv = getUnitVector(x, y); + } + + // GPV[] Get Projection Vector + // 0x0C + function GPV(state) { + var stack = state.stack; + var pv = state.pv; + + if (exports.DEBUG) { console.log(state.step, 'GPV[]'); } + + stack.push(pv.x * 0x4000); + stack.push(pv.y * 0x4000); + } + + // GFV[] Get Freedom Vector + // 0x0C + function GFV(state) { + var stack = state.stack; + var fv = state.fv; + + if (exports.DEBUG) { console.log(state.step, 'GFV[]'); } + + stack.push(fv.x * 0x4000); + stack.push(fv.y * 0x4000); + } + + // SFVTPV[] Set Freedom Vector To Projection Vector + // 0x0E + function SFVTPV(state) { + state.fv = state.pv; + + if (exports.DEBUG) { console.log(state.step, 'SFVTPV[]'); } + } + + // ISECT[] moves point p to the InterSECTion of two lines + // 0x0F + function ISECT(state) + { + var stack = state.stack; + var pa0i = stack.pop(); + var pa1i = stack.pop(); + var pb0i = stack.pop(); + var pb1i = stack.pop(); + var pi = stack.pop(); + var z0 = state.z0; + var z1 = state.z1; + var pa0 = z0[pa0i]; + var pa1 = z0[pa1i]; + var pb0 = z1[pb0i]; + var pb1 = z1[pb1i]; + var p = state.z2[pi]; + + if (exports.DEBUG) { console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi); } + + // math from + // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line + + var x1 = pa0.x; + var y1 = pa0.y; + var x2 = pa1.x; + var y2 = pa1.y; + var x3 = pb0.x; + var y3 = pb0.y; + var x4 = pb1.x; + var y4 = pb1.y; + + var div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); + var f1 = x1 * y2 - y1 * x2; + var f2 = x3 * y4 - y3 * x4; + + p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div; + p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div; + } + + // SRP0[] Set Reference Point 0 + // 0x10 + function SRP0(state) { + state.rp0 = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SRP0[]', state.rp0); } + } + + // SRP1[] Set Reference Point 1 + // 0x11 + function SRP1(state) { + state.rp1 = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SRP1[]', state.rp1); } + } + + // SRP1[] Set Reference Point 2 + // 0x12 + function SRP2(state) { + state.rp2 = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SRP2[]', state.rp2); } + } + + // SZP0[] Set Zone Pointer 0 + // 0x13 + function SZP0(state) { + var n = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SZP0[]', n); } + + state.zp0 = n; + + switch (n) { + case 0: + if (!state.tZone) { initTZone(state); } + state.z0 = state.tZone; + break; + case 1 : + state.z0 = state.gZone; + break; + default : + throw new Error('Invalid zone pointer'); + } + } + + // SZP1[] Set Zone Pointer 1 + // 0x14 + function SZP1(state) { + var n = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SZP1[]', n); } + + state.zp1 = n; + + switch (n) { + case 0: + if (!state.tZone) { initTZone(state); } + state.z1 = state.tZone; + break; + case 1 : + state.z1 = state.gZone; + break; + default : + throw new Error('Invalid zone pointer'); + } + } + + // SZP2[] Set Zone Pointer 2 + // 0x15 + function SZP2(state) { + var n = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SZP2[]', n); } + + state.zp2 = n; + + switch (n) { + case 0: + if (!state.tZone) { initTZone(state); } + state.z2 = state.tZone; + break; + case 1 : + state.z2 = state.gZone; + break; + default : + throw new Error('Invalid zone pointer'); + } + } + + // SZPS[] Set Zone PointerS + // 0x16 + function SZPS(state) { + var n = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SZPS[]', n); } + + state.zp0 = state.zp1 = state.zp2 = n; + + switch (n) { + case 0: + if (!state.tZone) { initTZone(state); } + state.z0 = state.z1 = state.z2 = state.tZone; + break; + case 1 : + state.z0 = state.z1 = state.z2 = state.gZone; + break; + default : + throw new Error('Invalid zone pointer'); + } + } + + // SLOOP[] Set LOOP variable + // 0x17 + function SLOOP(state) { + state.loop = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SLOOP[]', state.loop); } + } + + // RTG[] Round To Grid + // 0x18 + function RTG(state) { + if (exports.DEBUG) { console.log(state.step, 'RTG[]'); } + + state.round = roundToGrid; + } + + // RTHG[] Round To Half Grid + // 0x19 + function RTHG(state) { + if (exports.DEBUG) { console.log(state.step, 'RTHG[]'); } + + state.round = roundToHalfGrid; + } + + // SMD[] Set Minimum Distance + // 0x1A + function SMD(state) { + var d = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SMD[]', d); } + + state.minDis = d / 0x40; + } + + // ELSE[] ELSE clause + // 0x1B + function ELSE(state) { + // This instruction has been reached by executing a then branch + // so it just skips ahead until matching EIF. + // + // In case the IF was negative the IF[] instruction already + // skipped forward over the ELSE[] + + if (exports.DEBUG) { console.log(state.step, 'ELSE[]'); } + + skip(state, false); + } + + // JMPR[] JuMP Relative + // 0x1C + function JMPR(state) { + var o = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'JMPR[]', o); } + + // A jump by 1 would do nothing. + state.ip += o - 1; + } + + // SCVTCI[] Set Control Value Table Cut-In + // 0x1D + function SCVTCI(state) { + var n = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SCVTCI[]', n); } + + state.cvCutIn = n / 0x40; + } + + // DUP[] DUPlicate top stack element + // 0x20 + function DUP(state) { + var stack = state.stack; + + if (exports.DEBUG) { console.log(state.step, 'DUP[]'); } + + stack.push(stack[stack.length - 1]); + } + + // POP[] POP top stack element + // 0x21 + function POP(state) { + if (exports.DEBUG) { console.log(state.step, 'POP[]'); } + + state.stack.pop(); + } + + // CLEAR[] CLEAR the stack + // 0x22 + function CLEAR(state) { + if (exports.DEBUG) { console.log(state.step, 'CLEAR[]'); } + + state.stack.length = 0; + } + + // SWAP[] SWAP the top two elements on the stack + // 0x23 + function SWAP(state) { + var stack = state.stack; + + var a = stack.pop(); + var b = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SWAP[]'); } + + stack.push(a); + stack.push(b); + } + + // DEPTH[] DEPTH of the stack + // 0x24 + function DEPTH(state) { + var stack = state.stack; + + if (exports.DEBUG) { console.log(state.step, 'DEPTH[]'); } + + stack.push(stack.length); + } + + // LOOPCALL[] LOOPCALL function + // 0x2A + function LOOPCALL(state) { + var stack = state.stack; + var fn = stack.pop(); + var c = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'LOOPCALL[]', fn, c); } + + // saves callers program + var cip = state.ip; + var cprog = state.prog; + + state.prog = state.funcs[fn]; + + // executes the function + for (var i = 0; i < c; i++) { + exec(state); + + if (exports.DEBUG) { console.log( + ++state.step, + i + 1 < c ? 'next loopcall' : 'done loopcall', + i + ); } + } + + // restores the callers program + state.ip = cip; + state.prog = cprog; + } + + // CALL[] CALL function + // 0x2B + function CALL(state) { + var fn = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'CALL[]', fn); } + + // saves callers program + var cip = state.ip; + var cprog = state.prog; + + state.prog = state.funcs[fn]; + + // executes the function + exec(state); + + // restores the callers program + state.ip = cip; + state.prog = cprog; + + if (exports.DEBUG) { console.log(++state.step, 'returning from', fn); } + } + + // CINDEX[] Copy the INDEXed element to the top of the stack + // 0x25 + function CINDEX(state) { + var stack = state.stack; + var k = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'CINDEX[]', k); } + + // In case of k == 1, it copies the last element after popping + // thus stack.length - k. + stack.push(stack[stack.length - k]); + } + + // MINDEX[] Move the INDEXed element to the top of the stack + // 0x26 + function MINDEX(state) { + var stack = state.stack; + var k = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'MINDEX[]', k); } + + stack.push(stack.splice(stack.length - k, 1)[0]); + } + + // FDEF[] Function DEFinition + // 0x2C + function FDEF(state) { + if (state.env !== 'fpgm') { throw new Error('FDEF not allowed here'); } + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + + var fn = stack.pop(); + var ipBegin = ip; + + if (exports.DEBUG) { console.log(state.step, 'FDEF[]', fn); } + + while (prog[++ip] !== 0x2D){ } + + state.ip = ip; + state.funcs[fn] = prog.slice(ipBegin + 1, ip); + } + + // MDAP[a] Move Direct Absolute Point + // 0x2E-0x2F + function MDAP(round, state) { + var pi = state.stack.pop(); + var p = state.z0[pi]; + var fv = state.fv; + var pv = state.pv; + + if (exports.DEBUG) { console.log(state.step, 'MDAP[' + round + ']', pi); } + + var d = pv.distance(p, HPZero); + + if (round) { d = state.round(d); } + + fv.setRelative(p, HPZero, d, pv); + fv.touch(p); + + state.rp0 = state.rp1 = pi; + } + + // IUP[a] Interpolate Untouched Points through the outline + // 0x30 + function IUP(v, state) { + var z2 = state.z2; + var pLen = z2.length - 2; + var cp; + var pp; + var np; + + if (exports.DEBUG) { console.log(state.step, 'IUP[' + v.axis + ']'); } + + for (var i = 0; i < pLen; i++) { + cp = z2[i]; // current point + + // if this point has been touched go on + if (v.touched(cp)) { continue; } + + pp = cp.prevTouched(v); + + // no point on the contour has been touched? + if (pp === cp) { continue; } + + np = cp.nextTouched(v); + + if (pp === np) { + // only one point on the contour has been touched + // so simply moves the point like that + + v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); + } + + v.interpolate(cp, pp, np, v); + } + } + + // SHP[] SHift Point using reference point + // 0x32-0x33 + function SHP(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var loop = state.loop; + var z2 = state.z2; + + while (loop--) + { + var pi = stack.pop(); + var p = z2[pi]; + + var d = pv.distance(rp, rp, false, true); + fv.setRelative(p, p, d, pv); + fv.touch(p); + + if (exports.DEBUG) { + console.log( + state.step, + (state.loop > 1 ? + 'loop ' + (state.loop - loop) + ': ' : + '' + ) + + 'SHP[' + (a ? 'rp1' : 'rp2') + ']', pi + ); + } + } + + state.loop = 1; + } + + // SHC[] SHift Contour using reference point + // 0x36-0x37 + function SHC(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var ci = stack.pop(); + var sp = state.z2[state.contours[ci]]; + var p = sp; + + if (exports.DEBUG) { console.log(state.step, 'SHC[' + a + ']', ci); } + + var d = pv.distance(rp, rp, false, true); + + do { + if (p !== rp) { fv.setRelative(p, p, d, pv); } + p = p.nextPointOnContour; + } while (p !== sp); + } + + // SHZ[] SHift Zone using reference point + // 0x36-0x37 + function SHZ(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + + var e = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SHZ[' + a + ']', e); } + + var z; + switch (e) { + case 0 : z = state.tZone; break; + case 1 : z = state.gZone; break; + default : throw new Error('Invalid zone'); + } + + var p; + var d = pv.distance(rp, rp, false, true); + var pLen = z.length - 2; + for (var i = 0; i < pLen; i++) + { + p = z[i]; + fv.setRelative(p, p, d, pv); + //if (p !== rp) fv.setRelative(p, p, d, pv); + } + } + + // SHPIX[] SHift point by a PIXel amount + // 0x38 + function SHPIX(state) { + var stack = state.stack; + var loop = state.loop; + var fv = state.fv; + var d = stack.pop() / 0x40; + var z2 = state.z2; + + while (loop--) { + var pi = stack.pop(); + var p = z2[pi]; + + if (exports.DEBUG) { + console.log( + state.step, + (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + + 'SHPIX[]', pi, d + ); + } + + fv.setRelative(p, p, d); + fv.touch(p); + } + + state.loop = 1; + } + + // IP[] Interpolate Point + // 0x39 + function IP(state) { + var stack = state.stack; + var rp1i = state.rp1; + var rp2i = state.rp2; + var loop = state.loop; + var rp1 = state.z0[rp1i]; + var rp2 = state.z1[rp2i]; + var fv = state.fv; + var pv = state.dpv; + var z2 = state.z2; + + while (loop--) { + var pi = stack.pop(); + var p = z2[pi]; + + if (exports.DEBUG) { + console.log( + state.step, + (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + + 'IP[]', pi, rp1i, '<->', rp2i + ); + } + + fv.interpolate(p, rp1, rp2, pv); + + fv.touch(p); + } + + state.loop = 1; + } + + // MSIRP[a] Move Stack Indirect Relative Point + // 0x3A-0x3B + function MSIRP(a, state) { + var stack = state.stack; + var d = stack.pop() / 64; + var pi = stack.pop(); + var p = state.z1[pi]; + var rp0 = state.z0[state.rp0]; + var fv = state.fv; + var pv = state.pv; + + fv.setRelative(p, rp0, d, pv); + fv.touch(p); + + if (exports.DEBUG) { console.log(state.step, 'MSIRP[' + a + ']', d, pi); } + + state.rp1 = state.rp0; + state.rp2 = pi; + if (a) { state.rp0 = pi; } + } + + // ALIGNRP[] Align to reference point. + // 0x3C + function ALIGNRP(state) { + var stack = state.stack; + var rp0i = state.rp0; + var rp0 = state.z0[rp0i]; + var loop = state.loop; + var fv = state.fv; + var pv = state.pv; + var z1 = state.z1; + + while (loop--) { + var pi = stack.pop(); + var p = z1[pi]; + + if (exports.DEBUG) { + console.log( + state.step, + (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + + 'ALIGNRP[]', pi + ); + } + + fv.setRelative(p, rp0, 0, pv); + fv.touch(p); + } + + state.loop = 1; + } + + // RTG[] Round To Double Grid + // 0x3D + function RTDG(state) { + if (exports.DEBUG) { console.log(state.step, 'RTDG[]'); } + + state.round = roundToDoubleGrid; + } + + // MIAP[a] Move Indirect Absolute Point + // 0x3E-0x3F + function MIAP(round, state) { + var stack = state.stack; + var n = stack.pop(); + var pi = stack.pop(); + var p = state.z0[pi]; + var fv = state.fv; + var pv = state.pv; + var cv = state.cvt[n]; + + if (exports.DEBUG) { + console.log( + state.step, + 'MIAP[' + round + ']', + n, '(', cv, ')', pi + ); + } + + var d = pv.distance(p, HPZero); + + if (round) { + if (Math.abs(d - cv) < state.cvCutIn) { d = cv; } + + d = state.round(d); + } + + fv.setRelative(p, HPZero, d, pv); + + if (state.zp0 === 0) { + p.xo = p.x; + p.yo = p.y; + } + + fv.touch(p); + + state.rp0 = state.rp1 = pi; + } + + // NPUSB[] PUSH N Bytes + // 0x40 + function NPUSHB(state) { + var prog = state.prog; + var ip = state.ip; + var stack = state.stack; + + var n = prog[++ip]; + + if (exports.DEBUG) { console.log(state.step, 'NPUSHB[]', n); } + + for (var i = 0; i < n; i++) { stack.push(prog[++ip]); } + + state.ip = ip; + } + + // NPUSHW[] PUSH N Words + // 0x41 + function NPUSHW(state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + var n = prog[++ip]; + + if (exports.DEBUG) { console.log(state.step, 'NPUSHW[]', n); } + + for (var i = 0; i < n; i++) { + var w = (prog[++ip] << 8) | prog[++ip]; + if (w & 0x8000) { w = -((w ^ 0xffff) + 1); } + stack.push(w); + } + + state.ip = ip; + } + + // WS[] Write Store + // 0x42 + function WS(state) { + var stack = state.stack; + var store = state.store; + + if (!store) { store = state.store = []; } + + var v = stack.pop(); + var l = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'WS', v, l); } + + store[l] = v; + } + + // RS[] Read Store + // 0x43 + function RS(state) { + var stack = state.stack; + var store = state.store; + + var l = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'RS', l); } + + var v = (store && store[l]) || 0; + + stack.push(v); + } + + // WCVTP[] Write Control Value Table in Pixel units + // 0x44 + function WCVTP(state) { + var stack = state.stack; + + var v = stack.pop(); + var l = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'WCVTP', v, l); } + + state.cvt[l] = v / 0x40; + } + + // RCVT[] Read Control Value Table entry + // 0x45 + function RCVT(state) { + var stack = state.stack; + var cvte = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'RCVT', cvte); } + + stack.push(state.cvt[cvte] * 0x40); + } + + // GC[] Get Coordinate projected onto the projection vector + // 0x46-0x47 + function GC(a, state) { + var stack = state.stack; + var pi = stack.pop(); + var p = state.z2[pi]; + + if (exports.DEBUG) { console.log(state.step, 'GC[' + a + ']', pi); } + + stack.push(state.dpv.distance(p, HPZero, a, false) * 0x40); + } + + // MD[a] Measure Distance + // 0x49-0x4A + function MD(a, state) { + var stack = state.stack; + var pi2 = stack.pop(); + var pi1 = stack.pop(); + var p2 = state.z1[pi2]; + var p1 = state.z0[pi1]; + var d = state.dpv.distance(p1, p2, a, a); + + if (exports.DEBUG) { console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d); } + + state.stack.push(Math.round(d * 64)); + } + + // MPPEM[] Measure Pixels Per EM + // 0x4B + function MPPEM(state) { + if (exports.DEBUG) { console.log(state.step, 'MPPEM[]'); } + state.stack.push(state.ppem); + } + + // FLIPON[] set the auto FLIP Boolean to ON + // 0x4D + function FLIPON(state) { + if (exports.DEBUG) { console.log(state.step, 'FLIPON[]'); } + state.autoFlip = true; + } + + // LT[] Less Than + // 0x50 + function LT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'LT[]', e2, e1); } + + stack.push(e1 < e2 ? 1 : 0); + } + + // LTEQ[] Less Than or EQual + // 0x53 + function LTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'LTEQ[]', e2, e1); } + + stack.push(e1 <= e2 ? 1 : 0); + } + + // GTEQ[] Greater Than + // 0x52 + function GT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'GT[]', e2, e1); } + + stack.push(e1 > e2 ? 1 : 0); + } + + // GTEQ[] Greater Than or EQual + // 0x53 + function GTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'GTEQ[]', e2, e1); } + + stack.push(e1 >= e2 ? 1 : 0); + } + + // EQ[] EQual + // 0x54 + function EQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'EQ[]', e2, e1); } + + stack.push(e2 === e1 ? 1 : 0); + } + + // NEQ[] Not EQual + // 0x55 + function NEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'NEQ[]', e2, e1); } + + stack.push(e2 !== e1 ? 1 : 0); + } + + // ODD[] ODD + // 0x56 + function ODD(state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'ODD[]', n); } + + stack.push(Math.trunc(n) % 2 ? 1 : 0); + } + + // EVEN[] EVEN + // 0x57 + function EVEN(state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'EVEN[]', n); } + + stack.push(Math.trunc(n) % 2 ? 0 : 1); + } + + // IF[] IF test + // 0x58 + function IF(state) { + var test = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'IF[]', test); } + + // if test is true it just continues + // if not the ip is skipped until matching ELSE or EIF + if (!test) { + skip(state, true); + + if (exports.DEBUG) { console.log(state.step, 'EIF[]'); } + } + } + + // EIF[] End IF + // 0x59 + function EIF(state) { + // this can be reached normally when + // executing an else branch. + // -> just ignore it + + if (exports.DEBUG) { console.log(state.step, 'EIF[]'); } + } + + // AND[] logical AND + // 0x5A + function AND(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'AND[]', e2, e1); } + + stack.push(e2 && e1 ? 1 : 0); + } + + // OR[] logical OR + // 0x5B + function OR(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'OR[]', e2, e1); } + + stack.push(e2 || e1 ? 1 : 0); + } + + // NOT[] logical NOT + // 0x5C + function NOT(state) { + var stack = state.stack; + var e = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'NOT[]', e); } + + stack.push(e ? 0 : 1); + } + + // DELTAP1[] DELTA exception P1 + // DELTAP2[] DELTA exception P2 + // DELTAP3[] DELTA exception P3 + // 0x5D, 0x71, 0x72 + function DELTAP123(b, state) { + var stack = state.stack; + var n = stack.pop(); + var fv = state.fv; + var pv = state.pv; + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + var z0 = state.z0; + + if (exports.DEBUG) { console.log(state.step, 'DELTAP[' + b + ']', n, stack); } + + for (var i = 0; i < n; i++) { + var pi = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 0xF0) >> 4); + if (appem !== ppem) { continue; } + + var mag = (arg & 0x0F) - 8; + if (mag >= 0) { mag++; } + if (exports.DEBUG) { console.log(state.step, 'DELTAPFIX', pi, 'by', mag * ds); } + + var p = z0[pi]; + fv.setRelative(p, p, mag * ds, pv); + } + } + + // SDB[] Set Delta Base in the graphics state + // 0x5E + function SDB(state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SDB[]', n); } + + state.deltaBase = n; + } + + // SDS[] Set Delta Shift in the graphics state + // 0x5F + function SDS(state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SDS[]', n); } + + state.deltaShift = Math.pow(0.5, n); + } + + // ADD[] ADD + // 0x60 + function ADD(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'ADD[]', n2, n1); } + + stack.push(n1 + n2); + } + + // SUB[] SUB + // 0x61 + function SUB(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SUB[]', n2, n1); } + + stack.push(n1 - n2); + } + + // DIV[] DIV + // 0x62 + function DIV(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'DIV[]', n2, n1); } + + stack.push(n1 * 64 / n2); + } + + // MUL[] MUL + // 0x63 + function MUL(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'MUL[]', n2, n1); } + + stack.push(n1 * n2 / 64); + } + + // ABS[] ABSolute value + // 0x64 + function ABS(state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'ABS[]', n); } + + stack.push(Math.abs(n)); + } + + // NEG[] NEGate + // 0x65 + function NEG(state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'NEG[]', n); } + + stack.push(-n); + } + + // FLOOR[] FLOOR + // 0x66 + function FLOOR(state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'FLOOR[]', n); } + + stack.push(Math.floor(n / 0x40) * 0x40); + } + + // CEILING[] CEILING + // 0x67 + function CEILING(state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'CEILING[]', n); } + + stack.push(Math.ceil(n / 0x40) * 0x40); + } + + // ROUND[ab] ROUND value + // 0x68-0x6B + function ROUND(dt, state) { + var stack = state.stack; + var n = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'ROUND[]'); } + + stack.push(state.round(n / 0x40) * 0x40); + } + + // WCVTF[] Write Control Value Table in Funits + // 0x70 + function WCVTF(state) { + var stack = state.stack; + var v = stack.pop(); + var l = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'WCVTF[]', v, l); } + + state.cvt[l] = v * state.ppem / state.font.unitsPerEm; + } + + // DELTAC1[] DELTA exception C1 + // DELTAC2[] DELTA exception C2 + // DELTAC3[] DELTA exception C3 + // 0x73, 0x74, 0x75 + function DELTAC123(b, state) { + var stack = state.stack; + var n = stack.pop(); + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + + if (exports.DEBUG) { console.log(state.step, 'DELTAC[' + b + ']', n, stack); } + + for (var i = 0; i < n; i++) { + var c = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 0xF0) >> 4); + if (appem !== ppem) { continue; } + + var mag = (arg & 0x0F) - 8; + if (mag >= 0) { mag++; } + + var delta = mag * ds; + + if (exports.DEBUG) { console.log(state.step, 'DELTACFIX', c, 'by', delta); } + + state.cvt[c] += delta; + } + } + + // SROUND[] Super ROUND + // 0x76 + function SROUND(state) { + var n = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'SROUND[]', n); } + + state.round = roundSuper; + + var period; + + switch (n & 0xC0) { + case 0x00: + period = 0.5; + break; + case 0x40: + period = 1; + break; + case 0x80: + period = 2; + break; + default: + throw new Error('invalid SROUND value'); + } + + state.srPeriod = period; + + switch (n & 0x30) { + case 0x00: + state.srPhase = 0; + break; + case 0x10: + state.srPhase = 0.25 * period; + break; + case 0x20: + state.srPhase = 0.5 * period; + break; + case 0x30: + state.srPhase = 0.75 * period; + break; + default: throw new Error('invalid SROUND value'); + } + + n &= 0x0F; + + if (n === 0) { state.srThreshold = 0; } + else { state.srThreshold = (n / 8 - 0.5) * period; } + } + + // S45ROUND[] Super ROUND 45 degrees + // 0x77 + function S45ROUND(state) { + var n = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'S45ROUND[]', n); } + + state.round = roundSuper; + + var period; + + switch (n & 0xC0) { + case 0x00: + period = Math.sqrt(2) / 2; + break; + case 0x40: + period = Math.sqrt(2); + break; + case 0x80: + period = 2 * Math.sqrt(2); + break; + default: + throw new Error('invalid S45ROUND value'); + } + + state.srPeriod = period; + + switch (n & 0x30) { + case 0x00: + state.srPhase = 0; + break; + case 0x10: + state.srPhase = 0.25 * period; + break; + case 0x20: + state.srPhase = 0.5 * period; + break; + case 0x30: + state.srPhase = 0.75 * period; + break; + default: + throw new Error('invalid S45ROUND value'); + } + + n &= 0x0F; + + if (n === 0) { state.srThreshold = 0; } + else { state.srThreshold = (n / 8 - 0.5) * period; } + } + + // ROFF[] Round Off + // 0x7A + function ROFF(state) { + if (exports.DEBUG) { console.log(state.step, 'ROFF[]'); } + + state.round = roundOff; + } + + // RUTG[] Round Up To Grid + // 0x7C + function RUTG(state) { + if (exports.DEBUG) { console.log(state.step, 'RUTG[]'); } + + state.round = roundUpToGrid; + } + + // RDTG[] Round Down To Grid + // 0x7D + function RDTG(state) { + if (exports.DEBUG) { console.log(state.step, 'RDTG[]'); } + + state.round = roundDownToGrid; + } + + // SCANCTRL[] SCAN conversion ConTRoL + // 0x85 + function SCANCTRL(state) { + var n = state.stack.pop(); + + // ignored by opentype.js + + if (exports.DEBUG) { console.log(state.step, 'SCANCTRL[]', n); } + } + + // SDPVTL[a] Set Dual Projection Vector To Line + // 0x86-0x87 + function SDPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + + if (exports.DEBUG) { console.log(state.step, 'SDPVTL[' + a + ']', p2i, p1i); } + + var dx; + var dy; + + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + + state.dpv = getUnitVector(dx, dy); + } + + // GETINFO[] GET INFOrmation + // 0x88 + function GETINFO(state) { + var stack = state.stack; + var sel = stack.pop(); + var r = 0; + + if (exports.DEBUG) { console.log(state.step, 'GETINFO[]', sel); } + + // v35 as in no subpixel hinting + if (sel & 0x01) { r = 35; } + + // TODO rotation and stretch currently not supported + // and thus those GETINFO are always 0. + + // opentype.js is always gray scaling + if (sel & 0x20) { r |= 0x1000; } + + stack.push(r); + } + + // ROLL[] ROLL the top three stack elements + // 0x8A + function ROLL(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + var c = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'ROLL[]'); } + + stack.push(b); + stack.push(a); + stack.push(c); + } + + // MAX[] MAXimum of top two stack elements + // 0x8B + function MAX(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'MAX[]', e2, e1); } + + stack.push(Math.max(e1, e2)); + } + + // MIN[] MINimum of top two stack elements + // 0x8C + function MIN(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'MIN[]', e2, e1); } + + stack.push(Math.min(e1, e2)); + } + + // SCANTYPE[] SCANTYPE + // 0x8D + function SCANTYPE(state) { + var n = state.stack.pop(); + // ignored by opentype.js + if (exports.DEBUG) { console.log(state.step, 'SCANTYPE[]', n); } + } + + // INSTCTRL[] INSTCTRL + // 0x8D + function INSTCTRL(state) { + var s = state.stack.pop(); + var v = state.stack.pop(); + + if (exports.DEBUG) { console.log(state.step, 'INSTCTRL[]', s, v); } + + switch (s) { + case 1 : state.inhibitGridFit = !!v; return; + case 2 : state.ignoreCvt = !!v; return; + default: throw new Error('invalid INSTCTRL[] selector'); + } + } + + // PUSHB[abc] PUSH Bytes + // 0xB0-0xB7 + function PUSHB(n, state) { + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + + if (exports.DEBUG) { console.log(state.step, 'PUSHB[' + n + ']'); } + + for (var i = 0; i < n; i++) { stack.push(prog[++ip]); } + + state.ip = ip; + } + + // PUSHW[abc] PUSH Words + // 0xB8-0xBF + function PUSHW(n, state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + + if (exports.DEBUG) { console.log(state.ip, 'PUSHW[' + n + ']'); } + + for (var i = 0; i < n; i++) { + var w = (prog[++ip] << 8) | prog[++ip]; + if (w & 0x8000) { w = -((w ^ 0xffff) + 1); } + stack.push(w); + } + + state.ip = ip; + } + + // MDRP[abcde] Move Direct Relative Point + // 0xD0-0xEF + // (if indirect is 0) + // + // and + // + // MIRP[abcde] Move Indirect Relative Point + // 0xE0-0xFF + // (if indirect is 1) + + function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { + var stack = state.stack; + var cvte = indirect && stack.pop(); + var pi = stack.pop(); + var rp0i = state.rp0; + var rp = state.z0[rp0i]; + var p = state.z1[pi]; + + var md = state.minDis; + var fv = state.fv; + var pv = state.dpv; + var od; // original distance + var d; // moving distance + var sign; // sign of distance + var cv; + + d = od = pv.distance(p, rp, true, true); + sign = d >= 0 ? 1 : -1; // Math.sign would be 0 in case of 0 + + // TODO consider autoFlip + d = Math.abs(d); + + if (indirect) { + cv = state.cvt[cvte]; + + if (ro && Math.abs(d - cv) < state.cvCutIn) { d = cv; } + } + + if (keepD && d < md) { d = md; } + + if (ro) { d = state.round(d); } + + fv.setRelative(p, rp, sign * d, pv); + fv.touch(p); + + if (exports.DEBUG) { + console.log( + state.step, + (indirect ? 'MIRP[' : 'MDRP[') + + (setRp0 ? 'M' : 'm') + + (keepD ? '>' : '_') + + (ro ? 'R' : '_') + + (dt === 0 ? 'Gr' : (dt === 1 ? 'Bl' : (dt === 2 ? 'Wh' : ''))) + + ']', + indirect ? + cvte + '(' + state.cvt[cvte] + ',' + cv + ')' : + '', + pi, + '(d =', od, '->', sign * d, ')' + ); + } + + state.rp1 = state.rp0; + state.rp2 = pi; + if (setRp0) { state.rp0 = pi; } + } + + /* + * The instruction table. + */ + instructionTable = [ + /* 0x00 */ SVTCA.bind(undefined, yUnitVector), + /* 0x01 */ SVTCA.bind(undefined, xUnitVector), + /* 0x02 */ SPVTCA.bind(undefined, yUnitVector), + /* 0x03 */ SPVTCA.bind(undefined, xUnitVector), + /* 0x04 */ SFVTCA.bind(undefined, yUnitVector), + /* 0x05 */ SFVTCA.bind(undefined, xUnitVector), + /* 0x06 */ SPVTL.bind(undefined, 0), + /* 0x07 */ SPVTL.bind(undefined, 1), + /* 0x08 */ SFVTL.bind(undefined, 0), + /* 0x09 */ SFVTL.bind(undefined, 1), + /* 0x0A */ SPVFS, + /* 0x0B */ SFVFS, + /* 0x0C */ GPV, + /* 0x0D */ GFV, + /* 0x0E */ SFVTPV, + /* 0x0F */ ISECT, + /* 0x10 */ SRP0, + /* 0x11 */ SRP1, + /* 0x12 */ SRP2, + /* 0x13 */ SZP0, + /* 0x14 */ SZP1, + /* 0x15 */ SZP2, + /* 0x16 */ SZPS, + /* 0x17 */ SLOOP, + /* 0x18 */ RTG, + /* 0x19 */ RTHG, + /* 0x1A */ SMD, + /* 0x1B */ ELSE, + /* 0x1C */ JMPR, + /* 0x1D */ SCVTCI, + /* 0x1E */ undefined, // TODO SSWCI + /* 0x1F */ undefined, // TODO SSW + /* 0x20 */ DUP, + /* 0x21 */ POP, + /* 0x22 */ CLEAR, + /* 0x23 */ SWAP, + /* 0x24 */ DEPTH, + /* 0x25 */ CINDEX, + /* 0x26 */ MINDEX, + /* 0x27 */ undefined, // TODO ALIGNPTS + /* 0x28 */ undefined, + /* 0x29 */ undefined, // TODO UTP + /* 0x2A */ LOOPCALL, + /* 0x2B */ CALL, + /* 0x2C */ FDEF, + /* 0x2D */ undefined, // ENDF (eaten by FDEF) + /* 0x2E */ MDAP.bind(undefined, 0), + /* 0x2F */ MDAP.bind(undefined, 1), + /* 0x30 */ IUP.bind(undefined, yUnitVector), + /* 0x31 */ IUP.bind(undefined, xUnitVector), + /* 0x32 */ SHP.bind(undefined, 0), + /* 0x33 */ SHP.bind(undefined, 1), + /* 0x34 */ SHC.bind(undefined, 0), + /* 0x35 */ SHC.bind(undefined, 1), + /* 0x36 */ SHZ.bind(undefined, 0), + /* 0x37 */ SHZ.bind(undefined, 1), + /* 0x38 */ SHPIX, + /* 0x39 */ IP, + /* 0x3A */ MSIRP.bind(undefined, 0), + /* 0x3B */ MSIRP.bind(undefined, 1), + /* 0x3C */ ALIGNRP, + /* 0x3D */ RTDG, + /* 0x3E */ MIAP.bind(undefined, 0), + /* 0x3F */ MIAP.bind(undefined, 1), + /* 0x40 */ NPUSHB, + /* 0x41 */ NPUSHW, + /* 0x42 */ WS, + /* 0x43 */ RS, + /* 0x44 */ WCVTP, + /* 0x45 */ RCVT, + /* 0x46 */ GC.bind(undefined, 0), + /* 0x47 */ GC.bind(undefined, 1), + /* 0x48 */ undefined, // TODO SCFS + /* 0x49 */ MD.bind(undefined, 0), + /* 0x4A */ MD.bind(undefined, 1), + /* 0x4B */ MPPEM, + /* 0x4C */ undefined, // TODO MPS + /* 0x4D */ FLIPON, + /* 0x4E */ undefined, // TODO FLIPOFF + /* 0x4F */ undefined, // TODO DEBUG + /* 0x50 */ LT, + /* 0x51 */ LTEQ, + /* 0x52 */ GT, + /* 0x53 */ GTEQ, + /* 0x54 */ EQ, + /* 0x55 */ NEQ, + /* 0x56 */ ODD, + /* 0x57 */ EVEN, + /* 0x58 */ IF, + /* 0x59 */ EIF, + /* 0x5A */ AND, + /* 0x5B */ OR, + /* 0x5C */ NOT, + /* 0x5D */ DELTAP123.bind(undefined, 1), + /* 0x5E */ SDB, + /* 0x5F */ SDS, + /* 0x60 */ ADD, + /* 0x61 */ SUB, + /* 0x62 */ DIV, + /* 0x63 */ MUL, + /* 0x64 */ ABS, + /* 0x65 */ NEG, + /* 0x66 */ FLOOR, + /* 0x67 */ CEILING, + /* 0x68 */ ROUND.bind(undefined, 0), + /* 0x69 */ ROUND.bind(undefined, 1), + /* 0x6A */ ROUND.bind(undefined, 2), + /* 0x6B */ ROUND.bind(undefined, 3), + /* 0x6C */ undefined, // TODO NROUND[ab] + /* 0x6D */ undefined, // TODO NROUND[ab] + /* 0x6E */ undefined, // TODO NROUND[ab] + /* 0x6F */ undefined, // TODO NROUND[ab] + /* 0x70 */ WCVTF, + /* 0x71 */ DELTAP123.bind(undefined, 2), + /* 0x72 */ DELTAP123.bind(undefined, 3), + /* 0x73 */ DELTAC123.bind(undefined, 1), + /* 0x74 */ DELTAC123.bind(undefined, 2), + /* 0x75 */ DELTAC123.bind(undefined, 3), + /* 0x76 */ SROUND, + /* 0x77 */ S45ROUND, + /* 0x78 */ undefined, // TODO JROT[] + /* 0x79 */ undefined, // TODO JROF[] + /* 0x7A */ ROFF, + /* 0x7B */ undefined, + /* 0x7C */ RUTG, + /* 0x7D */ RDTG, + /* 0x7E */ POP, // actually SANGW, supposed to do only a pop though + /* 0x7F */ POP, // actually AA, supposed to do only a pop though + /* 0x80 */ undefined, // TODO FLIPPT + /* 0x81 */ undefined, // TODO FLIPRGON + /* 0x82 */ undefined, // TODO FLIPRGOFF + /* 0x83 */ undefined, + /* 0x84 */ undefined, + /* 0x85 */ SCANCTRL, + /* 0x86 */ SDPVTL.bind(undefined, 0), + /* 0x87 */ SDPVTL.bind(undefined, 1), + /* 0x88 */ GETINFO, + /* 0x89 */ undefined, // TODO IDEF + /* 0x8A */ ROLL, + /* 0x8B */ MAX, + /* 0x8C */ MIN, + /* 0x8D */ SCANTYPE, + /* 0x8E */ INSTCTRL, + /* 0x8F */ undefined, + /* 0x90 */ undefined, + /* 0x91 */ undefined, + /* 0x92 */ undefined, + /* 0x93 */ undefined, + /* 0x94 */ undefined, + /* 0x95 */ undefined, + /* 0x96 */ undefined, + /* 0x97 */ undefined, + /* 0x98 */ undefined, + /* 0x99 */ undefined, + /* 0x9A */ undefined, + /* 0x9B */ undefined, + /* 0x9C */ undefined, + /* 0x9D */ undefined, + /* 0x9E */ undefined, + /* 0x9F */ undefined, + /* 0xA0 */ undefined, + /* 0xA1 */ undefined, + /* 0xA2 */ undefined, + /* 0xA3 */ undefined, + /* 0xA4 */ undefined, + /* 0xA5 */ undefined, + /* 0xA6 */ undefined, + /* 0xA7 */ undefined, + /* 0xA8 */ undefined, + /* 0xA9 */ undefined, + /* 0xAA */ undefined, + /* 0xAB */ undefined, + /* 0xAC */ undefined, + /* 0xAD */ undefined, + /* 0xAE */ undefined, + /* 0xAF */ undefined, + /* 0xB0 */ PUSHB.bind(undefined, 1), + /* 0xB1 */ PUSHB.bind(undefined, 2), + /* 0xB2 */ PUSHB.bind(undefined, 3), + /* 0xB3 */ PUSHB.bind(undefined, 4), + /* 0xB4 */ PUSHB.bind(undefined, 5), + /* 0xB5 */ PUSHB.bind(undefined, 6), + /* 0xB6 */ PUSHB.bind(undefined, 7), + /* 0xB7 */ PUSHB.bind(undefined, 8), + /* 0xB8 */ PUSHW.bind(undefined, 1), + /* 0xB9 */ PUSHW.bind(undefined, 2), + /* 0xBA */ PUSHW.bind(undefined, 3), + /* 0xBB */ PUSHW.bind(undefined, 4), + /* 0xBC */ PUSHW.bind(undefined, 5), + /* 0xBD */ PUSHW.bind(undefined, 6), + /* 0xBE */ PUSHW.bind(undefined, 7), + /* 0xBF */ PUSHW.bind(undefined, 8), + /* 0xC0 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0), + /* 0xC1 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1), + /* 0xC2 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2), + /* 0xC3 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3), + /* 0xC4 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0), + /* 0xC5 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1), + /* 0xC6 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2), + /* 0xC7 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3), + /* 0xC8 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0), + /* 0xC9 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1), + /* 0xCA */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2), + /* 0xCB */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3), + /* 0xCC */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0), + /* 0xCD */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1), + /* 0xCE */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2), + /* 0xCF */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3), + /* 0xD0 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0), + /* 0xD1 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1), + /* 0xD2 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2), + /* 0xD3 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3), + /* 0xD4 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0), + /* 0xD5 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1), + /* 0xD6 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2), + /* 0xD7 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3), + /* 0xD8 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0), + /* 0xD9 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1), + /* 0xDA */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2), + /* 0xDB */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3), + /* 0xDC */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0), + /* 0xDD */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1), + /* 0xDE */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2), + /* 0xDF */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3), + /* 0xE0 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0), + /* 0xE1 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1), + /* 0xE2 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2), + /* 0xE3 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3), + /* 0xE4 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0), + /* 0xE5 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1), + /* 0xE6 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2), + /* 0xE7 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3), + /* 0xE8 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0), + /* 0xE9 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1), + /* 0xEA */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2), + /* 0xEB */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3), + /* 0xEC */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0), + /* 0xED */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1), + /* 0xEE */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2), + /* 0xEF */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3), + /* 0xF0 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0), + /* 0xF1 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1), + /* 0xF2 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2), + /* 0xF3 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3), + /* 0xF4 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0), + /* 0xF5 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1), + /* 0xF6 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2), + /* 0xF7 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3), + /* 0xF8 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0), + /* 0xF9 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1), + /* 0xFA */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2), + /* 0xFB */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3), + /* 0xFC */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0), + /* 0xFD */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1), + /* 0xFE */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2), + /* 0xFF */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3) + ]; + + /***************************** + Mathematical Considerations + ****************************** + + fv ... refers to freedom vector + pv ... refers to projection vector + rp ... refers to reference point + p ... refers to to point being operated on + d ... refers to distance + + SETRELATIVE: + ============ + + case freedom vector == x-axis: + ------------------------------ + + (pv) + .-' + rpd .-' + .-* + d .-'90°' + .-' ' + .-' ' + *-' ' b + rp ' + ' + ' + p *----------*-------------- (fv) + pm + + rpdx = rpx + d * pv.x + rpdy = rpy + d * pv.y + + equation of line b + + y - rpdy = pvns * (x- rpdx) + + y = p.y + + x = rpdx + ( p.y - rpdy ) / pvns + + + case freedom vector == y-axis: + ------------------------------ + + * pm + |\ + | \ + | \ + | \ + | \ + | \ + | \ + | \ + | \ + | \ b + | \ + | \ + | \ .-' (pv) + | 90° \.-' + | .-'* rpd + | .-' + * *-' d + p rp + + rpdx = rpx + d * pv.x + rpdy = rpy + d * pv.y + + equation of line b: + pvns ... normal slope to pv + + y - rpdy = pvns * (x - rpdx) + + x = p.x + + y = rpdy + pvns * (p.x - rpdx) + + + + generic case: + ------------- + + + .'(fv) + .' + .* pm + .' ! + .' . + .' ! + .' . b + .' ! + * . + p ! + 90° . ... (pv) + ...-*-''' + ...---''' rpd + ...---''' d + *--''' + rp + + rpdx = rpx + d * pv.x + rpdy = rpy + d * pv.y + + equation of line b: + pvns... normal slope to pv + + y - rpdy = pvns * (x - rpdx) + + equation of freedom vector line: + fvs ... slope of freedom vector (=fy/fx) + + y - py = fvs * (x - px) + + + on pm both equations are true for same x/y + + y - rpdy = pvns * (x - rpdx) + + y - py = fvs * (x - px) + + form to y and set equal: + + pvns * (x - rpdx) + rpdy = fvs * (x - px) + py + + expand: + + pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py + + switch: + + fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy + + solve for x: + + fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy + + + + fvs * px - pvns * rpdx + rpdy - py + x = ----------------------------------- + fvs - pvns + + and: + + y = fvs * (x - px) + py + + + + INTERPOLATE: + ============ + + Examples of point interpolation. + + The weight of the movement of the reference point gets bigger + the further the other reference point is away, thus the safest + option (that is avoiding 0/0 divisions) is to weight the + original distance of the other point by the sum of both distances. + + If the sum of both distances is 0, then move the point by the + arithmetic average of the movement of both reference points. + + + + + (+6) + rp1o *---->*rp1 + . . (+12) + . . rp2o *---------->* rp2 + . . . . + . . . . + . 10 20 . . + |.........|...................| . + . . . + . . (+8) . + po *------>*p . + . . . + . 12 . 24 . + |...........|.......................| + 36 + + + ------- + + + + (+10) + rp1o *-------->*rp1 + . . (-10) + . . rp2 *<---------* rpo2 + . . . . + . . . . + . 10 . 30 . . + |.........|.............................| + . . + . (+5) . + po *--->* p . + . . . + . . 20 . + |....|..............| + 5 15 + + + ------- + + + (+10) + rp1o *-------->*rp1 + . . + . . + rp2o *-------->*rp2 + + + (+10) + po *-------->* p + + ------- + + + (+10) + rp1o *-------->*rp1 + . . + . .(+30) + rp2o *---------------------------->*rp2 + + + (+25) + po *----------------------->* p + + + + vim: set ts=4 sw=4 expandtab: + *****/ + + /** + * Converts a string into a list of tokens. + */ + + /** + * Create a new token + * @param {string} char a single char + */ + function Token(char) { + this.char = char; + this.state = {}; + this.activeState = null; + } + + /** + * Create a new context range + * @param {number} startIndex range start index + * @param {number} endOffset range end index offset + * @param {string} contextName owner context name + */ + function ContextRange(startIndex, endOffset, contextName) { + this.contextName = contextName; + this.startIndex = startIndex; + this.endOffset = endOffset; + } + + /** + * Check context start and end + * @param {string} contextName a unique context name + * @param {function} checkStart a predicate function the indicates a context's start + * @param {function} checkEnd a predicate function the indicates a context's end + */ + function ContextChecker(contextName, checkStart, checkEnd) { + this.contextName = contextName; + this.openRange = null; + this.ranges = []; + this.checkStart = checkStart; + this.checkEnd = checkEnd; + } + + /** + * @typedef ContextParams + * @type Object + * @property {array} context context items + * @property {number} currentIndex current item index + */ + + /** + * Create a context params + * @param {array} context a list of items + * @param {number} currentIndex current item index + */ + function ContextParams(context, currentIndex) { + this.context = context; + this.index = currentIndex; + this.length = context.length; + this.current = context[currentIndex]; + this.backtrack = context.slice(0, currentIndex); + this.lookahead = context.slice(currentIndex + 1); + } + + /** + * Create an event instance + * @param {string} eventId event unique id + */ + function Event(eventId) { + this.eventId = eventId; + this.subscribers = []; + } + + /** + * Initialize a core events and auto subscribe required event handlers + * @param {any} events an object that enlists core events handlers + */ + function initializeCoreEvents(events) { + var this$1 = this; + + var coreEvents = [ + 'start', 'end', 'next', 'newToken', 'contextStart', + 'contextEnd', 'insertToken', 'removeToken', 'removeRange', + 'replaceToken', 'replaceRange', 'composeRUD', 'updateContextsRanges' + ]; + + coreEvents.forEach(function (eventId) { + Object.defineProperty(this$1.events, eventId, { + value: new Event(eventId) + }); + }); + + if (!!events) { + coreEvents.forEach(function (eventId) { + var event = events[eventId]; + if (typeof event === 'function') { + this$1.events[eventId].subscribe(event); + } + }); + } + var requiresContextUpdate = [ + 'insertToken', 'removeToken', 'removeRange', + 'replaceToken', 'replaceRange', 'composeRUD' + ]; + requiresContextUpdate.forEach(function (eventId) { + this$1.events[eventId].subscribe( + this$1.updateContextsRanges + ); + }); + } + + /** + * Converts a string into a list of tokens + * @param {any} events tokenizer core events + */ + function Tokenizer(events) { + this.tokens = []; + this.registeredContexts = {}; + this.contextCheckers = []; + this.events = {}; + this.registeredModifiers = []; + + initializeCoreEvents.call(this, events); + } + + /** + * Sets the state of a token, usually called by a state modifier. + * @param {string} key state item key + * @param {any} value state item value + */ + Token.prototype.setState = function(key, value) { + this.state[key] = value; + this.activeState = { key: key, value: this.state[key] }; + return this.activeState; + }; + + Token.prototype.getState = function (stateId) { + return this.state[stateId] || null; + }; + + /** + * Checks if an index exists in the tokens list. + * @param {number} index token index + */ + Tokenizer.prototype.inboundIndex = function(index) { + return index >= 0 && index < this.tokens.length; + }; + + /** + * Compose and apply a list of operations (replace, update, delete) + * @param {array} RUDs replace, update and delete operations + * TODO: Perf. Optimization (lengthBefore === lengthAfter ? dispatch once) + */ + Tokenizer.prototype.composeRUD = function (RUDs) { + var this$1 = this; + + var silent = true; + var state = RUDs.map(function (RUD) { return ( + this$1[RUD[0]].apply(this$1, RUD.slice(1).concat(silent)) + ); }); + var hasFAILObject = function (obj) { return ( + typeof obj === 'object' && + obj.hasOwnProperty('FAIL') + ); }; + if (state.every(hasFAILObject)) { + return { + FAIL: "composeRUD: one or more operations hasn't completed successfully", + report: state.filter(hasFAILObject) + }; + } + this.dispatch('composeRUD', [state.filter(function (op) { return !hasFAILObject(op); })]); + }; + + /** + * Replace a range of tokens with a list of tokens + * @param {number} startIndex range start index + * @param {number} offset range offset + * @param {token} tokens a list of tokens to replace + * @param {boolean} silent dispatch events and update context ranges + */ + Tokenizer.prototype.replaceRange = function (startIndex, offset, tokens, silent) { + offset = offset !== null ? offset : this.tokens.length; + var isTokenType = tokens.every(function (token) { return token instanceof Token; }); + if (!isNaN(startIndex) && this.inboundIndex(startIndex) && isTokenType) { + var replaced = this.tokens.splice.apply( + this.tokens, [startIndex, offset].concat(tokens) + ); + if (!silent) { this.dispatch('replaceToken', [startIndex, offset, tokens]); } + return [replaced, tokens]; + } else { + return { FAIL: 'replaceRange: invalid tokens or startIndex.' }; + } + }; + + /** + * Replace a token with another token + * @param {number} index token index + * @param {token} token a token to replace + * @param {boolean} silent dispatch events and update context ranges + */ + Tokenizer.prototype.replaceToken = function (index, token, silent) { + if (!isNaN(index) && this.inboundIndex(index) && token instanceof Token) { + var replaced = this.tokens.splice(index, 1, token); + if (!silent) { this.dispatch('replaceToken', [index, token]); } + return [replaced[0], token]; + } else { + return { FAIL: 'replaceToken: invalid token or index.' }; + } + }; + + /** + * Removes a range of tokens + * @param {number} startIndex range start index + * @param {number} offset range offset + * @param {boolean} silent dispatch events and update context ranges + */ + Tokenizer.prototype.removeRange = function(startIndex, offset, silent) { + offset = !isNaN(offset) ? offset : this.tokens.length; + var tokens = this.tokens.splice(startIndex, offset); + if (!silent) { this.dispatch('removeRange', [tokens, startIndex, offset]); } + return tokens; + }; + + /** + * Remove a token at a certain index + * @param {number} index token index + * @param {boolean} silent dispatch events and update context ranges + */ + Tokenizer.prototype.removeToken = function(index, silent) { + if (!isNaN(index) && this.inboundIndex(index)) { + var token = this.tokens.splice(index, 1); + if (!silent) { this.dispatch('removeToken', [token, index]); } + return token; + } else { + return { FAIL: 'removeToken: invalid token index.' }; + } + }; + + /** + * Insert a list of tokens at a certain index + * @param {array} tokens a list of tokens to insert + * @param {number} index insert the list of tokens at index + * @param {boolean} silent dispatch events and update context ranges + */ + Tokenizer.prototype.insertToken = function (tokens, index, silent) { + var tokenType = tokens.every( + function (token) { return token instanceof Token; } + ); + if (tokenType) { + this.tokens.splice.apply( + this.tokens, [index, 0].concat(tokens) + ); + if (!silent) { this.dispatch('insertToken', [tokens, index]); } + return tokens; + } else { + return { FAIL: 'insertToken: invalid token(s).' }; + } + }; + + /** + * A state modifier that is called on 'newToken' event + * @param {string} modifierId state modifier id + * @param {function} condition a predicate function that returns true or false + * @param {function} modifier a function to update token state + */ + Tokenizer.prototype.registerModifier = function(modifierId, condition, modifier) { + this.events.newToken.subscribe(function(token, contextParams) { + var conditionParams = [token, contextParams]; + var canApplyModifier = ( + condition === null || + condition.apply(this, conditionParams) === true + ); + var modifierParams = [token, contextParams]; + if (canApplyModifier) { + var newStateValue = modifier.apply(this, modifierParams); + token.setState(modifierId, newStateValue); + } + }); + this.registeredModifiers.push(modifierId); + }; + + /** + * Subscribe a handler to an event + * @param {function} eventHandler an event handler function + */ + Event.prototype.subscribe = function (eventHandler) { + if (typeof eventHandler === 'function') { + return ((this.subscribers.push(eventHandler)) - 1); + } else { + return { FAIL: ("invalid '" + (this.eventId) + "' event handler")}; + } + }; + + /** + * Unsubscribe an event handler + * @param {string} subsId subscription id + */ + Event.prototype.unsubscribe = function (subsId) { + this.subscribers.splice(subsId, 1); + }; + + /** + * Sets context params current value index + * @param {number} index context params current value index + */ + ContextParams.prototype.setCurrentIndex = function(index) { + this.index = index; + this.current = this.context[index]; + this.backtrack = this.context.slice(0, index); + this.lookahead = this.context.slice(index + 1); + }; + + /** + * Get an item at an offset from the current value + * example (current value is 3): + * 1 2 [3] 4 5 | items values + * -2 -1 0 1 2 | offset values + * @param {number} offset an offset from current value index + */ + ContextParams.prototype.get = function (offset) { + switch (true) { + case (offset === 0): + return this.current; + case (offset < 0 && Math.abs(offset) <= this.backtrack.length): + return this.backtrack.slice(offset)[0]; + case (offset > 0 && offset <= this.lookahead.length): + return this.lookahead[offset - 1]; + default: + return null; + } + }; + + /** + * Converts a context range into a string value + * @param {contextRange} range a context range + */ + Tokenizer.prototype.rangeToText = function (range) { + if (range instanceof ContextRange) { + return ( + this.getRangeTokens(range) + .map(function (token) { return token.char; }).join('') + ); + } + }; + + /** + * Converts all tokens into a string + */ + Tokenizer.prototype.getText = function () { + return this.tokens.map(function (token) { return token.char; }).join(''); + }; + + /** + * Get a context by name + * @param {string} contextName context name to get + */ + Tokenizer.prototype.getContext = function (contextName) { + var context = this.registeredContexts[contextName]; + return !!context ? context : null; + }; + + /** + * Subscribes a new event handler to an event + * @param {string} eventName event name to subscribe to + * @param {function} eventHandler a function to be invoked on event + */ + Tokenizer.prototype.on = function(eventName, eventHandler) { + var event = this.events[eventName]; + if (!!event) { + return event.subscribe(eventHandler); + } else { + return null; + } + }; + + /** + * Dispatches an event + * @param {string} eventName event name + * @param {any} args event handler arguments + */ + Tokenizer.prototype.dispatch = function(eventName, args) { + var this$1 = this; + + var event = this.events[eventName]; + if (event instanceof Event) { + event.subscribers.forEach(function (subscriber) { + subscriber.apply(this$1, args || []); + }); + } + }; + + /** + * Register a new context checker + * @param {string} contextName a unique context name + * @param {function} contextStartCheck a predicate function that returns true on context start + * @param {function} contextEndCheck a predicate function that returns true on context end + * TODO: call tokenize on registration to update context ranges with the new context. + */ + Tokenizer.prototype.registerContextChecker = function(contextName, contextStartCheck, contextEndCheck) { + if (!!this.getContext(contextName)) { return { + FAIL: + ("context name '" + contextName + "' is already registered.") + }; } + if (typeof contextStartCheck !== 'function') { return { + FAIL: + "missing context start check." + }; } + if (typeof contextEndCheck !== 'function') { return { + FAIL: + "missing context end check." + }; } + var contextCheckers = new ContextChecker( + contextName, contextStartCheck, contextEndCheck + ); + this.registeredContexts[contextName] = contextCheckers; + this.contextCheckers.push(contextCheckers); + return contextCheckers; + }; + + /** + * Gets a context range tokens + * @param {contextRange} range a context range + */ + Tokenizer.prototype.getRangeTokens = function(range) { + var endIndex = range.startIndex + range.endOffset; + return [].concat( + this.tokens + .slice(range.startIndex, endIndex) + ); + }; + + /** + * Gets the ranges of a context + * @param {string} contextName context name + */ + Tokenizer.prototype.getContextRanges = function(contextName) { + var context = this.getContext(contextName); + if (!!context) { + return context.ranges; + } else { + return { FAIL: ("context checker '" + contextName + "' is not registered.") }; + } + }; + + /** + * Resets context ranges to run context update + */ + Tokenizer.prototype.resetContextsRanges = function () { + var registeredContexts = this.registeredContexts; + for (var contextName in registeredContexts) { + if (registeredContexts.hasOwnProperty(contextName)) { + var context = registeredContexts[contextName]; + context.ranges = []; + } + } + }; + + /** + * Updates context ranges + */ + Tokenizer.prototype.updateContextsRanges = function () { + this.resetContextsRanges(); + var chars = this.tokens.map(function (token) { return token.char; }); + for (var i = 0; i < chars.length; i++) { + var contextParams = new ContextParams(chars, i); + this.runContextCheck(contextParams); + } + this.dispatch('updateContextsRanges', [this.registeredContexts]); + }; + + /** + * Sets the end offset of an open range + * @param {number} offset range end offset + * @param {string} contextName context name + */ + Tokenizer.prototype.setEndOffset = function (offset, contextName) { + var startIndex = this.getContext(contextName).openRange.startIndex; + var range = new ContextRange(startIndex, offset, contextName); + var ranges = this.getContext(contextName).ranges; + range.rangeId = contextName + "." + (ranges.length); + ranges.push(range); + this.getContext(contextName).openRange = null; + return range; + }; + + /** + * Runs a context check on the current context + * @param {contextParams} contextParams current context params + */ + Tokenizer.prototype.runContextCheck = function(contextParams) { + var this$1 = this; + + var index = contextParams.index; + this.contextCheckers.forEach(function (contextChecker) { + var contextName = contextChecker.contextName; + var openRange = this$1.getContext(contextName).openRange; + if (!openRange && contextChecker.checkStart(contextParams)) { + openRange = new ContextRange(index, null, contextName); + this$1.getContext(contextName).openRange = openRange; + this$1.dispatch('contextStart', [contextName, index]); + } + if (!!openRange && contextChecker.checkEnd(contextParams)) { + var offset = (index - openRange.startIndex) + 1; + var range = this$1.setEndOffset(offset, contextName); + this$1.dispatch('contextEnd', [contextName, range]); + } + }); + }; + + /** + * Converts a text into a list of tokens + * @param {string} text a text to tokenize + */ + Tokenizer.prototype.tokenize = function (text) { + this.tokens = []; + this.resetContextsRanges(); + var chars = Array.from(text); + this.dispatch('start'); + for (var i = 0; i < chars.length; i++) { + var char = chars[i]; + var contextParams = new ContextParams(chars, i); + this.dispatch('next', [contextParams]); + this.runContextCheck(contextParams); + var token = new Token(char); + this.tokens.push(token); + this.dispatch('newToken', [token, contextParams]); + } + this.dispatch('end', [this.tokens]); + return this.tokens; + }; + + // ╭─┄┄┄────────────────────────┄─────────────────────────────────────────────╮ + // ┊ Character Class Assertions ┊ Checks if a char belongs to a certain class ┊ + // ╰─╾──────────────────────────┄─────────────────────────────────────────────╯ + // jscs:disable maximumLineLength + /** + * Check if a char is Arabic + * @param {string} c a single char + */ + function isArabicChar(c) { + return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c); + } + + /** + * Check if a char is an isolated arabic char + * @param {string} c a single char + */ + function isIsolatedArabicChar(char) { + return /[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char); + } + + /** + * Check if a char is an Arabic Tashkeel char + * @param {string} c a single char + */ + function isTashkeelArabicChar(char) { + return /[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char); + } + + /** + * Check if a char is Latin + * @param {string} c a single char + */ + function isLatinChar(c) { + return /[A-z]/.test(c); + } + + /** + * Check if a char is whitespace char + * @param {string} c a single char + */ + function isWhiteSpace(c) { + return /\s/.test(c); + } + + /** + * Query a feature by some of it's properties to lookup a glyph substitution. + */ + + /** + * Create feature query instance + * @param {Font} font opentype font instance + */ + function FeatureQuery(font) { + this.font = font; + this.features = {}; + } + + /** + * @typedef SubstitutionAction + * @type Object + * @property {number} id substitution type + * @property {string} tag feature tag + * @property {any} substitution substitution value(s) + */ + + /** + * Create a substitution action instance + * @param {SubstitutionAction} action + */ + function SubstitutionAction(action) { + this.id = action.id; + this.tag = action.tag; + this.substitution = action.substitution; + } + + /** + * Lookup a coverage table + * @param {number} glyphIndex glyph index + * @param {CoverageTable} coverage coverage table + */ + function lookupCoverage(glyphIndex, coverage) { + if (!glyphIndex) { return -1; } + switch (coverage.format) { + case 1: + return coverage.glyphs.indexOf(glyphIndex); + + case 2: + var ranges = coverage.ranges; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (glyphIndex >= range.start && glyphIndex <= range.end) { + var offset = glyphIndex - range.start; + return range.index + offset; + } + } + break; + default: + return -1; // not found + } + return -1; + } + + /** + * Handle a single substitution - format 1 + * @param {ContextParams} contextParams context params to lookup + */ + function singleSubstitutionFormat1(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { return null; } + return glyphIndex + subtable.deltaGlyphId; + } + + /** + * Handle a single substitution - format 2 + * @param {ContextParams} contextParams context params to lookup + */ + function singleSubstitutionFormat2(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { return null; } + return subtable.substitute[substituteIndex]; + } + + /** + * Lookup a list of coverage tables + * @param {any} coverageList a list of coverage tables + * @param {ContextParams} contextParams context params to lookup + */ + function lookupCoverageList(coverageList, contextParams) { + var lookupList = []; + for (var i = 0; i < coverageList.length; i++) { + var coverage = coverageList[i]; + var glyphIndex = contextParams.current; + glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex; + var lookupIndex = lookupCoverage(glyphIndex, coverage); + if (lookupIndex !== -1) { + lookupList.push(lookupIndex); + } + } + if (lookupList.length !== coverageList.length) { return -1; } + return lookupList; + } + + /** + * Handle chaining context substitution - format 3 + * @param {ContextParams} contextParams context params to lookup + */ + function chainingSubstitutionFormat3(contextParams, subtable) { + var lookupsCount = ( + subtable.inputCoverage.length + + subtable.lookaheadCoverage.length + + subtable.backtrackCoverage.length + ); + if (contextParams.context.length < lookupsCount) { return []; } + // INPUT LOOKUP // + var inputLookups = lookupCoverageList( + subtable.inputCoverage, contextParams + ); + if (inputLookups === -1) { return []; } + // LOOKAHEAD LOOKUP // + var lookaheadOffset = subtable.inputCoverage.length - 1; + if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) { return []; } + var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset); + while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) { + lookaheadContext.shift(); + } + var lookaheadParams = new ContextParams(lookaheadContext, 0); + var lookaheadLookups = lookupCoverageList( + subtable.lookaheadCoverage, lookaheadParams + ); + // BACKTRACK LOOKUP // + var backtrackContext = [].concat(contextParams.backtrack); + backtrackContext.reverse(); + while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) { + backtrackContext.shift(); + } + if (backtrackContext.length < subtable.backtrackCoverage.length) { return []; } + var backtrackParams = new ContextParams(backtrackContext, 0); + var backtrackLookups = lookupCoverageList( + subtable.backtrackCoverage, backtrackParams + ); + var contextRulesMatch = ( + inputLookups.length === subtable.inputCoverage.length && + lookaheadLookups.length === subtable.lookaheadCoverage.length && + backtrackLookups.length === subtable.backtrackCoverage.length + ); + var substitutions = []; + if (contextRulesMatch) { + for (var i = 0; i < subtable.lookupRecords.length; i++) { + var lookupRecord = subtable.lookupRecords[i]; + var lookupListIndex = lookupRecord.lookupListIndex; + var lookupTable = this.getLookupByIndex(lookupListIndex); + for (var s = 0; s < lookupTable.subtables.length; s++) { + var subtable$1 = lookupTable.subtables[s]; + var lookup = this.getLookupMethod(lookupTable, subtable$1); + var substitutionType = this.getSubstitutionType(lookupTable, subtable$1); + if (substitutionType === '12') { + for (var n = 0; n < inputLookups.length; n++) { + var glyphIndex = contextParams.get(n); + var substitution = lookup(glyphIndex); + if (substitution) { substitutions.push(substitution); } + } + } + } + } + } + return substitutions; + } + + /** + * Handle ligature substitution - format 1 + * @param {ContextParams} contextParams context params to lookup + */ + function ligatureSubstitutionFormat1(contextParams, subtable) { + // COVERAGE LOOKUP // + var glyphIndex = contextParams.current; + var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (ligSetIndex === -1) { return null; } + // COMPONENTS LOOKUP + // (!) note, components are ordered in the written direction. + var ligature; + var ligatureSet = subtable.ligatureSets[ligSetIndex]; + for (var s = 0; s < ligatureSet.length; s++) { + ligature = ligatureSet[s]; + for (var l = 0; l < ligature.components.length; l++) { + var lookaheadItem = contextParams.lookahead[l]; + var component = ligature.components[l]; + if (lookaheadItem !== component) { break; } + if (l === ligature.components.length - 1) { return ligature; } + } + } + return null; + } + + /** + * Handle decomposition substitution - format 1 + * @param {number} glyphIndex glyph index + * @param {any} subtable subtable + */ + function decompositionSubstitutionFormat1(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { return null; } + return subtable.sequences[substituteIndex]; + } + + /** + * Get default script features indexes + */ + FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function () { + var scripts = this.font.tables.gsub.scripts; + for (var s = 0; s < scripts.length; s++) { + var script = scripts[s]; + if (script.tag === 'DFLT') { return ( + script.script.defaultLangSys.featureIndexes + ); } + } + return []; + }; + + /** + * Get feature indexes of a specific script + * @param {string} scriptTag script tag + */ + FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) { + var tables = this.font.tables; + if (!tables.gsub) { return []; } + if (!scriptTag) { return this.getDefaultScriptFeaturesIndexes(); } + var scripts = this.font.tables.gsub.scripts; + for (var i = 0; i < scripts.length; i++) { + var script = scripts[i]; + if (script.tag === scriptTag && script.script.defaultLangSys) { + return script.script.defaultLangSys.featureIndexes; + } else { + var langSysRecords = script.langSysRecords; + if (!!langSysRecords) { + for (var j = 0; j < langSysRecords.length; j++) { + var langSysRecord = langSysRecords[j]; + if (langSysRecord.tag === scriptTag) { + var langSys = langSysRecord.langSys; + return langSys.featureIndexes; + } + } + } + } + } + return this.getDefaultScriptFeaturesIndexes(); + }; + + /** + * Map a feature tag to a gsub feature + * @param {any} features gsub features + * @param {string} scriptTag script tag + */ + FeatureQuery.prototype.mapTagsToFeatures = function (features, scriptTag) { + var tags = {}; + for (var i = 0; i < features.length; i++) { + var tag = features[i].tag; + var feature = features[i].feature; + tags[tag] = feature; + } + this.features[scriptTag].tags = tags; + }; + + /** + * Get features of a specific script + * @param {string} scriptTag script tag + */ + FeatureQuery.prototype.getScriptFeatures = function (scriptTag) { + var features = this.features[scriptTag]; + if (this.features.hasOwnProperty(scriptTag)) { return features; } + var featuresIndexes = this.getScriptFeaturesIndexes(scriptTag); + if (!featuresIndexes) { return null; } + var gsub = this.font.tables.gsub; + features = featuresIndexes.map(function (index) { return gsub.features[index]; }); + this.features[scriptTag] = features; + this.mapTagsToFeatures(features, scriptTag); + return features; + }; + + /** + * Get substitution type + * @param {any} lookupTable lookup table + * @param {any} subtable subtable + */ + FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) { + var lookupType = lookupTable.lookupType.toString(); + var substFormat = subtable.substFormat.toString(); + return lookupType + substFormat; + }; + + /** + * Get lookup method + * @param {any} lookupTable lookup table + * @param {any} subtable subtable + */ + FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) { + var this$1 = this; + + var substitutionType = this.getSubstitutionType(lookupTable, subtable); + switch (substitutionType) { + case '11': + return function (glyphIndex) { return singleSubstitutionFormat1.apply( + this$1, [glyphIndex, subtable] + ); }; + case '12': + return function (glyphIndex) { return singleSubstitutionFormat2.apply( + this$1, [glyphIndex, subtable] + ); }; + case '63': + return function (contextParams) { return chainingSubstitutionFormat3.apply( + this$1, [contextParams, subtable] + ); }; + case '41': + return function (contextParams) { return ligatureSubstitutionFormat1.apply( + this$1, [contextParams, subtable] + ); }; + case '21': + return function (glyphIndex) { return decompositionSubstitutionFormat1.apply( + this$1, [glyphIndex, subtable] + ); }; + default: + throw new Error( + "lookupType: " + (lookupTable.lookupType) + " - " + + "substFormat: " + (subtable.substFormat) + " " + + "is not yet supported" + ); + } + }; + + /** + * [ LOOKUP TYPES ] + * ------------------------------- + * Single 1; + * Multiple 2; + * Alternate 3; + * Ligature 4; + * Context 5; + * ChainingContext 6; + * ExtensionSubstitution 7; + * ReverseChainingContext 8; + * ------------------------------- + * + */ + + /** + * @typedef FQuery + * @type Object + * @param {string} tag feature tag + * @param {string} script feature script + * @param {ContextParams} contextParams context params + */ + + /** + * Lookup a feature using a query parameters + * @param {FQuery} query feature query + */ + FeatureQuery.prototype.lookupFeature = function (query) { + var contextParams = query.contextParams; + var currentIndex = contextParams.index; + var feature = this.getFeature({ + tag: query.tag, script: query.script + }); + if (!feature) { return new Error( + "font '" + (this.font.names.fullName.en) + "' " + + "doesn't support feature '" + (query.tag) + "' " + + "for script '" + (query.script) + "'." + ); } + var lookups = this.getFeatureLookups(feature); + var substitutions = [].concat(contextParams.context); + for (var l = 0; l < lookups.length; l++) { + var lookupTable = lookups[l]; + var subtables = this.getLookupSubtables(lookupTable); + for (var s = 0; s < subtables.length; s++) { + var subtable = subtables[s]; + var substType = this.getSubstitutionType(lookupTable, subtable); + var lookup = this.getLookupMethod(lookupTable, subtable); + var substitution = (void 0); + switch (substType) { + case '11': + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 11, tag: query.tag, substitution: substitution + })); + } + break; + case '12': + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 12, tag: query.tag, substitution: substitution + })); + } + break; + case '63': + substitution = lookup(contextParams); + if (Array.isArray(substitution) && substitution.length) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 63, tag: query.tag, substitution: substitution + })); + } + break; + case '41': + substitution = lookup(contextParams); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 41, tag: query.tag, substitution: substitution + })); + } + break; + case '21': + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 21, tag: query.tag, substitution: substitution + })); + } + break; + } + contextParams = new ContextParams(substitutions, currentIndex); + if (Array.isArray(substitution) && !substitution.length) { continue; } + substitution = null; + } + } + return substitutions.length ? substitutions : null; + }; + + /** + * Checks if a font supports a specific features + * @param {FQuery} query feature query object + */ + FeatureQuery.prototype.supports = function (query) { + if (!query.script) { return false; } + this.getScriptFeatures(query.script); + var supportedScript = this.features.hasOwnProperty(query.script); + if (!query.tag) { return supportedScript; } + var supportedFeature = ( + this.features[query.script].some(function (feature) { return feature.tag === query.tag; }) + ); + return supportedScript && supportedFeature; + }; + + /** + * Get lookup table subtables + * @param {any} lookupTable lookup table + */ + FeatureQuery.prototype.getLookupSubtables = function (lookupTable) { + return lookupTable.subtables || null; + }; + + /** + * Get lookup table by index + * @param {number} index lookup table index + */ + FeatureQuery.prototype.getLookupByIndex = function (index) { + var lookups = this.font.tables.gsub.lookups; + return lookups[index] || null; + }; + + /** + * Get lookup tables for a feature + * @param {string} feature + */ + FeatureQuery.prototype.getFeatureLookups = function (feature) { + // TODO: memoize + return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this)); + }; + + /** + * Query a feature by it's properties + * @param {any} query an object that describes the properties of a query + */ + FeatureQuery.prototype.getFeature = function getFeature(query) { + if (!this.font) { return { FAIL: "No font was found"}; } + if (!this.features.hasOwnProperty(query.script)) { + this.getScriptFeatures(query.script); + } + var scriptFeatures = this.features[query.script]; + if (!scriptFeatures) { return ( + { FAIL: ("No feature for script " + (query.script))} + ); } + if (!scriptFeatures.tags[query.tag]) { return null; } + return this.features[query.script].tags[query.tag]; + }; + + /** + * Arabic word context checkers + */ + + function arabicWordStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return ( + // ? arabic first char + (prevChar === null && isArabicChar(char)) || + // ? arabic char preceded with a non arabic char + (!isArabicChar(prevChar) && isArabicChar(char)) + ); + } + + function arabicWordEndCheck(contextParams) { + var nextChar = contextParams.get(1); + return ( + // ? last arabic char + (nextChar === null) || + // ? next char is not arabic + (!isArabicChar(nextChar)) + ); + } + + var arabicWordCheck = { + startCheck: arabicWordStartCheck, + endCheck: arabicWordEndCheck + }; + + /** + * Arabic sentence context checkers + */ + + function arabicSentenceStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return ( + // ? an arabic char preceded with a non arabic char + (isArabicChar(char) || isTashkeelArabicChar(char)) && + !isArabicChar(prevChar) + ); + } + + function arabicSentenceEndCheck(contextParams) { + var nextChar = contextParams.get(1); + switch (true) { + case nextChar === null: + return true; + case (!isArabicChar(nextChar) && !isTashkeelArabicChar(nextChar)): + var nextIsWhitespace = isWhiteSpace(nextChar); + if (!nextIsWhitespace) { return true; } + if (nextIsWhitespace) { + var arabicCharAhead = false; + arabicCharAhead = ( + contextParams.lookahead.some( + function (c) { return isArabicChar(c) || isTashkeelArabicChar(c); } + ) + ); + if (!arabicCharAhead) { return true; } + } + break; + default: + return false; + } + } + + var arabicSentenceCheck = { + startCheck: arabicSentenceStartCheck, + endCheck: arabicSentenceEndCheck + }; + + /** + * Apply single substitution format 1 + * @param {Array} substitutions substitutions + * @param {any} tokens a list of tokens + * @param {number} index token index + */ + function singleSubstitutionFormat1$1(action, tokens, index) { + tokens[index].setState(action.tag, action.substitution); + } + + /** + * Apply single substitution format 2 + * @param {Array} substitutions substitutions + * @param {any} tokens a list of tokens + * @param {number} index token index + */ + function singleSubstitutionFormat2$1(action, tokens, index) { + tokens[index].setState(action.tag, action.substitution); + } + + /** + * Apply chaining context substitution format 3 + * @param {Array} substitutions substitutions + * @param {any} tokens a list of tokens + * @param {number} index token index + */ + function chainingSubstitutionFormat3$1(action, tokens, index) { + action.substitution.forEach(function (subst, offset) { + var token = tokens[index + offset]; + token.setState(action.tag, subst); + }); + } + + /** + * Apply ligature substitution format 1 + * @param {Array} substitutions substitutions + * @param {any} tokens a list of tokens + * @param {number} index token index + */ + function ligatureSubstitutionFormat1$1(action, tokens, index) { + var token = tokens[index]; + token.setState(action.tag, action.substitution.ligGlyph); + var compsCount = action.substitution.components.length; + for (var i = 0; i < compsCount; i++) { + token = tokens[index + i + 1]; + token.setState('deleted', true); + } + } + + /** + * Supported substitutions + */ + var SUBSTITUTIONS = { + 11: singleSubstitutionFormat1$1, + 12: singleSubstitutionFormat2$1, + 63: chainingSubstitutionFormat3$1, + 41: ligatureSubstitutionFormat1$1 + }; + + /** + * Apply substitutions to a list of tokens + * @param {Array} substitutions substitutions + * @param {any} tokens a list of tokens + * @param {number} index token index + */ + function applySubstitution(action, tokens, index) { + if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) { + SUBSTITUTIONS[action.id](action, tokens, index); + } + } + + /** + * Apply Arabic presentation forms to a range of tokens + */ + + /** + * Check if a char can be connected to it's preceding char + * @param {ContextParams} charContextParams context params of a char + */ + function willConnectPrev(charContextParams) { + var backtrack = [].concat(charContextParams.backtrack); + for (var i = backtrack.length - 1; i >= 0; i--) { + var prevChar = backtrack[i]; + var isolated = isIsolatedArabicChar(prevChar); + var tashkeel = isTashkeelArabicChar(prevChar); + if (!isolated && !tashkeel) { return true; } + if (isolated) { return false; } + } + return false; + } + + /** + * Check if a char can be connected to it's proceeding char + * @param {ContextParams} charContextParams context params of a char + */ + function willConnectNext(charContextParams) { + if (isIsolatedArabicChar(charContextParams.current)) { return false; } + for (var i = 0; i < charContextParams.lookahead.length; i++) { + var nextChar = charContextParams.lookahead[i]; + var tashkeel = isTashkeelArabicChar(nextChar); + if (!tashkeel) { return true; } + } + return false; + } + + /** + * Apply arabic presentation forms to a list of tokens + * @param {ContextRange} range a range of tokens + */ + function arabicPresentationForms(range) { + var this$1 = this; + + var script = 'arab'; + var tags = this.featuresTags[script]; + var tokens = this.tokenizer.getRangeTokens(range); + if (tokens.length === 1) { return; } + var contextParams = new ContextParams( + tokens.map(function (token) { return token.getState('glyphIndex'); } + ), 0); + var charContextParams = new ContextParams( + tokens.map(function (token) { return token.char; } + ), 0); + tokens.forEach(function (token, index) { + if (isTashkeelArabicChar(token.char)) { return; } + contextParams.setCurrentIndex(index); + charContextParams.setCurrentIndex(index); + var CONNECT = 0; // 2 bits 00 (10: can connect next) (01: can connect prev) + if (willConnectPrev(charContextParams)) { CONNECT |= 1; } + if (willConnectNext(charContextParams)) { CONNECT |= 2; } + var tag; + switch (CONNECT) { + case 1: (tag = 'fina'); break; + case 2: (tag = 'init'); break; + case 3: (tag = 'medi'); break; + } + if (tags.indexOf(tag) === -1) { return; } + var substitutions = this$1.query.lookupFeature({ + tag: tag, script: script, contextParams: contextParams + }); + if (substitutions instanceof Error) { return console.info(substitutions.message); } + substitutions.forEach(function (action, index) { + if (action instanceof SubstitutionAction) { + applySubstitution(action, tokens, index); + contextParams.context[index] = action.substitution; + } + }); + }); + } + + /** + * Apply Arabic required ligatures feature to a range of tokens + */ + + /** + * Update context params + * @param {any} tokens a list of tokens + * @param {number} index current item index + */ + function getContextParams(tokens, index) { + var context = tokens.map(function (token) { return token.activeState.value; }); + return new ContextParams(context, index || 0); + } + + /** + * Apply Arabic required ligatures to a context range + * @param {ContextRange} range a range of tokens + */ + function arabicRequiredLigatures(range) { + var this$1 = this; + + var script = 'arab'; + var tokens = this.tokenizer.getRangeTokens(range); + var contextParams = getContextParams(tokens); + contextParams.context.forEach(function (glyphIndex, index) { + contextParams.setCurrentIndex(index); + var substitutions = this$1.query.lookupFeature({ + tag: 'rlig', script: script, contextParams: contextParams + }); + if (substitutions.length) { + substitutions.forEach( + function (action) { return applySubstitution(action, tokens, index); } + ); + contextParams = getContextParams(tokens); + } + }); + } + + /** + * Latin word context checkers + */ + + function latinWordStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return ( + // ? latin first char + (prevChar === null && isLatinChar(char)) || + // ? latin char preceded with a non latin char + (!isLatinChar(prevChar) && isLatinChar(char)) + ); + } + + function latinWordEndCheck(contextParams) { + var nextChar = contextParams.get(1); + return ( + // ? last latin char + (nextChar === null) || + // ? next char is not latin + (!isLatinChar(nextChar)) + ); + } + + var latinWordCheck = { + startCheck: latinWordStartCheck, + endCheck: latinWordEndCheck + }; + + /** + * Apply Latin ligature feature to a range of tokens + */ + + /** + * Update context params + * @param {any} tokens a list of tokens + * @param {number} index current item index + */ + function getContextParams$1(tokens, index) { + var context = tokens.map(function (token) { return token.activeState.value; }); + return new ContextParams(context, index || 0); + } + + /** + * Apply Arabic required ligatures to a context range + * @param {ContextRange} range a range of tokens + */ + function latinLigature(range) { + var this$1 = this; + + var script = 'latn'; + var tokens = this.tokenizer.getRangeTokens(range); + var contextParams = getContextParams$1(tokens); + contextParams.context.forEach(function (glyphIndex, index) { + contextParams.setCurrentIndex(index); + var substitutions = this$1.query.lookupFeature({ + tag: 'liga', script: script, contextParams: contextParams + }); + if (substitutions.length) { + substitutions.forEach( + function (action) { return applySubstitution(action, tokens, index); } + ); + contextParams = getContextParams$1(tokens); + } + }); + } + + /** + * Infer bidirectional properties for a given text and apply + * the corresponding layout rules. + */ + + /** + * Create Bidi. features + * @param {string} baseDir text base direction. value either 'ltr' or 'rtl' + */ + function Bidi(baseDir) { + this.baseDir = baseDir || 'ltr'; + this.tokenizer = new Tokenizer(); + this.featuresTags = {}; + } + + /** + * Sets Bidi text + * @param {string} text a text input + */ + Bidi.prototype.setText = function (text) { + this.text = text; + }; + + /** + * Store essential context checks: + * arabic word check for applying gsub features + * arabic sentence check for adjusting arabic layout + */ + Bidi.prototype.contextChecks = ({ + latinWordCheck: latinWordCheck, + arabicWordCheck: arabicWordCheck, + arabicSentenceCheck: arabicSentenceCheck + }); + + /** + * Register arabic word check + */ + function registerContextChecker(checkId) { + var check = this.contextChecks[(checkId + "Check")]; + return this.tokenizer.registerContextChecker( + checkId, check.startCheck, check.endCheck + ); + } + + /** + * Perform pre tokenization procedure then + * tokenize text input + */ + function tokenizeText() { + registerContextChecker.call(this, 'latinWord'); + registerContextChecker.call(this, 'arabicWord'); + registerContextChecker.call(this, 'arabicSentence'); + return this.tokenizer.tokenize(this.text); + } + + /** + * Reverse arabic sentence layout + * TODO: check base dir before applying adjustments - priority low + */ + function reverseArabicSentences() { + var this$1 = this; + + var ranges = this.tokenizer.getContextRanges('arabicSentence'); + ranges.forEach(function (range) { + var rangeTokens = this$1.tokenizer.getRangeTokens(range); + this$1.tokenizer.replaceRange( + range.startIndex, + range.endOffset, + rangeTokens.reverse() + ); + }); + } + + /** + * Register supported features tags + * @param {script} script script tag + * @param {Array} tags features tags list + */ + Bidi.prototype.registerFeatures = function (script, tags) { + var this$1 = this; + + var supportedTags = tags.filter( + function (tag) { return this$1.query.supports({script: script, tag: tag}); } + ); + if (!this.featuresTags.hasOwnProperty(script)) { + this.featuresTags[script] = supportedTags; + } else { + this.featuresTags[script] = + this.featuresTags[script].concat(supportedTags); + } + }; + + /** + * Apply GSUB features + * @param {Array} tagsList a list of features tags + * @param {string} script a script tag + * @param {Font} font opentype font instance + */ + Bidi.prototype.applyFeatures = function (font, features) { + if (!font) { throw new Error( + 'No valid font was provided to apply features' + ); } + if (!this.query) { this.query = new FeatureQuery(font); } + for (var f = 0; f < features.length; f++) { + var feature = features[f]; + if (!this.query.supports({script: feature.script})) { continue; } + this.registerFeatures(feature.script, feature.tags); + } + }; + + /** + * Register a state modifier + * @param {string} modifierId state modifier id + * @param {function} condition a predicate function that returns true or false + * @param {function} modifier a modifier function to set token state + */ + Bidi.prototype.registerModifier = function (modifierId, condition, modifier) { + this.tokenizer.registerModifier(modifierId, condition, modifier); + }; + + /** + * Check if 'glyphIndex' is registered + */ + function checkGlyphIndexStatus() { + if (this.tokenizer.registeredModifiers.indexOf('glyphIndex') === -1) { + throw new Error( + 'glyphIndex modifier is required to apply ' + + 'arabic presentation features.' + ); + } + } + + /** + * Apply arabic presentation forms features + */ + function applyArabicPresentationForms() { + var this$1 = this; + + var script = 'arab'; + if (!this.featuresTags.hasOwnProperty(script)) { return; } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges('arabicWord'); + ranges.forEach(function (range) { + arabicPresentationForms.call(this$1, range); + }); + } + + /** + * Apply required arabic ligatures + */ + function applyArabicRequireLigatures() { + var this$1 = this; + + var script = 'arab'; + if (!this.featuresTags.hasOwnProperty(script)) { return; } + var tags = this.featuresTags[script]; + if (tags.indexOf('rlig') === -1) { return; } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges('arabicWord'); + ranges.forEach(function (range) { + arabicRequiredLigatures.call(this$1, range); + }); + } + + /** + * Apply required arabic ligatures + */ + function applyLatinLigatures() { + var this$1 = this; + + var script = 'latn'; + if (!this.featuresTags.hasOwnProperty(script)) { return; } + var tags = this.featuresTags[script]; + if (tags.indexOf('liga') === -1) { return; } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges('latinWord'); + ranges.forEach(function (range) { + latinLigature.call(this$1, range); + }); + } + + /** + * Check if a context is registered + * @param {string} contextId context id + */ + Bidi.prototype.checkContextReady = function (contextId) { + return !!this.tokenizer.getContext(contextId); + }; + + /** + * Apply features to registered contexts + */ + Bidi.prototype.applyFeaturesToContexts = function () { + if (this.checkContextReady('arabicWord')) { + applyArabicPresentationForms.call(this); + applyArabicRequireLigatures.call(this); + } + if (this.checkContextReady('latinWord')) { + applyLatinLigatures.call(this); + } + if (this.checkContextReady('arabicSentence')) { + reverseArabicSentences.call(this); + } + }; + + /** + * process text input + * @param {string} text an input text + */ + Bidi.prototype.processText = function(text) { + if (!this.text || this.text !== text) { + this.setText(text); + tokenizeText.call(this); + this.applyFeaturesToContexts(); + } + }; + + /** + * Process a string of text to identify and adjust + * bidirectional text entities. + * @param {string} text input text + */ + Bidi.prototype.getBidiText = function (text) { + this.processText(text); + return this.tokenizer.getText(); + }; + + /** + * Get the current state index of each token + * @param {text} text an input text + */ + Bidi.prototype.getTextGlyphs = function (text) { + this.processText(text); + var indexes = []; + for (var i = 0; i < this.tokenizer.tokens.length; i++) { + var token = this.tokenizer.tokens[i]; + if (token.state.deleted) { continue; } + var index = token.activeState.value; + indexes.push(Array.isArray(index) ? index[0] : index); + } + return indexes; + }; + + // The Font object + + /** + * @typedef FontOptions + * @type Object + * @property {Boolean} empty - whether to create a new empty font + * @property {string} familyName + * @property {string} styleName + * @property {string=} fullName + * @property {string=} postScriptName + * @property {string=} designer + * @property {string=} designerURL + * @property {string=} manufacturer + * @property {string=} manufacturerURL + * @property {string=} license + * @property {string=} licenseURL + * @property {string=} version + * @property {string=} description + * @property {string=} copyright + * @property {string=} trademark + * @property {Number} unitsPerEm + * @property {Number} ascender + * @property {Number} descender + * @property {Number} createdTimestamp + * @property {string=} weightClass + * @property {string=} widthClass + * @property {string=} fsSelection + */ + + /** + * A Font represents a loaded OpenType font file. + * It contains a set of glyphs and methods to draw text on a drawing context, + * or to get a path representing the text. + * @exports opentype.Font + * @class + * @param {FontOptions} + * @constructor + */ + function Font(options) { + options = options || {}; + options.tables = options.tables || {}; + + if (!options.empty) { + // Check that we've provided the minimum set of names. + checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); + checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); + checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); + checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); + checkArgument(options.descender <= 0, 'When creating a new Font object, negative descender value is required.'); + + // OS X will complain if the names are empty, so we put a single space everywhere by default. + this.names = { + fontFamily: {en: options.familyName || ' '}, + fontSubfamily: {en: options.styleName || ' '}, + fullName: {en: options.fullName || options.familyName + ' ' + options.styleName}, + // postScriptName may not contain any whitespace + postScriptName: {en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, '')}, + designer: {en: options.designer || ' '}, + designerURL: {en: options.designerURL || ' '}, + manufacturer: {en: options.manufacturer || ' '}, + manufacturerURL: {en: options.manufacturerURL || ' '}, + license: {en: options.license || ' '}, + licenseURL: {en: options.licenseURL || ' '}, + version: {en: options.version || 'Version 0.1'}, + description: {en: options.description || ' '}, + copyright: {en: options.copyright || ' '}, + trademark: {en: options.trademark || ' '} + }; + this.unitsPerEm = options.unitsPerEm || 1000; + this.ascender = options.ascender; + this.descender = options.descender; + this.createdTimestamp = options.createdTimestamp; + this.tables = Object.assign(options.tables, { + os2: Object.assign({ + usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, + usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, + fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR, + }, options.tables.os2) + }); + } + + this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. + this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); + this.encoding = new DefaultEncoding(this); + this.position = new Position(this); + this.substitution = new Substitution(this); + this.tables = this.tables || {}; + + // needed for low memory mode only. + this._push = null; + this._hmtxTableData = {}; + + Object.defineProperty(this, 'hinting', { + get: function() { + if (this._hinting) { return this._hinting; } + if (this.outlinesFormat === 'truetype') { + return (this._hinting = new Hinting(this)); + } + } + }); + } + + /** + * Check if the font has a glyph for the given character. + * @param {string} + * @return {Boolean} + */ + Font.prototype.hasChar = function(c) { + return this.encoding.charToGlyphIndex(c) !== null; + }; + + /** + * Convert the given character to a single glyph index. + * Note that this function assumes that there is a one-to-one mapping between + * the given character and a glyph; for complex scripts this might not be the case. + * @param {string} + * @return {Number} + */ + Font.prototype.charToGlyphIndex = function(s) { + return this.encoding.charToGlyphIndex(s); + }; + + /** + * Convert the given character to a single Glyph object. + * Note that this function assumes that there is a one-to-one mapping between + * the given character and a glyph; for complex scripts this might not be the case. + * @param {string} + * @return {opentype.Glyph} + */ + Font.prototype.charToGlyph = function(c) { + var glyphIndex = this.charToGlyphIndex(c); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + // .notdef + glyph = this.glyphs.get(0); + } + + return glyph; + }; + + /** + * Update features + * @param {any} options features options + */ + Font.prototype.updateFeatures = function (options) { + // TODO: update all features options not only 'latn'. + return this.defaultRenderOptions.features.map(function (feature) { + if (feature.script === 'latn') { + return { + script: 'latn', + tags: feature.tags.filter(function (tag) { return options[tag]; }) + }; + } else { + return feature; + } + }); + }; + + /** + * Convert the given text to a list of Glyph objects. + * Note that there is no strict one-to-one mapping between characters and + * glyphs, so the list of returned glyphs can be larger or smaller than the + * length of the given string. + * @param {string} + * @param {GlyphRenderOptions} [options] + * @return {opentype.Glyph[]} + */ + Font.prototype.stringToGlyphs = function(s, options) { + var this$1 = this; + + + var bidi = new Bidi(); + + // Create and register 'glyphIndex' state modifier + var charToGlyphIndexMod = function (token) { return this$1.charToGlyphIndex(token.char); }; + bidi.registerModifier('glyphIndex', null, charToGlyphIndexMod); + + // roll-back to default features + var features = options ? + this.updateFeatures(options.features) : + this.defaultRenderOptions.features; + + bidi.applyFeatures(this, features); + + var indexes = bidi.getTextGlyphs(s); + + var length = indexes.length; + + // convert glyph indexes to glyph objects + var glyphs = new Array(length); + var notdef = this.glyphs.get(0); + for (var i = 0; i < length; i += 1) { + glyphs[i] = this.glyphs.get(indexes[i]) || notdef; + } + return glyphs; + }; + + /** + * @param {string} + * @return {Number} + */ + Font.prototype.nameToGlyphIndex = function(name) { + return this.glyphNames.nameToGlyphIndex(name); + }; + + /** + * @param {string} + * @return {opentype.Glyph} + */ + Font.prototype.nameToGlyph = function(name) { + var glyphIndex = this.nameToGlyphIndex(name); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + // .notdef + glyph = this.glyphs.get(0); + } + + return glyph; + }; + + /** + * @param {Number} + * @return {String} + */ + Font.prototype.glyphIndexToName = function(gid) { + if (!this.glyphNames.glyphIndexToName) { + return ''; + } + + return this.glyphNames.glyphIndexToName(gid); + }; + + /** + * Retrieve the value of the kerning pair between the left glyph (or its index) + * and the right glyph (or its index). If no kerning pair is found, return 0. + * The kerning value gets added to the advance width when calculating the spacing + * between glyphs. + * For GPOS kerning, this method uses the default script and language, which covers + * most use cases. To have greater control, use font.position.getKerningValue . + * @param {opentype.Glyph} leftGlyph + * @param {opentype.Glyph} rightGlyph + * @return {Number} + */ + Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { + leftGlyph = leftGlyph.index || leftGlyph; + rightGlyph = rightGlyph.index || rightGlyph; + var gposKerning = this.position.defaultKerningTables; + if (gposKerning) { + return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph); + } + // "kern" table + return this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0; + }; + + /** + * @typedef GlyphRenderOptions + * @type Object + * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used. + * See https://www.microsoft.com/typography/otspec/scripttags.htm + * @property {string} [language='dflt'] - language system used to determine which features to apply. + * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx + * @property {boolean} [kerning=true] - whether to include kerning values + * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system. + * See https://www.microsoft.com/typography/otspec/featuretags.htm + */ + Font.prototype.defaultRenderOptions = { + kerning: true, + features: [ + /** + * these 4 features are required to render Arabic text properly + * and shouldn't be turned off when rendering arabic text. + */ + { script: 'arab', tags: ['init', 'medi', 'fina', 'rlig'] }, + { script: 'latn', tags: ['liga', 'rlig'] } + ] + }; + + /** + * Helper function that invokes the given callback for each glyph in the given text. + * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text + * @param {string} text - The text to apply. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + * @param {Function} callback + */ + Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) { + x = x !== undefined ? x : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + options = Object.assign({}, this.defaultRenderOptions, options); + var fontScale = 1 / this.unitsPerEm * fontSize; + var glyphs = this.stringToGlyphs(text, options); + var kerningLookups; + if (options.kerning) { + var script = options.script || this.position.getDefaultScriptName(); + kerningLookups = this.position.getKerningTables(script, options.language); + } + for (var i = 0; i < glyphs.length; i += 1) { + var glyph = glyphs[i]; + callback.call(this, glyph, x, y, fontSize, options); + if (glyph.advanceWidth) { + x += glyph.advanceWidth * fontScale; + } + + if (options.kerning && i < glyphs.length - 1) { + // We should apply position adjustment lookups in a more generic way. + // Here we only use the xAdvance value. + var kerningValue = kerningLookups ? + this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : + this.getKerningValue(glyph, glyphs[i + 1]); + x += kerningValue * fontScale; + } + + if (options.letterSpacing) { + x += options.letterSpacing * fontSize; + } else if (options.tracking) { + x += (options.tracking / 1000) * fontSize; + } + } + return x; + }; + + /** + * Create a Path object that represents the given text. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + * @return {opentype.Path} + */ + Font.prototype.getPath = function(text, x, y, fontSize, options) { + var fullPath = new Path(); + this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + fullPath.extend(glyphPath); + }); + return fullPath; + }; + + /** + * Create an array of Path objects that represent the glyphs of a given text. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + * @return {opentype.Path[]} + */ + Font.prototype.getPaths = function(text, x, y, fontSize, options) { + var glyphPaths = []; + this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + glyphPaths.push(glyphPath); + }); + + return glyphPaths; + }; + + /** + * Returns the advance width of a text. + * + * This is something different than Path.getBoundingBox() as for example a + * suffixed whitespace increases the advanceWidth but not the bounding box + * or an overhanging letter like a calligraphic 'f' might have a quite larger + * bounding box than its advance width. + * + * This corresponds to canvas2dContext.measureText(text).width + * + * @param {string} text - The text to create. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + * @return advance width + */ + Font.prototype.getAdvanceWidth = function(text, fontSize, options) { + return this.forEachGlyph(text, 0, 0, fontSize, options, function() {}); + }; + + /** + * Draw the text on the given drawing context. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + */ + Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { + this.getPath(text, x, y, fontSize, options).draw(ctx); + }; + + /** + * Draw the points of all glyphs in the text. + * On-curve points will be drawn in blue, off-curve points will be drawn in red. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + */ + Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { + this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + glyph.drawPoints(ctx, gX, gY, gFontSize); + }); + }; + + /** + * Draw lines indicating important font measurements for all glyphs in the text. + * Black lines indicate the origin of the coordinate system (point 0,0). + * Blue lines indicate the glyph bounding box. + * Green line indicates the advance width of the glyph. + * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. + * @param {string} text - The text to create. + * @param {number} [x=0] - Horizontal position of the beginning of the text. + * @param {number} [y=0] - Vertical position of the *baseline* of the text. + * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. + * @param {GlyphRenderOptions=} options + */ + Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { + this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + glyph.drawMetrics(ctx, gX, gY, gFontSize); + }); + }; + + /** + * @param {string} + * @return {string} + */ + Font.prototype.getEnglishName = function(name) { + var translations = this.names[name]; + if (translations) { + return translations.en; + } + }; + + /** + * Validate + */ + Font.prototype.validate = function() { + var _this = this; + + function assert(predicate, message) { + } + + function assertNamePresent(name) { + var englishName = _this.getEnglishName(name); + assert(englishName && englishName.trim().length > 0); + } + + // Identification information + assertNamePresent('fontFamily'); + assertNamePresent('weightName'); + assertNamePresent('manufacturer'); + assertNamePresent('copyright'); + assertNamePresent('version'); + + // Dimension information + assert(this.unitsPerEm > 0); + }; + + /** + * Convert the font object to a SFNT data structure. + * This structure contains all the necessary tables and metadata to create a binary OTF file. + * @return {opentype.Table} + */ + Font.prototype.toTables = function() { + return sfnt.fontToTable(this); + }; + /** + * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. + */ + Font.prototype.toBuffer = function() { + console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); + return this.toArrayBuffer(); + }; + /** + * Converts a `opentype.Font` into an `ArrayBuffer` + * @return {ArrayBuffer} + */ + Font.prototype.toArrayBuffer = function() { + var sfntTable = this.toTables(); + var bytes = sfntTable.encode(); + var buffer = new ArrayBuffer(bytes.length); + var intArray = new Uint8Array(buffer); + for (var i = 0; i < bytes.length; i++) { + intArray[i] = bytes[i]; + } + + return buffer; + }; + + /** + * Initiate a download of the OpenType font. + */ + Font.prototype.download = function(fileName) { + var familyName = this.getEnglishName('fontFamily'); + var styleName = this.getEnglishName('fontSubfamily'); + fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; + var arrayBuffer = this.toArrayBuffer(); + + if (isBrowser()) { + window.URL = window.URL || window.webkitURL; + + if (window.URL) { + var dataView = new DataView(arrayBuffer); + var blob = new Blob([dataView], {type: 'font/opentype'}); + + var link = document.createElement('a'); + link.href = window.URL.createObjectURL(blob); + link.download = fileName; + + var event = document.createEvent('MouseEvents'); + event.initEvent('click', true, false); + link.dispatchEvent(event); + } else { + console.warn('Font file could not be downloaded. Try using a different browser.'); + } + } else { + var fs = require('fs'); + var buffer = arrayBufferToNodeBuffer(arrayBuffer); + fs.writeFileSync(fileName, buffer); + } + }; + /** + * @private + */ + Font.prototype.fsSelectionValues = { + ITALIC: 0x001, //1 + UNDERSCORE: 0x002, //2 + NEGATIVE: 0x004, //4 + OUTLINED: 0x008, //8 + STRIKEOUT: 0x010, //16 + BOLD: 0x020, //32 + REGULAR: 0x040, //64 + USER_TYPO_METRICS: 0x080, //128 + WWS: 0x100, //256 + OBLIQUE: 0x200 //512 + }; + + /** + * @private + */ + Font.prototype.usWidthClasses = { + ULTRA_CONDENSED: 1, + EXTRA_CONDENSED: 2, + CONDENSED: 3, + SEMI_CONDENSED: 4, + MEDIUM: 5, + SEMI_EXPANDED: 6, + EXPANDED: 7, + EXTRA_EXPANDED: 8, + ULTRA_EXPANDED: 9 + }; + + /** + * @private + */ + Font.prototype.usWeightClasses = { + THIN: 100, + EXTRA_LIGHT: 200, + LIGHT: 300, + NORMAL: 400, + MEDIUM: 500, + SEMI_BOLD: 600, + BOLD: 700, + EXTRA_BOLD: 800, + BLACK: 900 + }; + + // The `fvar` table stores font variation axes and instances. + + function addName(name, names) { + var nameString = JSON.stringify(name); + var nameID = 256; + for (var nameKey in names) { + var n = parseInt(nameKey); + if (!n || n < 256) { + continue; + } + + if (JSON.stringify(names[nameKey]) === nameString) { + return n; + } + + if (nameID <= n) { + nameID = n + 1; + } + } + + names[nameID] = name; + return nameID; + } + + function makeFvarAxis(n, axis, names) { + var nameID = addName(axis.name, names); + return [ + {name: 'tag_' + n, type: 'TAG', value: axis.tag}, + {name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16}, + {name: 'defaultValue_' + n, type: 'FIXED', value: axis.defaultValue << 16}, + {name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16}, + {name: 'flags_' + n, type: 'USHORT', value: 0}, + {name: 'nameID_' + n, type: 'USHORT', value: nameID} + ]; + } + + function parseFvarAxis(data, start, names) { + var axis = {}; + var p = new parse.Parser(data, start); + axis.tag = p.parseTag(); + axis.minValue = p.parseFixed(); + axis.defaultValue = p.parseFixed(); + axis.maxValue = p.parseFixed(); + p.skip('uShort', 1); // reserved for flags; no values defined + axis.name = names[p.parseUShort()] || {}; + return axis; + } + + function makeFvarInstance(n, inst, axes, names) { + var nameID = addName(inst.name, names); + var fields = [ + {name: 'nameID_' + n, type: 'USHORT', value: nameID}, + {name: 'flags_' + n, type: 'USHORT', value: 0} + ]; + + for (var i = 0; i < axes.length; ++i) { + var axisTag = axes[i].tag; + fields.push({ + name: 'axis_' + n + ' ' + axisTag, + type: 'FIXED', + value: inst.coordinates[axisTag] << 16 + }); + } + + return fields; + } + + function parseFvarInstance(data, start, axes, names) { + var inst = {}; + var p = new parse.Parser(data, start); + inst.name = names[p.parseUShort()] || {}; + p.skip('uShort', 1); // reserved for flags; no values defined + + inst.coordinates = {}; + for (var i = 0; i < axes.length; ++i) { + inst.coordinates[axes[i].tag] = p.parseFixed(); + } + + return inst; + } + + function makeFvarTable(fvar, names) { + var result = new table.Table('fvar', [ + {name: 'version', type: 'ULONG', value: 0x10000}, + {name: 'offsetToData', type: 'USHORT', value: 0}, + {name: 'countSizePairs', type: 'USHORT', value: 2}, + {name: 'axisCount', type: 'USHORT', value: fvar.axes.length}, + {name: 'axisSize', type: 'USHORT', value: 20}, + {name: 'instanceCount', type: 'USHORT', value: fvar.instances.length}, + {name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4} + ]); + result.offsetToData = result.sizeOf(); + + for (var i = 0; i < fvar.axes.length; i++) { + result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names)); + } + + for (var j = 0; j < fvar.instances.length; j++) { + result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names)); + } + + return result; + } + + function parseFvarTable(data, start, names) { + var p = new parse.Parser(data, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 0x00010000, 'Unsupported fvar table version.'); + var offsetToData = p.parseOffset16(); + // Skip countSizePairs. + p.skip('uShort', 1); + var axisCount = p.parseUShort(); + var axisSize = p.parseUShort(); + var instanceCount = p.parseUShort(); + var instanceSize = p.parseUShort(); + + var axes = []; + for (var i = 0; i < axisCount; i++) { + axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names)); + } + + var instances = []; + var instanceStart = start + offsetToData + axisCount * axisSize; + for (var j = 0; j < instanceCount; j++) { + instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names)); + } + + return {axes: axes, instances: instances}; + } + + var fvar = { make: makeFvarTable, parse: parseFvarTable }; + + // The `GPOS` table contains kerning pairs, among other things. + + var subtableParsers$1 = new Array(10); // subtableParsers[0] is unused + + // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-1-single-adjustment-positioning-subtable + // this = Parser instance + subtableParsers$1[1] = function parseLookup1() { + var start = this.offset + this.relativeOffset; + var posformat = this.parseUShort(); + if (posformat === 1) { + return { + posFormat: 1, + coverage: this.parsePointer(Parser.coverage), + value: this.parseValueRecord() + }; + } else if (posformat === 2) { + return { + posFormat: 2, + coverage: this.parsePointer(Parser.coverage), + values: this.parseValueRecordList() + }; + } + check.assert(false, '0x' + start.toString(16) + ': GPOS lookup type 1 format must be 1 or 2.'); + }; + + // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable + subtableParsers$1[2] = function parseLookup2() { + var start = this.offset + this.relativeOffset; + var posFormat = this.parseUShort(); + check.assert(posFormat === 1 || posFormat === 2, '0x' + start.toString(16) + ': GPOS lookup type 2 format must be 1 or 2.'); + var coverage = this.parsePointer(Parser.coverage); + var valueFormat1 = this.parseUShort(); + var valueFormat2 = this.parseUShort(); + if (posFormat === 1) { + // Adjustments for Glyph Pairs + return { + posFormat: posFormat, + coverage: coverage, + valueFormat1: valueFormat1, + valueFormat2: valueFormat2, + pairSets: this.parseList(Parser.pointer(Parser.list(function() { + return { // pairValueRecord + secondGlyph: this.parseUShort(), + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + }))) + }; + } else if (posFormat === 2) { + var classDef1 = this.parsePointer(Parser.classDef); + var classDef2 = this.parsePointer(Parser.classDef); + var class1Count = this.parseUShort(); + var class2Count = this.parseUShort(); + return { + // Class Pair Adjustment + posFormat: posFormat, + coverage: coverage, + valueFormat1: valueFormat1, + valueFormat2: valueFormat2, + classDef1: classDef1, + classDef2: classDef2, + class1Count: class1Count, + class2Count: class2Count, + classRecords: this.parseList(class1Count, Parser.list(class2Count, function() { + return { + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + })) + }; + } + }; + + subtableParsers$1[3] = function parseLookup3() { return { error: 'GPOS Lookup 3 not supported' }; }; + subtableParsers$1[4] = function parseLookup4() { return { error: 'GPOS Lookup 4 not supported' }; }; + subtableParsers$1[5] = function parseLookup5() { return { error: 'GPOS Lookup 5 not supported' }; }; + subtableParsers$1[6] = function parseLookup6() { return { error: 'GPOS Lookup 6 not supported' }; }; + subtableParsers$1[7] = function parseLookup7() { return { error: 'GPOS Lookup 7 not supported' }; }; + subtableParsers$1[8] = function parseLookup8() { return { error: 'GPOS Lookup 8 not supported' }; }; + subtableParsers$1[9] = function parseLookup9() { return { error: 'GPOS Lookup 9 not supported' }; }; + + // https://docs.microsoft.com/en-us/typography/opentype/spec/gpos + function parseGposTable(data, start) { + start = start || 0; + var p = new Parser(data, start); + var tableVersion = p.parseVersion(1); + check.argument(tableVersion === 1 || tableVersion === 1.1, 'Unsupported GPOS table version ' + tableVersion); + + if (tableVersion === 1) { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers$1) + }; + } else { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers$1), + variations: p.parseFeatureVariationsList() + }; + } + + } + + // GPOS Writing ////////////////////////////////////////////// + // NOT SUPPORTED + var subtableMakers$1 = new Array(10); + + function makeGposTable(gpos) { + return new table.Table('GPOS', [ + {name: 'version', type: 'ULONG', value: 0x10000}, + {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gpos.scripts)}, + {name: 'features', type: 'TABLE', value: new table.FeatureList(gpos.features)}, + {name: 'lookups', type: 'TABLE', value: new table.LookupList(gpos.lookups, subtableMakers$1)} + ]); + } + + var gpos = { parse: parseGposTable, make: makeGposTable }; + + // The `kern` table contains kerning pairs. + + function parseWindowsKernTable(p) { + var pairs = {}; + // Skip nTables. + p.skip('uShort'); + var subtableVersion = p.parseUShort(); + check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.'); + // Skip subtableLength, subtableCoverage + p.skip('uShort', 2); + var nPairs = p.parseUShort(); + // Skip searchRange, entrySelector, rangeShift. + p.skip('uShort', 3); + for (var i = 0; i < nPairs; i += 1) { + var leftIndex = p.parseUShort(); + var rightIndex = p.parseUShort(); + var value = p.parseShort(); + pairs[leftIndex + ',' + rightIndex] = value; + } + return pairs; + } + + function parseMacKernTable(p) { + var pairs = {}; + // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits. + // Skip the rest. + p.skip('uShort'); + var nTables = p.parseULong(); + //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').'); + if (nTables > 1) { + console.warn('Only the first kern subtable is supported.'); + } + p.skip('uLong'); + var coverage = p.parseUShort(); + var subtableVersion = coverage & 0xFF; + p.skip('uShort'); + if (subtableVersion === 0) { + var nPairs = p.parseUShort(); + // Skip searchRange, entrySelector, rangeShift. + p.skip('uShort', 3); + for (var i = 0; i < nPairs; i += 1) { + var leftIndex = p.parseUShort(); + var rightIndex = p.parseUShort(); + var value = p.parseShort(); + pairs[leftIndex + ',' + rightIndex] = value; + } + } + return pairs; + } + + // Parse the `kern` table which contains kerning pairs. + function parseKernTable(data, start) { + var p = new parse.Parser(data, start); + var tableVersion = p.parseUShort(); + if (tableVersion === 0) { + return parseWindowsKernTable(p); + } else if (tableVersion === 1) { + return parseMacKernTable(p); + } else { + throw new Error('Unsupported kern table version (' + tableVersion + ').'); + } + } + + var kern = { parse: parseKernTable }; + + // The `loca` table stores the offsets to the locations of the glyphs in the font. + + // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, + // relative to the beginning of the glyphData table. + // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) + // The loca table has two versions: a short version where offsets are stored as uShorts, and a long + // version where offsets are stored as uLongs. The `head` table specifies which version to use + // (under indexToLocFormat). + function parseLocaTable(data, start, numGlyphs, shortVersion) { + var p = new parse.Parser(data, start); + var parseFn = shortVersion ? p.parseUShort : p.parseULong; + // There is an extra entry after the last index element to compute the length of the last glyph. + // That's why we use numGlyphs + 1. + var glyphOffsets = []; + for (var i = 0; i < numGlyphs + 1; i += 1) { + var glyphOffset = parseFn.call(p); + if (shortVersion) { + // The short table version stores the actual offset divided by 2. + glyphOffset *= 2; + } + + glyphOffsets.push(glyphOffset); + } + + return glyphOffsets; + } + + var loca = { parse: parseLocaTable }; + + // opentype.js + + /** + * The opentype library. + * @namespace opentype + */ + + // File loaders ///////////////////////////////////////////////////////// + /** + * Loads a font from a file. The callback throws an error message as the first parameter if it fails + * and the font as an ArrayBuffer in the second parameter if it succeeds. + * @param {string} path - The path of the file + * @param {Function} callback - The function to call when the font load completes + */ + function loadFromFile(path, callback) { + var fs = require('fs'); + fs.readFile(path, function(err, buffer) { + if (err) { + return callback(err.message); + } + + callback(null, nodeBufferToArrayBuffer(buffer)); + }); + } + /** + * Loads a font from a URL. The callback throws an error message as the first parameter if it fails + * and the font as an ArrayBuffer in the second parameter if it succeeds. + * @param {string} url - The URL of the font file. + * @param {Function} callback - The function to call when the font load completes + */ + function loadFromUrl(url, callback) { + var request = new XMLHttpRequest(); + request.open('get', url, true); + request.responseType = 'arraybuffer'; + request.onload = function() { + if (request.response) { + return callback(null, request.response); + } else { + return callback('Font could not be loaded: ' + request.statusText); + } + }; + + request.onerror = function () { + callback('Font could not be loaded'); + }; + + request.send(); + } + + // Table Directory Entries ////////////////////////////////////////////// + /** + * Parses OpenType table entries. + * @param {DataView} + * @param {Number} + * @return {Object[]} + */ + function parseOpenTypeTableEntries(data, numTables) { + var tableEntries = []; + var p = 12; + for (var i = 0; i < numTables; i += 1) { + var tag = parse.getTag(data, p); + var checksum = parse.getULong(data, p + 4); + var offset = parse.getULong(data, p + 8); + var length = parse.getULong(data, p + 12); + tableEntries.push({tag: tag, checksum: checksum, offset: offset, length: length, compression: false}); + p += 16; + } + + return tableEntries; + } + + /** + * Parses WOFF table entries. + * @param {DataView} + * @param {Number} + * @return {Object[]} + */ + function parseWOFFTableEntries(data, numTables) { + var tableEntries = []; + var p = 44; // offset to the first table directory entry. + for (var i = 0; i < numTables; i += 1) { + var tag = parse.getTag(data, p); + var offset = parse.getULong(data, p + 4); + var compLength = parse.getULong(data, p + 8); + var origLength = parse.getULong(data, p + 12); + var compression = (void 0); + if (compLength < origLength) { + compression = 'WOFF'; + } else { + compression = false; + } + + tableEntries.push({tag: tag, offset: offset, compression: compression, + compressedLength: compLength, length: origLength}); + p += 20; + } + + return tableEntries; + } + + /** + * @typedef TableData + * @type Object + * @property {DataView} data - The DataView + * @property {number} offset - The data offset. + */ + + /** + * @param {DataView} + * @param {Object} + * @return {TableData} + */ + function uncompressTable(data, tableEntry) { + if (tableEntry.compression === 'WOFF') { + var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2); + var outBuffer = new Uint8Array(tableEntry.length); + tinyInflate(inBuffer, outBuffer); + if (outBuffer.byteLength !== tableEntry.length) { + throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length'); + } + + var view = new DataView(outBuffer.buffer, 0); + return {data: view, offset: 0}; + } else { + return {data: data, offset: tableEntry.offset}; + } + } + + // Public API /////////////////////////////////////////////////////////// + + /** + * Parse the OpenType file data (as an ArrayBuffer) and return a Font object. + * Throws an error if the font could not be parsed. + * @param {ArrayBuffer} + * @param {Object} opt - options for parsing + * @return {opentype.Font} + */ + function parseBuffer(buffer, opt) { + opt = (opt === undefined || opt === null) ? {} : opt; + + var indexToLocFormat; + var ltagTable; + + // Since the constructor can also be called to create new fonts from scratch, we indicate this + // should be an empty font that we'll fill with our own data. + var font = new Font({empty: true}); + + // OpenType fonts use big endian byte ordering. + // We can't rely on typed array view types, because they operate with the endianness of the host computer. + // Instead we use DataViews where we can specify endianness. + var data = new DataView(buffer, 0); + var numTables; + var tableEntries = []; + var signature = parse.getTag(data, 0); + if (signature === String.fromCharCode(0, 1, 0, 0) || signature === 'true' || signature === 'typ1') { + font.outlinesFormat = 'truetype'; + numTables = parse.getUShort(data, 4); + tableEntries = parseOpenTypeTableEntries(data, numTables); + } else if (signature === 'OTTO') { + font.outlinesFormat = 'cff'; + numTables = parse.getUShort(data, 4); + tableEntries = parseOpenTypeTableEntries(data, numTables); + } else if (signature === 'wOFF') { + var flavor = parse.getTag(data, 4); + if (flavor === String.fromCharCode(0, 1, 0, 0)) { + font.outlinesFormat = 'truetype'; + } else if (flavor === 'OTTO') { + font.outlinesFormat = 'cff'; + } else { + throw new Error('Unsupported OpenType flavor ' + signature); + } + + numTables = parse.getUShort(data, 12); + tableEntries = parseWOFFTableEntries(data, numTables); + } else { + throw new Error('Unsupported OpenType signature ' + signature); + } + + var cffTableEntry; + var fvarTableEntry; + var glyfTableEntry; + var gposTableEntry; + var gsubTableEntry; + var hmtxTableEntry; + var kernTableEntry; + var locaTableEntry; + var nameTableEntry; + var metaTableEntry; + var p; + + for (var i = 0; i < numTables; i += 1) { + var tableEntry = tableEntries[i]; + var table = (void 0); + switch (tableEntry.tag) { + case 'cmap': + table = uncompressTable(data, tableEntry); + font.tables.cmap = cmap.parse(table.data, table.offset); + font.encoding = new CmapEncoding(font.tables.cmap); + break; + case 'cvt ' : + table = uncompressTable(data, tableEntry); + p = new parse.Parser(table.data, table.offset); + font.tables.cvt = p.parseShortList(tableEntry.length / 2); + break; + case 'fvar': + fvarTableEntry = tableEntry; + break; + case 'fpgm' : + table = uncompressTable(data, tableEntry); + p = new parse.Parser(table.data, table.offset); + font.tables.fpgm = p.parseByteList(tableEntry.length); + break; + case 'head': + table = uncompressTable(data, tableEntry); + font.tables.head = head.parse(table.data, table.offset); + font.unitsPerEm = font.tables.head.unitsPerEm; + indexToLocFormat = font.tables.head.indexToLocFormat; + break; + case 'hhea': + table = uncompressTable(data, tableEntry); + font.tables.hhea = hhea.parse(table.data, table.offset); + font.ascender = font.tables.hhea.ascender; + font.descender = font.tables.hhea.descender; + font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics; + break; + case 'hmtx': + hmtxTableEntry = tableEntry; + break; + case 'ltag': + table = uncompressTable(data, tableEntry); + ltagTable = ltag.parse(table.data, table.offset); + break; + case 'maxp': + table = uncompressTable(data, tableEntry); + font.tables.maxp = maxp.parse(table.data, table.offset); + font.numGlyphs = font.tables.maxp.numGlyphs; + break; + case 'name': + nameTableEntry = tableEntry; + break; + case 'OS/2': + table = uncompressTable(data, tableEntry); + font.tables.os2 = os2.parse(table.data, table.offset); + break; + case 'post': + table = uncompressTable(data, tableEntry); + font.tables.post = post.parse(table.data, table.offset); + font.glyphNames = new GlyphNames(font.tables.post); + break; + case 'prep' : + table = uncompressTable(data, tableEntry); + p = new parse.Parser(table.data, table.offset); + font.tables.prep = p.parseByteList(tableEntry.length); + break; + case 'glyf': + glyfTableEntry = tableEntry; + break; + case 'loca': + locaTableEntry = tableEntry; + break; + case 'CFF ': + cffTableEntry = tableEntry; + break; + case 'kern': + kernTableEntry = tableEntry; + break; + case 'GPOS': + gposTableEntry = tableEntry; + break; + case 'GSUB': + gsubTableEntry = tableEntry; + break; + case 'meta': + metaTableEntry = tableEntry; + break; + } + } + + var nameTable = uncompressTable(data, nameTableEntry); + font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable); + font.names = font.tables.name; + + if (glyfTableEntry && locaTableEntry) { + var shortVersion = indexToLocFormat === 0; + var locaTable = uncompressTable(data, locaTableEntry); + var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion); + var glyfTable = uncompressTable(data, glyfTableEntry); + font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font, opt); + } else if (cffTableEntry) { + var cffTable = uncompressTable(data, cffTableEntry); + cff.parse(cffTable.data, cffTable.offset, font, opt); + } else { + throw new Error('Font doesn\'t contain TrueType or CFF outlines.'); + } + + var hmtxTable = uncompressTable(data, hmtxTableEntry); + hmtx.parse(font, hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs, opt); + addGlyphNames(font, opt); + + if (kernTableEntry) { + var kernTable = uncompressTable(data, kernTableEntry); + font.kerningPairs = kern.parse(kernTable.data, kernTable.offset); + } else { + font.kerningPairs = {}; + } + + if (gposTableEntry) { + var gposTable = uncompressTable(data, gposTableEntry); + font.tables.gpos = gpos.parse(gposTable.data, gposTable.offset); + font.position.init(); + } + + if (gsubTableEntry) { + var gsubTable = uncompressTable(data, gsubTableEntry); + font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset); + } + + if (fvarTableEntry) { + var fvarTable = uncompressTable(data, fvarTableEntry); + font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names); + } + + if (metaTableEntry) { + var metaTable = uncompressTable(data, metaTableEntry); + font.tables.meta = meta.parse(metaTable.data, metaTable.offset); + font.metas = font.tables.meta; + } + + return font; + } + + /** + * Asynchronously load the font from a URL or a filesystem. When done, call the callback + * with two arguments `(err, font)`. The `err` will be null on success, + * the `font` is a Font object. + * We use the node.js callback convention so that + * opentype.js can integrate with frameworks like async.js. + * @alias opentype.load + * @param {string} url - The URL of the font to load. + * @param {Function} callback - The callback. + */ + function load(url, callback, opt) { + var isNode = typeof window === 'undefined'; + var loadFn = isNode ? loadFromFile : loadFromUrl; + + return new Promise(function (resolve, reject) { + loadFn(url, function(err, arrayBuffer) { + if (err) { + if (callback) { + return callback(err); + } else { + reject(err); + } + } + var font; + try { + font = parseBuffer(arrayBuffer, opt); + } catch (e) { + if (callback) { + return callback(e, null); + } else { + reject(e); + } + } + if (callback) { + return callback(null, font); + } else { + resolve(font); + } + }); + }); + } + + /** + * Synchronously load the font from a URL or file. + * When done, returns the font object or throws an error. + * @alias opentype.loadSync + * @param {string} url - The URL of the font to load. + * @param {Object} opt - opt.lowMemory + * @return {opentype.Font} + */ + function loadSync(url, opt) { + var fs = require('fs'); + var buffer = fs.readFileSync(url); + return parseBuffer(nodeBufferToArrayBuffer(buffer), opt); + } + + var opentype = /*#__PURE__*/Object.freeze({ + __proto__: null, + Font: Font, + Glyph: Glyph, + Path: Path, + BoundingBox: BoundingBox, + _parse: parse, + parse: parseBuffer, + load: load, + loadSync: loadSync + }); + + exports.BoundingBox = BoundingBox; + exports.Font = Font; + exports.Glyph = Glyph; + exports.Path = Path; + exports._parse = parse; + exports.default = opentype; + exports.load = load; + exports.loadSync = loadSync; + exports.parse = parseBuffer; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +//# sourceMappingURL=opentype.js.map diff --git a/node_modules/lv_font_conv/node_modules/opentype.js/package.json b/node_modules/lv_font_conv/node_modules/opentype.js/package.json new file mode 100644 index 00000000..8c75ccad --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/opentype.js/package.json @@ -0,0 +1,102 @@ +{ + "_args": [ + [ + "opentype.js@1.3.3", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "opentype.js@1.3.3", + "_id": "opentype.js@1.3.3", + "_inBundle": false, + "_integrity": "sha512-/qIY/+WnKGlPIIPhbeNjynfD2PO15G9lA/xqlX2bDH+4lc3Xz5GCQ68mqxj3DdUv6AJqCeaPvuAoH8mVL0zcuA==", + "_location": "/opentype.js", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "opentype.js@1.3.3", + "name": "opentype.js", + "escapedName": "opentype.js", + "rawSpec": "1.3.3", + "saveSpec": null, + "fetchSpec": "1.3.3" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-1.3.3.tgz", + "_spec": "1.3.3", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "author": { + "name": "Frederik De Bleser", + "email": "frederik@debleser.be" + }, + "bin": { + "ot": "bin/ot" + }, + "browser": { + "fs": false + }, + "bugs": { + "url": "https://github.com/opentypejs/opentype.js/issues" + }, + "dependencies": { + "string.prototype.codepointat": "^0.2.1", + "tiny-inflate": "^1.0.3" + }, + "description": "OpenType font parser", + "devDependencies": { + "@babel/preset-env": "^7.9.5", + "buble": "^0.20.0", + "cross-env": "^7.0.2", + "jscs": "^3.0.7", + "jshint": "^2.11.0", + "mocha": "^7.1.1", + "reify": "^0.20.12", + "rollup": "^1.32.1", + "rollup-plugin-buble": "^0.19.8", + "rollup-plugin-commonjs": "^10.1.0", + "rollup-plugin-license": "^0.9.0", + "rollup-plugin-node-resolve": "^5.2.0", + "uglify-js": "^3.8.1" + }, + "engines": { + "node": ">= 8.0.0" + }, + "files": [ + "LICENSE", + "RELEASES.md", + "README.md", + "bin", + "dist", + "src" + ], + "homepage": "https://github.com/opentypejs/opentype.js#readme", + "keywords": [ + "graphics", + "fonts", + "font", + "opentype", + "otf", + "ttf", + "woff", + "type" + ], + "license": "MIT", + "main": "dist/opentype.js", + "module": "dist/opentype.module.js", + "name": "opentype.js", + "repository": { + "type": "git", + "url": "git://github.com/opentypejs/opentype.js.git" + }, + "scripts": { + "build": "rollup -c", + "dist": "npm run test && npm run build && npm run minify", + "minify": "uglifyjs --source-map \"url='opentype.min.js.map'\" --compress --mangle --output ./dist/opentype.min.js -- ./dist/opentype.js", + "start": "node ./bin/server.js", + "test": "mocha --require reify --recursive && jshint . && jscs .", + "watch": "rollup -c -w" + }, + "version": "1.3.3" +} diff --git a/node_modules/lv_font_conv/node_modules/pngjs/LICENSE b/node_modules/lv_font_conv/node_modules/pngjs/LICENSE new file mode 100644 index 00000000..6942e254 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/LICENSE @@ -0,0 +1,20 @@ +pngjs2 original work Copyright (c) 2015 Luke Page & Original Contributors +pngjs derived work Copyright (c) 2012 Kuba Niegowski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/pngjs/README.md b/node_modules/lv_font_conv/node_modules/pngjs/README.md new file mode 100644 index 00000000..2aef03d9 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/README.md @@ -0,0 +1,433 @@ +[![Build Status](https://travis-ci.com/lukeapage/pngjs.svg?branch=master)](https://travis-ci.com/lukeapage/pngjs) [![Build status](https://ci.appveyor.com/api/projects/status/qo5x8ayutr028108/branch/master?svg=true)](https://ci.appveyor.com/project/lukeapage/pngjs/branch/master) [![codecov](https://codecov.io/gh/lukeapage/pngjs/branch/master/graph/badge.svg)](https://codecov.io/gh/lukeapage/pngjs) [![npm version](https://badge.fury.io/js/pngjs.svg)](http://badge.fury.io/js/pngjs) + +# pngjs + +Simple PNG encoder/decoder for Node.js with no dependencies. + +Based on the original [pngjs](https://github.com/niegowski/node-pngjs) with the follow enhancements. + +- Support for reading 1,2,4 & 16 bit files +- Support for reading interlace files +- Support for reading `tTRNS` transparent colours +- Support for writing colortype 0 (grayscale), colortype 2 (RGB), colortype 4 (grayscale alpha) and colortype 6 (RGBA) +- Sync interface as well as async +- API compatible with pngjs and node-pngjs + +Known lack of support for: + +- Extended PNG e.g. Animation +- Writing in colortype 3 (indexed color) + +# Table of Contents + +- [Requirements](#requirements) +- [Comparison Table](#comparison-table) +- [Tests](#tests) +- [Installation](#installation) +- [Browser](#browser) +- [Example](#example) +- [Async API](#async-api) +- [Sync API](#sync-api) +- [Changelog](#changelog) + +# Comparison Table + +| Name | Forked From | Sync | Async | 16 Bit | 1/2/4 Bit | Interlace | Gamma | Encodes | Tested | +| ------------- | ----------- | ---- | ----- | ------ | --------- | --------- | ------ | ------- | ------ | +| pngjs | | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | +| node-png | pngjs | No | Yes | No | No | No | Hidden | Yes | Manual | +| png-coder | pngjs | No | Yes | Yes | No | No | Hidden | Yes | Manual | +| pngparse | | No | Yes | No | Yes | No | No | No | Yes | +| pngparse-sync | pngparse | Yes | No | No | Yes | No | No | No | Yes | +| png-async | | No | Yes | No | No | No | No | Yes | Yes | +| png-js | | No | Yes | No | No | No | No | No | No | + +Native C++ node decoders: + +- png +- png-sync (sync version of above) +- pixel-png +- png-img + +# Tests + +Tested using [PNG Suite](http://www.schaik.com/pngsuite/). We read every file into pngjs, output it in standard 8bit colour, synchronously and asynchronously, then compare the original with the newly saved images. + +To run the tests, fetch the repo (tests are not distributed via npm) and install with `npm i`, run `npm test`. + +The only thing not converted is gamma correction - this is because multiple vendors will do gamma correction differently, so the tests will have different results on different browsers. + +# Installation + +``` +$ npm install pngjs --save +``` + +# Browser + +The package has been build with a [Browserify](browserify.org) version (`npm run browserify`) and you can use the browser version by including in your code: + +``` +import { PNG } from 'pngjs/browser'; +``` + +# Example + +```js +var fs = require("fs"), + PNG = require("pngjs").PNG; + +fs.createReadStream("in.png") + .pipe( + new PNG({ + filterType: 4, + }) + ) + .on("parsed", function () { + for (var y = 0; y < this.height; y++) { + for (var x = 0; x < this.width; x++) { + var idx = (this.width * y + x) << 2; + + // invert color + this.data[idx] = 255 - this.data[idx]; + this.data[idx + 1] = 255 - this.data[idx + 1]; + this.data[idx + 2] = 255 - this.data[idx + 2]; + + // and reduce opacity + this.data[idx + 3] = this.data[idx + 3] >> 1; + } + } + + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +For more examples see `examples` folder. + +# Async API + +As input any color type is accepted (grayscale, rgb, palette, grayscale with alpha, rgb with alpha) but 8 bit per sample (channel) is the only supported bit depth. Interlaced mode is not supported. + +## Class: PNG + +`PNG` is readable and writable `Stream`. + +### Options + +- `width` - use this with `height` if you want to create png from scratch +- `height` - as above +- `checkCRC` - whether parser should be strict about checksums in source stream (default: `true`) +- `deflateChunkSize` - chunk size used for deflating data chunks, this should be power of 2 and must not be less than 256 and more than 32\*1024 (default: 32 kB) +- `deflateLevel` - compression level for deflate (default: 9) +- `deflateStrategy` - compression strategy for deflate (default: 3) +- `deflateFactory` - deflate stream factory (default: `zlib.createDeflate`) +- `filterType` - png filtering method for scanlines (default: -1 => auto, accepts array of numbers 0-4) +- `colorType` - the output colorType - see constants. 0 = grayscale, no alpha, 2 = color, no alpha, 4 = grayscale & alpha, 6 = color & alpha. Default currently 6, but in the future may calculate best mode. +- `inputColorType` - the input colorType - see constants. Default is 6 (RGBA) +- `bitDepth` - the bitDepth of the output, 8 or 16 bits. Input data is expected to have this bit depth. + 16 bit data is expected in the system endianness (Default: 8) +- `inputHasAlpha` - whether the input bitmap has 4 bytes per pixel (rgb and alpha) or 3 (rgb - no alpha). +- `bgColor` - an object containing red, green, and blue values between 0 and 255 + that is used when packing a PNG if alpha is not to be included (default: 255,255,255) + +### Event "metadata" + +`function(metadata) { }` +Image's header has been parsed, metadata contains this information: + +- `width` image size in pixels +- `height` image size in pixels +- `palette` image is paletted +- `color` image is not grayscale +- `alpha` image contains alpha channel +- `interlace` image is interlaced + +### Event: "parsed" + +`function(data) { }` +Input image has been completely parsed, `data` is complete and ready for modification. + +### Event: "error" + +`function(error) { }` + +### png.parse(data, [callback]) + +Parses PNG file data. Can be `String` or `Buffer`. Alternatively you can stream data to instance of PNG. + +Optional `callback` is once called on `error` or `parsed`. The callback gets +two arguments `(err, data)`. + +Returns `this` for method chaining. + +#### Example + +```js +new PNG({ filterType: 4 }).parse(imageData, function (error, data) { + console.log(error, data); +}); +``` + +### png.pack() + +Starts converting data to PNG file Stream. + +Returns `this` for method chaining. + +### png.bitblt(dst, sx, sy, w, h, dx, dy) + +Helper for image manipulation, copies a rectangle of pixels from current (i.e. the source) image (`sx`, `sy`, `w`, `h`) to `dst` image (at `dx`, `dy`). + +Returns `this` for method chaining. + +For example, the following code copies the top-left 100x50 px of `in.png` into dst and writes it to `out.png`: + +```js +var dst = new PNG({ width: 100, height: 50 }); +fs.createReadStream("in.png") + .pipe(new PNG()) + .on("parsed", function () { + this.bitblt(dst, 0, 0, 100, 50, 0, 0); + dst.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +### Property: adjustGamma() + +Helper that takes data and adjusts it to be gamma corrected. Note that it is not 100% reliable with transparent colours because that requires knowing the background colour the bitmap is rendered on to. + +In tests against PNG suite it compared 100% with chrome on all 8 bit and below images. On IE there were some differences. + +The following example reads a file, adjusts the gamma (which sets the gamma to 0) and writes it out again, effectively removing any gamma correction from the image. + +```js +fs.createReadStream("in.png") + .pipe(new PNG()) + .on("parsed", function () { + this.adjustGamma(); + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +### Property: width + +Width of image in pixels + +### Property: height + +Height of image in pixels + +### Property: data + +Buffer of image pixel data. Every pixel consists 4 bytes: R, G, B, A (opacity). + +### Property: gamma + +Gamma of image (0 if not specified) + +## Packing a PNG and removing alpha (RGBA to RGB) + +When removing the alpha channel from an image, there needs to be a background color to correctly +convert each pixel's transparency to the appropriate RGB value. By default, pngjs will flatten +the image against a white background. You can override this in the options: + +```js +var fs = require("fs"), + PNG = require("pngjs").PNG; + +fs.createReadStream("in.png") + .pipe( + new PNG({ + colorType: 2, + bgColor: { + red: 0, + green: 255, + blue: 0, + }, + }) + ) + .on("parsed", function () { + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +# Sync API + +## PNG.sync + +### PNG.sync.read(buffer) + +Take a buffer and returns a PNG image. The properties on the image include the meta data and `data` as per the async API above. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +``` + +### PNG.sync.write(png) + +Take a PNG image and returns a buffer. The properties on the image include the meta data and `data` as per the async API above. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +var options = { colorType: 6 }; +var buffer = PNG.sync.write(png, options); +fs.writeFileSync('out.png', buffer); +``` + +### PNG.adjustGamma(src) + +Adjusts the gamma of a sync image. See the async adjustGamma. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +PNG.adjustGamma(png); +``` + +# Changelog + +### 6.0.0 - 24/10/2020 + +- BREAKING - Sync version now throws if there is unexpected content at the end of the stream. +- BREAKING - Drop support for node 10 (Though nothing incompatible in this release yet) +- Reduce the number of files included in the package + +### 5.1.0 - 13/09/2020 + +- Add option to skip rescaling + +### 5.0.0 - 15/04/2020 + +- Drop support for Node 8 +- Browserified bundle may now contain ES20(15-20) code if the supported node version supports it. Please run the browserified version through babel if you need to support older browsers. + +### 4.0.1 - 15/04/2020 + +- Fix to possible null reference in nextTick of async method + +### 4.0.0 - 09/04/2020 + +- Fix issue in newer nodes with using Buffer +- Fix async issue with some png files +- Drop support for Node 4 & 6 + +### 3.4.0 - 09/03/2019 + +- Include whether the png has alpha in the meta data +- emit an error if the image is truncated instead of hanging +- Add a browserified version +- speed up some mapping functions + +### 3.3.3 - 19/04/2018 + +- Real fix for node 9 + +### 3.3.2 - 16/02/2018 + +- Fix for node 9 + +### 3.3.1 - 15/11/2017 + +- Bugfixes and removal of es6 + +### 3.3.0 + +- Add writing 16 bit channels and support for grayscale input + +### 3.2.0 - 30/04/2017 + +- Support for encoding 8-bit grayscale images + +### 3.1.0 - 30/04/2017 + +- Support for pngs with zlib chunks that are malformed after valid data + +### 3.0.1 - 16/02/2017 + +- Fix single pixel pngs + +### 3.0.0 - 03/08/2016 + +- Drop support for node below v4 and iojs. Pin to 2.3.0 to use with old, unsupported or patched node versions. + +### 2.3.0 - 22/04/2016 + +- Support for sync in node 0.10 + +### 2.2.0 - 04/12/2015 + +- Add sync write api +- Fix newfile example +- Correct comparison table + +### 2.1.0 - 28/10/2015 + +- rename package to pngjs +- added 'bgColor' option + +### 2.0.0 - 08/10/2015 + +- fixes to readme +- _breaking change_ - bitblt on the png prototype now doesn't take a unused, unnecessary src first argument + +### 1.2.0 - 13/09/2015 + +- support passing colorType to write PNG's and writing bitmaps without alpha information + +### 1.1.0 - 07/09/2015 + +- support passing a deflate factory for controlled compression + +### 1.0.2 - 22/08/2015 + +- Expose all PNG creation info + +### 1.0.1 - 21/08/2015 + +- Fix non square interlaced files + +### 1.0.0 - 08/08/2015 + +- More tests +- source linted +- maintainability refactorings +- async API - exceptions in reading now emit warnings +- documentation improvement - sync api now documented, adjustGamma documented +- breaking change - gamma chunk is now written. previously a read then write would destroy gamma information, now it is persisted. + +### 0.0.3 - 03/08/2015 + +- Error handling fixes +- ignore files for smaller npm footprint + +### 0.0.2 - 02/08/2015 + +- Bugfixes to interlacing, support for transparent colours + +### 0.0.1 - 02/08/2015 + +- Initial release, see pngjs for older changelog. + +# License + +(The MIT License) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/bitmapper.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/bitmapper.js new file mode 100644 index 00000000..18378a02 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/bitmapper.js @@ -0,0 +1,267 @@ +"use strict"; + +let interlaceUtils = require("./interlace"); + +let pixelBppMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, data, pxPos, rawPos) { + if (rawPos === data.length) { + throw new Error("Ran out of data"); + } + + let pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = 0xff; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function (pxData, data, pxPos, rawPos) { + if (rawPos + 1 >= data.length) { + throw new Error("Ran out of data"); + } + + let pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = data[rawPos + 1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, data, pxPos, rawPos) { + if (rawPos + 2 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = 0xff; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, data, pxPos, rawPos) { + if (rawPos + 3 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = data[rawPos + 3]; + }, +]; + +let pixelBppCustomMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = maxBit; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function (pxData, pixelData, pxPos) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = pixelData[1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = maxBit; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, pixelData, pxPos) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = pixelData[3]; + }, +]; + +function bitRetriever(data, depth) { + let leftOver = []; + let i = 0; + + function split() { + if (i === data.length) { + throw new Error("Ran out of data"); + } + let byte = data[i]; + i++; + let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1; + switch (depth) { + default: + throw new Error("unrecognised depth"); + case 16: + byte2 = data[i]; + i++; + leftOver.push((byte << 8) + byte2); + break; + case 4: + byte2 = byte & 0x0f; + byte1 = byte >> 4; + leftOver.push(byte1, byte2); + break; + case 2: + byte4 = byte & 3; + byte3 = (byte >> 2) & 3; + byte2 = (byte >> 4) & 3; + byte1 = (byte >> 6) & 3; + leftOver.push(byte1, byte2, byte3, byte4); + break; + case 1: + byte8 = byte & 1; + byte7 = (byte >> 1) & 1; + byte6 = (byte >> 2) & 1; + byte5 = (byte >> 3) & 1; + byte4 = (byte >> 4) & 1; + byte3 = (byte >> 5) & 1; + byte2 = (byte >> 6) & 1; + byte1 = (byte >> 7) & 1; + leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8); + break; + } + } + + return { + get: function (count) { + while (leftOver.length < count) { + split(); + } + let returner = leftOver.slice(0, count); + leftOver = leftOver.slice(count); + return returner; + }, + resetAfterLine: function () { + leftOver.length = 0; + }, + end: function () { + if (i !== data.length) { + throw new Error("extra data found"); + } + }, + }; +} + +function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pxPos = getPxPos(x, y, imagePass); + pixelBppMapper[bpp](pxData, data, pxPos, rawPos); + rawPos += bpp; //eslint-disable-line no-param-reassign + } + } + return rawPos; +} + +function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pixelData = bits.get(bpp); + let pxPos = getPxPos(x, y, imagePass); + pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); + } + bits.resetAfterLine(); + } +} + +exports.dataToBitMap = function (data, bitmapInfo) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let depth = bitmapInfo.depth; + let bpp = bitmapInfo.bpp; + let interlace = bitmapInfo.interlace; + let bits; + + if (depth !== 8) { + bits = bitRetriever(data, depth); + } + let pxData; + if (depth <= 8) { + pxData = Buffer.alloc(width * height * 4); + } else { + pxData = new Uint16Array(width * height * 4); + } + let maxBit = Math.pow(2, depth) - 1; + let rawPos = 0; + let images; + let getPxPos; + + if (interlace) { + images = interlaceUtils.getImagePasses(width, height); + getPxPos = interlaceUtils.getInterlaceIterator(width, height); + } else { + let nonInterlacedPxPos = 0; + getPxPos = function () { + let returner = nonInterlacedPxPos; + nonInterlacedPxPos += 4; + return returner; + }; + images = [{ width: width, height: height }]; + } + + for (let imageIndex = 0; imageIndex < images.length; imageIndex++) { + if (depth === 8) { + rawPos = mapImage8Bit( + images[imageIndex], + pxData, + getPxPos, + bpp, + data, + rawPos + ); + } else { + mapImageCustomBit( + images[imageIndex], + pxData, + getPxPos, + bpp, + bits, + maxBit + ); + } + } + if (depth === 8) { + if (rawPos !== data.length) { + throw new Error("extra data found"); + } + } else { + bits.end(); + } + + return pxData; +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/bitpacker.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/bitpacker.js new file mode 100644 index 00000000..d7a4e656 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/bitpacker.js @@ -0,0 +1,158 @@ +"use strict"; + +let constants = require("./constants"); + +module.exports = function (dataIn, width, height, options) { + let outHasAlpha = + [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf( + options.colorType + ) !== -1; + if (options.colorType === options.inputColorType) { + let bigEndian = (function () { + let buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] !== 256; + })(); + // If no need to convert to grayscale and alpha is present/absent in both, take a fast route + if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) { + return dataIn; + } + } + + // map to a UInt16 array if data is 16bit, fix endianness below + let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); + + let maxValue = 255; + let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType]; + if (inBpp === 4 && !options.inputHasAlpha) { + inBpp = 3; + } + let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType]; + if (options.bitDepth === 16) { + maxValue = 65535; + outBpp *= 2; + } + let outData = Buffer.alloc(width * height * outBpp); + + let inIndex = 0; + let outIndex = 0; + + let bgColor = options.bgColor || {}; + if (bgColor.red === undefined) { + bgColor.red = maxValue; + } + if (bgColor.green === undefined) { + bgColor.green = maxValue; + } + if (bgColor.blue === undefined) { + bgColor.blue = maxValue; + } + + function getRGBA() { + let red; + let green; + let blue; + let alpha = maxValue; + switch (options.inputColorType) { + case constants.COLORTYPE_COLOR_ALPHA: + alpha = data[inIndex + 3]; + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_COLOR: + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_ALPHA: + alpha = data[inIndex + 1]; + red = data[inIndex]; + green = red; + blue = red; + break; + case constants.COLORTYPE_GRAYSCALE: + red = data[inIndex]; + green = red; + blue = red; + break; + default: + throw new Error( + "input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + + if (options.inputHasAlpha) { + if (!outHasAlpha) { + alpha /= maxValue; + red = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), + maxValue + ); + green = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), + maxValue + ); + blue = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), + maxValue + ); + } + } + return { red: red, green: green, blue: blue, alpha: alpha }; + } + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let rgba = getRGBA(data, inIndex); + + switch (options.colorType) { + case constants.COLORTYPE_COLOR_ALPHA: + case constants.COLORTYPE_COLOR: + if (options.bitDepth === 8) { + outData[outIndex] = rgba.red; + outData[outIndex + 1] = rgba.green; + outData[outIndex + 2] = rgba.blue; + if (outHasAlpha) { + outData[outIndex + 3] = rgba.alpha; + } + } else { + outData.writeUInt16BE(rgba.red, outIndex); + outData.writeUInt16BE(rgba.green, outIndex + 2); + outData.writeUInt16BE(rgba.blue, outIndex + 4); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 6); + } + } + break; + case constants.COLORTYPE_ALPHA: + case constants.COLORTYPE_GRAYSCALE: { + // Convert to grayscale and alpha + let grayscale = (rgba.red + rgba.green + rgba.blue) / 3; + if (options.bitDepth === 8) { + outData[outIndex] = grayscale; + if (outHasAlpha) { + outData[outIndex + 1] = rgba.alpha; + } + } else { + outData.writeUInt16BE(grayscale, outIndex); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 2); + } + } + break; + } + default: + throw new Error("unrecognised color Type " + options.colorType); + } + + inIndex += inBpp; + outIndex += outBpp; + } + } + + return outData; +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/chunkstream.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/chunkstream.js new file mode 100644 index 00000000..95b46d48 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/chunkstream.js @@ -0,0 +1,189 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); + +let ChunkStream = (module.exports = function () { + Stream.call(this); + + this._buffers = []; + this._buffered = 0; + + this._reads = []; + this._paused = false; + + this._encoding = "utf8"; + this.writable = true; +}); +util.inherits(ChunkStream, Stream); + +ChunkStream.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); + + process.nextTick( + function () { + this._process(); + + // its paused and there is not enought data then ask for more + if (this._paused && this._reads && this._reads.length > 0) { + this._paused = false; + + this.emit("drain"); + } + }.bind(this) + ); +}; + +ChunkStream.prototype.write = function (data, encoding) { + if (!this.writable) { + this.emit("error", new Error("Stream not writable")); + return false; + } + + let dataBuffer; + if (Buffer.isBuffer(data)) { + dataBuffer = data; + } else { + dataBuffer = Buffer.from(data, encoding || this._encoding); + } + + this._buffers.push(dataBuffer); + this._buffered += dataBuffer.length; + + this._process(); + + // ok if there are no more read requests + if (this._reads && this._reads.length === 0) { + this._paused = true; + } + + return this.writable && !this._paused; +}; + +ChunkStream.prototype.end = function (data, encoding) { + if (data) { + this.write(data, encoding); + } + + this.writable = false; + + // already destroyed + if (!this._buffers) { + return; + } + + // enqueue or handle end + if (this._buffers.length === 0) { + this._end(); + } else { + this._buffers.push(null); + this._process(); + } +}; + +ChunkStream.prototype.destroySoon = ChunkStream.prototype.end; + +ChunkStream.prototype._end = function () { + if (this._reads.length > 0) { + this.emit("error", new Error("Unexpected end of input")); + } + + this.destroy(); +}; + +ChunkStream.prototype.destroy = function () { + if (!this._buffers) { + return; + } + + this.writable = false; + this._reads = null; + this._buffers = null; + + this.emit("close"); +}; + +ChunkStream.prototype._processReadAllowingLess = function (read) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + // first we need to peek into first buffer + let smallerBuf = this._buffers[0]; + + // ok there is more data than we need + if (smallerBuf.length > read.length) { + this._buffered -= read.length; + this._buffers[0] = smallerBuf.slice(read.length); + + read.func.call(this, smallerBuf.slice(0, read.length)); + } else { + // ok this is less than maximum length so use it all + this._buffered -= smallerBuf.length; + this._buffers.shift(); // == smallerBuf + + read.func.call(this, smallerBuf); + } +}; + +ChunkStream.prototype._processRead = function (read) { + this._reads.shift(); // == read + + let pos = 0; + let count = 0; + let data = Buffer.alloc(read.length); + + // create buffer for all data + while (pos < read.length) { + let buf = this._buffers[count++]; + let len = Math.min(buf.length, read.length - pos); + + buf.copy(data, pos, 0, len); + pos += len; + + // last buffer wasn't used all so just slice it and leave + if (len !== buf.length) { + this._buffers[--count] = buf.slice(len); + } + } + + // remove all used buffers + if (count > 0) { + this._buffers.splice(0, count); + } + + this._buffered -= read.length; + + read.func.call(this, data); +}; + +ChunkStream.prototype._process = function () { + try { + // as long as there is any data and read requests + while (this._buffered > 0 && this._reads && this._reads.length > 0) { + let read = this._reads[0]; + + // read any data (but no more than length) + if (read.allowLess) { + this._processReadAllowingLess(read); + } else if (this._buffered >= read.length) { + // ok we can meet some expectations + + this._processRead(read); + } else { + // not enought data to satisfy first request in queue + // so we need to wait for more + break; + } + } + + if (this._buffers && !this.writable) { + this._end(); + } + } catch (ex) { + this.emit("error", ex); + } +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/constants.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/constants.js new file mode 100644 index 00000000..21fdad68 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/constants.js @@ -0,0 +1,32 @@ +"use strict"; + +module.exports = { + PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], + + TYPE_IHDR: 0x49484452, + TYPE_IEND: 0x49454e44, + TYPE_IDAT: 0x49444154, + TYPE_PLTE: 0x504c5445, + TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase + TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase + + // color-type bits + COLORTYPE_GRAYSCALE: 0, + COLORTYPE_PALETTE: 1, + COLORTYPE_COLOR: 2, + COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha + + // color-type combinations + COLORTYPE_PALETTE_COLOR: 3, + COLORTYPE_COLOR_ALPHA: 6, + + COLORTYPE_TO_BPP_MAP: { + 0: 1, + 2: 3, + 3: 1, + 4: 2, + 6: 4, + }, + + GAMMA_DIVISION: 100000, +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/crc.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/crc.js new file mode 100644 index 00000000..950ec8ae --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/crc.js @@ -0,0 +1,40 @@ +"use strict"; + +let crcTable = []; + +(function () { + for (let i = 0; i < 256; i++) { + let currentCrc = i; + for (let j = 0; j < 8; j++) { + if (currentCrc & 1) { + currentCrc = 0xedb88320 ^ (currentCrc >>> 1); + } else { + currentCrc = currentCrc >>> 1; + } + } + crcTable[i] = currentCrc; + } +})(); + +let CrcCalculator = (module.exports = function () { + this._crc = -1; +}); + +CrcCalculator.prototype.write = function (data) { + for (let i = 0; i < data.length; i++) { + this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8); + } + return true; +}; + +CrcCalculator.prototype.crc32 = function () { + return this._crc ^ -1; +}; + +CrcCalculator.crc32 = function (buf) { + let crc = -1; + for (let i = 0; i < buf.length; i++) { + crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return crc ^ -1; +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-pack.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-pack.js new file mode 100644 index 00000000..32c85c40 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-pack.js @@ -0,0 +1,171 @@ +"use strict"; + +let paethPredictor = require("./paeth-predictor"); + +function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + rawData[rawPos + x] = pxData[pxPos + x]; + } +} + +function filterSumNone(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + + for (let i = pxPos; i < length; i++) { + sum += Math.abs(pxData[i]); + } + return sum; +} + +function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + rawData[rawPos + x] = val; + } +} + +function filterSumSub(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + sum += Math.abs(val); + } + + return sum; +} + +function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - up; + + rawData[rawPos + x] = val; + } +} + +function filterSumUp(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + for (let x = pxPos; x < length; x++) { + let up = pxPos > 0 ? pxData[x - byteWidth] : 0; + let val = pxData[x] - up; + + sum += Math.abs(val); + } + + return sum; +} + +function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + rawData[rawPos + x] = val; + } +} + +function filterSumAvg(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + sum += Math.abs(val); + } + + return sum; +} + +function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + rawData[rawPos + x] = val; + } +} + +function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + sum += Math.abs(val); + } + + return sum; +} + +let filters = { + 0: filterNone, + 1: filterSub, + 2: filterUp, + 3: filterAvg, + 4: filterPaeth, +}; + +let filterSums = { + 0: filterSumNone, + 1: filterSumSub, + 2: filterSumUp, + 3: filterSumAvg, + 4: filterSumPaeth, +}; + +module.exports = function (pxData, width, height, options, bpp) { + let filterTypes; + if (!("filterType" in options) || options.filterType === -1) { + filterTypes = [0, 1, 2, 3, 4]; + } else if (typeof options.filterType === "number") { + filterTypes = [options.filterType]; + } else { + throw new Error("unrecognised filter types"); + } + + if (options.bitDepth === 16) { + bpp *= 2; + } + let byteWidth = width * bpp; + let rawPos = 0; + let pxPos = 0; + let rawData = Buffer.alloc((byteWidth + 1) * height); + + let sel = filterTypes[0]; + + for (let y = 0; y < height; y++) { + if (filterTypes.length > 1) { + // find best filter for this line (with lowest sum of values) + let min = Infinity; + + for (let i = 0; i < filterTypes.length; i++) { + let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp); + if (sum < min) { + sel = filterTypes[i]; + min = sum; + } + } + } + + rawData[rawPos] = sel; + rawPos++; + filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); + rawPos += byteWidth; + pxPos += byteWidth; + } + return rawData; +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse-async.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse-async.js new file mode 100644 index 00000000..832b86cd --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse-async.js @@ -0,0 +1,24 @@ +"use strict"; + +let util = require("util"); +let ChunkStream = require("./chunkstream"); +let Filter = require("./filter-parse"); + +let FilterAsync = (module.exports = function (bitmapInfo) { + ChunkStream.call(this); + + let buffers = []; + let that = this; + this._filter = new Filter(bitmapInfo, { + read: this.read.bind(this), + write: function (buffer) { + buffers.push(buffer); + }, + complete: function () { + that.emit("complete", Buffer.concat(buffers)); + }, + }); + + this._filter.start(); +}); +util.inherits(FilterAsync, ChunkStream); diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse-sync.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse-sync.js new file mode 100644 index 00000000..6924d161 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse-sync.js @@ -0,0 +1,21 @@ +"use strict"; + +let SyncReader = require("./sync-reader"); +let Filter = require("./filter-parse"); + +exports.process = function (inBuffer, bitmapInfo) { + let outBuffers = []; + let reader = new SyncReader(inBuffer); + let filter = new Filter(bitmapInfo, { + read: reader.read.bind(reader), + write: function (bufferPart) { + outBuffers.push(bufferPart); + }, + complete: function () {}, + }); + + filter.start(); + reader.process(); + + return Buffer.concat(outBuffers); +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse.js new file mode 100644 index 00000000..3a32e5ee --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/filter-parse.js @@ -0,0 +1,177 @@ +"use strict"; + +let interlaceUtils = require("./interlace"); +let paethPredictor = require("./paeth-predictor"); + +function getByteWidth(width, bpp, depth) { + let byteWidth = width * bpp; + if (depth !== 8) { + byteWidth = Math.ceil(byteWidth / (8 / depth)); + } + return byteWidth; +} + +let Filter = (module.exports = function (bitmapInfo, dependencies) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let interlace = bitmapInfo.interlace; + let bpp = bitmapInfo.bpp; + let depth = bitmapInfo.depth; + + this.read = dependencies.read; + this.write = dependencies.write; + this.complete = dependencies.complete; + + this._imageIndex = 0; + this._images = []; + if (interlace) { + let passes = interlaceUtils.getImagePasses(width, height); + for (let i = 0; i < passes.length; i++) { + this._images.push({ + byteWidth: getByteWidth(passes[i].width, bpp, depth), + height: passes[i].height, + lineIndex: 0, + }); + } + } else { + this._images.push({ + byteWidth: getByteWidth(width, bpp, depth), + height: height, + lineIndex: 0, + }); + } + + // when filtering the line we look at the pixel to the left + // the spec also says it is done on a byte level regardless of the number of pixels + // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back + // a pixel rather than just a different byte part. However if we are sub byte, we ignore. + if (depth === 8) { + this._xComparison = bpp; + } else if (depth === 16) { + this._xComparison = bpp * 2; + } else { + this._xComparison = 1; + } +}); + +Filter.prototype.start = function () { + this.read( + this._images[this._imageIndex].byteWidth + 1, + this._reverseFilterLine.bind(this) + ); +}; + +Filter.prototype._unFilterType1 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + unfilteredLine[x] = rawByte + f1Left; + } +}; + +Filter.prototype._unFilterType2 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f2Up = lastLine ? lastLine[x] : 0; + unfilteredLine[x] = rawByte + f2Up; + } +}; + +Filter.prototype._unFilterType3 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f3Up = lastLine ? lastLine[x] : 0; + let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f3Add = Math.floor((f3Left + f3Up) / 2); + unfilteredLine[x] = rawByte + f3Add; + } +}; + +Filter.prototype._unFilterType4 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f4Up = lastLine ? lastLine[x] : 0; + let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; + let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); + unfilteredLine[x] = rawByte + f4Add; + } +}; + +Filter.prototype._reverseFilterLine = function (rawData) { + let filter = rawData[0]; + let unfilteredLine; + let currentImage = this._images[this._imageIndex]; + let byteWidth = currentImage.byteWidth; + + if (filter === 0) { + unfilteredLine = rawData.slice(1, byteWidth + 1); + } else { + unfilteredLine = Buffer.alloc(byteWidth); + + switch (filter) { + case 1: + this._unFilterType1(rawData, unfilteredLine, byteWidth); + break; + case 2: + this._unFilterType2(rawData, unfilteredLine, byteWidth); + break; + case 3: + this._unFilterType3(rawData, unfilteredLine, byteWidth); + break; + case 4: + this._unFilterType4(rawData, unfilteredLine, byteWidth); + break; + default: + throw new Error("Unrecognised filter type - " + filter); + } + } + + this.write(unfilteredLine); + + currentImage.lineIndex++; + if (currentImage.lineIndex >= currentImage.height) { + this._lastLine = null; + this._imageIndex++; + currentImage = this._images[this._imageIndex]; + } else { + this._lastLine = unfilteredLine; + } + + if (currentImage) { + // read, using the byte width that may be from the new current image + this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this)); + } else { + this._lastLine = null; + this.complete(); + } +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/format-normaliser.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/format-normaliser.js new file mode 100644 index 00000000..209b66bb --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/format-normaliser.js @@ -0,0 +1,93 @@ +"use strict"; + +function dePalette(indata, outdata, width, height, palette) { + let pxPos = 0; + // use values from palette + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let color = palette[indata[pxPos]]; + + if (!color) { + throw new Error("index " + indata[pxPos] + " not in palette"); + } + + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = color[i]; + } + pxPos += 4; + } + } +} + +function replaceTransparentColor(indata, outdata, width, height, transColor) { + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let makeTrans = false; + + if (transColor.length === 1) { + if (transColor[0] === indata[pxPos]) { + makeTrans = true; + } + } else if ( + transColor[0] === indata[pxPos] && + transColor[1] === indata[pxPos + 1] && + transColor[2] === indata[pxPos + 2] + ) { + makeTrans = true; + } + if (makeTrans) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = 0; + } + } + pxPos += 4; + } + } +} + +function scaleDepth(indata, outdata, width, height, depth) { + let maxOutSample = 255; + let maxInSample = Math.pow(2, depth) - 1; + let pxPos = 0; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = Math.floor( + (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5 + ); + } + pxPos += 4; + } + } +} + +module.exports = function (indata, imageData, skipRescale = false) { + let depth = imageData.depth; + let width = imageData.width; + let height = imageData.height; + let colorType = imageData.colorType; + let transColor = imageData.transColor; + let palette = imageData.palette; + + let outdata = indata; // only different for 16 bits + + if (colorType === 3) { + // paletted + dePalette(indata, outdata, width, height, palette); + } else { + if (transColor) { + replaceTransparentColor(indata, outdata, width, height, transColor); + } + // if it needs scaling + if (depth !== 8 && !skipRescale) { + // if we need to change the buffer size + if (depth === 16) { + outdata = Buffer.alloc(width * height * 4); + } + scaleDepth(indata, outdata, width, height, depth); + } + } + return outdata; +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/interlace.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/interlace.js new file mode 100644 index 00000000..a035cb15 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/interlace.js @@ -0,0 +1,95 @@ +"use strict"; + +// Adam 7 +// 0 1 2 3 4 5 6 7 +// 0 x 6 4 6 x 6 4 6 +// 1 7 7 7 7 7 7 7 7 +// 2 5 6 5 6 5 6 5 6 +// 3 7 7 7 7 7 7 7 7 +// 4 3 6 4 6 3 6 4 6 +// 5 7 7 7 7 7 7 7 7 +// 6 5 6 5 6 5 6 5 6 +// 7 7 7 7 7 7 7 7 7 + +let imagePasses = [ + { + // pass 1 - 1px + x: [0], + y: [0], + }, + { + // pass 2 - 1px + x: [4], + y: [0], + }, + { + // pass 3 - 2px + x: [0, 4], + y: [4], + }, + { + // pass 4 - 4px + x: [2, 6], + y: [0, 4], + }, + { + // pass 5 - 8px + x: [0, 2, 4, 6], + y: [2, 6], + }, + { + // pass 6 - 16px + x: [1, 3, 5, 7], + y: [0, 2, 4, 6], + }, + { + // pass 7 - 32px + x: [0, 1, 2, 3, 4, 5, 6, 7], + y: [1, 3, 5, 7], + }, +]; + +exports.getImagePasses = function (width, height) { + let images = []; + let xLeftOver = width % 8; + let yLeftOver = height % 8; + let xRepeats = (width - xLeftOver) / 8; + let yRepeats = (height - yLeftOver) / 8; + for (let i = 0; i < imagePasses.length; i++) { + let pass = imagePasses[i]; + let passWidth = xRepeats * pass.x.length; + let passHeight = yRepeats * pass.y.length; + for (let j = 0; j < pass.x.length; j++) { + if (pass.x[j] < xLeftOver) { + passWidth++; + } else { + break; + } + } + for (let j = 0; j < pass.y.length; j++) { + if (pass.y[j] < yLeftOver) { + passHeight++; + } else { + break; + } + } + if (passWidth > 0 && passHeight > 0) { + images.push({ width: passWidth, height: passHeight, index: i }); + } + } + return images; +}; + +exports.getInterlaceIterator = function (width) { + return function (x, y, pass) { + let outerXLeftOver = x % imagePasses[pass].x.length; + let outerX = + ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 + + imagePasses[pass].x[outerXLeftOver]; + let outerYLeftOver = y % imagePasses[pass].y.length; + let outerY = + ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 + + imagePasses[pass].y[outerYLeftOver]; + return outerX * 4 + outerY * width * 4; + }; +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/packer-async.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/packer-async.js new file mode 100644 index 00000000..f3df73aa --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/packer-async.js @@ -0,0 +1,50 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let constants = require("./constants"); +let Packer = require("./packer"); + +let PackerAsync = (module.exports = function (opt) { + Stream.call(this); + + let options = opt || {}; + + this._packer = new Packer(options); + this._deflate = this._packer.createDeflate(); + + this.readable = true; +}); +util.inherits(PackerAsync, Stream); + +PackerAsync.prototype.pack = function (data, width, height, gamma) { + // Signature + this.emit("data", Buffer.from(constants.PNG_SIGNATURE)); + this.emit("data", this._packer.packIHDR(width, height)); + + if (gamma) { + this.emit("data", this._packer.packGAMA(gamma)); + } + + let filteredData = this._packer.filterData(data, width, height); + + // compress it + this._deflate.on("error", this.emit.bind(this, "error")); + + this._deflate.on( + "data", + function (compressedData) { + this.emit("data", this._packer.packIDAT(compressedData)); + }.bind(this) + ); + + this._deflate.on( + "end", + function () { + this.emit("data", this._packer.packIEND()); + this.emit("end"); + }.bind(this) + ); + + this._deflate.end(filteredData); +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/packer-sync.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/packer-sync.js new file mode 100644 index 00000000..f5ab0b3d --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/packer-sync.js @@ -0,0 +1,56 @@ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let constants = require("./constants"); +let Packer = require("./packer"); + +module.exports = function (metaData, opt) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let options = opt || {}; + + let packer = new Packer(options); + + let chunks = []; + + // Signature + chunks.push(Buffer.from(constants.PNG_SIGNATURE)); + + // Header + chunks.push(packer.packIHDR(metaData.width, metaData.height)); + + if (metaData.gamma) { + chunks.push(packer.packGAMA(metaData.gamma)); + } + + let filteredData = packer.filterData( + metaData.data, + metaData.width, + metaData.height + ); + + // compress it + let compressedData = zlib.deflateSync( + filteredData, + packer.getDeflateOptions() + ); + filteredData = null; + + if (!compressedData || !compressedData.length) { + throw new Error("bad png - invalid compressed data response"); + } + chunks.push(packer.packIDAT(compressedData)); + + // End + chunks.push(packer.packIEND()); + + return Buffer.concat(chunks); +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/packer.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/packer.js new file mode 100644 index 00000000..4aba12c8 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/packer.js @@ -0,0 +1,129 @@ +"use strict"; + +let constants = require("./constants"); +let CrcStream = require("./crc"); +let bitPacker = require("./bitpacker"); +let filter = require("./filter-pack"); +let zlib = require("zlib"); + +let Packer = (module.exports = function (options) { + this._options = options; + + options.deflateChunkSize = options.deflateChunkSize || 32 * 1024; + options.deflateLevel = + options.deflateLevel != null ? options.deflateLevel : 9; + options.deflateStrategy = + options.deflateStrategy != null ? options.deflateStrategy : 3; + options.inputHasAlpha = + options.inputHasAlpha != null ? options.inputHasAlpha : true; + options.deflateFactory = options.deflateFactory || zlib.createDeflate; + options.bitDepth = options.bitDepth || 8; + // This is outputColorType + options.colorType = + typeof options.colorType === "number" + ? options.colorType + : constants.COLORTYPE_COLOR_ALPHA; + options.inputColorType = + typeof options.inputColorType === "number" + ? options.inputColorType + : constants.COLORTYPE_COLOR_ALPHA; + + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.colorType) === -1 + ) { + throw new Error( + "option color type:" + options.colorType + " is not supported at present" + ); + } + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.inputColorType) === -1 + ) { + throw new Error( + "option input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + if (options.bitDepth !== 8 && options.bitDepth !== 16) { + throw new Error( + "option bit depth:" + options.bitDepth + " is not supported at present" + ); + } +}); + +Packer.prototype.getDeflateOptions = function () { + return { + chunkSize: this._options.deflateChunkSize, + level: this._options.deflateLevel, + strategy: this._options.deflateStrategy, + }; +}; + +Packer.prototype.createDeflate = function () { + return this._options.deflateFactory(this.getDeflateOptions()); +}; + +Packer.prototype.filterData = function (data, width, height) { + // convert to correct format for filtering (e.g. right bpp and bit depth) + let packedData = bitPacker(data, width, height, this._options); + + // filter pixel data + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType]; + let filteredData = filter(packedData, width, height, this._options, bpp); + return filteredData; +}; + +Packer.prototype._packChunk = function (type, data) { + let len = data ? data.length : 0; + let buf = Buffer.alloc(len + 12); + + buf.writeUInt32BE(len, 0); + buf.writeUInt32BE(type, 4); + + if (data) { + data.copy(buf, 8); + } + + buf.writeInt32BE( + CrcStream.crc32(buf.slice(4, buf.length - 4)), + buf.length - 4 + ); + return buf; +}; + +Packer.prototype.packGAMA = function (gamma) { + let buf = Buffer.alloc(4); + buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0); + return this._packChunk(constants.TYPE_gAMA, buf); +}; + +Packer.prototype.packIHDR = function (width, height) { + let buf = Buffer.alloc(13); + buf.writeUInt32BE(width, 0); + buf.writeUInt32BE(height, 4); + buf[8] = this._options.bitDepth; // Bit depth + buf[9] = this._options.colorType; // colorType + buf[10] = 0; // compression + buf[11] = 0; // filter + buf[12] = 0; // interlace + + return this._packChunk(constants.TYPE_IHDR, buf); +}; + +Packer.prototype.packIDAT = function (data) { + return this._packChunk(constants.TYPE_IDAT, data); +}; + +Packer.prototype.packIEND = function () { + return this._packChunk(constants.TYPE_IEND, null); +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/paeth-predictor.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/paeth-predictor.js new file mode 100644 index 00000000..9634497d --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/paeth-predictor.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function paethPredictor(left, above, upLeft) { + let paeth = left + above - upLeft; + let pLeft = Math.abs(paeth - left); + let pAbove = Math.abs(paeth - above); + let pUpLeft = Math.abs(paeth - upLeft); + + if (pLeft <= pAbove && pLeft <= pUpLeft) { + return left; + } + if (pAbove <= pUpLeft) { + return above; + } + return upLeft; +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/parser-async.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/parser-async.js new file mode 100644 index 00000000..1aacde34 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/parser-async.js @@ -0,0 +1,169 @@ +"use strict"; + +let util = require("util"); +let zlib = require("zlib"); +let ChunkStream = require("./chunkstream"); +let FilterAsync = require("./filter-parse-async"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +let ParserAsync = (module.exports = function (options) { + ChunkStream.call(this); + + this._parser = new Parser(options, { + read: this.read.bind(this), + error: this._handleError.bind(this), + metadata: this._handleMetaData.bind(this), + gamma: this.emit.bind(this, "gamma"), + palette: this._handlePalette.bind(this), + transColor: this._handleTransColor.bind(this), + finished: this._finished.bind(this), + inflateData: this._inflateData.bind(this), + simpleTransparency: this._simpleTransparency.bind(this), + headersFinished: this._headersFinished.bind(this), + }); + this._options = options; + this.writable = true; + + this._parser.start(); +}); +util.inherits(ParserAsync, ChunkStream); + +ParserAsync.prototype._handleError = function (err) { + this.emit("error", err); + + this.writable = false; + + this.destroy(); + + if (this._inflate && this._inflate.destroy) { + this._inflate.destroy(); + } + + if (this._filter) { + this._filter.destroy(); + // For backward compatibility with Node 7 and below. + // Suppress errors due to _inflate calling write() even after + // it's destroy()'ed. + this._filter.on("error", function () {}); + } + + this.errord = true; +}; + +ParserAsync.prototype._inflateData = function (data) { + if (!this._inflate) { + if (this._bitmapInfo.interlace) { + this._inflate = zlib.createInflate(); + + this._inflate.on("error", this.emit.bind(this, "error")); + this._filter.on("complete", this._complete.bind(this)); + + this._inflate.pipe(this._filter); + } else { + let rowSize = + ((this._bitmapInfo.width * + this._bitmapInfo.bpp * + this._bitmapInfo.depth + + 7) >> + 3) + + 1; + let imageSize = rowSize * this._bitmapInfo.height; + let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); + + this._inflate = zlib.createInflate({ chunkSize: chunkSize }); + let leftToInflate = imageSize; + + let emitError = this.emit.bind(this, "error"); + this._inflate.on("error", function (err) { + if (!leftToInflate) { + return; + } + + emitError(err); + }); + this._filter.on("complete", this._complete.bind(this)); + + let filterWrite = this._filter.write.bind(this._filter); + this._inflate.on("data", function (chunk) { + if (!leftToInflate) { + return; + } + + if (chunk.length > leftToInflate) { + chunk = chunk.slice(0, leftToInflate); + } + + leftToInflate -= chunk.length; + + filterWrite(chunk); + }); + + this._inflate.on("end", this._filter.end.bind(this._filter)); + } + } + this._inflate.write(data); +}; + +ParserAsync.prototype._handleMetaData = function (metaData) { + this._metaData = metaData; + this._bitmapInfo = Object.create(metaData); + + this._filter = new FilterAsync(this._bitmapInfo); +}; + +ParserAsync.prototype._handleTransColor = function (transColor) { + this._bitmapInfo.transColor = transColor; +}; + +ParserAsync.prototype._handlePalette = function (palette) { + this._bitmapInfo.palette = palette; +}; + +ParserAsync.prototype._simpleTransparency = function () { + this._metaData.alpha = true; +}; + +ParserAsync.prototype._headersFinished = function () { + // Up until this point, we don't know if we have a tRNS chunk (alpha) + // so we can't emit metadata any earlier + this.emit("metadata", this._metaData); +}; + +ParserAsync.prototype._finished = function () { + if (this.errord) { + return; + } + + if (!this._inflate) { + this.emit("error", "No Inflate block"); + } else { + // no more data to inflate + this._inflate.end(); + } +}; + +ParserAsync.prototype._complete = function (filteredData) { + if (this.errord) { + return; + } + + let normalisedBitmapData; + + try { + let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); + + normalisedBitmapData = formatNormaliser( + bitmapData, + this._bitmapInfo, + this._options.skipRescale + ); + bitmapData = null; + } catch (ex) { + this._handleError(ex); + return; + } + + this.emit("parsed", normalisedBitmapData); +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/parser-sync.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/parser-sync.js new file mode 100644 index 00000000..76cb134b --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/parser-sync.js @@ -0,0 +1,112 @@ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +let inflateSync = require("./sync-inflate"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let SyncReader = require("./sync-reader"); +let FilterSync = require("./filter-parse-sync"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +module.exports = function (buffer, options) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let err; + function handleError(_err_) { + err = _err_; + } + + let metaData; + function handleMetaData(_metaData_) { + metaData = _metaData_; + } + + function handleTransColor(transColor) { + metaData.transColor = transColor; + } + + function handlePalette(palette) { + metaData.palette = palette; + } + + function handleSimpleTransparency() { + metaData.alpha = true; + } + + let gamma; + function handleGamma(_gamma_) { + gamma = _gamma_; + } + + let inflateDataList = []; + function handleInflateData(inflatedData) { + inflateDataList.push(inflatedData); + } + + let reader = new SyncReader(buffer); + + let parser = new Parser(options, { + read: reader.read.bind(reader), + error: handleError, + metadata: handleMetaData, + gamma: handleGamma, + palette: handlePalette, + transColor: handleTransColor, + inflateData: handleInflateData, + simpleTransparency: handleSimpleTransparency, + }); + + parser.start(); + reader.process(); + + if (err) { + throw err; + } + + //join together the inflate datas + let inflateData = Buffer.concat(inflateDataList); + inflateDataList.length = 0; + + let inflatedData; + if (metaData.interlace) { + inflatedData = zlib.inflateSync(inflateData); + } else { + let rowSize = + ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1; + let imageSize = rowSize * metaData.height; + inflatedData = inflateSync(inflateData, { + chunkSize: imageSize, + maxLength: imageSize, + }); + } + inflateData = null; + + if (!inflatedData || !inflatedData.length) { + throw new Error("bad png - invalid inflate data response"); + } + + let unfilteredData = FilterSync.process(inflatedData, metaData); + inflateData = null; + + let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); + unfilteredData = null; + + let normalisedBitmapData = formatNormaliser( + bitmapData, + metaData, + options.skipRescale + ); + + metaData.data = normalisedBitmapData; + metaData.gamma = gamma || 0; + + return metaData; +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/parser.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/parser.js new file mode 100644 index 00000000..51a8f2a5 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/parser.js @@ -0,0 +1,290 @@ +"use strict"; + +let constants = require("./constants"); +let CrcCalculator = require("./crc"); + +let Parser = (module.exports = function (options, dependencies) { + this._options = options; + options.checkCRC = options.checkCRC !== false; + + this._hasIHDR = false; + this._hasIEND = false; + this._emittedHeadersFinished = false; + + // input flags/metadata + this._palette = []; + this._colorType = 0; + + this._chunks = {}; + this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this); + this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this); + this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this); + this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this); + this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this); + this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this); + + this.read = dependencies.read; + this.error = dependencies.error; + this.metadata = dependencies.metadata; + this.gamma = dependencies.gamma; + this.transColor = dependencies.transColor; + this.palette = dependencies.palette; + this.parsed = dependencies.parsed; + this.inflateData = dependencies.inflateData; + this.finished = dependencies.finished; + this.simpleTransparency = dependencies.simpleTransparency; + this.headersFinished = dependencies.headersFinished || function () {}; +}); + +Parser.prototype.start = function () { + this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this)); +}; + +Parser.prototype._parseSignature = function (data) { + let signature = constants.PNG_SIGNATURE; + + for (let i = 0; i < signature.length; i++) { + if (data[i] !== signature[i]) { + this.error(new Error("Invalid file signature")); + return; + } + } + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._parseChunkBegin = function (data) { + // chunk content length + let length = data.readUInt32BE(0); + + // chunk type + let type = data.readUInt32BE(4); + let name = ""; + for (let i = 4; i < 8; i++) { + name += String.fromCharCode(data[i]); + } + + //console.log('chunk ', name, length); + + // chunk flags + let ancillary = Boolean(data[4] & 0x20); // or critical + // priv = Boolean(data[5] & 0x20), // or public + // safeToCopy = Boolean(data[7] & 0x20); // or unsafe + + if (!this._hasIHDR && type !== constants.TYPE_IHDR) { + this.error(new Error("Expected IHDR on beggining")); + return; + } + + this._crc = new CrcCalculator(); + this._crc.write(Buffer.from(name)); + + if (this._chunks[type]) { + return this._chunks[type](length); + } + + if (!ancillary) { + this.error(new Error("Unsupported critical chunk type " + name)); + return; + } + + this.read(length + 4, this._skipChunk.bind(this)); +}; + +Parser.prototype._skipChunk = function (/*data*/) { + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._handleChunkEnd = function () { + this.read(4, this._parseChunkEnd.bind(this)); +}; + +Parser.prototype._parseChunkEnd = function (data) { + let fileCrc = data.readInt32BE(0); + let calcCrc = this._crc.crc32(); + + // check CRC + if (this._options.checkCRC && calcCrc !== fileCrc) { + this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc)); + return; + } + + if (!this._hasIEND) { + this.read(8, this._parseChunkBegin.bind(this)); + } +}; + +Parser.prototype._handleIHDR = function (length) { + this.read(length, this._parseIHDR.bind(this)); +}; +Parser.prototype._parseIHDR = function (data) { + this._crc.write(data); + + let width = data.readUInt32BE(0); + let height = data.readUInt32BE(4); + let depth = data[8]; + let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha + let compr = data[10]; + let filter = data[11]; + let interlace = data[12]; + + // console.log(' width', width, 'height', height, + // 'depth', depth, 'colorType', colorType, + // 'compr', compr, 'filter', filter, 'interlace', interlace + // ); + + if ( + depth !== 8 && + depth !== 4 && + depth !== 2 && + depth !== 1 && + depth !== 16 + ) { + this.error(new Error("Unsupported bit depth " + depth)); + return; + } + if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) { + this.error(new Error("Unsupported color type")); + return; + } + if (compr !== 0) { + this.error(new Error("Unsupported compression method")); + return; + } + if (filter !== 0) { + this.error(new Error("Unsupported filter method")); + return; + } + if (interlace !== 0 && interlace !== 1) { + this.error(new Error("Unsupported interlace method")); + return; + } + + this._colorType = colorType; + + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; + + this._hasIHDR = true; + + this.metadata({ + width: width, + height: height, + depth: depth, + interlace: Boolean(interlace), + palette: Boolean(colorType & constants.COLORTYPE_PALETTE), + color: Boolean(colorType & constants.COLORTYPE_COLOR), + alpha: Boolean(colorType & constants.COLORTYPE_ALPHA), + bpp: bpp, + colorType: colorType, + }); + + this._handleChunkEnd(); +}; + +Parser.prototype._handlePLTE = function (length) { + this.read(length, this._parsePLTE.bind(this)); +}; +Parser.prototype._parsePLTE = function (data) { + this._crc.write(data); + + let entries = Math.floor(data.length / 3); + // console.log('Palette:', entries); + + for (let i = 0; i < entries; i++) { + this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]); + } + + this.palette(this._palette); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleTRNS = function (length) { + this.simpleTransparency(); + this.read(length, this._parseTRNS.bind(this)); +}; +Parser.prototype._parseTRNS = function (data) { + this._crc.write(data); + + // palette + if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) { + if (this._palette.length === 0) { + this.error(new Error("Transparency chunk must be after palette")); + return; + } + if (data.length > this._palette.length) { + this.error(new Error("More transparent colors than palette size")); + return; + } + for (let i = 0; i < data.length; i++) { + this._palette[i][3] = data[i]; + } + this.palette(this._palette); + } + + // for colorType 0 (grayscale) and 2 (rgb) + // there might be one gray/color defined as transparent + if (this._colorType === constants.COLORTYPE_GRAYSCALE) { + // grey, 2 bytes + this.transColor([data.readUInt16BE(0)]); + } + if (this._colorType === constants.COLORTYPE_COLOR) { + this.transColor([ + data.readUInt16BE(0), + data.readUInt16BE(2), + data.readUInt16BE(4), + ]); + } + + this._handleChunkEnd(); +}; + +Parser.prototype._handleGAMA = function (length) { + this.read(length, this._parseGAMA.bind(this)); +}; +Parser.prototype._parseGAMA = function (data) { + this._crc.write(data); + this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleIDAT = function (length) { + if (!this._emittedHeadersFinished) { + this._emittedHeadersFinished = true; + this.headersFinished(); + } + this.read(-length, this._parseIDAT.bind(this, length)); +}; +Parser.prototype._parseIDAT = function (length, data) { + this._crc.write(data); + + if ( + this._colorType === constants.COLORTYPE_PALETTE_COLOR && + this._palette.length === 0 + ) { + throw new Error("Expected palette not found"); + } + + this.inflateData(data); + let leftOverLength = length - data.length; + + if (leftOverLength > 0) { + this._handleIDAT(leftOverLength); + } else { + this._handleChunkEnd(); + } +}; + +Parser.prototype._handleIEND = function (length) { + this.read(length, this._parseIEND.bind(this)); +}; +Parser.prototype._parseIEND = function (data) { + this._crc.write(data); + + this._hasIEND = true; + this._handleChunkEnd(); + + if (this.finished) { + this.finished(); + } +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/png-sync.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/png-sync.js new file mode 100644 index 00000000..68cac9bc --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/png-sync.js @@ -0,0 +1,12 @@ +"use strict"; + +let parse = require("./parser-sync"); +let pack = require("./packer-sync"); + +exports.read = function (buffer, options) { + return parse(buffer, options || {}); +}; + +exports.write = function (png, options) { + return pack(png, options); +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/png.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/png.js new file mode 100644 index 00000000..0b8af3f7 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/png.js @@ -0,0 +1,194 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let Parser = require("./parser-async"); +let Packer = require("./packer-async"); +let PNGSync = require("./png-sync"); + +let PNG = (exports.PNG = function (options) { + Stream.call(this); + + options = options || {}; // eslint-disable-line no-param-reassign + + // coerce pixel dimensions to integers (also coerces undefined -> 0): + this.width = options.width | 0; + this.height = options.height | 0; + + this.data = + this.width > 0 && this.height > 0 + ? Buffer.alloc(4 * this.width * this.height) + : null; + + if (options.fill && this.data) { + this.data.fill(0); + } + + this.gamma = 0; + this.readable = this.writable = true; + + this._parser = new Parser(options); + + this._parser.on("error", this.emit.bind(this, "error")); + this._parser.on("close", this._handleClose.bind(this)); + this._parser.on("metadata", this._metadata.bind(this)); + this._parser.on("gamma", this._gamma.bind(this)); + this._parser.on( + "parsed", + function (data) { + this.data = data; + this.emit("parsed", data); + }.bind(this) + ); + + this._packer = new Packer(options); + this._packer.on("data", this.emit.bind(this, "data")); + this._packer.on("end", this.emit.bind(this, "end")); + this._parser.on("close", this._handleClose.bind(this)); + this._packer.on("error", this.emit.bind(this, "error")); +}); +util.inherits(PNG, Stream); + +PNG.sync = PNGSync; + +PNG.prototype.pack = function () { + if (!this.data || !this.data.length) { + this.emit("error", "No data provided"); + return this; + } + + process.nextTick( + function () { + this._packer.pack(this.data, this.width, this.height, this.gamma); + }.bind(this) + ); + + return this; +}; + +PNG.prototype.parse = function (data, callback) { + if (callback) { + let onParsed, onError; + + onParsed = function (parsedData) { + this.removeListener("error", onError); + + this.data = parsedData; + callback(null, this); + }.bind(this); + + onError = function (err) { + this.removeListener("parsed", onParsed); + + callback(err, null); + }.bind(this); + + this.once("parsed", onParsed); + this.once("error", onError); + } + + this.end(data); + return this; +}; + +PNG.prototype.write = function (data) { + this._parser.write(data); + return true; +}; + +PNG.prototype.end = function (data) { + this._parser.end(data); +}; + +PNG.prototype._metadata = function (metadata) { + this.width = metadata.width; + this.height = metadata.height; + + this.emit("metadata", metadata); +}; + +PNG.prototype._gamma = function (gamma) { + this.gamma = gamma; +}; + +PNG.prototype._handleClose = function () { + if (!this._parser.writable && !this._packer.readable) { + this.emit("close"); + } +}; + +PNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) { + // eslint-disable-line max-params + // coerce pixel dimensions to integers (also coerces undefined -> 0): + /* eslint-disable no-param-reassign */ + srcX |= 0; + srcY |= 0; + width |= 0; + height |= 0; + deltaX |= 0; + deltaY |= 0; + /* eslint-enable no-param-reassign */ + + if ( + srcX > src.width || + srcY > src.height || + srcX + width > src.width || + srcY + height > src.height + ) { + throw new Error("bitblt reading outside image"); + } + + if ( + deltaX > dst.width || + deltaY > dst.height || + deltaX + width > dst.width || + deltaY + height > dst.height + ) { + throw new Error("bitblt writing outside image"); + } + + for (let y = 0; y < height; y++) { + src.data.copy( + dst.data, + ((deltaY + y) * dst.width + deltaX) << 2, + ((srcY + y) * src.width + srcX) << 2, + ((srcY + y) * src.width + srcX + width) << 2 + ); + } +}; + +PNG.prototype.bitblt = function ( + dst, + srcX, + srcY, + width, + height, + deltaX, + deltaY +) { + // eslint-disable-line max-params + + PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); + return this; +}; + +PNG.adjustGamma = function (src) { + if (src.gamma) { + for (let y = 0; y < src.height; y++) { + for (let x = 0; x < src.width; x++) { + let idx = (src.width * y + x) << 2; + + for (let i = 0; i < 3; i++) { + let sample = src.data[idx + i] / 255; + sample = Math.pow(sample, 1 / 2.2 / src.gamma); + src.data[idx + i] = Math.round(sample * 255); + } + } + } + src.gamma = 0; + } +}; + +PNG.prototype.adjustGamma = function () { + PNG.adjustGamma(this); +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/sync-inflate.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/sync-inflate.js new file mode 100644 index 00000000..4da0d5f0 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/sync-inflate.js @@ -0,0 +1,168 @@ +"use strict"; + +let assert = require("assert").ok; +let zlib = require("zlib"); +let util = require("util"); + +let kMaxLength = require("buffer").kMaxLength; + +function Inflate(opts) { + if (!(this instanceof Inflate)) { + return new Inflate(opts); + } + + if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { + opts.chunkSize = zlib.Z_MIN_CHUNK; + } + + zlib.Inflate.call(this, opts); + + // Node 8 --> 9 compatibility check + this._offset = this._offset === undefined ? this._outOffset : this._offset; + this._buffer = this._buffer || this._outBuffer; + + if (opts && opts.maxLength != null) { + this._maxLength = opts.maxLength; + } +} + +function createInflate(opts) { + return new Inflate(opts); +} + +function _close(engine, callback) { + if (callback) { + process.nextTick(callback); + } + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) { + return; + } + + engine._handle.close(); + engine._handle = null; +} + +Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) { + if (typeof asyncCb === "function") { + return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); + } + + let self = this; + + let availInBefore = chunk && chunk.length; + let availOutBefore = this._chunkSize - this._offset; + let leftToInflate = this._maxLength; + let inOff = 0; + + let buffers = []; + let nread = 0; + + let error; + this.on("error", function (err) { + error = err; + }); + + function handleChunk(availInAfter, availOutAfter) { + if (self._hadError) { + return; + } + + let have = availOutBefore - availOutAfter; + assert(have >= 0, "have should not go down"); + + if (have > 0) { + let out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + + if (out.length > leftToInflate) { + out = out.slice(0, leftToInflate); + } + + buffers.push(out); + nread += out.length; + leftToInflate -= out.length; + + if (leftToInflate === 0) { + return false; + } + } + + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + return true; + } + + return false; + } + + assert(this._handle, "zlib binding closed"); + let res; + do { + res = this._handle.writeSync( + flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore + ); // out_len + // Node 8 --> 9 compatibility check + res = res || this._writeState; + } while (!this._hadError && handleChunk(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError( + "Cannot create final Buffer. It would be larger than 0x" + + kMaxLength.toString(16) + + " bytes" + ); + } + + let buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; +}; + +util.inherits(Inflate, zlib.Inflate); + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === "string") { + buffer = Buffer.from(buffer); + } + if (!(buffer instanceof Buffer)) { + throw new TypeError("Not a string or buffer"); + } + + let flushFlag = engine._finishFlushFlag; + if (flushFlag == null) { + flushFlag = zlib.Z_FINISH; + } + + return engine._processChunk(buffer, flushFlag); +} + +function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +} + +module.exports = exports = inflateSync; +exports.Inflate = Inflate; +exports.createInflate = createInflate; +exports.inflateSync = inflateSync; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/lib/sync-reader.js b/node_modules/lv_font_conv/node_modules/pngjs/lib/sync-reader.js new file mode 100644 index 00000000..213d1a75 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/lib/sync-reader.js @@ -0,0 +1,45 @@ +"use strict"; + +let SyncReader = (module.exports = function (buffer) { + this._buffer = buffer; + this._reads = []; +}); + +SyncReader.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); +}; + +SyncReader.prototype.process = function () { + // as long as there is any data and read requests + while (this._reads.length > 0 && this._buffer.length) { + let read = this._reads[0]; + + if ( + this._buffer.length && + (this._buffer.length >= read.length || read.allowLess) + ) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + let buf = this._buffer; + + this._buffer = buf.slice(read.length); + + read.func.call(this, buf.slice(0, read.length)); + } else { + break; + } + } + + if (this._reads.length > 0) { + throw new Error("There are some read requests waitng on finished stream"); + } + + if (this._buffer.length > 0) { + throw new Error("unrecognised content at end of stream"); + } +}; diff --git a/node_modules/lv_font_conv/node_modules/pngjs/package.json b/node_modules/lv_font_conv/node_modules/pngjs/package.json new file mode 100644 index 00000000..1f696a7e --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/pngjs/package.json @@ -0,0 +1,129 @@ +{ + "_args": [ + [ + "pngjs@6.0.0", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "pngjs@6.0.0", + "_id": "pngjs@6.0.0", + "_inBundle": false, + "_integrity": "sha512-TRzzuFRRmEoSW/p1KVAmiOgPco2Irlah+bGFCeNfJXxxYGwSw7YwAOAcd7X28K/m5bjBWKsC29KyoMfHbypayg==", + "_location": "/pngjs", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "pngjs@6.0.0", + "name": "pngjs", + "escapedName": "pngjs", + "rawSpec": "6.0.0", + "saveSpec": null, + "fetchSpec": "6.0.0" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/pngjs/-/pngjs-6.0.0.tgz", + "_spec": "6.0.0", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "bugs": { + "url": "https://github.com/lukeapage/pngjs/issues" + }, + "contributors": [ + { + "name": "Alexandre Paré" + }, + { + "name": "Gaurav Mali" + }, + { + "name": "Gusts Kaksis" + }, + { + "name": "Kuba Niegowski" + }, + { + "name": "Luke Page" + }, + { + "name": "Pietajan De Potter" + }, + { + "name": "Steven Sojka" + }, + { + "name": "liangzeng" + }, + { + "name": "Michael Vogt" + }, + { + "name": "Xin-Xin Wang" + }, + { + "name": "toriningen" + }, + { + "name": "Eugene Kulabuhov" + } + ], + "description": "PNG encoder/decoder in pure JS, supporting any bit size & interlace, async & sync with full test suite.", + "devDependencies": { + "browserify": "17.0.0", + "buffer-equal": "1.0.0", + "codecov": "3.7.1", + "connect": "3.7.0", + "eslint": "7.8.1", + "eslint-config-prettier": "6.14.0", + "nyc": "15.1.0", + "prettier": "2.1.1", + "puppeteer": "5.4.0", + "serve-static": "1.14.1", + "tap-dot": "2.0.0", + "tape": "5.0.1" + }, + "directories": { + "lib": "lib", + "example": "examples", + "test": "test" + }, + "engines": { + "node": ">=12.13.0" + }, + "files": [ + "browser.js", + "lib/" + ], + "homepage": "https://github.com/lukeapage/pngjs", + "keywords": [ + "PNG", + "decoder", + "encoder", + "js-png", + "node-png", + "parser", + "png", + "png-js", + "png-parse", + "pngjs" + ], + "license": "MIT", + "main": "./lib/png.js", + "name": "pngjs", + "repository": { + "type": "git", + "url": "git://github.com/lukeapage/pngjs.git" + }, + "scripts": { + "browserify": "browserify lib/png.js --standalone png > browser.js", + "build": "yarn prepublish", + "coverage": "nyc --reporter=lcov --reporter=text-summary tape test/*-spec.js nolarge", + "lint": "eslint .", + "prepublish": "yarn browserify", + "prettier:check": "prettier --check .", + "prettier:write": "prettier --write .", + "test": "yarn lint && yarn prettier:check && tape test/*-spec.js | tap-dot && node test/run-compare" + }, + "version": "6.0.0" +} diff --git a/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/LICENSE-MIT.txt b/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/LICENSE-MIT.txt new file mode 100644 index 00000000..a41e0a7e --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +Copyright Mathias Bynens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/README.md b/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/README.md new file mode 100644 index 00000000..d648b879 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/README.md @@ -0,0 +1,47 @@ +# ES6 `String.prototype.codePointAt` polyfill [![Build status](https://travis-ci.org/mathiasbynens/String.prototype.codePointAt.svg?branch=master)](https://travis-ci.org/mathiasbynens/String.prototype.codePointAt) + +A robust & optimized ES3-compatible polyfill for [the `String.prototype.codePointAt` method in ECMAScript 6](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.codepointat). + +Other polyfills for `String.prototype.codePointAt` are available: + +* by [Norbert Lindenberg](http://norbertlindenberg.com/) (fails some tests) +* by [Steven Levithan](http://stevenlevithan.com/) (fails some tests) +* by [Paul Miller](http://paulmillr.com/) (~~[fails some tests](https://github.com/paulmillr/es6-shim/issues/166)~~ passes all tests) + +## Installation + +In a browser: + +```html + +``` + +Via [npm](http://npmjs.org/): + +```bash +npm install string.prototype.codepointat +``` + +Then, in [Node.js](http://nodejs.org/): + +```js +require('string.prototype.codepointat'); + +// On Windows and on Mac systems with default settings, case doesn’t matter, +// which allows you to do this instead: +require('String.prototype.codePointAt'); +``` + +## Notes + +[A polyfill + test suite for `String.fromCodePoint`](https://mths.be/fromcodepoint) is available, too. + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +This polyfill is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/codepointat.js b/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/codepointat.js new file mode 100644 index 00000000..f724c892 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/codepointat.js @@ -0,0 +1,54 @@ +/*! https://mths.be/codepointat v0.2.0 by @mathias */ +if (!String.prototype.codePointAt) { + (function() { + 'use strict'; // needed to support `apply`/`call` with `undefined`/`null` + var defineProperty = (function() { + // IE 8 only supports `Object.defineProperty` on DOM elements + try { + var object = {}; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch(error) {} + return result; + }()); + var codePointAt = function(position) { + if (this == null) { + throw TypeError(); + } + var string = String(this); + var size = string.length; + // `ToInteger` + var index = position ? Number(position) : 0; + if (index != index) { // better `isNaN` + index = 0; + } + // Account for out-of-bounds indices: + if (index < 0 || index >= size) { + return undefined; + } + // Get the first code unit + var first = string.charCodeAt(index); + var second; + if ( // check if it’s the start of a surrogate pair + first >= 0xD800 && first <= 0xDBFF && // high surrogate + size > index + 1 // there is a next code unit + ) { + second = string.charCodeAt(index + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; + }; + if (defineProperty) { + defineProperty(String.prototype, 'codePointAt', { + 'value': codePointAt, + 'configurable': true, + 'writable': true + }); + } else { + String.prototype.codePointAt = codePointAt; + } + }()); +} diff --git a/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/package.json b/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/package.json new file mode 100644 index 00000000..cee4e79d --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/string.prototype.codepointat/package.json @@ -0,0 +1,62 @@ +{ + "_args": [ + [ + "string.prototype.codepointat@0.2.1", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "string.prototype.codepointat@0.2.1", + "_id": "string.prototype.codepointat@0.2.1", + "_inBundle": false, + "_integrity": "sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==", + "_location": "/string.prototype.codepointat", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "string.prototype.codepointat@0.2.1", + "name": "string.prototype.codepointat", + "escapedName": "string.prototype.codepointat", + "rawSpec": "0.2.1", + "saveSpec": null, + "fetchSpec": "0.2.1" + }, + "_requiredBy": [ + "/opentype.js" + ], + "_resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz", + "_spec": "0.2.1", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "bugs": { + "url": "https://github.com/mathiasbynens/String.prototype.codePointAt/issues" + }, + "description": "A robust & optimized `String.prototype.codePointAt` polyfill, based on the ECMAScript 6 specification.", + "files": [ + "LICENSE-MIT.txt", + "codepointat.js" + ], + "homepage": "https://mths.be/codepointat", + "keywords": [ + "string", + "unicode", + "es6", + "ecmascript", + "polyfill" + ], + "license": "MIT", + "main": "codepointat.js", + "name": "string.prototype.codepointat", + "repository": { + "type": "git", + "url": "git+https://github.com/mathiasbynens/String.prototype.codePointAt.git" + }, + "scripts": { + "cover": "istanbul cover --report html --verbose --dir coverage tests/tests.js", + "test": "node tests/tests.js" + }, + "version": "0.2.1" +} diff --git a/node_modules/lv_font_conv/node_modules/tiny-inflate/LICENSE b/node_modules/lv_font_conv/node_modules/tiny-inflate/LICENSE new file mode 100644 index 00000000..62914548 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/tiny-inflate/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2015-present Devon Govett + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/lv_font_conv/node_modules/tiny-inflate/index.js b/node_modules/lv_font_conv/node_modules/tiny-inflate/index.js new file mode 100644 index 00000000..44d1151b --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/tiny-inflate/index.js @@ -0,0 +1,375 @@ +var TINF_OK = 0; +var TINF_DATA_ERROR = -3; + +function Tree() { + this.table = new Uint16Array(16); /* table of code length counts */ + this.trans = new Uint16Array(288); /* code -> symbol translation table */ +} + +function Data(source, dest) { + this.source = source; + this.sourceIndex = 0; + this.tag = 0; + this.bitcount = 0; + + this.dest = dest; + this.destLen = 0; + + this.ltree = new Tree(); /* dynamic length/symbol tree */ + this.dtree = new Tree(); /* dynamic distance tree */ +} + +/* --------------------------------------------------- * + * -- uninitialized global data (static structures) -- * + * --------------------------------------------------- */ + +var sltree = new Tree(); +var sdtree = new Tree(); + +/* extra bits and base tables for length codes */ +var length_bits = new Uint8Array(30); +var length_base = new Uint16Array(30); + +/* extra bits and base tables for distance codes */ +var dist_bits = new Uint8Array(30); +var dist_base = new Uint16Array(30); + +/* special ordering of code length codes */ +var clcidx = new Uint8Array([ + 16, 17, 18, 0, 8, 7, 9, 6, + 10, 5, 11, 4, 12, 3, 13, 2, + 14, 1, 15 +]); + +/* used by tinf_decode_trees, avoids allocations every call */ +var code_tree = new Tree(); +var lengths = new Uint8Array(288 + 32); + +/* ----------------------- * + * -- utility functions -- * + * ----------------------- */ + +/* build extra bits and base tables */ +function tinf_build_bits_base(bits, base, delta, first) { + var i, sum; + + /* build bits table */ + for (i = 0; i < delta; ++i) bits[i] = 0; + for (i = 0; i < 30 - delta; ++i) bits[i + delta] = i / delta | 0; + + /* build base table */ + for (sum = first, i = 0; i < 30; ++i) { + base[i] = sum; + sum += 1 << bits[i]; + } +} + +/* build the fixed huffman trees */ +function tinf_build_fixed_trees(lt, dt) { + var i; + + /* build fixed length tree */ + for (i = 0; i < 7; ++i) lt.table[i] = 0; + + lt.table[7] = 24; + lt.table[8] = 152; + lt.table[9] = 112; + + for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i; + for (i = 0; i < 144; ++i) lt.trans[24 + i] = i; + for (i = 0; i < 8; ++i) lt.trans[24 + 144 + i] = 280 + i; + for (i = 0; i < 112; ++i) lt.trans[24 + 144 + 8 + i] = 144 + i; + + /* build fixed distance tree */ + for (i = 0; i < 5; ++i) dt.table[i] = 0; + + dt.table[5] = 32; + + for (i = 0; i < 32; ++i) dt.trans[i] = i; +} + +/* given an array of code lengths, build a tree */ +var offs = new Uint16Array(16); + +function tinf_build_tree(t, lengths, off, num) { + var i, sum; + + /* clear code length count table */ + for (i = 0; i < 16; ++i) t.table[i] = 0; + + /* scan symbol lengths, and sum code length counts */ + for (i = 0; i < num; ++i) t.table[lengths[off + i]]++; + + t.table[0] = 0; + + /* compute offset table for distribution sort */ + for (sum = 0, i = 0; i < 16; ++i) { + offs[i] = sum; + sum += t.table[i]; + } + + /* create code->symbol translation table (symbols sorted by code) */ + for (i = 0; i < num; ++i) { + if (lengths[off + i]) t.trans[offs[lengths[off + i]]++] = i; + } +} + +/* ---------------------- * + * -- decode functions -- * + * ---------------------- */ + +/* get one bit from source stream */ +function tinf_getbit(d) { + /* check if tag is empty */ + if (!d.bitcount--) { + /* load next tag */ + d.tag = d.source[d.sourceIndex++]; + d.bitcount = 7; + } + + /* shift bit out of tag */ + var bit = d.tag & 1; + d.tag >>>= 1; + + return bit; +} + +/* read a num bit value from a stream and add base */ +function tinf_read_bits(d, num, base) { + if (!num) + return base; + + while (d.bitcount < 24) { + d.tag |= d.source[d.sourceIndex++] << d.bitcount; + d.bitcount += 8; + } + + var val = d.tag & (0xffff >>> (16 - num)); + d.tag >>>= num; + d.bitcount -= num; + return val + base; +} + +/* given a data stream and a tree, decode a symbol */ +function tinf_decode_symbol(d, t) { + while (d.bitcount < 24) { + d.tag |= d.source[d.sourceIndex++] << d.bitcount; + d.bitcount += 8; + } + + var sum = 0, cur = 0, len = 0; + var tag = d.tag; + + /* get more bits while code value is above sum */ + do { + cur = 2 * cur + (tag & 1); + tag >>>= 1; + ++len; + + sum += t.table[len]; + cur -= t.table[len]; + } while (cur >= 0); + + d.tag = tag; + d.bitcount -= len; + + return t.trans[sum + cur]; +} + +/* given a data stream, decode dynamic trees from it */ +function tinf_decode_trees(d, lt, dt) { + var hlit, hdist, hclen; + var i, num, length; + + /* get 5 bits HLIT (257-286) */ + hlit = tinf_read_bits(d, 5, 257); + + /* get 5 bits HDIST (1-32) */ + hdist = tinf_read_bits(d, 5, 1); + + /* get 4 bits HCLEN (4-19) */ + hclen = tinf_read_bits(d, 4, 4); + + for (i = 0; i < 19; ++i) lengths[i] = 0; + + /* read code lengths for code length alphabet */ + for (i = 0; i < hclen; ++i) { + /* get 3 bits code length (0-7) */ + var clen = tinf_read_bits(d, 3, 0); + lengths[clcidx[i]] = clen; + } + + /* build code length tree */ + tinf_build_tree(code_tree, lengths, 0, 19); + + /* decode code lengths for the dynamic trees */ + for (num = 0; num < hlit + hdist;) { + var sym = tinf_decode_symbol(d, code_tree); + + switch (sym) { + case 16: + /* copy previous code length 3-6 times (read 2 bits) */ + var prev = lengths[num - 1]; + for (length = tinf_read_bits(d, 2, 3); length; --length) { + lengths[num++] = prev; + } + break; + case 17: + /* repeat code length 0 for 3-10 times (read 3 bits) */ + for (length = tinf_read_bits(d, 3, 3); length; --length) { + lengths[num++] = 0; + } + break; + case 18: + /* repeat code length 0 for 11-138 times (read 7 bits) */ + for (length = tinf_read_bits(d, 7, 11); length; --length) { + lengths[num++] = 0; + } + break; + default: + /* values 0-15 represent the actual code lengths */ + lengths[num++] = sym; + break; + } + } + + /* build dynamic trees */ + tinf_build_tree(lt, lengths, 0, hlit); + tinf_build_tree(dt, lengths, hlit, hdist); +} + +/* ----------------------------- * + * -- block inflate functions -- * + * ----------------------------- */ + +/* given a stream and two trees, inflate a block of data */ +function tinf_inflate_block_data(d, lt, dt) { + while (1) { + var sym = tinf_decode_symbol(d, lt); + + /* check for end of block */ + if (sym === 256) { + return TINF_OK; + } + + if (sym < 256) { + d.dest[d.destLen++] = sym; + } else { + var length, dist, offs; + var i; + + sym -= 257; + + /* possibly get more bits from length code */ + length = tinf_read_bits(d, length_bits[sym], length_base[sym]); + + dist = tinf_decode_symbol(d, dt); + + /* possibly get more bits from distance code */ + offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]); + + /* copy match */ + for (i = offs; i < offs + length; ++i) { + d.dest[d.destLen++] = d.dest[i]; + } + } + } +} + +/* inflate an uncompressed block of data */ +function tinf_inflate_uncompressed_block(d) { + var length, invlength; + var i; + + /* unread from bitbuffer */ + while (d.bitcount > 8) { + d.sourceIndex--; + d.bitcount -= 8; + } + + /* get length */ + length = d.source[d.sourceIndex + 1]; + length = 256 * length + d.source[d.sourceIndex]; + + /* get one's complement of length */ + invlength = d.source[d.sourceIndex + 3]; + invlength = 256 * invlength + d.source[d.sourceIndex + 2]; + + /* check length */ + if (length !== (~invlength & 0x0000ffff)) + return TINF_DATA_ERROR; + + d.sourceIndex += 4; + + /* copy block */ + for (i = length; i; --i) + d.dest[d.destLen++] = d.source[d.sourceIndex++]; + + /* make sure we start next block on a byte boundary */ + d.bitcount = 0; + + return TINF_OK; +} + +/* inflate stream from source to dest */ +function tinf_uncompress(source, dest) { + var d = new Data(source, dest); + var bfinal, btype, res; + + do { + /* read final block flag */ + bfinal = tinf_getbit(d); + + /* read block type (2 bits) */ + btype = tinf_read_bits(d, 2, 0); + + /* decompress block */ + switch (btype) { + case 0: + /* decompress uncompressed block */ + res = tinf_inflate_uncompressed_block(d); + break; + case 1: + /* decompress block with fixed huffman trees */ + res = tinf_inflate_block_data(d, sltree, sdtree); + break; + case 2: + /* decompress block with dynamic huffman trees */ + tinf_decode_trees(d, d.ltree, d.dtree); + res = tinf_inflate_block_data(d, d.ltree, d.dtree); + break; + default: + res = TINF_DATA_ERROR; + } + + if (res !== TINF_OK) + throw new Error('Data error'); + + } while (!bfinal); + + if (d.destLen < d.dest.length) { + if (typeof d.dest.slice === 'function') + return d.dest.slice(0, d.destLen); + else + return d.dest.subarray(0, d.destLen); + } + + return d.dest; +} + +/* -------------------- * + * -- initialization -- * + * -------------------- */ + +/* build fixed huffman trees */ +tinf_build_fixed_trees(sltree, sdtree); + +/* build extra bits and base tables */ +tinf_build_bits_base(length_bits, length_base, 4, 3); +tinf_build_bits_base(dist_bits, dist_base, 2, 1); + +/* fix a special case */ +length_bits[28] = 0; +length_base[28] = 258; + +module.exports = tinf_uncompress; diff --git a/node_modules/lv_font_conv/node_modules/tiny-inflate/package.json b/node_modules/lv_font_conv/node_modules/tiny-inflate/package.json new file mode 100644 index 00000000..53399e20 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/tiny-inflate/package.json @@ -0,0 +1,60 @@ +{ + "_args": [ + [ + "tiny-inflate@1.0.3", + "/home/vitaly/Dropbox/Coding/lv_font_conv" + ] + ], + "_from": "tiny-inflate@1.0.3", + "_id": "tiny-inflate@1.0.3", + "_inBundle": false, + "_integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "_location": "/tiny-inflate", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "tiny-inflate@1.0.3", + "name": "tiny-inflate", + "escapedName": "tiny-inflate", + "rawSpec": "1.0.3", + "saveSpec": null, + "fetchSpec": "1.0.3" + }, + "_requiredBy": [ + "/opentype.js", + "/unicode-trie" + ], + "_resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "_spec": "1.0.3", + "_where": "/home/vitaly/Dropbox/Coding/lv_font_conv", + "author": { + "name": "Devon Govett", + "email": "devongovett@gmail.com" + }, + "bugs": { + "url": "https://github.com/devongovett/tiny-inflate/issues" + }, + "description": "A tiny inflate implementation", + "devDependencies": { + "mocha": "^2.1.0" + }, + "homepage": "https://github.com/devongovett/tiny-inflate", + "keywords": [ + "inflate", + "zlib", + "gzip", + "zip" + ], + "license": "MIT", + "main": "index.js", + "name": "tiny-inflate", + "repository": { + "type": "git", + "url": "git://github.com/devongovett/tiny-inflate.git" + }, + "scripts": { + "test": "mocha" + }, + "version": "1.0.3" +} diff --git a/node_modules/lv_font_conv/node_modules/tiny-inflate/readme.md b/node_modules/lv_font_conv/node_modules/tiny-inflate/readme.md new file mode 100644 index 00000000..dd8c408c --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/tiny-inflate/readme.md @@ -0,0 +1,31 @@ +# tiny-inflate + +This is a port of Joergen Ibsen's [tiny inflate](https://bitbucket.org/jibsen/tinf) to JavaScript. +Minified it is about 3KB, or 1.3KB gzipped. While being very small, it is also reasonably fast +(about 30% - 50% slower than [pako](https://github.com/nodeca/pako) on average), and should be +good enough for many applications. If you need the absolute best performance, however, you'll +need to use a larger library such as pako that contains additional optimizations. + +## Installation + + npm install tiny-inflate + +## Example + +To use tiny-inflate, you need two things: a buffer of data compressed with deflate, +and the decompressed size (often stored in a file header) to allocate your output buffer. +Input and output buffers can be either node `Buffer`s, or `Uint8Array`s. + +```javascript +var inflate = require('tiny-inflate'); + +var compressedBuffer = new Bufer([ ... ]); +var decompressedSize = ...; +var outputBuffer = new Buffer(decompressedSize); + +inflate(compressedBuffer, outputBuffer); +``` + +## License + +MIT diff --git a/node_modules/lv_font_conv/node_modules/tiny-inflate/test/index.js b/node_modules/lv_font_conv/node_modules/tiny-inflate/test/index.js new file mode 100644 index 00000000..f4e8c88f --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/tiny-inflate/test/index.js @@ -0,0 +1,75 @@ +var inflate = require('../'); +var zlib = require('zlib'); +var fs = require('fs'); +var assert = require('assert'); +var uncompressed = fs.readFileSync(__dirname + '/lorem.txt'); + +describe('tiny-inflate', function() { + var compressed, noCompression, fixed; + + function deflate(buf, options, fn) { + var chunks = []; + zlib.createDeflateRaw(options) + .on('data', function(chunk) { + chunks.push(chunk); + }) + .on('error', fn) + .on('end', function() { + fn(null, Buffer.concat(chunks)); + }) + .end(buf); + } + + before(function(done) { + zlib.deflateRaw(uncompressed, function(err, data) { + compressed = data; + done(); + }); + }); + + before(function(done) { + deflate(uncompressed, { level: zlib.Z_NO_COMPRESSION }, function(err, data) { + noCompression = data; + done(); + }); + }); + + before(function(done) { + deflate(uncompressed, { strategy: zlib.Z_FIXED }, function(err, data) { + fixed = data; + done(); + }); + }); + + it('should inflate some data', function() { + var out = Buffer.alloc(uncompressed.length); + inflate(compressed, out); + assert.deepEqual(out, uncompressed); + }); + + it('should slice output buffer', function() { + var out = Buffer.alloc(uncompressed.length + 1024); + var res = inflate(compressed, out); + assert.deepEqual(res, uncompressed); + assert.equal(res.length, uncompressed.length); + }); + + it('should handle uncompressed blocks', function() { + var out = Buffer.alloc(uncompressed.length); + inflate(noCompression, out); + assert.deepEqual(out, uncompressed); + }); + + it('should handle fixed huffman blocks', function() { + var out = Buffer.alloc(uncompressed.length); + inflate(fixed, out); + assert.deepEqual(out, uncompressed); + }); + + it('should handle typed arrays', function() { + var input = new Uint8Array(compressed); + var out = new Uint8Array(uncompressed.length); + inflate(input, out); + assert.deepEqual(out, new Uint8Array(uncompressed)); + }); +}); diff --git a/node_modules/lv_font_conv/node_modules/tiny-inflate/test/lorem.txt b/node_modules/lv_font_conv/node_modules/tiny-inflate/test/lorem.txt new file mode 100644 index 00000000..c37b0a59 --- /dev/null +++ b/node_modules/lv_font_conv/node_modules/tiny-inflate/test/lorem.txt @@ -0,0 +1,199 @@ +Lorem ipsum dolor sit amet, sea pertinax pertinacia appellantur in, est ad esse assentior mediocritatem, magna populo menandri cum te. Vel augue menandri eu, at integre appareat splendide duo. Est ne tollit ullamcorper, eu pro falli diceret perpetua, sea ferri numquam legendos ut. Diceret suscipiantur at nec, his ei nulla mentitum efficiantur. Errem saepe ei vis. + + Per melius aperiri eu. Et interesset philosophia vim, graece denique intellegam duo at, te vix quot apeirian dignissim. Ei essent percipitur nam, natum possit interpretaris sea ea. Cum assum adipisci cotidieque ut, ut veri tollit duo. Erat idque volutpat mea ut, mel nominati splendide vulputate ea. + + No ferri partem ceteros pro. Everti volumus menandri at pro. Cum illud euripidis cu, mazim deterruisset ei eum. Ex alia dolorem insolens per, malis clita laboramus duo ut, ridens appareat philosophia ea quo. + + Vix elit tantas phaedrum et, ea quo vide facete scriptorem. Ut facer laboramus definitiones has, viris dictas regione at eos. Noluisse constituto vix at, nec malorum rationibus te. Nec numquam definiebas id, vim id liber munere. Simul discere reprimique qui eu. Et aeterno aperiri disputando vix. + + Usu ne denique albucius gloriatur. Pri in novum electram, ei amet electram quo. Vix summo recusabo dissentiunt no. Natum mediocrem maiestatis ut eum, vocibus nominavi has in, affert civibus te nam. Cibo minim ex nec. + + Ipsum tibique deseruisse vel ut. Ad laudem iracundia eam. Eum id legere scripta nominavi, vim melius ceteros et, ea tale enim nec. Aeque facete signiferumque ne est, vis ei sint persequeris. Ei magna veritus nec, enim aliquando ex pro. + + Verear noluisse qui eu, id mutat possit nec. Ad est melius placerat, soluta facilisi et vel. Id his simul consul praesent, no nam nihil perfecto, quo in mucius corrumpit. Assum ceteros cotidieque et nam, illum quaeque cum et. Numquam laoreet his at, in vis suas quando suscipit. + + Ne graece efficiendi interpretaris cum. In vide dictas cotidieque sed. Ea est augue vidisse. Eu epicurei salutandi est, etiam oratio imperdiet ex his. Te pri novum meliore sensibus. An nec eius dicant, iracundia consectetuer per ex. An iuvaret meliore constituto eam, latine detraxit mea eu, mel eu aperiri moderatius. + + Per commodo virtute eu. Eius euripidis nam eu, cum ne praesent vituperata, vix at integre verterem posidonium. Eu adhuc labores eam, temporibus reformidans eos id. Feugiat labores nam ne, eu sed nostro veritus, mea in consul evertitur repudiandae. Cu eos detracto voluptaria consetetur. + + Sit vidit mundi offendit ad. Usu semper vivendo eloquentiam eu. Nonumes deleniti ex vim, fabulas forensibus ad eam. Mazim admodum petentium sed et, has eu eirmod eruditi laoreet. An eam hinc erant. Et semper accumsan similique cum. Sea at inani error. + + Te commodo delicata abhorreant cum, iusto lucilius ut sed, ea his evertitur scripserit. Te eligendi scriptorem sit. Mel quodsi meliore dissentias ei, cum deserunt moderatius ex, error sanctus adversarium eam et. Eam et appareat placerat tincidunt, ius an quidam putant delenit, utinam partem quo ea. Mei legendos constituto scribentur eu, usu ea consul facilisis. Purto veritus lobortis te sea. + + Ne sea ludus solet decore, in cum erat dicta labitur. Doctus maluisset scripserit qui in. Qui at postea audiam, has ut aperiam dissentiet, vix ut harum nemore integre. Sit ad lucilius deseruisse, iuvaret percipit in pro. Sed referrentur voluptatibus ne, his ei nullam omnesque aliquando. + + Ius te purto augue fierent, mea et decore feugiat definiebas. Dolor abhorreant deseruisse at sit, corpora tacimates duo ut. Dicta equidem ne has. At pri elit magna vocibus, ipsum vidisse definiebas id cum. Ex pri laudem assentior. + + Aliquip referrentur id vim, sea labores nominati recteque id. Torquatos adversarium no mel, pri eu impedit fastidii, in usu tollit electram. Ad esse facer nec, mel id laudem adipisci, pri eu vocent efficiantur. Cu est posse possit. Vis definiebas neglegentur ad, pro facer sanctus propriae id. Sit epicurei comprehensam signiferumque ea, ad eam vero admodum scaevola. + + Nec an vivendo ocurreret, qui id nihil fastidii ocurreret. Vis ei mazim zril, dictas aperiri aliquando per ad, sit ne harum postea appellantur. No munere periculis reprimique duo, ut nam unum animal repudiandae. Cibo vocent dissentias te mea. Sea te elit denique volutpat, nec ne epicuri mentitum delicata. + + Ius eros aeterno torquatos ex, et per nisl accusata. Ne nam nonumy discere, in vim nemore commune. Cu pri nibh pertinacia assueverit, duo percipit definitionem ne, delectus voluptaria et vix. Mutat appellantur mea ad, ad pericula suavitate nam. Primis rationibus mei eu. Ad dolorem verterem deserunt eam, in decore probatus consulatu sed. Quo ut ullum epicuri. + + Quod contentiones ea quo. Et nihil conclusionemque mel, offendit perfecto eam eu. Suas case nam et. Ex elit doctus civibus mei, eam facilis scaevola ne. His elit scripta constituto eu, mea tantas petentium ut. + + Eos dicam intellegam id. Cum omnes concludaturque ea. Qui in semper legendos intellegebat. Option mediocrem eam id. Doctus principes deterruisset pro ad, qui ea fugit populo repudiare. + + Sed ne summo percipitur. Eu porro persius vix, an vix esse fastidii delicatissimi, elit rationibus dissentias cu eam. Te dolorem scriptorem mei, no mei aeque tibique. Iisque molestie ei ius. + + Ius eu vide salutatus. Ut modus errem nam, latine vocibus referrentur an has, his laudem docendi at. Mei in enim aeterno, sea id dolores placerat signiferumque. Mea modo semper maluisset at, vel te magna eruditi. Eam in verear tacimates concludaturque. Nam cu porro mediocritatem, platonem splendide in has, dicit dolor populo mei et. Melius saperet tacimates nam an, mentitum fabellas assueverit duo id, sea an nihil tritani inciderint. + + At vim option nominati quaerendum. Dolor vituperata dissentiunt eu nec, an modo appareat suscipiantur sea. In vim suas eligendi sadipscing. Ne nihil molestie ius, sumo aperiri argumentum sit ea, eius principes te sit. Eam no fugit mazim alterum. Sed ignota sententiae in. At pro illud reprimique. + + At nec vivendo luptatum, vel congue oratio cu. Audire sententiae ius an. Antiopam scripserit et duo, illud commune te his. Posse disputationi vix in, quod oporteat id eam. Legimus admodum docendi cum at, cu postea deserunt periculis per. + + Sonet clita ponderum sea ei, est ex semper fabellas. Te vix elitr congue phaedrum, ea eum argumentum eloquentiam. Te elitr suavitate definitionem eum. Est inciderint comprehensam cu, ei ius dolor dignissim assueverit. + + Eos ut dolorum albucius placerat, mel erat mentitum cu. Nec copiosae periculis in, ex vix everti consectetuer. Pro at dicat utroque, iracundia sententiae in usu, sit no cibo natum alienum. Duo audiam placerat ei. Cu mel philosophia disputationi. + + Eam fierent maiestatis instructior no, cu sea iusto iriure voluptatum. Vide numquam vivendo ex est, an vel nulla similique posidonium. No mea tritani molestiae, pro te placerat sensibus. Mel ad posse mucius vocent, te populo timeam democritum mel. + + Pri suscipit luptatum eu, et persius accumsan argumentum sea. In paulo tempor possit sea. Vidisse viderer ut vix, vix ex hinc solet. Altera principes qui in, est utroque scaevola eu. + + Lobortis gubergren mediocritatem ne has, te eum adhuc pericula vulputate, cu antiopam posidonium percipitur mei. Mandamus sapientem et sed. Ea dicta quodsi aperiri sea, ad putent posidonium sea. Duo et molestie erroribus, facete gloriatur eam te, ne eam accusam interesset instructior. Eam posidonium reformidans at. Duo menandri pericula te, qui accumsan facilisi expetendis ut. Et eum dicunt persius pertinacia, vis recteque eloquentiam te. + + Habemus blandit at pri, ad quando consequat per. Mea id adhuc dolores definitionem, in platonem mediocrem abhorreant per, vis cu hinc harum qualisque. Et purto lorem intellegam vel, summo apeirian cum no. At vel nonumy volutpat quaerendum. Ludus fastidii fabellas ut eum, no nec assum homero sanctus. + + His at doming forensibus honestatis, et nostrum praesent eum. At dolores patrioque sententiae eos, quaeque corpora qui no. Nec postea senserit persecuti ei, ad sea invenire voluptatibus, ne veniam lobortis repudiandae mea. Et nam integre democritum. Ex populo menandri qui. Ei duo aeterno accommodare, nibh ponderum iudicabit id vel, cu eos platonem postulant omittantur. + + Mollis molestie nam an, duo an option patrioque posidonium. Putant luptatum aliquando mea ei. Ut quas semper perfecto mei, ei ius justo possit epicurei. Cum odio omnium eu, gubergren definitionem eum ex. Tempor definitionem pri at, ad sit nihil postea moderatius. + + An cum verear scribentur, duo et purto tempor euripidis. Aeterno postulant ut eam, no diam inermis argumentum eos, posse blandit incorrupte ne pri. Est commodo laoreet conclusionemque ei. Graeci tacimates ei eum. Ad nec forensibus voluptaria, mea in alii putent, sed facer ceteros ad. + + Vidisse vivendo placerat duo ex, pri malorum definitionem ex. Decore virtute accumsan cum ad, ex eum postea putant euismod. Mei id alia populo democritum, mei ea adhuc posse. Et primis hendrerit signiferumque nam, ei vis modo lobortis recteque. Saepe persius aliquid et sit, vel everti feugait ne. + + Qui ex laoreet argumentum temporibus, agam tacimates intellegam ad qui. At wisi perfecto has, an sit viris definitionem. No quo sint tincidunt, vim adhuc expetenda ut, nam ad everti expetendis. Adhuc soleat doming nec eu, dicta summo sapientem mei te, nostro mediocrem dignissim ex eos. Id alienum mediocritatem mea, te error iriure placerat pri, feugiat platonem vituperatoribus mea te. + + Quo elit legere consequuntur in, in fabulas ancillae mea, sed scripta mentitum tacimates ei. Mazim phaedrum interpretaris et per, te patrioque assueverit vim. Populo commodo imperdiet vix ut. Mea modo bonorum ut, cu pri enim posse efficiantur. + + Sea veri ancillae adipisci te, quot tota modus ad sea. Suas malorum per ex, mazim rationibus ad vix. Ius ullum deserunt id. Quas corrumpit constituam no mei. Ut quo deleniti atomorum omittantur. Clita feugait docendi ei cum, no mea modo menandri, nam mundi doming an. No altera commodo pri. + + Vel fastidii convenire ex. Vim soleat maluisset te, et expetendis sadipscing liberavisse has. Per sale facilisis accommodare in. Cu option incorrupte nec. + + An eam vocibus intellegat, possit aliquid ex eum, tale mentitum oportere at duo. Ad eam audiam consectetuer, eu meliore verterem mediocritatem has, nam etiam reprimique ut. Nullam adipisci mei in, ad duo quem simul veniam. Vis at tempor sententiae. Te essent iisque aperiam vis. + + Te vix etiam quando ullamcorper, mel ei offendit iudicabit necessitatibus, usu assum facilisi sensibus ex. Alterum adversarium vis ad. Odio fierent deleniti ex cum. Quo an bonorum inciderint, harum simul maiorum in mel, ex legimus alienum corrumpit has. Pri soluta lobortis adipiscing te, eos clita ponderum mandamus at, elit meis assum mea in. Tale intellegebat cu vim, facilis expetenda democritum duo te, cu his causae dissentiet liberavisse. + + Primis latine epicurei no mea. Nam ad quis putant everti, no fugit minimum disputando vix. Laudem neglegentur te qui. Vel splendide efficiendi at, sed liber urbanitas no. Id his atqui inermis scriptorem, vituperata adversarium eos cu, pro in movet accommodare. + + Munere indoctum eu duo. Id eam duis voluptua expetenda, et prodesset inciderint ius. An nibh elitr deseruisse usu. Idque copiosae nam ea, ne tempor omittantur definitionem vis, et cum sumo principes. Quo rebum viderer minimum ex, est at melius blandit. + + Ut adolescens definitiones sed. Est ut erant legendos, in quo facilis salutatus. Agam expetenda salutatus ut sit, quo ex fuisset repudiandae, tale probo aliquip mea id. No vix diceret scaevola. Posidonium conclusionemque ut est. Quo porro menandri assentior ei. + + Vocent neglegentur intellegebat sit id. Et ullum accusam sea, ex nam aeque ubique ocurreret, ea cum quidam euismod. Eam ne zril alienum. Mea id veritus alienum. Mei simul appareat nominati no. Cum option accumsan ea, ne eos legimus dissentiunt. + + Everti prodesset scripserit ea cum, eam nostrud adolescens deterruisset an. Deseruisse definiebas eos ne, mel ex nisl meliore consulatu, per te scripta gubergren. Vix cu novum admodum recusabo, te omnes similique efficiantur nec. Suas novum semper duo ex. Vocibus cotidieque cu qui, at sale malorum intellegam mel. Quo errem accumsan ullamcorper cu, eu quo liber quidam conceptam. + + Scripta habemus quaestio id usu. Id vis utroque forensibus, cu simul fabulas efficiantur vis, ad mel cibo quas feugait. Eros expetendis in cum. No cum aeterno menandri consetetur, quo ex alterum probatus. Eu audire tritani ius, ei labore commune detraxit est. Unum sapientem cotidieque ei vel, ullum prompta per ex. Recteque persequeris quo ei, volutpat quaerendum ex sea. + + Qui phaedrum dissentiunt ne, sea debet fuisset ut. Ridens virtute pro an. Eos at stet modus iisque. Usu ea esse sententiae, deleniti salutandi ne sit, semper graecis sensibus vis ne. Ea corrumpit assueverit mel, in ignota quodsi nominati vix. + + Sea equidem vivendo ut, sed cibo nusquam id, nostro integre te mei. Etiam tractatos et duo, ut ludus dolore pri. Eius hendrerit cu vel, quo ei quodsi causae ullamcorper, per cibo nihil at. Ea voluptatum incorrupte duo, dolore debitis no usu. Ei clita concludaturque cum. Quo quas quando persecuti cu, eruditi scripserit cum eu. + + Ex eleifend philosophia has. Sint repudiandae in sea, et prima latine persecuti eum, pro ea everti expetendis. At his stet facete minimum, sed in delenit maiestatis. Cum ei omittam contentiones, suas sale melius ei cum, mel id vocent propriae necessitatibus. Vix amet nibh ea, autem movet ne vel. + + Accusata percipitur ut vim. Decore tritani scriptorem vis eu, vis volutpat reprehendunt ea. Postea inciderint vix an, no dicunt tamquam mel, usu id illud sensibus expetendis. Ex his aliquip blandit appellantur. + + Officiis evertitur ut mea, cu illud omnesque scripserit eam. Simul vituperatoribus an eum, mel quidam disputando cu, nibh probatus consequat ei mei. Eam populo appareat inimicus ei. Ne officiis definitiones his, vis vero simul similique ei. Iudico oratio elaboraret vim et, id posse nemore eirmod has. + + Pro in veniam consul expetenda, an est movet consequuntur, ex ius admodum recusabo ullamcorper. Mei an utroque ceteros singulis, id eum iudico latine. At est reque lorem intellegat. Quando corpora qui ea. Quo vocent salutatus id. + + Wisi ignota concludaturque est ex. Mea ad inermis vituperatoribus. Dolor persius inimicus ad nec, etiam dignissim qui ex. Ridens quodsi sed ex. Pro in etiam antiopam, eos graece eripuit ad. Affert soluta mei te, pri illud graecis id, vel sint vivendo at. Mea eu veri dicta offendit, cu has sint copiosae. + + Duo libris salutatus ad, porro principes mel ex. Nec iudico consectetuer no. Ut pri causae qualisque democritum. Habeo homero iuvaret at mei. Atqui aliquam eu mea. Gubergren delicatissimi vim ad, amet quodsi efficiendi te ius. Everti latine vulputate pro te, in nam falli definiebas, duo harum graeco nusquam no. + + Per ne aeterno appareat, melius verear tamquam eam id, mei ei invidunt atomorum. Eu doctus viderer eam, sea eu possit dolorem appetere, efficiantur necessitatibus mel cu. Ad est suas officiis, assum erant eum cu, eum erat vitae te. Habemus scaevola no per, nominati adipiscing et eam. + + Ei stet quidam scaevola quo, ius cu noster officiis. Has dolorum vulputate voluptaria ea, ei ius audiam liberavisse. Duo in accumsan constituam, sea esse deseruisse ad. Ne eam eligendi sensibus. Ea rebum porro interesset sed, te alii tritani singulis vis, vel enim liber ne. Movet numquam salutatus eu vim. Nam ad deleniti interpretaris conclusionemque. + + Ea offendit apeirian reprimique ius, accusam incorrupte voluptatibus ei duo. Hinc ponderum detraxit vel te, has no labore regione. Sint impetus duo ex, cu has liber soluta fierent. Vix ut cibo mollis deseruisse. + + Cum id tale disputationi, usu adhuc tritani ea. Id vim volumus quaerendum delicatissimi, no vix dolorum legimus corpora, justo dicit id duo. Ancillae concludaturque at usu. Vim diceret singulis incorrupte eu, oratio nullam quo et. Et sea mediocrem vituperatoribus, fugit tacimates deterruisset cum et. Mel ne sale soleat, vim ad labitur equidem, eos ea justo noluisse. + + An nam consectetuer necessitatibus, eos ei mazim persecuti. Libris explicari dissentiunt te vis, te per veniam sadipscing. Ut diceret euismod vix, duo discere inermis ea. No sit veri sensibus cotidieque, inermis sadipscing reprehendunt qui ad, elitr referrentur repudiandae eu est. Vis quem probo postulant no. Ad viris tollit ullamcorper pri, congue discere ad usu. + + Eam te cetero reprehendunt. His ad ferri feugiat invenire, oratio indoctum id pro. Errem omittam sed et, est no quando omnesque platonem, sed quis philosophia ei. Vix ut porro aeque habemus, eu eam consul nominati omittantur. + + At pri everti indoctum, ullum adipiscing instructior qui ad. Usu ignota omittam ex. At audire vocibus pericula vix, usu ex reque feugait. Ne sea electram salutandi moderatius, te qui verterem scripserit adversarium, an sed tantas lobortis intellegat. + + Ad quas suscipit atomorum duo, quo saepe maiestatis eu. Nostro expetenda ea usu, in atqui doming eam. Vis utroque consulatu ne. Zril noster scripta in eum, vim ad dicam facete legendos, et sit civibus consequat. Eum autem periculis ex. Sed ne nemore eligendi, his legimus verterem ad. + + Est ad amet possit latine. Sed ne legere populo, has pericula scribentur voluptatibus eu. Usu in nonumy vituperata. Aeque oratio gubergren mea ad, quo eu debet dolorum contentiones. Veri expetenda ex mel, eu veniam apeirian vis, aeterno debitis id his. + + Ei ius consul nonumes. Id qui porro periculis, quando dolore iisque qui id. Quo ex simul convenire, vix ei erat petentium, mea cu clita causae. Tale facilisis ex pri, vim ne vide laudem mnesarchum. Duo option blandit ex. Eu est modus vitae, nam in latine maiorum. + + Est an quis quaeque disputando, sit an postulant expetenda, dolor erroribus consequuntur ad vel. Ius phaedrum cotidieque ei, omnis persius copiosae eu vim. Pri facer consequat eu, esse copiosae facilisis mei ne. Ubique convenire no sit. + + Nec regione prompta no. Et quo recteque concludaturque, et ius nostro mollis regione. Ad aliquid lucilius scriptorem eam. Sit at summo eligendi omittantur, ius ea paulo option referrentur. Rationibus inciderint mediocritatem sea id, in dicant assentior sea, quidam copiosae reprehendunt in usu. Cu appetere scripserit vix. Mea mollis audiam aliquam ea, te qui adhuc nonumes deserunt. + + Duo ad facilis consequuntur, vis vide mutat in. At inani ludus eam, an sit quod primis, ea est integre consetetur. Has dolorem salutandi te, tota doctus sit ne, cum ex minimum convenire. Ne legere deterruisset vel, partem phaedrum ne pro, vim modo facete fabellas ex. Cu vix possim eleifend posidonium. Ne est sumo impetus. No quo ubique neglegentur, in usu aliquando scripserit reformidans. + + Vix et numquam expetendis. Ei quas senserit vel, ne has placerat conclusionemque. Noster perpetua euripidis ex sit. Ex mel vidit nonumy vituperata, duo ad nostrum liberavisse. Primis signiferumque duo te, ius te hinc aeque laoreet, ne eius voluptua pri. Dico eros copiosae sed ei, duo cu laudem propriae gubergren. + + Unum erant oratio duo cu, qui no audiam fabulas ornatus. Nihil omnium offendit ad cum, ea ius inermis appetere nominati. Ei nam vero oratio corrumpit. Atqui voluptatibus mei id, at duo assum nostrud aliquando. At nec laudem ridens phaedrum. Dicunt qualisque eum an, ex natum persecuti adipiscing vix, tritani consulatu persecuti nam id. + + In pro mundi percipit, eum tibique eloquentiam in, mea illud ullum altera ex. Veniam epicuri ex mea, quot eruditi definiebas eu duo. Vel augue regione consectetuer ei, appetere moderatius eos in. Laoreet lucilius vim eu. At oratio eirmod qui. + + Altera labitur qui ei, in eam libris primis. Eirmod audiam te vel, eu mei case vide ponderum, an principes persecuti neglegentur mei. Ferri vulputate instructior no vix, in est vidisse detraxit molestiae. Te sit quot choro adipisci, no labore indoctum deterruisset cum. Elit ancillae appetere usu at, mundi dissentias te quo. Mentitum erroribus ad pri. + + Usu ei vero possit appetere. Id erroribus constituam quo. Sit id quidam pertinacia, epicuri delicata eu has, debet melius evertitur ut sed. Id est alienum voluptua. Sit eu dico discere accusata, cu mazim viderer numquam usu, has an solum pertinax. Vel natum summo te, mel integre perfecto consetetur et. + + Postea luptatum menandri cu has, no nam neglegentur necessitatibus. Deseruisse reprehendunt ne mea, lorem tollit nonumes ne vim. Eu pro amet populo, omnesque ponderum sadipscing et ius, ad debet consequat dissentiet vix. Ius nulla aliquip complectitur et, id sed repudiare necessitatibus, et erant legimus invidunt vel. Magna labore democritum vis ei. + + Ne has consulatu reprehendunt, ad nam nulla integre admodum, no has everti impedit perpetua. Tempor antiopam dissentias pro et, ex per legere electram. Ut ius brute omnesque consequat, an his dissentias persequeris. Dicta ludus tritani eam ei. + + Minim rationibus et usu, eam in elit senserit. Stet harum qualisque eu has. Cu decore nostrud sit, mea magna iracundia te, vix tritani convenire imperdiet at. Te pri dictas appetere, brute velit ius ad. Veri dicit legere pri at, sea tation fierent molestie eu. Eum et paulo consul. + + Veri iusto mei id, reque invidunt ne his, te agam dolore electram nam. Est ullum oporteat facilisi eu, dicunt officiis ad eos. Vis ut populo similique. Et minim platonem percipitur usu. Et usu saperet alienum consequuntur, per ad luptatum concludaturque, cibo duis definitionem vix an. + + Ancillae iracundia eu vix, mazim conceptam no qui. Sit nihil epicuri voluptatibus in, an sale debet vis. Porro congue senserit quo an. Facer constituam vel no, facete pertinacia adolescens pro ut, errem nullam menandri ius an. Ex tractatos periculis interpretaris eum, vim ornatus patrioque an. Ius magna iudicabit reprehendunt at, ea viris ornatus sit, eum in vidisse percipitur. + + Vel agam interpretaris ex, zril deserunt electram in duo. Eu eam vero atqui maiorum. Ne pri alia meis decore, vis ea expetenda dissentiet. Cu quis evertitur intellegat cum, ea sed posse expetendis liberavisse, sed ne quis deseruisse. Solum ignota causae ad quo, ferri erant est id, vim ut choro liberavisse. Ne nam causae reformidans, possit percipitur id has. Case tota id has, pri tation ancillae sensibus te. + + Posse aperiam sit id, est in dicam iracundia. Eum mollis dolores te, at vis laoreet habemus fuisset. Vim nibh civibus signiferumque eu. Fierent reformidans an quo. Exerci dissentiunt ex pri, per illum debitis et. + + Vel tota exerci facilis eu. Est primis atomorum id. Hinc insolens dissentiet duo et, iusto inermis salutatus vel ne. Corpora propriae vituperata ex est, sit quod ignota deterruisset no, elitr tempor suscipit ex nam. Eripuit repudiandae his cu, fabulas inermis accumsan ei eum. Nisl molestie ex pri, sea veniam graecis expetenda eu. + + Vel possim moderatius cu, sea no dicit aliquip erroribus, eam te debet partem. Sea no graeco vocent probatus, qui ut fugit delectus definiebas. Id soluta viderer per, tritani disputando necessitatibus ad vix. Eleifend facilisis percipitur at pri. Sit dicat adipisci ex, mundi solet doming nec te, ne maiorum tractatos evertitur sit. At velit propriae eos, mel alii invenire id. + + Ei per minim voluptaria, ea mel scaevola mediocrem euripidis. Et quo wisi sonet eirmod, consul tritani delenit vis id, per id mutat facer. Accusam patrioque eu cum, te cum quot saepe scribentur. Eros summo mnesarchum sed ut, ad possit nostrum comprehensam ius. + + In elitr nullam eam, cu mea mentitum omnesque. Ex has wisi consequat. Sed simul offendit argumentum no, solet corpora lucilius cu vis. Nec ut legimus suscipit, ne usu mucius latine, nusquam mentitum perpetua ad vel. Vidisse feugait facilisis an sea. + + Mel ne oblique menandri, nam graecis antiopam id. Id sanctus referrentur contentiones eam, et eam purto consequat, te vix quod tantas bonorum. Fabellas sapientem consulatu eu per. Iudico possim per ei, eu vide adversarium per. Usu vero essent albucius et, nec veritus ancillae prodesset eu, ipsum probatus cu sea. In quod tantas iudicabit eam, his et odio augue iuvaret. + + Eum an iisque oportere dignissim, est convenire molestiae interesset at, eam id dico audiam quaerendum. Est prompta ocurreret adversarium id, sumo legendos iracundia pri ea, quo ei agam aeque. Ei vix omnes conclusionemque, nec ut novum urbanitas honestatis. Sumo moderatius eos no, ea saperet impedit petentium vel. Vim in harum blandit, posse gubergren deterruisset ex ius. Ei error menandri platonem duo, partiendo qualisque nam te. + + Erat nobis maluisset at sed. Ius no dolor soluta. Has ne sumo brute suavitate, his ne viris aeterno omittantur. Te usu delenit philosophia. Mei wisi libris deseruisse eu. + + Tantas constituam per ei, doctus timeam ea vim. Quo ei putent delicata, eu quo aeterno labores. Qui liber eripuit singulis te, qui diam appareat similique ex, aliquip feugait noluisse cu vis. Dicant recteque definitiones ex mea. Cu exerci dictas eleifend duo, id nonumes denique vix, pri magna facer saperet ei. + + Aeque quodsi partiendo in est, partem malorum intellegebat et per, mea no porro ipsum oratio. Mel sale meliore fuisset ad, per aeque aperiam nominavi ex. Ad tantas meliore placerat mel, mel in prompta torquatos, nulla mollis tamquam pri cu. An quo noster intellegat. Utroque antiopam similique ius eu, at duo ullum apeirian reprimique, vide quaeque assueverit eam ea. + + Mel no quod viris latine, no platonem dissentiunt ius, quis amet gloriatur no eos. Ei mea ancillae probatus. Ad molestiae moderatius vim. Ex soluta meliore molestiae has, ne sea quas natum. Movet verterem vis no, vis amet homero an. Ius dicta tantas id. + + Pri ut modus disputationi, iudico ignota commune eam ut. Vim integre eripuit appareat in, malorum inermis perpetua his cu. Altera alienum mediocrem eu vis. Omnis honestatis repudiandae in qui, his quis duis te, novum rationibus cu est. Eos ut dicant molestie, pri argumentum quaerendum adversarium te. Ea cetero deserunt conceptam pri. + + Augue utroque iudicabit ei vim, ea per dico debet. Cu per regione feugait, sensibus necessitatibus cu cum, at mundi aliquando per. In cum latine evertitur definitionem. Sit movet aperiri liberavisse ad, pro paulo veniam eu. Vel ut cotidieque definitionem, adhuc movet intellegebat quo ne. + + Eum deleniti gubergren an, dolor utamur omittam ea ius. Eam movet possim accommodare et. Ius cu malorum tibique, ludus eligendi id pro. Solum vulputate efficiendi ex quo. + + Regione fierent eu per. No amet iuvaret efficiantur usu. Sit minim sensibus no, his principes gloriatur adversarium no. Ubique definitionem ne vis, vis propriae intellegebat te. Tibique suscipiantur his no. + + Eu quo elit cetero scripserit, maiestatis scripserit pri in, vim cu tibique eligendi. Ne tritani gubergren vituperatoribus quo, melius facilisi ne has. Id pro vivendo fuisset, ex causae utroque deleniti mea. Ad eam percipit perfecto, mutat justo essent at vim. Eros novum duo et, in pri melius blandit. Affert albucius eos ad. Singulis mnesarchum ea mel, eos dictas nominavi reprimique no. + + Ei qui congue voluptatibus. Nam no tritani elaboraret. Conceptam rationibus expetendis duo no. Vivendo reprimique cum te, qui timeam copiosae id, modo delicata ius ad. Nam cu dico aliquip, eu pro legimus officiis delicata, fugit quando ea per. + + In eos equidem accommodare. Electram principes ad usu. Nec adversarium disputationi in, sed feugait lucilius ut. Ludus hendrerit cu ius. + + Cum suscipit gloriatur ea. Id aeterno principes euripidis nam, mea id probo graeco verterem, vulputate ullamcorper definitionem in pri. Mel cu detraxit assueverit. Quo et posse fastidii, ei ponderum delicata sed, has brute forensibus ut. Quo option pericula ea, nam gubergren assueverit te. + + Graece doming intellegebat duo in, ullum clita expetenda nam at. Diam alienum menandri sit id. Unum clita consulatu duo id. Per in mucius legendos scribentur, sea quod phaedrum ut, facete animal dissentias no usu. Quo te dico suavitate. Est te erant congue vivendum, oporteat forensibus in his. + + Pro no eleifend reprehendunt, ut meis consetetur argumentum mei. Id vis harum ornatus cotidieque. Inani libris volumus ea qui. Ius at suas percipit voluptatum, pro solet invidunt honestatis ei, et nam delectus reprimique instructior. Nam id tacimates argumentum dissentiet, mei an sint adipiscing. + + Quando cotidieque sit at, ei sed tantas ancillae verterem, cum nibh omittam ut. Erant laboramus moderatius te eum. Civibus adipiscing sed ne, vix eu erant euripidis. Illud qualisque at nec, id tale sint facete per. Vero autem democritum eam an. + + Mel mazim prodesset ad. An vis alii suas congue, vim veri illum iisque et, in modus perfecto deseruisse vel. Sed summo fuisset fierent an. Vel eu bonorum ornatus, alii decore nec ad. Eu dicta constituto mea. + + Id sint stet graece usu. Cu sit essent reformidans, eos eius ridens et. Usu voluptaria posidonium cu. \ No newline at end of file diff --git a/node_modules/lv_font_conv/package.json b/node_modules/lv_font_conv/package.json new file mode 100644 index 00000000..e0f1464f --- /dev/null +++ b/node_modules/lv_font_conv/package.json @@ -0,0 +1,61 @@ +{ + "name": "lv_font_conv", + "version": "1.5.2", + "description": "Rasterize vector fonts for embedded use. Supports subsettings & merge.", + "keywords": [ + "font", + "convertor", + "embedded" + ], + "repository": "lvgl/lv_font_conv", + "license": "MIT", + "files": [ + "lv_font_conv.js", + "lib/" + ], + "bin": { + "lv_font_conv": "lv_font_conv.js" + }, + "scripts": { + "start": "parcel ./web/index.html --open", + "build": "parcel build ./web/index.html ./web/content.html --public-url ./", + "build:dockerimage": "docker build -t lv_font_conv_freetype ./support", + "build:freetype": "docker run --rm -v $(pwd):/src/lv_font_conv -it lv_font_conv_freetype ./lv_font_conv/support/build.sh", + "lint": "eslint .", + "test": "npm run lint && nyc mocha --recursive", + "coverage": "npm run test && nyc report --reporter html", + "shrink-deps": "shx rm -rf node_modules/opentype.js/src node_modules/opentype.js/dist/opentype.{m,js.m}* node_modules/pngjs/browser.js", + "prepublishOnly": "npm run shrink-deps" + }, + "dependencies": { + "argparse": "^2.0.0", + "bit-buffer": "^0.2.5", + "debug": "^4.1.1", + "make-error": "^1.3.5", + "mkdirp": "^1.0.4", + "opentype.js": "^1.1.0", + "pngjs": "^6.0.0" + }, + "bundledDependencies": [ + "argparse", + "bit-buffer", + "debug", + "make-error", + "mkdirp", + "opentype.js", + "pngjs" + ], + "devDependencies": { + "eslint": "^7.21.0", + "file-saver": "^2.0.2", + "mocha": "^8.3.0", + "nyc": "^15.1.0", + "parcel-bundler": "^1.12.4", + "posthtml-include": "^1.6.2", + "roboto-fontface": "^0.10.0", + "shx": "^0.3.2" + }, + "browserslist": [ + "last 1 Chrome version" + ] +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 00000000..75a67e67 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,118 @@ +{ + "name": "InfiniTime", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "lv_font_conv": "^1.5.2" + } + }, + "node_modules/lv_font_conv": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/lv_font_conv/-/lv_font_conv-1.5.2.tgz", + "integrity": "sha512-0UapRSTkVP/pnB8Z4r2HDHx5p2dJx/xUG1+14u/WXo59mwuC7BahR+Bnx/66jKoDrG1wFQwn9ZzoyMxRHOD9bg==", + "bundleDependencies": [ + "argparse", + "bit-buffer", + "debug", + "make-error", + "mkdirp", + "opentype.js", + "pngjs" + ], + "dependencies": { + "argparse": "^2.0.0", + "bit-buffer": "^0.2.5", + "debug": "^4.1.1", + "make-error": "^1.3.5", + "mkdirp": "^1.0.4", + "opentype.js": "^1.1.0", + "pngjs": "^6.0.0" + }, + "bin": { + "lv_font_conv": "lv_font_conv.js" + } + }, + "node_modules/lv_font_conv/node_modules/argparse": { + "version": "2.0.1", + "inBundle": true, + "license": "Python-2.0" + }, + "node_modules/lv_font_conv/node_modules/bit-buffer": { + "version": "0.2.5", + "inBundle": true, + "license": "MIT" + }, + "node_modules/lv_font_conv/node_modules/debug": { + "version": "4.3.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/lv_font_conv/node_modules/make-error": { + "version": "1.3.6", + "inBundle": true, + "license": "ISC" + }, + "node_modules/lv_font_conv/node_modules/mkdirp": { + "version": "1.0.4", + "inBundle": true, + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/lv_font_conv/node_modules/ms": { + "version": "2.1.2", + "inBundle": true, + "license": "MIT" + }, + "node_modules/lv_font_conv/node_modules/opentype.js": { + "version": "1.3.3", + "inBundle": true, + "license": "MIT", + "dependencies": { + "string.prototype.codepointat": "^0.2.1", + "tiny-inflate": "^1.0.3" + }, + "bin": { + "ot": "bin/ot" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/lv_font_conv/node_modules/pngjs": { + "version": "6.0.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=12.13.0" + } + }, + "node_modules/lv_font_conv/node_modules/string.prototype.codepointat": { + "version": "0.2.1", + "inBundle": true, + "license": "MIT" + }, + "node_modules/lv_font_conv/node_modules/tiny-inflate": { + "version": "1.0.3", + "inBundle": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 00000000..d339766c --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "lv_font_conv": "^1.5.2" + } +} diff --git a/src/displayapp/screens/WatchFaceTerminal.cpp b/src/displayapp/screens/WatchFaceTerminal.cpp index 64166033..dd929641 100644 --- a/src/displayapp/screens/WatchFaceTerminal.cpp +++ b/src/displayapp/screens/WatchFaceTerminal.cpp @@ -1,3 +1,4 @@ +#include #include #include "displayapp/screens/WatchFaceTerminal.h" #include "displayapp/screens/BatteryIcon.h" @@ -41,7 +42,7 @@ WatchFaceTerminal::WatchFaceTerminal(Controllers::DateTime& dateTimeController, connectState = lv_label_create(lv_scr_act(), nullptr); lv_label_set_recolor(connectState, true); - lv_obj_align(connectState, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 0, 60); + lv_obj_align(connectState, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 0, 80); notificationIcon = lv_label_create(lv_scr_act(), nullptr); lv_obj_align(notificationIcon, nullptr, LV_ALIGN_IN_LEFT_MID, 0, -100); @@ -55,7 +56,7 @@ WatchFaceTerminal::WatchFaceTerminal(Controllers::DateTime& dateTimeController, lv_label_set_text_static(label_prompt_1, "user@watch:~ $ now"); label_prompt_2 = lv_label_create(lv_scr_act(), nullptr); - lv_obj_align(label_prompt_2, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 0, 80); + lv_obj_align(label_prompt_2, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 0, 100); lv_label_set_text_static(label_prompt_2, "user@watch:~ $"); label_time = lv_label_create(lv_scr_act(), nullptr); @@ -74,6 +75,10 @@ WatchFaceTerminal::WatchFaceTerminal(Controllers::DateTime& dateTimeController, lv_label_set_recolor(weatherStatus, true); lv_obj_align(weatherStatus, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 0, 40); + bytesFree = lv_label_create(lv_scr_act(), nullptr); + lv_label_set_recolor(bytesFree, true); + lv_obj_align(bytesFree, lv_scr_act(), LV_ALIGN_IN_LEFT_MID, 0, 60); + taskRefresh = lv_task_create(RefreshTaskCallback, LV_DISP_DEF_REFR_PERIOD, LV_TASK_PRIO_MID, this); Refresh(); } @@ -254,6 +259,8 @@ void WatchFaceTerminal::Refresh() { lv_label_set_text_static(weatherStatus, "[WTHR]No Data"); } } + + lv_label_set_text_fmt(bytesFree, "[MEM] %i B Free", xPortGetFreeHeapSize()); currentDateTime = std::chrono::time_point_cast(dateTimeController.CurrentDateTime()); diff --git a/src/displayapp/screens/WatchFaceTerminal.h b/src/displayapp/screens/WatchFaceTerminal.h index f36fb99c..4841ba39 100644 --- a/src/displayapp/screens/WatchFaceTerminal.h +++ b/src/displayapp/screens/WatchFaceTerminal.h @@ -61,6 +61,7 @@ namespace Pinetime { lv_obj_t* notificationIcon; lv_obj_t* connectState; lv_obj_t* weatherStatus; + lv_obj_t* bytesFree; Controllers::DateTime& dateTimeController; const Controllers::Battery& batteryController;