From 257ec9301bdc68747fd79c28f78ac0073124ab83 Mon Sep 17 00:00:00 2001 From: shagi Date: Mon, 2 Nov 2020 18:37:13 +0100 Subject: [PATCH] Initial Commit --- .gitignore | 3 + LICENSE.txt | 674 + MANIFEST.in | 6 + README.md | 4 + build.py | 11 + negromate/__init__.py | 0 negromate/web/__init__.py | 1 + negromate/web/builder.py | 141 + negromate/web/commands.py | 11 + negromate/web/karaoke_templates.py | 89 + negromate/web/static/.gitignore | 2 + negromate/web/static/css/CyrBit.ttf | Bin 0 -> 17072 bytes negromate/web/static/css/cc-by-sa.png | Bin 0 -> 1697 bytes negromate/web/static/css/main.css | 118 + negromate/web/static/css/nm_icon.png | Bin 0 -> 5649 bytes negromate/web/static/js/libjass/.gitignore | 14 + negromate/web/static/js/libjass/.travis.yml | 7 + negromate/web/static/js/libjass/CHANGELOG.md | 133 + negromate/web/static/js/libjass/LICENSE | 202 + negromate/web/static/js/libjass/README.md | 171 + negromate/web/static/js/libjass/build.js | 281 + negromate/web/static/js/libjass/build/doc.ts | 884 + .../web/static/js/libjass/build/node.d.ts | 24 + .../web/static/js/libjass/build/tsconfig.json | 26 + .../static/js/libjass/build/typescript/ast.ts | 204 + .../js/libjass/build/typescript/compiler.ts | 308 + .../js/libjass/build/typescript/extras.d.ts | 22 + .../js/libjass/build/typescript/index.ts | 21 + .../js/libjass/build/typescript/walker.ts | 888 + .../web/static/js/libjass/build/uglify.js | 447 + .../static/js/libjass/build/umd-wrapper.js | 65 + negromate/web/static/js/libjass/package.json | 44 + .../web/static/js/libjass/src/globals.d.ts | 163 + negromate/web/static/js/libjass/src/index.ts | 137 + .../web/static/js/libjass/src/parser/index.ts | 23 + .../web/static/js/libjass/src/parser/misc.ts | 68 + .../web/static/js/libjass/src/parser/parse.ts | 2094 + .../js/libjass/src/parser/stream-parsers.ts | 438 + .../static/js/libjass/src/parser/streams.ts | 251 + .../web/static/js/libjass/src/parser/ttf.ts | 228 + .../static/js/libjass/src/parts/drawing.ts | 148 + .../web/static/js/libjass/src/parts/index.ts | 1326 + .../js/libjass/src/renderers/clocks/auto.ts | 252 + .../js/libjass/src/renderers/clocks/base.ts | 135 + .../js/libjass/src/renderers/clocks/manual.ts | 250 + .../js/libjass/src/renderers/clocks/video.ts | 122 + .../js/libjass/src/renderers/default.ts | 77 + .../static/js/libjass/src/renderers/index.ts | 29 + .../static/js/libjass/src/renderers/null.ts | 208 + .../js/libjass/src/renderers/settings.ts | 240 + .../src/renderers/web/animation-collection.ts | 126 + .../src/renderers/web/drawing-styles.ts | 131 + .../js/libjass/src/renderers/web/font-size.ts | 121 + .../js/libjass/src/renderers/web/keyframe.ts | 43 + .../js/libjass/src/renderers/web/renderer.ts | 1214 + .../libjass/src/renderers/web/span-styles.ts | 1093 + .../static/js/libjass/src/serialization.ts | 78 + .../web/static/js/libjass/src/settings.ts | 51 + .../web/static/js/libjass/src/tsconfig.json | 24 + .../web/static/js/libjass/src/tslint.json | 164 + .../web/static/js/libjass/src/types/ass.ts | 322 + .../static/js/libjass/src/types/attachment.ts | 78 + .../static/js/libjass/src/types/dialogue.ts | 270 + .../web/static/js/libjass/src/types/misc.ts | 103 + .../js/libjass/src/types/script-properties.ts | 106 + .../web/static/js/libjass/src/types/style.ts | 334 + .../web/static/js/libjass/src/utility/map.ts | 221 + .../static/js/libjass/src/utility/mixin.ts | 33 + .../static/js/libjass/src/utility/promise.ts | 497 + .../web/static/js/libjass/src/utility/set.ts | 178 + .../js/libjass/src/webworker/channel.ts | 195 + .../js/libjass/src/webworker/commands.ts | 28 + .../static/js/libjass/src/webworker/index.ts | 59 + .../static/js/libjass/src/webworker/misc.ts | 46 + .../web/static/js/libjass/tests/doc/doc.js | 84 + .../libjass/tests/functional/alpha/alpha.ass | 18 + .../libjass/tests/functional/alpha/alpha.js | 31 + .../tests/functional/alpha/chrome/alpha-1.png | Bin 0 -> 5591 bytes .../alpha/internet explorer/alpha-1.png | Bin 0 -> 17857 bytes .../js/libjass/tests/functional/auto-clock.js | 154 + .../tests/functional/fr/chrome/frz-01.png | Bin 0 -> 12237 bytes .../tests/functional/fr/chrome/frz-02.png | Bin 0 -> 3783 bytes .../tests/functional/fr/chrome/frz-03.png | Bin 0 -> 3789 bytes .../tests/functional/fr/chrome/frz-04.png | Bin 0 -> 3804 bytes .../tests/functional/fr/chrome/frz-05.png | Bin 0 -> 3791 bytes .../tests/functional/fr/chrome/frz-06.png | Bin 0 -> 3760 bytes .../tests/functional/fr/chrome/frz-07.png | Bin 0 -> 3779 bytes .../tests/functional/fr/chrome/frz-08.png | Bin 0 -> 3776 bytes .../tests/functional/fr/chrome/frz-09.png | Bin 0 -> 3828 bytes .../tests/functional/fr/chrome/frz-10.png | Bin 0 -> 3756 bytes .../js/libjass/tests/functional/fr/frz.ass | 32 + .../js/libjass/tests/functional/fr/frz.js | 40 + .../fr/internet explorer/frz-01.png | Bin 0 -> 80108 bytes .../fr/internet explorer/frz-02.png | Bin 0 -> 19387 bytes .../fr/internet explorer/frz-03.png | Bin 0 -> 19673 bytes .../fr/internet explorer/frz-04.png | Bin 0 -> 19771 bytes .../fr/internet explorer/frz-05.png | Bin 0 -> 19734 bytes .../fr/internet explorer/frz-06.png | Bin 0 -> 19862 bytes .../fr/internet explorer/frz-07.png | Bin 0 -> 19710 bytes .../fr/internet explorer/frz-08.png | Bin 0 -> 19786 bytes .../fr/internet explorer/frz-09.png | Bin 0 -> 19518 bytes .../fr/internet explorer/frz-10.png | Bin 0 -> 19568 bytes .../tests/functional/fsc/chrome/fsc-1.png | Bin 0 -> 17440 bytes .../js/libjass/tests/functional/fsc/fsc.ass | 18 + .../js/libjass/tests/functional/fsc/fsc.js | 31 + .../fsc/internet explorer/fsc-1.png | Bin 0 -> 35056 bytes .../tests/functional/kfx/chrome/kfx-1.png | Bin 0 -> 16585 bytes .../tests/functional/kfx/chrome/kfx-2.png | Bin 0 -> 17165 bytes .../tests/functional/kfx/chrome/kfx-3.png | Bin 0 -> 17165 bytes .../tests/functional/kfx/chrome/kfx-4.png | Bin 0 -> 16909 bytes .../tests/functional/kfx/chrome/kfx-5.png | Bin 0 -> 16001 bytes .../tests/functional/kfx/chrome/kfx-6.png | Bin 0 -> 16001 bytes .../kfx/internet explorer/kfx-1.png | Bin 0 -> 15073 bytes .../kfx/internet explorer/kfx-2.png | Bin 0 -> 15073 bytes .../kfx/internet explorer/kfx-3.png | Bin 0 -> 15073 bytes .../kfx/internet explorer/kfx-4.png | Bin 0 -> 15073 bytes .../kfx/internet explorer/kfx-5.png | Bin 0 -> 15073 bytes .../kfx/internet explorer/kfx-6.png | Bin 0 -> 15073 bytes .../js/libjass/tests/functional/kfx/kfx.ass | 18 + .../js/libjass/tests/functional/kfx/kfx.js | 36 + .../functional/outlines/chrome/outlines-1.png | Bin 0 -> 9559 bytes .../functional/outlines/chrome/outlines-2.png | Bin 0 -> 11490 bytes .../functional/outlines/chrome/outlines-3.png | Bin 0 -> 12280 bytes .../functional/outlines/chrome/outlines-4.png | Bin 0 -> 12280 bytes .../functional/outlines/chrome/subpixel-1.png | Bin 0 -> 23308 bytes .../functional/outlines/chrome/subpixel-2.png | Bin 0 -> 27422 bytes .../outlines/internet explorer/outlines-1.png | Bin 0 -> 10493 bytes .../outlines/internet explorer/outlines-2.png | Bin 0 -> 11954 bytes .../outlines/internet explorer/outlines-3.png | Bin 0 -> 10119 bytes .../outlines/internet explorer/outlines-4.png | Bin 0 -> 10119 bytes .../outlines/internet explorer/subpixel-1.png | Bin 0 -> 24993 bytes .../outlines/internet explorer/subpixel-2.png | Bin 0 -> 28744 bytes .../tests/functional/outlines/outlines.ass | 25 + .../tests/functional/outlines/outlines.js | 34 + .../tests/functional/outlines/subpixel.ass | 23 + .../tests/functional/outlines/subpixel.js | 32 + .../js/libjass/tests/functional/r/alpha.ass | 19 + .../js/libjass/tests/functional/r/alpha.js | 31 + .../tests/functional/r/chrome/alpha-1.png | Bin 0 -> 19067 bytes .../r/internet explorer/alpha-1.png | Bin 0 -> 21498 bytes .../js/libjass/tests/functional/t/alpha.ass | 24 + .../js/libjass/tests/functional/t/alpha.js | 36 + .../tests/functional/t/chrome/alpha-1.png | Bin 0 -> 23364 bytes .../tests/functional/t/chrome/alpha-2.png | Bin 0 -> 23364 bytes .../tests/functional/t/chrome/alpha-3.png | Bin 0 -> 24464 bytes .../tests/functional/t/chrome/alpha-4.png | Bin 0 -> 25235 bytes .../tests/functional/t/chrome/alpha-5.png | Bin 0 -> 25142 bytes .../tests/functional/t/chrome/alpha-6.png | Bin 0 -> 25142 bytes .../t/internet explorer/alpha-1.png | Bin 0 -> 22924 bytes .../t/internet explorer/alpha-2.png | Bin 0 -> 22924 bytes .../t/internet explorer/alpha-3.png | Bin 0 -> 22767 bytes .../t/internet explorer/alpha-4.png | Bin 0 -> 22555 bytes .../t/internet explorer/alpha-5.png | Bin 0 -> 23009 bytes .../t/internet explorer/alpha-6.png | Bin 0 -> 23009 bytes .../web/static/js/libjass/tests/intern-doc.js | 26 + .../web/static/js/libjass/tests/intern.js | 66 + .../tests/support/browser-test-page.css | 29 + .../tests/support/browser-test-page.html | 12 + .../js/libjass/tests/support/parser-test.js | 49 + .../js/libjass/tests/support/test-page.js | 143 + .../web/static/js/libjass/tests/unit/1.ass | 32 + .../web/static/js/libjass/tests/unit/2.ass | 43 + .../web/static/js/libjass/tests/unit/3.ass | 33 + .../web/static/js/libjass/tests/unit/4.ass | 22 + .../web/static/js/libjass/tests/unit/5.ass | 22 + .../web/static/js/libjass/tests/unit/6.ass | 24 + .../web/static/js/libjass/tests/unit/7.ass | 31 + .../web/static/js/libjass/tests/unit/8.ass | 44 + .../js/libjass/tests/unit/attachments.js | 57 + .../js/libjass/tests/unit/manual-clock.js | 189 + .../static/js/libjass/tests/unit/minified.js | 43 + .../js/libjass/tests/unit/miscellaneous.js | 471 + .../static/js/libjass/tests/unit/polyfills.js | 277 + .../js/libjass/tests/unit/primitives.js | 83 + .../js/libjass/tests/unit/serialization.js | 36 + .../web/static/js/libjass/tests/unit/tags.js | 220 + .../static/js/libjass/tests/unit/webworker.js | 73 + .../web/static/js/videojs-ass/.gitignore | 4 + negromate/web/static/js/videojs-ass/LICENSE | 13 + negromate/web/static/js/videojs-ass/README.md | 67 + .../web/static/js/videojs-ass/bower.json | 30 + .../web/static/js/videojs-ass/example.html | 61 + .../web/static/js/videojs-ass/package.json | 28 + .../static/js/videojs-ass/src/videojs.ass.css | 28 + .../static/js/videojs-ass/src/videojs.ass.js | 122 + .../js/videojs-playlist-ui/CHANGELOG.md | 166 + .../js/videojs-playlist-ui/CONTRIBUTING.md | 30 + .../web/static/js/videojs-playlist-ui/LICENSE | 13 + .../static/js/videojs-playlist-ui/README.md | 110 + .../dist/videojs-playlist-ui.cjs.js | 504 + .../dist/videojs-playlist-ui.css | 1 + .../dist/videojs-playlist-ui.es.js | 500 + .../dist/videojs-playlist-ui.js | 508 + .../dist/videojs-playlist-ui.min.js | 2 + .../dist/videojs-playlist-ui.vertical.css | 1 + ...videojs-playlist-ui.vertical.no-prefix.css | 1 + .../static/js/videojs-playlist-ui/index.html | 18 + .../js/videojs-playlist-ui/package.json | 143 + .../videojs-playlist-ui/scripts/karma.conf.js | 13 + .../scripts/postcss.config.js | 9 + .../scripts/rollup.config.js | 11 + .../js/videojs-playlist-ui/src/plugin.js | 479 + .../js/videojs-playlist-ui/src/plugin.scss | 288 + .../videojs-playlist-ui/test/dist/bundle.js | 6313 ++ .../test/example/oceans-low.jpg | Bin 0 -> 30787 bytes .../test/example/oceans.jpg | Bin 0 -> 87243 bytes .../videojs-playlist-ui/test/plugin.test.js | 576 + .../static/js/videojs-playlist/CHANGELOG.md | 149 + .../js/videojs-playlist/CONTRIBUTING.md | 30 + .../web/static/js/videojs-playlist/LICENSE | 13 + .../web/static/js/videojs-playlist/README.md | 96 + .../dist/videojs-playlist.cjs.js | 767 + .../dist/videojs-playlist.es.js | 763 + .../videojs-playlist/dist/videojs-playlist.js | 771 + .../dist/videojs-playlist.min.js | 2 + .../static/js/videojs-playlist/docs/api.md | 507 + .../docs/api/auto-advance.js.html | 148 + .../docs/api/fonts/OpenSans-Bold-webfont.eot | Bin 0 -> 19544 bytes .../docs/api/fonts/OpenSans-Bold-webfont.svg | 1830 + .../docs/api/fonts/OpenSans-Bold-webfont.woff | Bin 0 -> 22432 bytes .../api/fonts/OpenSans-BoldItalic-webfont.eot | Bin 0 -> 20133 bytes .../api/fonts/OpenSans-BoldItalic-webfont.svg | 1830 + .../fonts/OpenSans-BoldItalic-webfont.woff | Bin 0 -> 23048 bytes .../api/fonts/OpenSans-Italic-webfont.eot | Bin 0 -> 20265 bytes .../api/fonts/OpenSans-Italic-webfont.svg | 1830 + .../api/fonts/OpenSans-Italic-webfont.woff | Bin 0 -> 23188 bytes .../docs/api/fonts/OpenSans-Light-webfont.eot | Bin 0 -> 19514 bytes .../docs/api/fonts/OpenSans-Light-webfont.svg | 1831 + .../api/fonts/OpenSans-Light-webfont.woff | Bin 0 -> 22248 bytes .../fonts/OpenSans-LightItalic-webfont.eot | Bin 0 -> 20535 bytes .../fonts/OpenSans-LightItalic-webfont.svg | 1835 + .../fonts/OpenSans-LightItalic-webfont.woff | Bin 0 -> 23400 bytes .../api/fonts/OpenSans-Regular-webfont.eot | Bin 0 -> 19836 bytes .../api/fonts/OpenSans-Regular-webfont.svg | 1831 + .../api/fonts/OpenSans-Regular-webfont.woff | Bin 0 -> 22660 bytes .../js/videojs-playlist/docs/api/global.html | 1346 + .../js/videojs-playlist/docs/api/index.html | 65 + .../docs/api/play-item.js.html | 106 + .../docs/api/playlist-maker.js.html | 641 + .../videojs-playlist/docs/api/plugin.js.html | 77 + .../docs/api/scripts/linenumber.js | 25 + .../scripts/prettify/Apache-License-2.0.txt | 202 + .../docs/api/scripts/prettify/lang-css.js | 2 + .../docs/api/scripts/prettify/prettify.js | 28 + .../docs/api/styles/jsdoc-default.css | 358 + .../docs/api/styles/prettify-jsdoc.css | 111 + .../docs/api/styles/prettify-tomorrow.css | 132 + .../static/js/videojs-playlist/docs/index.md | 1 + .../web/static/js/videojs-playlist/index.html | 114 + .../static/js/videojs-playlist/package.json | 137 + .../js/videojs-playlist/scripts/karma.conf.js | 13 + .../videojs-playlist/scripts/rollup.config.js | 11 + .../js/videojs-playlist/src/auto-advance.js | 97 + .../js/videojs-playlist/src/play-item.js | 61 + .../js/videojs-playlist/src/playlist-maker.js | 590 + .../static/js/videojs-playlist/src/plugin.js | 26 + .../test/auto-advance.test.js | 167 + .../js/videojs-playlist/test/dist/bundle.js | 7242 ++ .../videojs-playlist/test/play-item.test.js | 137 + .../test/player-proxy-maker.js | 37 + .../test/playlist-maker.test.js | 901 + .../js/videojs-playlist/test/plugin.test.js | 20 + .../static/js/videojs/alt/video-js-cdn.css | 1663 + .../js/videojs/alt/video-js-cdn.min.css | 1 + .../web/static/js/videojs/alt/video.core.js | 29123 ++++++++ .../static/js/videojs/alt/video.core.min.js | 19 + .../static/js/videojs/alt/video.core.novtt.js | 27268 ++++++++ .../js/videojs/alt/video.core.novtt.min.js | 19 + .../web/static/js/videojs/alt/video.novtt.js | 53814 +++++++++++++++ .../static/js/videojs/alt/video.novtt.min.js | 28 + .../examples/elephantsdream/captions.ar.vtt | 330 + .../examples/elephantsdream/captions.en.vtt | 334 + .../examples/elephantsdream/captions.ja.vtt | 326 + .../examples/elephantsdream/captions.ru.vtt | 356 + .../examples/elephantsdream/captions.sv.vtt | 349 + .../examples/elephantsdream/chapters.en.vtt | 44 + .../elephantsdream/descriptions.en.vtt | 280 + .../examples/elephantsdream/index.html | 41 + .../web/static/js/videojs/examples/index.html | 18 + .../examples/shared/example-captions.vtt | 41 + .../videojs/examples/simple-embed/index.html | 23 + .../web/static/js/videojs/font/VideoJS.svg | 114 + .../web/static/js/videojs/font/VideoJS.ttf | Bin 0 -> 7080 bytes .../web/static/js/videojs/font/VideoJS.woff | Bin 0 -> 4324 bytes negromate/web/static/js/videojs/lang/ar.js | 34 + negromate/web/static/js/videojs/lang/ar.json | 34 + negromate/web/static/js/videojs/lang/ba.js | 26 + negromate/web/static/js/videojs/lang/ba.json | 26 + negromate/web/static/js/videojs/lang/bg.js | 26 + negromate/web/static/js/videojs/lang/bg.json | 26 + negromate/web/static/js/videojs/lang/ca.js | 26 + negromate/web/static/js/videojs/lang/ca.json | 26 + negromate/web/static/js/videojs/lang/cs.js | 85 + negromate/web/static/js/videojs/lang/cs.json | 85 + negromate/web/static/js/videojs/lang/cy.js | 85 + negromate/web/static/js/videojs/lang/cy.json | 85 + negromate/web/static/js/videojs/lang/da.js | 26 + negromate/web/static/js/videojs/lang/da.json | 26 + negromate/web/static/js/videojs/lang/de.js | 87 + negromate/web/static/js/videojs/lang/de.json | 88 + negromate/web/static/js/videojs/lang/el.js | 40 + negromate/web/static/js/videojs/lang/el.json | 40 + negromate/web/static/js/videojs/lang/en.js | 87 + negromate/web/static/js/videojs/lang/en.json | 87 + negromate/web/static/js/videojs/lang/es.js | 87 + negromate/web/static/js/videojs/lang/es.json | 87 + negromate/web/static/js/videojs/lang/fa.js | 84 + negromate/web/static/js/videojs/lang/fa.json | 84 + negromate/web/static/js/videojs/lang/fi.js | 26 + negromate/web/static/js/videojs/lang/fi.json | 26 + negromate/web/static/js/videojs/lang/fr.js | 84 + negromate/web/static/js/videojs/lang/fr.json | 84 + negromate/web/static/js/videojs/lang/gd.js | 87 + negromate/web/static/js/videojs/lang/gd.json | 87 + negromate/web/static/js/videojs/lang/gl.js | 87 + negromate/web/static/js/videojs/lang/gl.json | 87 + negromate/web/static/js/videojs/lang/he.js | 84 + negromate/web/static/js/videojs/lang/he.json | 84 + negromate/web/static/js/videojs/lang/hr.js | 26 + negromate/web/static/js/videojs/lang/hr.json | 26 + negromate/web/static/js/videojs/lang/hu.js | 26 + negromate/web/static/js/videojs/lang/hu.json | 26 + negromate/web/static/js/videojs/lang/it.js | 26 + negromate/web/static/js/videojs/lang/it.json | 26 + negromate/web/static/js/videojs/lang/ja.js | 26 + negromate/web/static/js/videojs/lang/ja.json | 26 + negromate/web/static/js/videojs/lang/ko.js | 26 + negromate/web/static/js/videojs/lang/ko.json | 26 + negromate/web/static/js/videojs/lang/nb.js | 87 + negromate/web/static/js/videojs/lang/nb.json | 87 + negromate/web/static/js/videojs/lang/nl.js | 84 + negromate/web/static/js/videojs/lang/nl.json | 84 + negromate/web/static/js/videojs/lang/nn.js | 87 + negromate/web/static/js/videojs/lang/nn.json | 87 + negromate/web/static/js/videojs/lang/oc.js | 87 + negromate/web/static/js/videojs/lang/oc.json | 87 + negromate/web/static/js/videojs/lang/pl.js | 34 + negromate/web/static/js/videojs/lang/pl.json | 34 + negromate/web/static/js/videojs/lang/pt-BR.js | 85 + .../web/static/js/videojs/lang/pt-BR.json | 86 + negromate/web/static/js/videojs/lang/pt-PT.js | 41 + .../web/static/js/videojs/lang/pt-PT.json | 41 + negromate/web/static/js/videojs/lang/ru.js | 85 + negromate/web/static/js/videojs/lang/ru.json | 85 + negromate/web/static/js/videojs/lang/sk.js | 85 + negromate/web/static/js/videojs/lang/sk.json | 85 + negromate/web/static/js/videojs/lang/sr.js | 26 + negromate/web/static/js/videojs/lang/sr.json | 26 + negromate/web/static/js/videojs/lang/sv.js | 87 + negromate/web/static/js/videojs/lang/sv.json | 87 + negromate/web/static/js/videojs/lang/tr.js | 76 + negromate/web/static/js/videojs/lang/tr.json | 76 + negromate/web/static/js/videojs/lang/uk.js | 85 + negromate/web/static/js/videojs/lang/uk.json | 85 + negromate/web/static/js/videojs/lang/vi.js | 84 + negromate/web/static/js/videojs/lang/vi.json | 84 + negromate/web/static/js/videojs/lang/zh-CN.js | 87 + .../web/static/js/videojs/lang/zh-CN.json | 87 + .../web/static/js/videojs/lang/zh-Hans.js | 87 + .../web/static/js/videojs/lang/zh-Hans.json | 87 + .../web/static/js/videojs/lang/zh-Hant.js | 87 + .../web/static/js/videojs/lang/zh-Hant.json | 87 + negromate/web/static/js/videojs/lang/zh-TW.js | 87 + .../web/static/js/videojs/lang/zh-TW.json | 87 + negromate/web/static/js/videojs/video-js.css | 1663 + .../web/static/js/videojs/video-js.min.css | 1 + negromate/web/static/js/videojs/video.cjs.js | 45026 +++++++++++++ negromate/web/static/js/videojs/video.es.js | 45022 +++++++++++++ negromate/web/static/js/videojs/video.js | 55669 ++++++++++++++++ negromate/web/static/js/videojs/video.min.js | 28 + negromate/web/static/libreto/libreto.png | Bin 0 -> 24526 bytes negromate/web/templates/base.html | 70 + negromate/web/templates/home.html | 13 + negromate/web/templates/index.html | 54 + negromate/web/templates/karaoke.ass | 9 + negromate/web/templates/playlist.html | 98 + negromate/web/templates/song.html | 56 + negromate/web/templates/todo.html | 40 + pyproject.toml | 3 + requirements.txt | 4 + setup.cfg | 39 + 381 files changed, 323267 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE.txt create mode 100644 MANIFEST.in create mode 100644 README.md create mode 100755 build.py create mode 100644 negromate/__init__.py create mode 100644 negromate/web/__init__.py create mode 100644 negromate/web/builder.py create mode 100644 negromate/web/commands.py create mode 100644 negromate/web/karaoke_templates.py create mode 100644 negromate/web/static/.gitignore create mode 100644 negromate/web/static/css/CyrBit.ttf create mode 100644 negromate/web/static/css/cc-by-sa.png create mode 100644 negromate/web/static/css/main.css create mode 100644 negromate/web/static/css/nm_icon.png create mode 100644 negromate/web/static/js/libjass/.gitignore create mode 100644 negromate/web/static/js/libjass/.travis.yml create mode 100644 negromate/web/static/js/libjass/CHANGELOG.md create mode 100644 negromate/web/static/js/libjass/LICENSE create mode 100644 negromate/web/static/js/libjass/README.md create mode 100644 negromate/web/static/js/libjass/build.js create mode 100644 negromate/web/static/js/libjass/build/doc.ts create mode 100644 negromate/web/static/js/libjass/build/node.d.ts create mode 100644 negromate/web/static/js/libjass/build/tsconfig.json create mode 100644 negromate/web/static/js/libjass/build/typescript/ast.ts create mode 100644 negromate/web/static/js/libjass/build/typescript/compiler.ts create mode 100644 negromate/web/static/js/libjass/build/typescript/extras.d.ts create mode 100644 negromate/web/static/js/libjass/build/typescript/index.ts create mode 100644 negromate/web/static/js/libjass/build/typescript/walker.ts create mode 100644 negromate/web/static/js/libjass/build/uglify.js create mode 100644 negromate/web/static/js/libjass/build/umd-wrapper.js create mode 100644 negromate/web/static/js/libjass/package.json create mode 100644 negromate/web/static/js/libjass/src/globals.d.ts create mode 100644 negromate/web/static/js/libjass/src/index.ts create mode 100644 negromate/web/static/js/libjass/src/parser/index.ts create mode 100644 negromate/web/static/js/libjass/src/parser/misc.ts create mode 100644 negromate/web/static/js/libjass/src/parser/parse.ts create mode 100644 negromate/web/static/js/libjass/src/parser/stream-parsers.ts create mode 100644 negromate/web/static/js/libjass/src/parser/streams.ts create mode 100644 negromate/web/static/js/libjass/src/parser/ttf.ts create mode 100644 negromate/web/static/js/libjass/src/parts/drawing.ts create mode 100644 negromate/web/static/js/libjass/src/parts/index.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/clocks/auto.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/clocks/base.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/clocks/manual.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/clocks/video.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/default.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/index.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/null.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/settings.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/web/animation-collection.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/web/drawing-styles.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/web/font-size.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/web/keyframe.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/web/renderer.ts create mode 100644 negromate/web/static/js/libjass/src/renderers/web/span-styles.ts create mode 100644 negromate/web/static/js/libjass/src/serialization.ts create mode 100644 negromate/web/static/js/libjass/src/settings.ts create mode 100644 negromate/web/static/js/libjass/src/tsconfig.json create mode 100644 negromate/web/static/js/libjass/src/tslint.json create mode 100644 negromate/web/static/js/libjass/src/types/ass.ts create mode 100644 negromate/web/static/js/libjass/src/types/attachment.ts create mode 100644 negromate/web/static/js/libjass/src/types/dialogue.ts create mode 100644 negromate/web/static/js/libjass/src/types/misc.ts create mode 100644 negromate/web/static/js/libjass/src/types/script-properties.ts create mode 100644 negromate/web/static/js/libjass/src/types/style.ts create mode 100644 negromate/web/static/js/libjass/src/utility/map.ts create mode 100644 negromate/web/static/js/libjass/src/utility/mixin.ts create mode 100644 negromate/web/static/js/libjass/src/utility/promise.ts create mode 100644 negromate/web/static/js/libjass/src/utility/set.ts create mode 100644 negromate/web/static/js/libjass/src/webworker/channel.ts create mode 100644 negromate/web/static/js/libjass/src/webworker/commands.ts create mode 100644 negromate/web/static/js/libjass/src/webworker/index.ts create mode 100644 negromate/web/static/js/libjass/src/webworker/misc.ts create mode 100644 negromate/web/static/js/libjass/tests/doc/doc.js create mode 100644 negromate/web/static/js/libjass/tests/functional/alpha/alpha.ass create mode 100644 negromate/web/static/js/libjass/tests/functional/alpha/alpha.js create mode 100644 negromate/web/static/js/libjass/tests/functional/alpha/chrome/alpha-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/alpha/internet explorer/alpha-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/auto-clock.js create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-01.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-02.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-03.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-04.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-05.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-06.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-07.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-08.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-09.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/chrome/frz-10.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/frz.ass create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/frz.js create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-01.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-02.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-03.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-04.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-05.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-06.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-07.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-08.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-09.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fr/internet explorer/frz-10.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fsc/chrome/fsc-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/fsc/fsc.ass create mode 100644 negromate/web/static/js/libjass/tests/functional/fsc/fsc.js create mode 100644 negromate/web/static/js/libjass/tests/functional/fsc/internet explorer/fsc-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/chrome/kfx-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/chrome/kfx-2.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/chrome/kfx-3.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/chrome/kfx-4.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/chrome/kfx-5.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/chrome/kfx-6.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/internet explorer/kfx-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/internet explorer/kfx-2.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/internet explorer/kfx-3.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/internet explorer/kfx-4.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/internet explorer/kfx-5.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/internet explorer/kfx-6.png create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/kfx.ass create mode 100644 negromate/web/static/js/libjass/tests/functional/kfx/kfx.js create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/chrome/outlines-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/chrome/outlines-2.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/chrome/outlines-3.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/chrome/outlines-4.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/chrome/subpixel-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/chrome/subpixel-2.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/internet explorer/outlines-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/internet explorer/outlines-2.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/internet explorer/outlines-3.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/internet explorer/outlines-4.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/internet explorer/subpixel-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/internet explorer/subpixel-2.png create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/outlines.ass create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/outlines.js create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/subpixel.ass create mode 100644 negromate/web/static/js/libjass/tests/functional/outlines/subpixel.js create mode 100644 negromate/web/static/js/libjass/tests/functional/r/alpha.ass create mode 100644 negromate/web/static/js/libjass/tests/functional/r/alpha.js create mode 100644 negromate/web/static/js/libjass/tests/functional/r/chrome/alpha-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/r/internet explorer/alpha-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/alpha.ass create mode 100644 negromate/web/static/js/libjass/tests/functional/t/alpha.js create mode 100644 negromate/web/static/js/libjass/tests/functional/t/chrome/alpha-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/chrome/alpha-2.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/chrome/alpha-3.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/chrome/alpha-4.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/chrome/alpha-5.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/chrome/alpha-6.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/internet explorer/alpha-1.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/internet explorer/alpha-2.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/internet explorer/alpha-3.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/internet explorer/alpha-4.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/internet explorer/alpha-5.png create mode 100644 negromate/web/static/js/libjass/tests/functional/t/internet explorer/alpha-6.png create mode 100644 negromate/web/static/js/libjass/tests/intern-doc.js create mode 100644 negromate/web/static/js/libjass/tests/intern.js create mode 100644 negromate/web/static/js/libjass/tests/support/browser-test-page.css create mode 100644 negromate/web/static/js/libjass/tests/support/browser-test-page.html create mode 100644 negromate/web/static/js/libjass/tests/support/parser-test.js create mode 100644 negromate/web/static/js/libjass/tests/support/test-page.js create mode 100644 negromate/web/static/js/libjass/tests/unit/1.ass create mode 100644 negromate/web/static/js/libjass/tests/unit/2.ass create mode 100644 negromate/web/static/js/libjass/tests/unit/3.ass create mode 100644 negromate/web/static/js/libjass/tests/unit/4.ass create mode 100644 negromate/web/static/js/libjass/tests/unit/5.ass create mode 100644 negromate/web/static/js/libjass/tests/unit/6.ass create mode 100644 negromate/web/static/js/libjass/tests/unit/7.ass create mode 100644 negromate/web/static/js/libjass/tests/unit/8.ass create mode 100644 negromate/web/static/js/libjass/tests/unit/attachments.js create mode 100644 negromate/web/static/js/libjass/tests/unit/manual-clock.js create mode 100644 negromate/web/static/js/libjass/tests/unit/minified.js create mode 100644 negromate/web/static/js/libjass/tests/unit/miscellaneous.js create mode 100644 negromate/web/static/js/libjass/tests/unit/polyfills.js create mode 100644 negromate/web/static/js/libjass/tests/unit/primitives.js create mode 100644 negromate/web/static/js/libjass/tests/unit/serialization.js create mode 100644 negromate/web/static/js/libjass/tests/unit/tags.js create mode 100644 negromate/web/static/js/libjass/tests/unit/webworker.js create mode 100644 negromate/web/static/js/videojs-ass/.gitignore create mode 100644 negromate/web/static/js/videojs-ass/LICENSE create mode 100644 negromate/web/static/js/videojs-ass/README.md create mode 100644 negromate/web/static/js/videojs-ass/bower.json create mode 100644 negromate/web/static/js/videojs-ass/example.html create mode 100644 negromate/web/static/js/videojs-ass/package.json create mode 100644 negromate/web/static/js/videojs-ass/src/videojs.ass.css create mode 100644 negromate/web/static/js/videojs-ass/src/videojs.ass.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/CHANGELOG.md create mode 100644 negromate/web/static/js/videojs-playlist-ui/CONTRIBUTING.md create mode 100644 negromate/web/static/js/videojs-playlist-ui/LICENSE create mode 100644 negromate/web/static/js/videojs-playlist-ui/README.md create mode 100644 negromate/web/static/js/videojs-playlist-ui/dist/videojs-playlist-ui.cjs.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/dist/videojs-playlist-ui.css create mode 100644 negromate/web/static/js/videojs-playlist-ui/dist/videojs-playlist-ui.es.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/dist/videojs-playlist-ui.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/dist/videojs-playlist-ui.min.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/dist/videojs-playlist-ui.vertical.css create mode 100644 negromate/web/static/js/videojs-playlist-ui/dist/videojs-playlist-ui.vertical.no-prefix.css create mode 100644 negromate/web/static/js/videojs-playlist-ui/index.html create mode 100644 negromate/web/static/js/videojs-playlist-ui/package.json create mode 100644 negromate/web/static/js/videojs-playlist-ui/scripts/karma.conf.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/scripts/postcss.config.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/scripts/rollup.config.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/src/plugin.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/src/plugin.scss create mode 100644 negromate/web/static/js/videojs-playlist-ui/test/dist/bundle.js create mode 100644 negromate/web/static/js/videojs-playlist-ui/test/example/oceans-low.jpg create mode 100644 negromate/web/static/js/videojs-playlist-ui/test/example/oceans.jpg create mode 100644 negromate/web/static/js/videojs-playlist-ui/test/plugin.test.js create mode 100644 negromate/web/static/js/videojs-playlist/CHANGELOG.md create mode 100644 negromate/web/static/js/videojs-playlist/CONTRIBUTING.md create mode 100644 negromate/web/static/js/videojs-playlist/LICENSE create mode 100644 negromate/web/static/js/videojs-playlist/README.md create mode 100644 negromate/web/static/js/videojs-playlist/dist/videojs-playlist.cjs.js create mode 100644 negromate/web/static/js/videojs-playlist/dist/videojs-playlist.es.js create mode 100644 negromate/web/static/js/videojs-playlist/dist/videojs-playlist.js create mode 100644 negromate/web/static/js/videojs-playlist/dist/videojs-playlist.min.js create mode 100644 negromate/web/static/js/videojs-playlist/docs/api.md create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/auto-advance.js.html create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Bold-webfont.eot create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Bold-webfont.svg create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Bold-webfont.woff create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-BoldItalic-webfont.eot create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-BoldItalic-webfont.svg create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-BoldItalic-webfont.woff create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Italic-webfont.eot create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Italic-webfont.svg create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Italic-webfont.woff create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Light-webfont.eot create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Light-webfont.svg create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Light-webfont.woff create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-LightItalic-webfont.eot create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-LightItalic-webfont.svg create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-LightItalic-webfont.woff create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Regular-webfont.eot create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Regular-webfont.svg create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/fonts/OpenSans-Regular-webfont.woff create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/global.html create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/index.html create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/play-item.js.html create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/playlist-maker.js.html create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/plugin.js.html create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/scripts/linenumber.js create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/scripts/prettify/Apache-License-2.0.txt create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/scripts/prettify/lang-css.js create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/scripts/prettify/prettify.js create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/styles/jsdoc-default.css create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/styles/prettify-jsdoc.css create mode 100644 negromate/web/static/js/videojs-playlist/docs/api/styles/prettify-tomorrow.css create mode 100644 negromate/web/static/js/videojs-playlist/docs/index.md create mode 100644 negromate/web/static/js/videojs-playlist/index.html create mode 100644 negromate/web/static/js/videojs-playlist/package.json create mode 100644 negromate/web/static/js/videojs-playlist/scripts/karma.conf.js create mode 100644 negromate/web/static/js/videojs-playlist/scripts/rollup.config.js create mode 100644 negromate/web/static/js/videojs-playlist/src/auto-advance.js create mode 100644 negromate/web/static/js/videojs-playlist/src/play-item.js create mode 100644 negromate/web/static/js/videojs-playlist/src/playlist-maker.js create mode 100644 negromate/web/static/js/videojs-playlist/src/plugin.js create mode 100644 negromate/web/static/js/videojs-playlist/test/auto-advance.test.js create mode 100644 negromate/web/static/js/videojs-playlist/test/dist/bundle.js create mode 100644 negromate/web/static/js/videojs-playlist/test/play-item.test.js create mode 100644 negromate/web/static/js/videojs-playlist/test/player-proxy-maker.js create mode 100644 negromate/web/static/js/videojs-playlist/test/playlist-maker.test.js create mode 100644 negromate/web/static/js/videojs-playlist/test/plugin.test.js create mode 100644 negromate/web/static/js/videojs/alt/video-js-cdn.css create mode 100644 negromate/web/static/js/videojs/alt/video-js-cdn.min.css create mode 100644 negromate/web/static/js/videojs/alt/video.core.js create mode 100644 negromate/web/static/js/videojs/alt/video.core.min.js create mode 100644 negromate/web/static/js/videojs/alt/video.core.novtt.js create mode 100644 negromate/web/static/js/videojs/alt/video.core.novtt.min.js create mode 100644 negromate/web/static/js/videojs/alt/video.novtt.js create mode 100644 negromate/web/static/js/videojs/alt/video.novtt.min.js create mode 100644 negromate/web/static/js/videojs/examples/elephantsdream/captions.ar.vtt create mode 100644 negromate/web/static/js/videojs/examples/elephantsdream/captions.en.vtt create mode 100644 negromate/web/static/js/videojs/examples/elephantsdream/captions.ja.vtt create mode 100644 negromate/web/static/js/videojs/examples/elephantsdream/captions.ru.vtt create mode 100644 negromate/web/static/js/videojs/examples/elephantsdream/captions.sv.vtt create mode 100644 negromate/web/static/js/videojs/examples/elephantsdream/chapters.en.vtt create mode 100644 negromate/web/static/js/videojs/examples/elephantsdream/descriptions.en.vtt create mode 100644 negromate/web/static/js/videojs/examples/elephantsdream/index.html create mode 100644 negromate/web/static/js/videojs/examples/index.html create mode 100644 negromate/web/static/js/videojs/examples/shared/example-captions.vtt create mode 100644 negromate/web/static/js/videojs/examples/simple-embed/index.html create mode 100755 negromate/web/static/js/videojs/font/VideoJS.svg create mode 100755 negromate/web/static/js/videojs/font/VideoJS.ttf create mode 100755 negromate/web/static/js/videojs/font/VideoJS.woff create mode 100644 negromate/web/static/js/videojs/lang/ar.js create mode 100644 negromate/web/static/js/videojs/lang/ar.json create mode 100644 negromate/web/static/js/videojs/lang/ba.js create mode 100644 negromate/web/static/js/videojs/lang/ba.json create mode 100644 negromate/web/static/js/videojs/lang/bg.js create mode 100644 negromate/web/static/js/videojs/lang/bg.json create mode 100644 negromate/web/static/js/videojs/lang/ca.js create mode 100644 negromate/web/static/js/videojs/lang/ca.json create mode 100644 negromate/web/static/js/videojs/lang/cs.js create mode 100644 negromate/web/static/js/videojs/lang/cs.json create mode 100644 negromate/web/static/js/videojs/lang/cy.js create mode 100644 negromate/web/static/js/videojs/lang/cy.json create mode 100644 negromate/web/static/js/videojs/lang/da.js create mode 100644 negromate/web/static/js/videojs/lang/da.json create mode 100644 negromate/web/static/js/videojs/lang/de.js create mode 100644 negromate/web/static/js/videojs/lang/de.json create mode 100644 negromate/web/static/js/videojs/lang/el.js create mode 100644 negromate/web/static/js/videojs/lang/el.json create mode 100644 negromate/web/static/js/videojs/lang/en.js create mode 100644 negromate/web/static/js/videojs/lang/en.json create mode 100644 negromate/web/static/js/videojs/lang/es.js create mode 100644 negromate/web/static/js/videojs/lang/es.json create mode 100644 negromate/web/static/js/videojs/lang/fa.js create mode 100644 negromate/web/static/js/videojs/lang/fa.json create mode 100644 negromate/web/static/js/videojs/lang/fi.js create mode 100644 negromate/web/static/js/videojs/lang/fi.json create mode 100644 negromate/web/static/js/videojs/lang/fr.js create mode 100644 negromate/web/static/js/videojs/lang/fr.json create mode 100644 negromate/web/static/js/videojs/lang/gd.js create mode 100755 negromate/web/static/js/videojs/lang/gd.json create mode 100644 negromate/web/static/js/videojs/lang/gl.js create mode 100644 negromate/web/static/js/videojs/lang/gl.json create mode 100644 negromate/web/static/js/videojs/lang/he.js create mode 100644 negromate/web/static/js/videojs/lang/he.json create mode 100644 negromate/web/static/js/videojs/lang/hr.js create mode 100644 negromate/web/static/js/videojs/lang/hr.json create mode 100644 negromate/web/static/js/videojs/lang/hu.js create mode 100644 negromate/web/static/js/videojs/lang/hu.json create mode 100644 negromate/web/static/js/videojs/lang/it.js create mode 100644 negromate/web/static/js/videojs/lang/it.json create mode 100644 negromate/web/static/js/videojs/lang/ja.js create mode 100644 negromate/web/static/js/videojs/lang/ja.json create mode 100644 negromate/web/static/js/videojs/lang/ko.js create mode 100644 negromate/web/static/js/videojs/lang/ko.json create mode 100644 negromate/web/static/js/videojs/lang/nb.js create mode 100644 negromate/web/static/js/videojs/lang/nb.json create mode 100644 negromate/web/static/js/videojs/lang/nl.js create mode 100644 negromate/web/static/js/videojs/lang/nl.json create mode 100644 negromate/web/static/js/videojs/lang/nn.js create mode 100644 negromate/web/static/js/videojs/lang/nn.json create mode 100644 negromate/web/static/js/videojs/lang/oc.js create mode 100644 negromate/web/static/js/videojs/lang/oc.json create mode 100644 negromate/web/static/js/videojs/lang/pl.js create mode 100644 negromate/web/static/js/videojs/lang/pl.json create mode 100644 negromate/web/static/js/videojs/lang/pt-BR.js create mode 100644 negromate/web/static/js/videojs/lang/pt-BR.json create mode 100644 negromate/web/static/js/videojs/lang/pt-PT.js create mode 100644 negromate/web/static/js/videojs/lang/pt-PT.json create mode 100644 negromate/web/static/js/videojs/lang/ru.js create mode 100644 negromate/web/static/js/videojs/lang/ru.json create mode 100644 negromate/web/static/js/videojs/lang/sk.js create mode 100644 negromate/web/static/js/videojs/lang/sk.json create mode 100644 negromate/web/static/js/videojs/lang/sr.js create mode 100644 negromate/web/static/js/videojs/lang/sr.json create mode 100644 negromate/web/static/js/videojs/lang/sv.js create mode 100644 negromate/web/static/js/videojs/lang/sv.json create mode 100644 negromate/web/static/js/videojs/lang/tr.js create mode 100644 negromate/web/static/js/videojs/lang/tr.json create mode 100644 negromate/web/static/js/videojs/lang/uk.js create mode 100644 negromate/web/static/js/videojs/lang/uk.json create mode 100644 negromate/web/static/js/videojs/lang/vi.js create mode 100644 negromate/web/static/js/videojs/lang/vi.json create mode 100644 negromate/web/static/js/videojs/lang/zh-CN.js create mode 100644 negromate/web/static/js/videojs/lang/zh-CN.json create mode 100644 negromate/web/static/js/videojs/lang/zh-Hans.js create mode 100644 negromate/web/static/js/videojs/lang/zh-Hans.json create mode 100644 negromate/web/static/js/videojs/lang/zh-Hant.js create mode 100644 negromate/web/static/js/videojs/lang/zh-Hant.json create mode 100644 negromate/web/static/js/videojs/lang/zh-TW.js create mode 100644 negromate/web/static/js/videojs/lang/zh-TW.json create mode 100644 negromate/web/static/js/videojs/video-js.css create mode 100644 negromate/web/static/js/videojs/video-js.min.css create mode 100644 negromate/web/static/js/videojs/video.cjs.js create mode 100644 negromate/web/static/js/videojs/video.es.js create mode 100644 negromate/web/static/js/videojs/video.js create mode 100644 negromate/web/static/js/videojs/video.min.js create mode 100644 negromate/web/static/libreto/libreto.png create mode 100644 negromate/web/templates/base.html create mode 100644 negromate/web/templates/home.html create mode 100644 negromate/web/templates/index.html create mode 100644 negromate/web/templates/karaoke.ass create mode 100644 negromate/web/templates/playlist.html create mode 100644 negromate/web/templates/song.html create mode 100644 negromate/web/templates/todo.html create mode 100644 pyproject.toml create mode 100644 requirements.txt create mode 100644 setup.cfg diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..db0e999 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/negromate.web.egg-info +/build +/dist diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..7774383 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,6 @@ +recursive-include negromate/web/templates * +recursive-include negromate/web/static * +recursive-exclude negromate/web/static/node_modules * +recursive-exclude negromate/web/static/js/libjass/node_modules * +exclude negromate/web/static/.gitignore +exclude negromate/web/static/package-lock.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..8b3b361 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +Negro Mate Web +================== + +Static html compiler for the web of Negro Mate. diff --git a/build.py b/build.py new file mode 100755 index 0000000..2fb5267 --- /dev/null +++ b/build.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +import sys +from pathlib import Path, PurePath + +from negromateweb.builder import Builder + +builder = Builder( + Path('../bideoak'), + Path('../libreto/libreto.pdf'), +) +builder.build() diff --git a/negromate/__init__.py b/negromate/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/negromate/web/__init__.py b/negromate/web/__init__.py new file mode 100644 index 0000000..9f68fef --- /dev/null +++ b/negromate/web/__init__.py @@ -0,0 +1 @@ +VERSION = "1.0" diff --git a/negromate/web/builder.py b/negromate/web/builder.py new file mode 100644 index 0000000..3ad4e5f --- /dev/null +++ b/negromate/web/builder.py @@ -0,0 +1,141 @@ +import os +from shutil import copy +import sys +from pathlib import Path +import subprocess + +from jinja2 import Environment, PackageLoader, select_autoescape +from jinja2.utils import Markup +import srt + +from negromate.songs import load_songs + +from .karaoke_templates import update_karaoke_songs + + +class SongPage: + def __init__(self, song): + self.song = song + + def get_context_data(self): + parsed_srt = None + if self.song.srt: + with self.song.srt.open('r') as srtfile: + try: + srt_str = srtfile.read().encode('utf-8').decode('utf-8-sig') + parsed_srt = list(srt.parse(srt_str)) + except Exception as e: + print("{}: srt parse error: {}".format(self.song.path.name, e)) + root_path = os.path.relpath(self.song.root, self.song.path) + return { + 'song': self, + 'parsed_srt': parsed_srt, + 'root_path': root_path, + } + + def render(self, builder, context): + ctx = self.get_context_data() + ctx.update(context) + builder.render('song.html', self.song.path, ctx) + + def __getattr__(self, name): + return getattr(self.song, name) + + +class Builder: + def __init__(self, root_folder, libreto): + self.root_folder = root_folder + self.libreto = libreto + self.src_dir = Path(__file__).parent + self.static_dir = self.src_dir / 'static' + + self.env = Environment( + loader=PackageLoader('negromate.web', 'templates'), + autoescape=select_autoescape(['html']), + ) + self.env.filters['url'] = self.url + self.env.filters['display_boolean'] = self.display_boolean + self.current_path = self.root_folder + + def url(self, path): + return os.path.relpath(path, self.current_path) + + def display_boolean(self, value): + if value: + return Markup('✓') + else: + return Markup('✗') + + def render(self, template, target, context): + html_file = target / 'index.html' + page_template = self.env.get_template(template) + root_path = os.path.relpath(self.root_folder, target) + context['root_path'] = root_path + + with html_file.open('w') as page: + page.write(page_template.render(context)) + + def build(self): + songs, pending_songs = load_songs(self.root_folder) + songs = [SongPage(s) for s in songs] + pending_songs = [SongPage(s) for s in pending_songs] + + global_context = { + 'songs': songs, + 'root_folder': self.root_folder, + } + + for song in songs: + self.current_path = song.path + song.render(self, global_context) + + self.render('index.html', self.root_folder, global_context) + + home = self.root_folder / 'home' + self.current_path = home + if not home.exists(): + home.mkdir() + self.render('home.html', home, global_context) + + playlist = self.root_folder / 'playlist' + self.current_path = playlist + if not playlist.exists(): + playlist.mkdir() + + self.render('playlist.html', playlist, global_context) + + todo = self.root_folder / 'todo' + self.current_path = todo + if not todo.exists(): + todo.mkdir() + todo_context = { + 'pending_songs': pending_songs, + } + todo_context.update(global_context) + self.render('todo.html', todo, todo_context) + + template_file = self.src_dir / 'templates' / 'karaoke.ass' + update_karaoke_songs(songs, template_file) + + static = self.root_folder / 'static' + + if not static.exists(): + static.mkdir() + + subprocess.check_call([ + 'rsync', + '-ra', + str(self.static_dir), + str(self.root_folder.absolute()), + ]) + + libreto = self.root_folder / 'static/libreto/libreto.pdf' + copy(str(self.libreto.absolute()), str(libreto.absolute())) + + +def main(): + builder = Builder( + Path(sys.argv[1]), + Path(sys.argv[2]), + ) + builder.build() diff --git a/negromate/web/commands.py b/negromate/web/commands.py new file mode 100644 index 0000000..b962667 --- /dev/null +++ b/negromate/web/commands.py @@ -0,0 +1,11 @@ +from pathlib import Path + +from .builder import Builder + + +def build(): + builder = Builder( + Path(sys.argv[1]), + Path(sys.argv[2]), + ) + builder.build() diff --git a/negromate/web/karaoke_templates.py b/negromate/web/karaoke_templates.py new file mode 100644 index 0000000..f64fb6f --- /dev/null +++ b/negromate/web/karaoke_templates.py @@ -0,0 +1,89 @@ +import os +import subprocess +import time +from contextlib import contextmanager + +import ass + +from negromate.songs.utils import needs_change + + +@contextmanager +def Xephyr_env(display=":2", *args, **kwargs): + env = os.environ.copy() + xephyr = subprocess.Popen(["Xephyr", display]) + env['DISPLAY'] = display + try: + yield env + finally: + xephyr.kill() + +def set_template(template_subtitles, orig_file, target_file=None): + if target_file is None: + target_file = orig_file + + with open(orig_file, 'r') as orig: + subtitles = ass.parse(orig) + + new_events = [] + for dialogue in template_subtitles.events: + new_events.append(dialogue) + + for dialogue in subtitles.events: + if dialogue.effect.startswith('code'): + continue + if dialogue.effect.startswith('template'): + continue + new_events.append(dialogue) + + subtitles.events = new_events + + with open(target_file, 'w', encoding='utf-8-sig') as target: + subtitles.dump_file(target) + + +def run(command, env, wait=None): + program = subprocess.Popen( + command, + env=env, + ) + if wait is not None: + time.sleep(wait) + + +def apply_template(subtitles, env): + run(["aegisub-3.2", subtitles], env=env, wait=2) + + # Si pide confirmación para cargar video ignorar el popup + run(["xdotool", "key", "Escape"], env=env, wait=0.1) + + # abrir el menú de automatización, bajar dos y darle a aplicar template + run(["xdotool", "key", "alt+u"], env=env, wait=0.1) + run(["xdotool", "key", "Down"], env=env, wait=0.1) + run(["xdotool", "key", "Down"], env=env, wait=0.1) + run(["xdotool", "key", "Return"], env=env, wait=2) + + # guardar + run(["xdotool", "key", "ctrl+s"], env=env) + + # cerrar programa + run(["xdotool", "key", "ctrl+q"], env=env) + + +def update_karaoke_songs(songs, template_file): + with open(template_file, 'r') as template: + template_subtitles = ass.parse(template) + + with Xephyr_env() as env: + for song in songs: + if song.metadata.get('karaoke'): + target = song.path / "{}.karaoke.ass".format(song.path.name) + if needs_change(target, (song.ass, template_file)): + set_template( + template_subtitles=template_subtitles, + orig_file=str(song.ass), + target_file=str(target) + ) + time.sleep(2) + apply_template(str(target), env) + time.sleep(2) diff --git a/negromate/web/static/.gitignore b/negromate/web/static/.gitignore new file mode 100644 index 0000000..d5f19d8 --- /dev/null +++ b/negromate/web/static/.gitignore @@ -0,0 +1,2 @@ +node_modules +package-lock.json diff --git a/negromate/web/static/css/CyrBit.ttf b/negromate/web/static/css/CyrBit.ttf new file mode 100644 index 0000000000000000000000000000000000000000..88b15d96fe8d83fa6eda3b0f7a7ec1832d82cba3 GIT binary patch literal 17072 zcmb_k3vgW3dH&Dt>b-ibq?K%A%u4bDgE5j;@=C@w*aia;HpDo_Aum*0w&lu_BMXda z>o|cnI3XEN<0zTTv}FiMfwT#2Ay3Cioiv?f(vYDJ5JJF9GL&SdG=m$4W^Ae7_n*h! z)x*x~%6IR%XaDoRALpFA*J4DZS`JHGZrQM5%f|N}eSJt|-7)mezy8|mHpmiFhkNwN z;+t>1vh$sXSM`gSZMfgMeQ*E1>buf6iIi*+i9NQffB(M8Nnnz7JMew^uAzfFpDI1^ zhDgP8B3FEW_dx%SbAK1hQfv*ww3wQ4wyZhELw8T6v5`SoDWPAUd zRB|6svG19^{dez^3E7Bt4>~f#{d)(#a_YKQMRE^=hwtng**{ix_NjYCR)gQfn?l)e z{$JncZhuehs$WZ09IztadgHoJ@cQg4_skcW+!OnB>?PcmON_lZFebKba*tHT%Xl06 zv|?h@AOEF2zmzWMZjK~;x4XvhtuZ^zQ7Hk|KKzM{3^vHr(HO4|5{ZeEHuKuJZzW{cx!}*iQ^{DM99iI9_xLEFpWuN<#!KX#U@@*Vx|_oPo91s#xfRPV$| z-aXH36W-}R$|uM9em{m@7CR1)$2I7MILNoh>12q?6L@g+R40zFKojHXFGYAg?x}j2 zfnFFlg^$qhary5fS9q@SuUAJa+739Pbp7}!Z_)3k_WyzOi*yLu-ZrW~^5RdYW8d%L z_`TW<-$xGQK;}W2Z!?E^7-0BIf8+Ft(_cIN=;;Svdg`TbzxbmUpL+4O7w@y00kK!al$MoOR8}Rc zYijFK^$m^brsg?w=Up`a;suvvT3Xu{E?T_g(xsPOzU+$SSGIR_X1lsqf*+ias_9rhq_hYtxE-(K~ z&uEb;lo4-!95yit-YSzK~c$#BViC7&-jQSwa5tEEz! zEL~8#vh?=Sq0;+GKUMnq(r=eOU;0|fTH>r8-kLq;{w7PW^T2k<_WwoAovIm(_2s zAF6+#{-OFW)_<@5)%xEwBpX^A)->GFa96|q4G%UPZ+N=lwZ>TE{KlTft&Mj#9&3E0 z@tcj`Z+yP-wR9{!Cw)!&j`X4QvGn8V4~OSU{vePeaN?Q zL0xG`wWS);ZQXr1V$~Bz%z=qDeVms7&K!_@fCEfc;qrhR$Ki1GnFHpeTqKuZw$%+7 zK|^1#^u?ue~`3D}j>@o~V9kDCJ=rdaZn zg&c!t%2g$`7~c%OBnKXHK(eH*`znL>#inp#G;ocN2TsQGMC}ivOeo%EW|?A5Ng5cb z2nb2clrEcY#%GX6xw9w~naTvdtj?tYu+%j)XoGXy>A1>TgIFyLN1Kzh2^!8U)5m!D zW>}I`m8Ln#AsET&BzX6Bw0cn9@xkufB~)=(C@+I zGKF@wdm>r?RO$%o?jccP3VCRWTDBG3NVV0tE{^5f^2Jlqq%OR2Ibe51O4gH4c$M z*YaNkt1e1d02B7y87PrF7GNtxx>Fh@Db-LPl#$P$JCl#VfHput86a?ar3@zf#wSko zjTgxQNXAy&K||pL#t97rIs#iFpll`TfGz<=_kuL4#A!Nj0M;^|(4_hTVv-6NhrH*` zMDUhTQypXzka0wWV(tS2=gydAv_I_wuTc9l=YTprk67sk@FH)+A{d5#fMLFYF9Q#A zLm|eCe3?E+?ACMXoz6AUgtSl|C|O$8pEU=j;QwVf^VThuo!My-Kj}~cUdbUT!6y)O zBmqk7DA0oUt3TCR+38X=Yf480TJ4~w9iKRYVUTn3Npn)=40(*1y1Bcpy9F*`vre|V z14?g5w=gCc55xr8n#En#06G#-wAN;3ndTeE3wQ{=$lQm2a5KQedGq;+HB`HeM;%wl zA2bfn6mu%|0MCHoRo`?}{GpzlQjZ}H^?$_y55O2uZAsDbCr)X60=kGl_>_Uf^lL@} zy_s%p^C85+pa@PvTYkWk#p^IzMxyi)1s)dMg9BDHuuB_7;VjM+Yfd($IDyM?I}SrD zcrg#qL(nEI0p$a$4Q`Ly`GQ8Gm90CgMndAH1JMC+XijssqQ+8fbE#?Q0T?INKo7P~ zGbWJX!3^WjdJFR<`Ov!5fKl|csIP)IWehB89;MfUSw$7_0dof;I-9l>@vWtG0JNg< z2P?rRQ)Qsh9O$5iQ1f&GW>%M7K^KSfC*mQ`tn(O8eqrctW^R@j3k$9g!&Ej~Xr4P` z^XWAGw4^waupymm0famS*b3~+Fk_GsbW{R*^joG0?*m$~bPQsUdM)9Y969X95Qv&a zK4yA@&Oq*nB}e6H4%IQFlZsNJ?Pvi{O~Xumj`Ci`;886KerIXS?ho`i z+H$Ue)^xnij-n`-^Q;>q&EY8can!ef0}AMl+v{p-kxl@=;s-;EVa`uDM{z9r8ruRj z0^Tc-1-U?vKFGRAYc)fuEhI-zrmc9!TaaE=|G}fJ(V^nPM2|iPq}C>!&%q{~CBmsu z!4!`9YK9uC^~%Ww88|IO?nS1{PsL{|H**F3Rc98I12{1+WA5^HbDT348P&EfF?iG` zz$5+Ij-+rJF@1~?;34nC6RFV*VK>;t5#Zv;Gzv3A{owQw3SsHT#qkL2%XI$83>6}f zDq;-!$Z++;O+d{7XoP7=^{V5U2{n3s?EokztRcqHWKQuEe1x+uIZ$Li@>IYHXp56s zp-?*l6H(Y1YKOuhi_VC%n{iO69m)bil-mr-gw=`9*PLuJ??Gmlmyf8gs@~oD!9_bY zMyr^?iBFipht;$ZoQS3zBCiE=TQvo;6zE}R1B6Ml5M%IqMmW8NIC*kT%zNuSWCprp zE=AKGjJ6`XL}~>s!w)$z)2Bp>^Hr;){|YH+6=#DO#l9Zc73exa}VA?z7IUw$nM9%rMW zdLRv7!GN9d#1f#YzzzO^mhNj{x5Tamm@!>GXZ#ZbuN+uhKb(wH^ATVv6~0BSum#!G z6Teo|TH&pY;$;yb_7FdQKFR$WX5#LK?lzw#w1g5jy__OY0u(!4p&%qV2?jc6Jmxn< zOp&iJzhS)3X_U*$2y}EiH9^?&AZzTWF=+#?6V;nxe+a-lfFY{Cz?AKy~wk zi`z9hA{BqBte3(P@cT?o7>I$j#TuIgb!J2cK%X|!bs#ijYc;h8zMwnsRjB*Ue$I9- zB4|D8r*NoDTtgqA#obPp@{4@Zrn58xQztx>2k3zFf-0X&2&wZB!T~#N;&c^(k<*3F})YLckzp}EuQB+Qk#K5*(#YN+rw$70_r%&7pw z8f5pSC;?PMxbyfexuEYZ!qvB}3OEV2MMAk!QP~1MJQkmP5>Kx=59N;KT=maIvea6T zzS&~4Ahg7_At^*pMxkQ04ry`2G^$Fh={cvE5;44|ETp|BwoPf<9oS2xO_s>z1==O> z3awwbvI;~gvt6K$Ikqz*xC!)a7SJN8Oxh2}0KCA-9-ZTGf7)_!rDVa0TTRpJcs97J zzxUT>^z)>3oq}yjw4dP3E{iakfJz**%t=!YTf?C?op|fBIIh`Ws#}7mQ2XTR`chd4 zzWI!9YX7CaAAV%v`xG8C_!;3lfdUZ&59hx8bRBRWrZPvbs27?sI18b?6vh9sJh45) zfxyQxGavXRM&R$py2Y}0-zrFXEhU_x|As<8a*e_Z;qNWmj|3=H?b`+5l&FwVzt74SJ7QGZrXZhb^mC~d;qoK0BF%$Tu>2Tu`#O%xC3F!XrM zLEJ93hm!$#;Pfhk(o#I<&-=l8;FTUZZOe182I|54S;;gGO{q2z4#&_WSuO>HIPFYBAH~S|i0(2KNCb);K?+ zhZJP7PYI|lOm*-i3|SE>pcLRx`D5wzwOVB5D~LY4XU?tl#JZmJq_T?d>85 zX?)QK10RdPOC$^VR5^}^H=2(y#Of>>({9i9cii{YxX~C;PgXfN86od5p0ceE!lvk# zyFOgMWBx~Xnzp}N!0UEL$d~3+?lE%r8ELc#rLa7JMPPUdPHx5M_5z6TDGMBxi@I5T z8zKBV?4i1K4fxdkf6lwk@{dtV^ zdfEtj0{xSa9a(aziHraftl~PZzzJ2%NwkeeuQQv$kt3Ne;an&iP#Bgfnv6)t>X>xw z{x4-kQe_+)j==&APp`0?<+BGqzTmU0K*#2Bt)ZIxFp^1+X24VdW2V_cYZK$u$1T^B za1-5a<}?zAE|j9h34Q#6{95_QuhvwT1-e_Xk&%N_a=1^mO$sk3`E`3vhD#%m zE@Tc)@RT$KWnp#><#QYg*!gM}C*DwRWWU$tMvSBXhTWrI zRdiSEf_ua8ep;_3O-)c2AmR09_XM==!d_52J-Vn?VYiyk7h!}@rlB%%!ZD$A zxe-n3=mK?$t2j+{YAsu*>}D0>nY77-T@$)kR=hR~*nRU*r-+Nbq-Dz1DY8W@>NWT* z_>JAWn_j2EfGPbVqa!_ebAXc6_MpnyFderqwAXJ+A9% z3Ge5>|9-Q}&!7p9_0d(RP1E<|;bV5s*w!ZG4Eh{*Y;~8IlZ^t-X?026librrm@@;| zDU6ZjIxQGVo6Fl43C%6L#I6f}0A6&o#`I!n)n17o+Qsq|n zqY+Ru)hEA$4I9ns)2vUw{a!BXleN>d`sDq&s6GJ}p1;~yp=^C(nBhU2w~@masW!eo zd5rXSHIuDRza6L@l%{E0l)rIQ+)dCeU#6G*&VE4hO)@ za9U|NPo}dWE&8QxQND)6g;8#Vh4=XBZ*G3!YZ3Rh8R<|C98S|A>JLNA*B^|Tq5h462K|dx2>JPee5M8%(t)SAP?mD>eTQB>(LTiH2-89E@*ax6inC~>x&>~1P ziq3v8w=**-ZL7gBlOc37MzRw5Hpbf8&h?DP6A*&9?q4WA@@SuqsIusLi$cqCZ1*^o zZ|$(-C-=acxH@v5 z8k2yfR5QR6wg68sV7FEPxSz8W*;IXiV-RCuN0x)=gPfS)lY)3G`YhS)G5dKBegn+> zM7_FS@#wCiovCEiSAfMbf;lRhx;>!3?Xkb?;kR6{lV2Z$+us z0FDFhjbXYfLMl}|%oJz3KkfGC3jVCWUyf?I8Cu|d94Fg6E$3DNOuwobCyw5P#R+&n zKOO2tbwj*9c5-O*r2I-HLWHv6^q*+ZkaDSc#d)g8m2!t`8$|8jx^@h@d(ySzc(cU5 zp~g5YHI=TvL@qaju8kkv8~)Iu<)uddzRFdZ7u3agI z%wyWFBoDE_(sq^7{c~+6*&n|{+cnx=uI)OsYvK#E-GFv|{G-}#RG2z#r_rv9O=!D` z{jry|Js0ho*wfm+NMXLI?TZ!WZf#$p?LFFFsPI--SFj!bA^XcM&#Jd_i~m>bPul)t z+P3@;%X)oF$q(vLSkGO`j+cQVo`?fC1F<@)^)#$;qO zVEEq47~XQ>-2kow7`YgVCPsS^Jr%6j?uyX;mpdVna=k1p5>XfLqnO( zgS&Q*?ayo;*gr6O*8m6L-IP&T2dsD}bN#{5b%VGP?Jm4RGX!=**g=h*|20}qf*}vVKb7GW%%?8VS5lX z$uw0)#f*X*Dz#q~B2m(rjs2tBcV}|TR1wQEgTsSkgZ)F9(Sf0X{`~{9Ft$bCE~1uq zs(`fB0Y#sY?Mkj6jz;!3?M)0I4BR60SZFvRW zjl%0cxZ4hx?fR{3**&;FvvXv4EOVfLe`fpWK>yglj?A6=2ZwiMHlTYwdqzex-OE>G zc8-qh&D;RfUUAdNuEFigw~y=<*#tbJphNZiA$R@ot$s+!_p1tc^1wO_=>_lpbR_x` z*C$rvvo`{9A-co*R@CfV0(X#s)Fl3?_&>$J9{&c;uf)F^{|9`3D=ff>*@4ed`hOU4 ze(L;oaLRa(fpQk~HX?r_2Te63-2*zmm_}hOU`Jv9VdVs0BQNN2ZUE1pXF7g~P6Mbo zvUUk_dl{-rg;ZkZmc%a?YcPwd!*kwx)W}9W?QO#EDCXdq?>xNyG9OQV7vR}v2ER{e z#S_qlvIuW;EkUkbDwpAz>@s-La#W6X=|HGt@!oPbJT8X}(u<68m8_E0vPQ0!YmjZ$ zAsVlh>)@@|!w+x7o5_9f!i~`1&3HfTtw;g4;{C<9A;@o&ZSr=xUEU$@ly@QbzXz46 zUtX1u%7>A;9+nT`UB-LmVoNJY{I9%$cOD1i`|?Bim7Ids z_d!z!@iyGE@*FC6iTnibiT_ki%a7$HQ)PCJRtug$K>N>cMcD>x3BAT*Q~qt>a}ydy>_*? zSM={39PDUs@67sEccIlC`d0W>M=rE_LaW!eIt%zZLSJWSb%j>I+!-);2F#rSb7#Pu z4Vbe5b2ebk2A;ElMmEsM1{&EwBO7RB1C6dgqbtzp3N*R`jjlkWE70f)G`a$fu0W$J z&{z>htOz4kgb^#kh!tT(E^w6#yyOBexxh;gWm%1e?<^vGC}5ApmzpY)99`kGb6v{$wRL{dZP2oyovsQ4gU`$gvOiz literal 0 HcmV?d00001 diff --git a/negromate/web/static/css/cc-by-sa.png b/negromate/web/static/css/cc-by-sa.png new file mode 100644 index 0000000000000000000000000000000000000000..e76aeffd876ae1ca70e124863b7acfa06831e83d GIT binary patch literal 1697 zcmV;S244AzP)Pwv1JY9U zHEK~?Rfs$&tklX>JyNOm ztV)N+hjjE@6I|Dx)p!hZ6jkASa4&SEvPsqn-DZ%3;Z+@E0NkY@`;6dbQ*41bCCAnZ z&;aVp!x_5s$sM}ZbM4YmKp)0tewyLAmBR{e3M@KP$gnl_2pamIR08^?eY?b~wKlSzX+2$S0_5beYdqE+v=By5K zT&Ii8NQgGJHISQG@!aD%8XOwb^^cB@(!|6B3$8^!=3uT<5IU(}2N*mFTDSnW#FjYr z>6ih$-rimsA0MZwsVPb(lPtJKAI9XlxHpqaQ@N&r3`+)GXq>!5Td}Z_DlDux@N|)S zdU`Z{V`Fr3azf^YK8#@w<~jkP)B1IQ;n2XBpaod28C-w|AkWUus96gH0tTS5>i`)W zhK<7-aD1^;ly-KvHL9?%V(|loWnly5CV6SY+G0(+09ffiJw2s-F2{mvH~MveaeU#F zz_~cuGPolnBbGbcs9_Uuk8H`%2~Nfu7gQlx@zxpzH&+cb0p1gq_5Ap_CBSIH((G`i zmHwwsp3pmQ_ZuV{iL|BP0C1YAA<=gskb;M<3IdpMOE$fBT&dvVV5gv3>)6!wC^woT!IwGEJBPh9@^Si)_iz zaF1Ppg?<1$FfhPi4h{|)_*hu+zb{`p(r*A58Jc>eax5#XSEdF;3*aB@9z+J;JT_ZD zPNE4bhHh{%GQLYR5eaG0gv7(I6JWG(I84LC!~B1&0Df`uqJ4nj+;D_N5+NTwENB() z0?c4AXgMa|FOD>HBjW=VW$PhZEEVHu0z53jwf}-5(BRDAsa0T0Q|-12OSI@t`HZau{V7;C90_(EzGB zO#ABIJ?3avVcP!@V5f^M2G^O}>Z@>+JBoD70ojKO9?KlIAUOuNONPU^oDrim08p_TcVHwx1LvgkLD zp~0f%Fs&ekY0+fkFs-Y~l_JrQ(`0iz>t&*`Ur#hpx)g~OY6x_1~>r~lE9l+~U zxvKz{i#>~fFL+<fKA6*N0Uvn5$ZKL3hG0c$*?l(WY$<%;28yonBKE5}0{P19slL3G%TXH*( zi~w%ATB7+s=iRD8&a;MJ*0k;gE{OJHA@ r1-Ih(jstupE`*5Qx&oqeZ&$to@Ym>elSGv`00000NkvXXu0mjf@eCw0 literal 0 HcmV?d00001 diff --git a/negromate/web/static/css/main.css b/negromate/web/static/css/main.css new file mode 100644 index 0000000..602f873 --- /dev/null +++ b/negromate/web/static/css/main.css @@ -0,0 +1,118 @@ +body { + display: flex; + flex-wrap: wrap; + background-color: #232323; + color: #aaa; + font-family: "CyrBit"; + font-size: 20pt; +} + +a { + color: #aaa; + text-decoration: none; +} + +header#header { + width:100%; + display: inline-block; +} + +footer { + font-size: smaller; + width: 100%; +} + +table { + width: 90%; + border: 1px solid white; + border-collapse: collapse; + margin: 0 auto; +} + +table td, table th { + border: 1px solid white; +} + +#menu { + display: inline-block; + flex: 1 10em; +} + +#menu ul { + list-style-type: none; + padding: 0; + border: 1px solid gray; + border-radius: 0.5em; +} + +#menu ul li { + border-bottom: 1px solid gray; + padding: 0.5em 1em; +} + +#libreto, #playlist, #onion, #todo { + border: 1px solid #aaa; + border-radius: 0.5em; + text-align: center; +} + +#libreto img { + width: 200px; + margin-left: auto; + margin-right: auto; + display: block; +} + +#content { + display: inline-block; + margin-left: 1em; + flex: 10; +} + +.songs { + display: flex; + flex-wrap: wrap; +} + +.songs figure { + flex: 0; + border: 1px solid gray; + text-align: center; + padding: 0.5em; + border-radius: 0.5em; +} + +.songs figure figcaption { + font-weight: bold; +} + +video { + width: 100%; +} + +.lyrics { + line-height: 1.2em; +} + +#song-playlist #video-playlist { + width: 100%; +} + +.vjs-mouse.vjs-playlist { + font-size: 15pt; +} + +.vjs-mouse.vjs-playlist .vjs-playlist-item-list { + display: flex; + flex-wrap: wrap; +} + +.vjs-playlist .vjs-playlist-item { + flex: 0 200px; + +} + +.video-js .vjs-big-play-button { + top: 50%; + left: 50%; +} diff --git a/negromate/web/static/css/nm_icon.png b/negromate/web/static/css/nm_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..6a8849ed988fdc90ac8ff56ed6356e57273c0a8d GIT binary patch literal 5649 zcmXw72RzjO|3`ieGA^UzY*``FkQ}l_Wn_MpnOR08 zvLZ^U-0$u2fBYZk?jHAfJbXUy_v`(9J;y8A+{}=TnV*@4hK9}9NY4^{XP&&F4B&Ik zV7V21F%T{p>d{b7US+Q;a=;a)KqI>l8XCCz$(uH#+lCfgWDGSn)n{B`f^dq-5rZS# z!6m*>eSD~H!1e1M{-HFw!5*%m9`2}c@6c-~Lt|5OTOvD>hK487Snr}$#N4)HB+hF3 zLyV^`qA;tMUO?aOG3#x=^Z^c}l$FJ$F-()q^{T$cxq`kYWd8Uj`92lp%I367)>747 zDo=K-u`KniWh5K(W>-UlSub9ff)^dyBl69W5OZ0)=p)IE^}utjY~HIKl%1<18x^^7D~>X{Q-&ZEaHp zwfJjlYIqerSsff5KYjiT@$&K-a921uIOudaS5{HMC?FuPzOkVb9VQGCG3hrZs=IUGA+1^g?8NJ-sFg14m{j(ba;J>5B!8fd#qdA+eH-=xQ6m%bpr#>X=-YoJhg7-_?c5| ztTrpdDJ6ck@B8~fU&qD36Aum#Ss?Y|?h1U}-QBx$zO}*_48z0|(|A1*q7iy|i|VIR zG&VnMG%2ear}l>&X_obk41hRf3z@>1^DrpTYI(vcVxC zK|3GSH6wQ8Y)#a@K|imrlX9hPm(x@i;%aN<4AS_O{SK0wn^m|G2oWtUf$*J=FsQpR zsEUm9>oZk0)jC)#jl06^^IMbV+==Pw?4Q4USzhXjAHAkTN5s$aJ+kcS>m&R-`ca@B z^5wZkP?AWtO;v9q3o3=#VX%FNsiPEtN#LG$D!MPZ%|e9FqoYSBkZF~3)l zysQjFZ0JF8%R&^3?-Zr$uH+Sz%P4DRQ4#rD2UU~B-_!^F|D@an16P5HmpIw_~ZQimF;Mc?S)sT$w)awjZAil99P%; zya2$>`nPX}c6NL?%*23*xw|_$?At<`U4v&(w{x$dn!38Mh6X>lzrMb{$~1Y)pzKA+ z+HzIxYf!nkPP)9zL3e<=lXV3L2m3{F&3b&0vu}jn{JBMJX=!n$(hB)soNh~+};+* z7f1Bo&C4r)^{T{ZczPP?zbIzfwx;%Ot`M}rTzLb?d&}i5fQNj;6+MFAt-rXy?RF=ojXhS^IDh_k^{L89pRJj?c*W0=7t5q=YdA|Uyng*UwVzT` zgAw7Nk#T6{Oixcw?IUMo^w&7HQ;xcuG>CMkPJzSu@7GKVLQp#ai&cKLC(s|j1xE?wwr^6V{o0|-|^e_zMXz558K-A;r%~#C#Hrsj9u%Q ztg=o1VbC11wzL#?Qoi}N8#X~4c4^q*;o)Cf4I`W|SeJT-jkB}RaLIW?8PyvbR(&1% z6%(HT1Vpl#SXkmMD;o#wZ|!z5;#&iSwV`MPxz2xH1C7B1k4w%iETjWea1BO8Mgk;e z>=p3v@bp}C1%2I65D*9s;n%N~3>Yu(Ks4REB2^CG>6*m&_*3HBV!64wJs9fhP=15` z+msY$Kv|rF5JtwUN}i$Va=9+bNu60m2_o}H=pU=jDzl53!zv+$htBNZ2)DeuTP zc?@M^Yx?yqBQ34B?Z#%SF)GU_q2zqHh=c^xA#u=MCoD|m;r!5nM$FNHBq$^f4M!rq zcpC12$J^98rIAR`9hk(03xZ5cOvOJbs>;d_UcM|g!bnJvau;iwn-Ls>ny3qslp85G zqoN34KM1DMx*3xUf%6EVm|w!8UJ|}=5zt#}`pv@~*za;D8O+4Ik3u0Seo0GHlM{jPoQw<%4D7t8?7Q^sTRFZw5e85MWS|Lck_7X#0zmR)p=jCW@KH6eQc^ zF}@>4Yt4a&n$*{4KyXBZwp;1X@Y4J;QE}PA%1ZC0@b$eEo@70I<29J)$o=cubcuE}e^F?%Yw1l*@=xZCl?ekVulce~NU7|n<>lLl3pYo8LhPG-c-Bg{iP zQu75OH#0p#2H#mUQ2_+=aA#h0APW{Nyw17M(@;q896!eVG_RCuh3D~1D0nq%t zzjpP+y_snVD7{hh z97wUSSY&~2watVIXmFrednS>HPS)e&2@50Cy3qmf>jt#kB^8N@HdZpWw1%}dfO`6MhYEv=4N9gHqKJRDbgVLlj=ZG?WQ zAjs^(SZS34nB6`ddm_p0?d|6pL?MK_f;_SNDn!7MkbhnYt{+>2@m=xoRq;wGhdAZszOl=ZD_8ys^64s}{H5r=t6CtgOAg$Y^+EWQ0KL zt}Ck|34}SZtgI{_LqCcc1-8kr?^dpf{u$=I%Rq($I{qOT+0US|KeUI-$@cCoj?T^| zn--~zh3U|B_9VlDc9$;N*9vGnZ%h%+8RX>T?7WZVO73|A0RZ(}4cOe;($m#FmGu@# z?FlbNd<0%;8KRSGl2}l{JDfy6tx^ z>tGT5nu|-E8eB&PA*!O1w^xAcwk;_xj({N)@1EDi9g5;|HvQOMIb{sx%fSaFa!qW= zCxo!l$0kzfJ@I5#`MB_Gk_rD~eH8GI3l6Tbva%8q5~%FGy*<~}CzTWmdia--vGFJU zo6=+lSB1hdmTW&&;i@_0e!X zzCm)Z8cotiJfV%nEh8)ihiIs;&o=S|v_nZzpPZWFT8ou+Y`O-(wUYHVhfl#>Hrkq-$DCaqyms5sTyxd%R{$3!xnYS;8KzUO!OsVGVr0x%w)S>Do(8K*E1-bD+@BPRKFBh43gXsh<3ky?x9S)eBY@O8H> zc*t3-s;a8M0r!=_jYp@a@5puh{r}cfVIL6%3Q6T7ED$Q{>Fbw78 z-NBG@31;9uyWggx=#P$mZ03oMvS^Xs+eyZiMt~AMtE!T{RJOI{cQH#)7@W|PNe>I$ z(b(Lay=#~u4Im@$7quklqlvGiKc>(nArLmU|2x*RFa_pnuE`f)@6NO-!&Zl9eQY^6 zQ=x0Yy|KAzVQXuMMgnJ`MmGi)(b~$(5KlBZtD!MR$TbCeGnoS$8XEHMSBKr{oqu%` z306nBX)l>;az;Hkq0Z7@iNDTkMDUD8D9Okluy$$=l#Suk!mWMN^4F(L9&?GC6+g#A z@8D&c+eDSMwS}TyEoeZZfEO?^F~P%)q;l&w^q+zC=KSs<$XCVv?4TYOskx&iC7G^N zn0fH1_+APP3*%aylxN1h2;1fl+Vt~%$punL7V8I^qqa5;B~?}UV8Wd{`$?LeE=~f* z2@p}b)z#IpdKezw)YR02c53$HtLl9jw8Ai!E6tUBF60YtA=3+}dhGFU@vNZ~7%@~s zpuWC-%hT$SM2dw^v*4V{L6MAuB7EZTH-TwyKu` zNI-=TFn0-(o;$AVZPCF&=yzM;qKgybUO5NMHg^GNqmozjqNFl?3=kbM-e#td8XN%Q> zZfD7C{>?6pIZAFVK6ARUxtYt^d0}CJBK4rTr3G&7OdkgvEv{G%(93^ALvQBW!?$(I z#>Xw)Jw4~PxTAh<@c~FByA#~p>}F$AQc_0e=1gua?+H_@s;k+&y}eWSkMUHUhS^l0 z9WdzvoP~o!Du`+#g`J()zAv$WWp6DHt_B198INomnQid0du(IpP6loM>EP>x&E;5? zLR`<+AwnH*gV%`XW1-AER(59QWqq%Qp!JG1BeN&BUF#HozOTHJ`ptsNBd<{)0;IjW zCSuYhZ{mvc)%i75f>WZ2WHDi-a(yYbdM8*3w_aJeTYj|tXnKgJ#!_RLDK zAkThoJO+^WUwE0k7)ver(IRssy$`bO@!!ZQ9zts@^}-%uxL7?WNG5&k8hR==t}86d z;VfzaMD>8zzxza_?)0_{zK;HL;?u~~YZ$U*mJyzBKkDYqWZ$z=+{_RNBrs1Ckd9jL zXJ{22hmDvyh&MmKEd~T>+g-lQapLRID?n18#YIF%YXSU|+$}9F)f}nkKv=0TE2*D3 zqy$?m0^lUw;{kzzfq^jo$T+p%JsX=@P%vOeoqltNqb`;jL-w4)Ct|tvPZB2B zZ3}+D@Wu`0y^xTv4;Fzn$$+1TFh zJ#kv@U|NFyt)$8=> z(^gg2XlJ4H+?h~eD2x<3$D3W}+jQV#?yI445(7pTXL`7Z5npxFvsp~o@ngT^H z_Mcm`Z%itAutFe{dyU-J_wkY1<`%$Yg1JS-+%hAuwGZp+U=5z{mQ4#|FXXIkOjgY_ z`67dm-os$wm!3U%KnsJxig$Sa^D4k$+&w&8`_lzfk`Yak#JGzi|A6!4JZZFnmblp1 zYNysfTIXAP^r0FhrhSd-L?;I?knZ)2jG&rYT8X(WqrRH}wnnC=O%bL6!!RhX%o5(g zfz{dB8Fx=9d4Hb#A{F!1wsv}DxtILwVB&Ie^=e+yJJ#gT2Ub#b-V+$Km>An^a1^?{ zzMc!rWBNezsgGSu4uQ}y%yR-$JM-N2)Zc&qA}0k0?bpA4?E>S8UEs6lUMVoIF&)r> z+|vK$T~Ss+0aR7B1r}M&mu7G`KYs<7H?`Pf%{6{%&^@eNnPuhk$bHYJlN&I%E|sEp zPit%Y3l+Tr57sS;=E9N$h;dy6Q(%4~4(G#R2!x8CGYHQYt0tGhqSa#lss-sQ5wW_R zU0t+bMZg$cymoEfr!n;Q_JYaPn>PI^lJF=s z(Ml?@qCy;?@6*l>JD4=KwzcUzFz;GvlzR|DSAPQJFMEEFFZ7i4%&(cAEc^ Zd%%!wSa-ht1DMp(80(wq)#$j~{vTJ1cB}vZ literal 0 HcmV?d00001 diff --git a/negromate/web/static/js/libjass/.gitignore b/negromate/web/static/js/libjass/.gitignore new file mode 100644 index 0000000..cdfdf26 --- /dev/null +++ b/negromate/web/static/js/libjass/.gitignore @@ -0,0 +1,14 @@ +/build/doc.js +/build/typescript/typescript.d.ts +/build/typescript/*.js + +/dist/ + +/lib/ +!/lib/libjass.css + +/node_modules/ + +/npm-debug.log + +/src/version.ts diff --git a/negromate/web/static/js/libjass/.travis.yml b/negromate/web/static/js/libjass/.travis.yml new file mode 100644 index 0000000..33eb227 --- /dev/null +++ b/negromate/web/static/js/libjass/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "6" + - "7" +before_script: + - "node ./build.js doc" +sudo: false diff --git a/negromate/web/static/js/libjass/CHANGELOG.md b/negromate/web/static/js/libjass/CHANGELOG.md new file mode 100644 index 0000000..1fef252 --- /dev/null +++ b/negromate/web/static/js/libjass/CHANGELOG.md @@ -0,0 +1,133 @@ +### v0.11.0 - 2016/01/24 +- BREAKING CHANGE - WebRenderer.resize(width, height) used to have a broken implementation of letterboxing to move the subs div right or down. Now it's WebRenderer.resize(width, height, left, top) and expects the caller to calculate letterboxing itself and supply left and top accordingly. DefaultRenderer does it using the video resolution and users of WebRenderer can do the same. +- BREAKING CHANGE - DefaultRenderer.resize() now ignores its parameters and always resizes to its video element's dimensions. It had already stopped resizing the video element when it was renamed from resizeVideo in v0.6.0, so it doesn't make sense to let it take a completely different width and height. +- BREAKING CHANGE - Removed fullscreen support in DefaultRenderer. It started out as a hack using max z-index and works on even fewer browsers now. It probably didn't work for you anyway so it should be no big loss. +- Implemented experimental support for \t +- Added RendererSettings.fallbackFonts to set the fallback fonts for all styles. Defaults to 'Arial, Helvetica, sans-serif, "Segoe UI Symbol"'. +- Better compatibility with loose ASS scripts - assume unnamed first section is Script Info, fall back to Default style for missing styles, recognize arbitrary-case property names, normalize asterisks in style names, etc. +- Various font size improvements - faster calculation, fix for incorrect size when line-height is overridden by site CSS, fix for incorrect scaled sizes for letterboxed subs, fix for incorrect metrics for web fonts, etc. The last one requires that all web fonts be specified in RendererSettings.fontMap to be rendered accurately. +- WebRenderer now supports using local() URLs in addition to url() in CSS font-face rules. +- Added RendererSettings.useAttachedFonts. If true, TTF fonts attached to the script will be used in addition to fonts specified in RendererSettings.fontMap. This setting is false by default, and should only be enabled on trusted fonts since it uses a very naive base64 and TTF parser to extract the font names from the attachment. It also requires ES6 typed arrays - ArrayBuffer, DataView, Uint8Array, etc. in the environment. +- Various pre-render, SVG filter and DOM perf improvements. +- Fixed \fscx and \fscy to not scale shadows. +- Fixed \fscx and \fscy to have optional values. +- Fixed \fs+ and \fs- to have required values. +- Fixed \r to use the target style's alpha values instead of 1. +- Fixed \fad subs to not flash after the fade-out ends with low-resolution clocks. +- Fixed outlines to not be darker than they should be. +- Fixed styles to not ignore the ScaleX and ScaleY properties in the script. +- Fixed lack of sufficient space between normal and italic text. +- Fixed SVG filters to interpolate in sRGB space instead of RGB. +- Fixed ASS parser to complain if a script doesn't have a Script Info section at all. +- The promise returned from ASS.from*() is now properly rejected due to errors from loading the script, instead of just remaining unresolved forever. +- Fixed SRT parser to swallow UTF-8 BOM just like the ASS parser. +- Fixed all clocks to suppress redundant ticks if the current timestamp hasn't change from the last tick. +- Fixed {AutoClock, VideoClock}.{setEnabled, toggle} methods to actually enable / disable the high-resolution timer. + + +### v0.10.0 - 2015/05/05 +- Implemented libjass.renderers.AutoClock, a clock that automatically ticks and generates clock events according to the state of an external driver. +- Implemented \k +- libjass.{Set, Map, Promise} can now be set to null to force the use of the polyfills, even if it defaulted to a runtime-provided implementation. +- Added ASS.fromReadableStream(), a function that can be used to parse ASS from a readable stream such as the response of window.fetch(). +- ASS.fromUrl() now tries to use window.fetch() if available instead of XMLHttpRequest. +- Fixed constant pausing and playing on Firefox triggered by how slowly it updates video.currentTime (wasn't noticeable but still undesirable). +- Fixed a dialogue's animation state not getting updated while seeking if the start and end times of the seek were within its start and end times. +- Fixed wrapping mode 1 (end-of-line wrapping) to actually wrap. +- Fixed parser to parse the time components of karaoke tags as centiseconds instead of seconds. +- Fixed parser to swallow leading BOM, if any. +- Fixed errors reported by webworker API were empty objects without message and stack properties. + + +### v0.9.0 - 2014/11/27 +- BREAKING CHANGE - ASS.fromString() now returns a Promise of an ASS object, not an ASS object directly. The synchronous ASS parser used by ASS.fromString() is no more. +- BACKWARD-COMPATIBLE CHANGE - WebRenderer constructor parameters order has changed from (ass, clock, settings, libjassSubsWrapper) to (ass, clock, libjassSubsWrapper, settings). The constructor will detect the old order and reorder accordingly. +- Added ASS.fromStream and ASS.fromXhr that read a stream and an XMLHttpRequest object's response respectively and return (a Promise of) an ASS object. Both of these parse the script asynchronously. +- Added RendererSettings.enableSvg that can be used to toggle the use of SVG filter effects for outlines and blur. +- libjass.js now has an AMD wrapper so that it can be used with RequireJS, etc. +- Settings parameter is now optional for WebRenderer and DefaultRenderer. +- Added support for clock rates apart from 1 to clocks and renderers. +- Added a parameter to libjass.createWorker to specify the path to libjass.js that will run in the worker. +- Fixed Style and Dialogue constructors not setting defaults for missing properties. +- Fixed color and alpha parser to support more formats. +- Fixed SRT parser to replace all HTML tags it finds, instead of just the first one. +- Fixed font size calculation to use the vertical scale instead of horizontal. +- Fixed line-height on newlines. +- Fixed missing perspective on X and Y rotations. + + +### v0.8.0 - 2014/08/16 +- Added web worker support. libjass.parse can now be offloaded to a web worker. +- Implemented \fs+ and \fs- +- Added ASS.addEvent() to add dialogue lines to an ASS object. +- Renamed ClockEvent.TimeUpdate to ClockEvent.Tick, and added ClockEvent.Stop +- Clock.enable() and .disable() now return a boolean to indicate whether the function had any effect. +- Added Clock.setEnabled() to force the enabled-state to the given value. +- Renamed ManualClock.timeUpdate() to ManualClock.tick() +- Moved WebRenderer.enable(), .disable() and .enabled to NullRenderer +- Fixed not being able to parse tags with default values. +- Fixed font preloader downloading the same font multiple times because it didn't filter for duplicates. +- Fixed min-width value not taking separate left and right margins into account. +- Fixed absolutely positioned subs were always left-aligned even if they had an alignment tag. +- Fixed blur and outlines getting truncated. + + +### v0.7.0 - 2014/05/15 +- Implemented \be +- Split a new renderer, WebRenderer, off DefaultRenderer that doesn't rely on a video element. +- All renderers now require a Clock to generate time events. VideoClock is a Clock backed by a video element, while ManualClock is a clock that can be used to generate arbitrary time events. + + +### v0.6.0 - 2014/03/24 +- All script properties and style properties are now parsed and stored in the ASS and Style objects. +- Basic SRT support, by passing in a libjass.Format argument to ASS.fromString() +- \clip and \iclip now have their drawing instructions parsed as an array of libjass.parts.drawing.Instruction's instead of just a string. +- Added DefaultRenderer.enable(), DefaultRenderer.disable() and DefaultRenderer.toggle() to change whether the renderer is displaying subtitles or not. +- DefaultRenderer.resizeVideo is now called DefaultRenderer.resize. Now it only resizes the subtitle wrapper div, not the video element. +- Replaced the 41ms setInterval-bsed timer with a requestAnimationFrame-based timer to reduce load on minimized or hidden browser tabs. +- DefaultRenderer now renders dialogues in the correct order according to the script. +- Fixed incorrect font sizes. +- Replaced jake with gulp. + + +### v0.5.0 - 2014/01/26 +- Removed preLoadFonts renderer setting. It was redundant with the actual fontMap setting since the presence or absence of that setting is enough to signal whether the user wants to preload fonts or not. +- Multiple renderers can now be used on the same page without conflicting with each other. +- Implemented \shad, \xshad, \yshad +- Fixed ASS draw scale being used incorrectly. +- ASS.resolutionX and ASS.resolutionY are now properties of ASS.properties, a ScriptProperties object. + + +### v0.4.0 - 2013/12/27 +- All parts moved from the libjass.tags namespace to the libjass.parts namespace. +- Replaced PEG.js parser with a hand-written one. This allows for parsing lines that are strictly invalid grammar but are parsed successfully by VSFilter or libass. +- All ASS tags are now supported by the parser. +- Removed the useHighResolutionTimer setting for DefaultRenderer. DefaultRenderer always uses the 41ms timer now. +- Implemented \move +- Implemented ASS draw +- Fixed subs overflowing the video dimensions still being visible. +- SVG filters are now used for outlines and blur. +- Delay parsing of dialogue lines till they need to be pre-rendered. As a side-effect, all fonts in the font map are preloaded now, not just the ones used in the current script. + + +### v0.3.0 - 2013/10/28 +- Moved libjass.DefaultRenderer to libjass.renderers.DefaultRenderer +- Added libjass.renderers.NullRenderer, a renderer that doesn't render anything. +- DefaultRenderer's fontMap setting is now a Map instead of an Object. It now supports more than one URL for each font name. +- DefaultRenderer now generates the subtitle wrapper div itself. +- DefaultRenderer now takes video letterboxing into account when resizing the subtitles. +- DefaultRenderer has a new setting useHighResolutionTimer that makes it use a 41ms timer instead of video.timeUpdate's 250ms timer. +- div IDs and CSS class names are now prefixed with "libjass-" to avoid collisions with other elements on the page. +- All numeric CSS property values are now truncated to three decimal places. +- Added ```jake watch``` that rebuilds and runs tests on changes to the source. +- Added ```jake doc``` that builds API documentation. +- Added Travis CI build. + + +### v0.2.0 - 2013/09/11 +- Added libjass.DefaultRenderer, a class that handles initializing the layer div's, preloading fonts, and drawing Dialogues based on the current video time. +- libjass.js can now be loaded in node. Only the parser can be used. +- Tests can now be run with ```jake test``` or ```npm test``` using Mocha. + +### v0.1.0 - 2013/08/29 +- First npm release. diff --git a/negromate/web/static/js/libjass/LICENSE b/negromate/web/static/js/libjass/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/negromate/web/static/js/libjass/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/negromate/web/static/js/libjass/README.md b/negromate/web/static/js/libjass/README.md new file mode 100644 index 0000000..385b82b --- /dev/null +++ b/negromate/web/static/js/libjass/README.md @@ -0,0 +1,171 @@ +[![Build Status](https://travis-ci.org/Arnavion/libjass.png?branch=master)](https://travis-ci.org/Arnavion/libjass) + +libjass is a JavaScript library written in TypeScript to render ASS subs in the browser. [Check out the demo.](http://arnavion.github.io/libjass/demo/index.xhtml) + + +### What's special about libjass? + +* libjass requires no tweaks to the ASS file from the original video. + +* libjass uses the browser's native CSS engine by converting the components of each line in the ASS script into a series of styled <div> and <span> elements. This allows all the layout and rendering to be handled by the browser instead of requiring complex and costly drawing and animation code. For example, libjass uses CSS3 animations to simulate tags such as \fad. While a canvas-drawing library would have to re-draw such a subtitle on the canvas for every frame of the video, libjass only renders it once and lets the browser render the fade effect. + +As a result, libjass is able to render subtitles with very low CPU usage. The downside to libjass's aproach is that it is hard (and potentially impossible) to map all effects possible in ASS (using \t, ASS draw) etc. into DOM elements. As of now, the subset of tags supported by libjass has no such problems. + + +### I want to use libjass for my website. What do I need to do? + +You can install the latest release of libjass + +* using npm with `npm install libjass` and load with `var libjass = require("libjass");` +* using bower with `bower install https://github.com/Arnavion/libjass/releases/download//libjass.zip` +* using jspm with `jspm install github:Arnavion/libjass` and load with `import libjass from "Arnavion/libjass";` + +Inside the package, you will find libjass.js and libjass.css, which you need to load on your website with your video. + +Alternatively, you can build libjass from source by cloning this repository and running `npm install`. This will install the dependencies and run the build. libjass.js and libjass.css will be found in the lib/ directory. + +Only libjass.js and libjass.css are needed to use libjass on your website. The other files are only used during the build process and you don't need to deploy them to your website. + + +### What are all these files? + +* The src/ directory contains the source of libjass. They are TypeScript files and get compiled into JavaScript for the browser using the TypeScript compiler. + +* build.js is the build script. The build command will use this script to build libjass.js. The build/ directory contains other files used for the build. + +* The tests/ directory contains unit and functional tests. + +* The lib/ directory contains libjass.js and libjass.css. You will need to deploy these to your website. + + +### How do I use libjass? + +The API documentation is linked in the Links section below. Here's an overview: + +* The [ASS.fromUrl()](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromUrl) function takes in a URL to an ASS script and returns a promise that resolves to an [ASS](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS) object. This ASS object represents the script properties, the line styles and dialogue lines in it. Alternatively, you can use [ASS.fromString()](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromString) to convert a string of the script contents into an ASS object. + +* Next, you initialize a renderer to render the subtitles. libjass ships with an easy-to-use renderer, the [DefaultRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer). It uses information from the ASS object to build up a series of div elements around the video tag. There is a wrapper (.libjass-subs) containing div's corresponding to the layers in the ASS script, and each layer has div's corresponding to the 9 alignment directions. libjass.css contains styles for these div's to render them at the correct location. + +* The renderer uses [window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame) as a source of timer ticks. In each tick, it determines the set of dialogues to be shown at the current video time, renders each of them as a div, and appendChild's the div into the appropriate layer+alignment div. + +* The renderer can be told to dynamically change the size of the subtitles based on user input by calling [WebRenderer.resize()](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.WebRenderer.resize) + +* Lastly, the renderer contains an implementation of preloading fonts before playing the video. It uses a map of font names to URLs - this map can be conveniently created from a CSS file containing @font-face rules using [RendererSettings.makeFontMapFromStyleElement()](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.RendererSettings.makeFontMapFromStyleElement) + +* For an example of using libjass, check out [the demo.](http://arnavion.github.io/libjass/demo/index.xhtml) It has comments explaining basic usage and pointers to some advanced usage. + + +### What browser and JavaScript features does libjass need? + +* libjass uses some ES5 features like getters and setters (via Object.defineProperty), and assumptions like the behavior of parseInt with leading zeros. It cannot be used with an ES3 environment. + +* libjass will use ES6 Set, Map and Promise if they're available on the global object. If they're not present, it will use its own minimal internal implementations. If you have implementations of these that you would like libjass to use but don't want to register them on the global object, you can provide them to libjass specifically by setting the [libjass.Set](http://arnavion.github.io/libjass/api.xhtml#libjass.Set), [libjass.Map](http://arnavion.github.io/libjass/api.xhtml#libjass.Map) and [libjass.Promise](http://arnavion.github.io/libjass/api.xhtml#libjass.Promise) properties. + +* [AutoClock](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.AutoClock) and [VideoClock](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.VideoClock) use [window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) to generate clock ticks. + +* [WebRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.WebRenderer) and [DefaultRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer) use [SVG filter effects for HTML](http://caniuse.com/#feat=svg-html) to render outlines and blur. This feature is not available on all browsers, so you can tell them to fall back to more widely available CSS methods by setting the [RendererSettings.enableSvg](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.RendererSettings.enableSvg) property to false. + +* WebRenderer and DefaultRenderer use [CSS3 animations](http://caniuse.com/#feat=css-animation) for effects like \mov and \fad. + +* Using fonts attached to the script requires [ES6 typed arrays](http://caniuse.com/#feat=typedarrays) (ArrayBuffer, DataView, Uint8Array, etc). + + +### Can I use libjass in node? + +libjass's parser works in node. Entire scripts can be parsed via [ASS.fromString()](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromString) + +```javascript +> var libjass = require("libjass") +undefined +> var ass; libjass.ASS.fromString(fs.readFileSync("mysubs.ass", "utf8")).then(function (result) { ass = result; }) +{} +> ass.properties.resolutionX +1280 +> ass.dialogues.length +9 +> ass.dialogues[0].toString() +'#0 [646.460-652.130] {\\fad(200,0)}Sapien rhoncus, suscipit posuere in nunc pellentesque' +> var parts = ass.dialogues[0].parts +undefined +> parts.length +2 +> parts[0] instanceof libjass.parts.Fade +true +> parts[0].toString() +'Fade { start: 0.2, end: 0 }' +``` + +[libjass.parser.parse](http://arnavion.github.io/libjass/api.xhtml#libjass.parser.parse) parses the first parameter using the second parameter as the rule name. For example, the [dialogueParts](http://arnavion.github.io/libjass/api.xhtml#./parser/parse.ParserRun.parse_dialogueParts) rule can be used to get an array of [libjass.parts](http://arnavion.github.io/libjass/api.xhtml#libjass.parts) objects that represent the parts of an ASS dialogue line. + +```javascript +> var parts = libjass.parser.parse("{\\an8}Are {\\i1}you{\\i0} the one who stole the clock?!", "dialogueParts") +undefined +> parts.join(" ") +'Alignment { value: 8 } Text { value: Are } Italic { value: true } Text { value: you } Italic { value: false } Text { value: the one who stole the clock?! }' +> parts.length +6 +> parts[0].toString() +'Alignment { value: 8 }' +> parts[0] instanceof libjass.parts.Alignment +true +> parts[0].value +8 +``` + +The rule names are derived from the methods on the [ParserRun class](http://arnavion.github.io/libjass/api.xhtml#./parser/parse.ParserRun). + +See the tests, particularly the ones in tests/unit/miscellaneous.js, for examples. + + +### Can I contribute? + +Yes! Feature requests, suggestions, bug reports and pull requests are welcome! I'm especially looking for details and edge-cases of the ASS syntax that libjass doesn't support. + +You can also join the IRC channel in the links section below and ask any questions. + + +### Supported features + +* Styles: Italic, Bold, Underline, StrikeOut, FontName, FontSize, ScaleX, ScaleY, Spacing, PrimaryColor, OutlineColor, BackColor, Outline, Shadow, Alignment, MarginL, MarginR, MarginV +* Tags: \i, \b, \u, \s, \bord, \xbord, \ybord, \shad, \xshad, \yshad, \be, \blur, \fn, \fs, \fscx, \fscy, \fsp, \frx, \fry, \frz, \fr, \fax, \fay, \c, \1c, \3c, \4c, \alpha, \1a, \3a, \4a, \an, \a, \k, \q, \r, \pos, \move, \fad, \fade, \t (experimental), \p +* Custom fonts, using CSS web fonts. + + +### Known issues + +* Unsupported tags: \fe, \2c, \2a, \K, \kf, \ko, \org, \clip, \iclip +* \an4, \an5, \an6 aren't positioned correctly. +* Smart line wrapping is not supported. Such lines are rendered as [wrapping style 1 (end-of-line wrapping).](http://docs.aegisub.org/3.0/ASS_Tags/#wrapstyle) +* Lines with multiple rotations aren't rotated the same as VSFilter or libass. See [#14](https://github.com/Arnavion/libjass/issues/14) +- Desktop renderers include borders when calculating space between adjacent lines. libjass doesn't. + + +### Links + +* [GitHub](https://github.com/Arnavion/libjass/) +* IRC channel - #libjass on irc.rizon.net +* [API documentation](http://arnavion.github.io/libjass/api.xhtml) +* [Aegisub's documentation on ASS](http://docs.aegisub.org/3.0/ASS_Tags/) + + +### License + +``` +libjass + +https://github.com/Arnavion/libjass + +Copyright 2013 Arnav Singh + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` diff --git a/negromate/web/static/js/libjass/build.js b/negromate/web/static/js/libjass/build.js new file mode 100644 index 0000000..2ec355c --- /dev/null +++ b/negromate/web/static/js/libjass/build.js @@ -0,0 +1,281 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var fs = require("fs"); +var path = require("path"); +var stream = require("stream"); + +var async = require("async"); + +var task = require("async-build"); + +(function () { + var _TypeScript = null; + var _UglifyJS = null; + var _npm = null; + + Object.defineProperties(global, { + TypeScript: { get: function () { return _TypeScript || (_TypeScript = require("./build/typescript/index.js")); } }, + UglifyJS: { get: function () { return _UglifyJS || (_UglifyJS = require("./build/uglify.js")); } }, + npm: { get: function () { return _npm || (_npm = require("npm")); } }, + }); +})(); + +task("build-tools", function (callback) { + async.every(["./build/typescript/typescript.d.ts", "./build/typescript/index.js", "./build/doc.js"], fs.exists.bind(fs), function (allExist) { + if (allExist) { + callback(); + return; + } + + var typescriptPath = path.join(require.resolve("typescript"), "..", ".."); + + async.waterfall([ + async.parallel.bind(async, [ + fs.readFile.bind(fs, path.join(typescriptPath, "lib", "typescript.d.ts"), "utf8"), + fs.readFile.bind(fs, "./build/typescript/extras.d.ts", "utf8") + ]), + function (results, callback) { + var newDts = results[0] + "\n\n" + results[1]; + fs.writeFile("./build/typescript/typescript.d.ts", newDts, "utf8", callback); + }, + function (callback) { + npm.load(function () { + npm.commands["run-script"](["build"], callback); + }); + } + ], callback); + }); +}); + +task("default", ["libjass.js", "libjass.min.js"]); + +task("version.ts", function (callback) { + fs.exists("./src/version.ts", function (exists) { + if (exists) { + callback(); + return; + } + + async.waterfall([ + fs.readFile.bind(fs, "./package.json"), + function (buffer, callback) { + try { + var packageJson = JSON.parse(buffer); + var versionString = packageJson.version; + var versionParts = versionString.split(".").map(function (num) { return parseInt(num); }); + var versionFileContents = + "/* tslint:disable */\n" + + "\n" + + "/**\n" + + " * The version of libjass. An array like\n" + + " *\n" + + " * [\"0.12.0\", 0, 12, 0]\n" + + " *\n" + + " * @type {!Array.}\n" + + " */\n" + + "export const version = " + JSON.stringify([versionString].concat(versionParts)) + ";\n"; + callback(null, versionFileContents); + } + catch (ex) { + callback(ex); + } + }, + function (contents, callback) { + fs.writeFile("./src/version.ts", contents, "utf8", callback); + } + ], callback); + }); +}); + +task("libjass.js", ["build-tools", "version.ts"], function (callback) { + fs.exists("./lib/libjass.js", function (exists) { + if (exists) { + callback(); + return; + } + + callback(null, task.src("./src/tsconfig.json") + .pipe(TypeScript.build("./src/index.ts", "libjass")) + .pipe(UglifyJS.build("libjass", ["AttachmentType", "BorderStyle", "ClockEvent", "Format", "WorkerCommands", "WrappingStyle"])) + .pipe(task.dest("./lib"))); + }); +}); + +task("libjass.min.js", ["libjass.js"], function (callback) { + fs.exists("./lib/libjass.min.js", function (exists) { + if (exists) { + callback(); + return; + } + + callback(null, task.src(["./lib/libjass.js", "./lib/libjass.js.map"], { relativeTo: "./lib" }) + .pipe(UglifyJS.minify()) + .pipe(task.dest("./lib"))); + }); +}); + +task("clean", task.clean(["./src/version.ts", "./lib/libjass.js", "./lib/libjass.js.map", "./lib/libjass.min.js", "./lib/libjass.min.js.map"])); + +task("watch", ["build-tools", "version.ts"], function (callback) { + npm.load(function () { + var testRunning = false; + var rerunTest = false; + + var startTest = function () { + npm.commands["run-script"](["test-lib"], function () { + testRunning = false; + + if (rerunTest) { + startTest(); + rerunTest = false; + } + }); + + testRunning = true; + }; + + var runTest = function () { + if (!testRunning) { + startTest(); + } + else { + rerunTest = true; + } + }; + + task.src("./src/tsconfig.json") + .pipe(TypeScript.watch("./src/index.ts", "libjass")) + .pipe(UglifyJS.watch("libjass", ["BorderStyle", "ClockEvent", "Format", "WorkerCommands", "WrappingStyle"])) + .pipe(task.dest("./lib")) + .pipe(new task.FileTransform(function (file) { + if (file.path === "libjass.js") { + runTest(); + } + })); + + task.watch("./tests/unit/", runTest); + }); +}); + +task("test-lib", ["libjass.js"], function (callback) { + npm.load(function () { + npm.commands["run-script"](["test-lib"], callback); + }); +}); + +task("test-minified", ["libjass.min.js"], function (callback) { + npm.load(function () { + npm.commands["run-script"](["test-minified"], callback); + }); +}); + +// Start Selenium server with +// java.exe -jar .\selenium-server-standalone-2.48.2.jar -Dwebdriver.ie.driver=IEDriverServer.exe -Dwebdriver.chrome.driver=chromedriver.exe +task("test-browser", ["libjass.js"], function (callback) { + npm.load(function () { + npm.commands["run-script"](["test-browser"], callback); + }); +}); + +task("test", ["test-lib", "test-minified"]); + +task("demo", ["libjass.js"], function () { + return task.src(["./lib/libjass.js", "./lib/libjass.js.map", "./lib/libjass.css"], { relativeTo: "./lib" }).pipe(task.dest("../libjass-gh-pages/demo/")); +}); + +task("doc", ["make-doc", "test-doc"]); + +task("make-doc", ["build-tools", "version.ts"], function () { + var Doc = require("./build/doc.js"); + + return task.src("./src/tsconfig.json") + .pipe(Doc.build("./api.xhtml", "./src/index.ts", "libjass")) + .pipe(task.dest("../libjass-gh-pages/")); +}); + +task("test-doc", ["make-doc", "libjass.js"], function (callback) { + npm.load(function () { + npm.commands["run-script"](["test-doc"], callback); + }); +}); + +task("dist", ["libjass.js", "libjass.min.js", "test", "test-browser", "demo", "doc"], function (callback) { + var inputFiles = [ + "./README.md", "./CHANGELOG.md", "./LICENSE", + "./lib/libjass.js", "./lib/libjass.js.map", + "./lib/libjass.min.js", "./lib/libjass.min.js.map", + "./lib/libjass.css" + ]; + + var files = Object.create(null); + inputFiles.forEach(function (filename) { + files["./dist/" + path.basename(filename)] = filename; + }); + + async.series([ + // Clean dist/ + task.clean(Object.keys(files).concat(["./dist/package.json"])), + + // Create dist/ if necessary + function (callback) { + fs.mkdir("./dist", function (err) { + if (err && err.code !== "EEXIST") { + callback(err); + return; + } + + callback(); + }); + }, + + // Copy all files except package.json + async.forEachOf.bind(async, files, function (inputFilename, outputFilename, callback) { + async.waterfall([fs.readFile.bind(fs, inputFilename), fs.writeFile.bind(fs, outputFilename)], callback); + }), + + // Copy package.json + async.waterfall.bind(async, [ + fs.readFile.bind(fs, "./package.json"), + function (data, callback) { + try { + var packageJson = JSON.parse(data); + packageJson.devDependencies = undefined; + packageJson.private = undefined; + packageJson.scripts = undefined; + packageJson.main = "libjass.js"; + } + catch (ex) { + callback(ex); + return; + } + + callback(null, new Buffer(JSON.stringify(packageJson, null, "\t"))); + }, + fs.writeFile.bind(fs, "./dist/package.json") + ]) + ], callback); +}); + +task.runArgv(function (err) { + if (err) { + process.exit(1); + } +}); diff --git a/negromate/web/static/js/libjass/build/doc.ts b/negromate/web/static/js/libjass/build/doc.ts new file mode 100644 index 0000000..f5a1606 --- /dev/null +++ b/negromate/web/static/js/libjass/build/doc.ts @@ -0,0 +1,884 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { FileTransform } from "async-build"; + +import * as AST from "./typescript/ast"; +import { Compiler } from "./typescript/compiler"; +import { walk } from "./typescript/walker"; + +function flatten(arr: T[][]): T[] { + let result: T[] = []; + + for (const a of arr) { + result = result.concat(a); + } + + return result; +} + +const sorter = (() => { + function visibilitySorter(value1: { isPrivate?: boolean; isProtected?: boolean; }, value2: { isPrivate?: boolean; isProtected?: boolean; }) { + if (value1.isPrivate === value2.isPrivate && value1.isProtected === value2.isProtected) { + return 0; + } + + if (value1.isPrivate) { + return 1; + } + + if (value2.isPrivate) { + return -1; + } + + if (value1.isProtected) { + return 1; + } + + if (value2.isProtected) { + return -1; + } + + return 0; + } + + const types = [AST.Property, AST.Function, AST.Interface, AST.Class, AST.Enum]; + function typeSorter(value1: AST.ModuleMember | AST.NamespaceMember, value2: AST.ModuleMember | AST.NamespaceMember) { + let type1Index = -1; + let type2Index = -1; + + types.every((type, index) => { + if (value1 instanceof type) { + type1Index = index; + } + if (value2 instanceof type) { + type2Index = index; + } + return (type1Index === -1) || (type2Index === -1); + }); + + return type1Index - type2Index; + } + + function nameSorter(value1: { name: string }, value2: { name: string }) { + return value1.name.localeCompare(value2.name); + } + + const sorters: ((value1: AST.ModuleMember, value2: AST.ModuleMember) => number)[] = [visibilitySorter, typeSorter, nameSorter]; + + return (value1: AST.ModuleMember, value2: AST.ModuleMember) => { + for (const sorter of sorters) { + const result = sorter(value1, value2); + + if (result !== 0) { + return result; + } + } + + return 0; + }; +})(); + +function indenter(indent: number) { + return (line: string) => ((line === "") ? line : (Array(indent + 1).join("\t") + line)); +} + +function sanitize(str: string) { + return str.replace(/&/g, "&").replace(//g, ">"); +} + +function toVariableName(item: { name: string }) { + // TODO: Handle non-letters (are both their toLowerCase() and toUpperCase()) + + const name = item.name; + let result = ""; + + for (let i = 0; i < name.length; i++) { + if (name[i] === name[i].toLowerCase()) { + // This is lower case. Write it as lower case. + result += name[i]; + } + + else { + // This is upper case. + + if (i === 0) { + // This is the first character. Write it as lower case. + result += name[i].toLowerCase(); + } + + else if (name[i - 1] === name[i - 1].toUpperCase()) { + // The previous character was upper case. + + if (i === name.length - 1) { + // This is the last character. Write it as lower case. + result += name[i].toLowerCase(); + } + else if (name[i + 1] === name[i + 1].toLowerCase()) { + // The next character is lower case so this is the start of a new word. Write this one as upper case. + result += name[i]; + } + else { + // The next character is upper case. Write this one as lower case. + result += name[i].toLowerCase(); + } + } + + else { + // Previous character was lower case so this is the start of a new word. Write this one as upper case. + result += name[i]; + } + } + } + + return result; +} + +function toUsageName(item: AST.Class | AST.Interface | AST.Function | AST.Property | AST.Enum): string { + if (item.parent instanceof AST.Module) { + return item.name; + } + + if (item instanceof AST.Class || item instanceof AST.Interface || item instanceof AST.Enum) { + if (item.isPrivate) { + return item.name; + } + + return item.fullName; + } + + if (item.parent instanceof AST.Namespace) { + if ((item as AST.CanBePrivate).isPrivate) { + return item.name; + } + + return item.fullName; + } + + if ((item as AST.CanBeStatic).isStatic) { + return toUsageName(item.parent as AST.Class | AST.Interface) + '.' + item.name; + } + + return toVariableName(item.parent) + '.' + item.name; +} + +function toId(item: { fullName?: string; name: string; }): string { + return sanitize((item.fullName === undefined) ? item.name : item.fullName); +} + +function toLink(item: AST.ModuleMember | AST.EnumMember | AST.TypeReference): string { + let result = `${ sanitize(item.name) }`; + + if (AST.hasGenerics(item) && item.generics.length > 0) { + const generics = item.generics as (string | AST.TypeReference | AST.IntrinsicTypeReference)[]; + result += sanitize(`.<${ generics.map(generic => + (generic instanceof AST.TypeReference || generic instanceof AST.IntrinsicTypeReference) ? generic.name : generic + ).join(', ') }>`); + } + + result += ''; + + return result; +} + +function writeDescription(text: string): string { + let result = sanitize(text).replace(/\{@link ([^} ]+)\}/g, (substring, linkTarget) => `${ linkTarget }`); + + let inCodeBlock = false; + result = result.split("\n").map(line => { + if (line.substr(0, " ".length) === " ") { + line = line.substr(" ".length); + + if (!inCodeBlock) { + inCodeBlock = true; + line = `
${ line }`;
+			}
+		}
+		else if (line.length > 0 && inCodeBlock) {
+			inCodeBlock = false;
+			line = `
${ line }`; + } + else if (line.length === 0 && !inCodeBlock) { + line = "

"; + } + + return line; + }).join("\n"); + + if (inCodeBlock) { + result += ''; + } + + result = `

${ result }

`.replace(/

\s*<\/p>/g, "").replace(/

\s+/g, "

").replace(/\s+<\/p>/g, "

"); + + if (result.substr("

".length).indexOf("

") === -1) { + result = result.substring("

".length, result.length - "

".length); + } + + return result; +} + +function writeParameters(parameters: AST.Parameter[]): string[] { + if (parameters.length === 0) { + return []; + } + + return [ + '
', + '
' + ].concat(flatten(parameters.map(parameter => { + return [ + `
${ sanitize(parameter.name) }
`, + `
${ sanitize(parameter.type) }
`, + `
${ writeDescription(parameter.description) }
` + ].concat(writeParameters(parameter.subParameters).map(indenter(2))); + }))).concat([ + '
', + '
' + ]); +} + +function functionToHtml(func: AST.Function): string[] { + return [ + `
`, + `
${ toLink(func) }
`, + '
', + ` ${ writeDescription(func.description) }`, + '
', + `
${
+				sanitize(
+					`${ (func.returnType !== null) ? 'var result = ' : '' }${ toUsageName(func) }(${
+					func.parameters.map(parameter => parameter.name).join(', ') });`
+				) }
` + ].concat(writeParameters(func.parameters).map(indenter(1))).concat( + (func.returnType === null) ? [] : [ + '
Returns
', + `
${ sanitize(func.returnType.type) }
`, + `
${ writeDescription(func.returnType.description) }
` + ] + ).concat([ + '
', + '' + ]); +} + +function interfaceToHtml(interfase: AST.Interface): string[] { + const members: AST.InterfaceMember[] = []; + Object.keys(interfase.members).forEach(memberName => members.push(interfase.members[memberName])); + + members.sort(sorter); + + return [ + `
`, + `
interface ${ toLink(interfase) }${ (interfase.baseTypes.length > 0) ? ` extends ${ + interfase.baseTypes.map(baseType => baseType instanceof AST.TypeReference ? toLink(baseType) : baseType.name).join(', ') + }` : '' }
`, + '
', + ` ${ writeDescription(interfase.description) }`, + '
', + '
' + ].concat(flatten(members.map(member => { + if (member instanceof AST.Property) { + return propertyToHtml(member).map(indenter(2)); + } + else if (member instanceof AST.Function) { + return functionToHtml(member).map(indenter(2)); + } + else { + throw new Error(`Unrecognized member type: ${ (member as any).constructor.name }`); + } + }))).concat([ + '
', + '
', + '' + ]); +} + +function classToHtml(clazz: AST.Class): string[] { + const members: AST.InterfaceMember[] = []; + Object.keys(clazz.members).forEach(memberName => members.push(clazz.members[memberName])); + + members.sort(sorter); + + return [ + `
`, + `
class ${ toLink(clazz) }${ + (clazz.baseType !== null) ? ` extends ${ (clazz.baseType instanceof AST.TypeReference) ? toLink(clazz.baseType) : clazz.baseType.name }` : '' }${ + (clazz.interfaces.length > 0) ? ` implements ${ clazz.interfaces.map(interfase => interfase instanceof AST.TypeReference ? toLink(interfase) : interfase.name).join(', ') }` : ''}
`, + '
', + ` ${ writeDescription(clazz.description) }`, + '
', + `
${
+				sanitize(
+					`var ${ toVariableName(clazz) } = new ${ toUsageName(clazz) }(${
+					clazz.parameters.map(parameter => parameter.name).join(', ') });`
+				) }
` + ].concat(writeParameters(clazz.parameters).map(indenter(1))).concat([ + '
' + ]).concat(flatten(members.map(member => { + if (member instanceof AST.Property) { + return propertyToHtml(member).map(indenter(2)); + } + else if (member instanceof AST.Function) { + return functionToHtml(member).map(indenter(2)); + } + else { + throw new Error(`Unrecognized member type: ${ (member as any).constructor.name }`); + } + }))).concat([ + '
', + '
', + '' + ]); +} + +function enumToHtml(enumType: AST.Enum): string[] { + return [ + `
`, + `
enum ${ sanitize(enumType.name) }
`, + '
', + ` ${ writeDescription(enumType.description) }`, + '
' + ].concat([ + '
' + ]).concat(flatten(enumType.members.map(member => [ + `
`, + `
${ toLink(member) } = ${ member.value }
`, + '
', + ` ${ writeDescription(member.description) }`, + '
', + '
' + ]))).concat([ + '
', + '
', + '' + ]); +} + +function propertyToHtml(property: AST.Property): string[] { + return [ + `
`, + `
${ toLink(property) }
` + ].concat((property.getter === null) ? [] : [ + `
Getter
`, + '
', + ` ${ writeDescription(property.getter.description) }`, + '
', + `
${ sanitize(`var result = ${ toUsageName(property) };`) }
`, + `
${ sanitize(property.getter.type) }
` + ]).concat((property.setter === null) ? [] : [ + `
Setter
`, + '
', + ` ${ writeDescription(property.setter.description) }`, + '
', + `
${ sanitize(`${ toUsageName(property) } = value;`) }
` + ].concat(writeParameters([new AST.Parameter("value", "", property.setter.type)]).map(indenter(1)))).concat([ + '
', + '' + ]); +} + +export function build(outputFilePath: string, root: string, rootNamespaceName: string): FileTransform { + const compiler = new Compiler(); + + return new FileTransform(function (file): void { + // Compile + compiler.compile(file); + + // Walk + const walkResult = walk(compiler, root, rootNamespaceName); + const namespaces = walkResult.namespaces; + const modules = walkResult.modules; + + // Make HTML + + const namespaceNames = Object.keys(namespaces) + .filter(namespaceName => namespaceName.substr(0, rootNamespaceName.length) === rootNamespaceName) + .sort((ns1, ns2) => ns1.localeCompare(ns2)); + + const moduleNames = Object.keys(modules).sort((ns1, ns2) => ns1.localeCompare(ns2)).filter(moduleName => Object.keys(modules[moduleName].members).length > 0); + + this.push({ + path: outputFilePath, + contents: Buffer.concat([new Buffer( +` + + + ${ rootNamespaceName } API Documentation + + + + + + +
+` + )]).concat(flatten(namespaceNames.map(namespaceName => { + const namespace = namespaces[namespaceName]; + + const namespaceMembers: AST.NamespaceMember[] = []; + for (const memberName of Object.keys(namespace.members)) { + namespaceMembers.push(namespace.members[memberName]); + } + + namespaceMembers.sort(sorter); + + const properties = namespaceMembers.filter(member => member instanceof AST.Property) as AST.Property[]; + const functions = namespaceMembers.filter(member => member instanceof AST.Function) as AST.Function[]; + const interfaces = namespaceMembers.filter(member => member instanceof AST.Interface) as AST.Interface[]; + const classes = namespaceMembers.filter(member => member instanceof AST.Class) as AST.Class[]; + const enums = namespaceMembers.filter(member => member instanceof AST.Enum) as AST.Enum[]; + + const result = [new Buffer( +`
+

Namespace ${ sanitize(namespaceName) }

+` + )]; + + if (properties.length > 0) { + result.push(new Buffer( +`
+

Properties

+` + )); + + for (const property of properties) { + result.push(new Buffer(propertyToHtml(property).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + if (functions.length > 0) { + result.push(new Buffer( +`
+

Free functions

+` + )); + + for (const func of functions) { + result.push(new Buffer(functionToHtml(func).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + if (interfaces.length > 0) { + result.push(new Buffer( +`
+

Interfaces

+` + )); + + for (const interfase of interfaces) { + result.push(new Buffer(interfaceToHtml(interfase).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + if (classes.length > 0) { + result.push(new Buffer( +`
+

Classes

+` + )); + + for (const clazz of classes) { + result.push(new Buffer(classToHtml(clazz).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + if (enums.length > 0) { + result.push(new Buffer( +`
+

Enums

+` + )); + + for (const enumType of enums) { + result.push(new Buffer(enumToHtml(enumType).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + result.push(new Buffer( +`
+` + )); + + return result; + }))).concat(flatten(moduleNames.map(moduleName => { + const module = modules[moduleName]; + + const moduleMembers: AST.ModuleMember[] = []; + for (const memberName of Object.keys(module.members)) { + const member = module.members[memberName]; + if ((member as AST.HasParent).parent === module) { + moduleMembers.push(member); + } + } + + if (moduleMembers.length === 0) { + return []; + } + + moduleMembers.sort(sorter); + + const properties = moduleMembers.filter(member => member instanceof AST.Property) as AST.Property[]; + const functions = moduleMembers.filter(member => member instanceof AST.Function) as AST.Function[]; + const interfaces = moduleMembers.filter(member => member instanceof AST.Interface) as AST.Interface[]; + const classes = moduleMembers.filter(member => member instanceof AST.Class) as AST.Class[]; + const enums = moduleMembers.filter(member => member instanceof AST.Enum) as AST.Enum[]; + + const result = [new Buffer( +`
+

Module ${ sanitize(moduleName) }

+` + )]; + + if (properties.length > 0) { + result.push(new Buffer( +`
+

Properties

+` + )); + + for (const property of properties) { + result.push(new Buffer(propertyToHtml(property).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + if (functions.length > 0) { + result.push(new Buffer( +`
+

Free functions

+` + )); + + for (const func of functions) { + result.push(new Buffer(functionToHtml(func).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + if (interfaces.length > 0) { + result.push(new Buffer( +`
+

Interfaces

+` + )); + + for (const interfase of interfaces) { + result.push(new Buffer(interfaceToHtml(interfase).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + if (classes.length > 0) { + result.push(new Buffer( +`
+

Classes

+` + )); + + for (const clazz of classes) { + result.push(new Buffer(classToHtml(clazz).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + if (enums.length > 0) { + result.push(new Buffer( +`
+

Enums

+` + )); + + for (const enumType of enums) { + result.push(new Buffer(enumToHtml(enumType).map(indenter(5)).join("\n"))); + } + + result.push(new Buffer( +`
+` + )); + } + + result.push(new Buffer( +`
+` + )); + + return result; + }))).concat([new Buffer( +`
+ + +` + )])) + }); + }); +} diff --git a/negromate/web/static/js/libjass/build/node.d.ts b/negromate/web/static/js/libjass/build/node.d.ts new file mode 100644 index 0000000..ec700f5 --- /dev/null +++ b/negromate/web/static/js/libjass/build/node.d.ts @@ -0,0 +1,24 @@ +// Type definitions for Node.js v0.12.0 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var require: { + resolve(id: string): string; +}; + +interface BufferConstructor { + new (str: string): Buffer; + prototype: Buffer; + concat(list: Buffer[]): Buffer; +} + +declare module "fs" { + export function existsSync(filename: string): boolean; + export function readFileSync(filename: string, options: { encoding: string }): string; +} + +declare module "path" { + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; +} diff --git a/negromate/web/static/js/libjass/build/tsconfig.json b/negromate/web/static/js/libjass/build/tsconfig.json new file mode 100644 index 0000000..5394740 --- /dev/null +++ b/negromate/web/static/js/libjass/build/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "noUnusedLocals": true, + "noUnusedParameters": false, + "strictNullChecks": false, + + "target": "es5", + "module": "commonjs", + "moduleResolution": "classic", + "noImplicitUseStrict": false, + "types": [] + }, + + "files": [ + "./typescript/index.ts", + "./doc.ts", + "./node.d.ts", + "./typescript/typescript.d.ts", + "../node_modules/async-build/typings.d.ts" + ] +} diff --git a/negromate/web/static/js/libjass/build/typescript/ast.ts b/negromate/web/static/js/libjass/build/typescript/ast.ts new file mode 100644 index 0000000..c90a89c --- /dev/null +++ b/negromate/web/static/js/libjass/build/typescript/ast.ts @@ -0,0 +1,204 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import ts = require("typescript"); + +export class HasParent { + public parent: HasParent = null; + + constructor(public name: string) { } + + get fullName(): string { + if (this.parent === null) { + return this.name; + } + + const parent = this.parent; + if (parent instanceof Namespace) { + return parent.getMemberFullName(this); + } + + return `${ this.parent.fullName }.${ this.name }`; + } +} + +export class Module extends HasParent { + public parent: Module = null; + + public members: { [name: string]: ModuleMember } = Object.create(null); + + constructor(public fileName: string) { + super(fileName); + } +} + +export type ModuleMember = Class | Interface | Function | Property | Enum | Reference; +export type ModuleMemberWithoutReference = Class | Interface | Function | Property | Enum; + +export class Reference { + constructor(public moduleName: string, public name: string, public isPrivate: boolean) { } +} + +export class Namespace extends HasParent { + public parent: Namespace = null; + + public members: { [name: string]: NamespaceMember } = Object.create(null); + + constructor(name: string) { + super(name); + } + + getMemberFullName(member: HasParent) { + return `${ this.fullName }.${ member.name }`; + } +} + +export type NamespaceMember = Class | Interface | Function | Property | Enum; + +export class Class extends HasParent { + public parent: Module | Namespace = null; + + public unresolvedBaseType: UnresolvedType | TypeReference | IntrinsicTypeReference; + public baseType: TypeReference | IntrinsicTypeReference = null; + + public unresolvedInterfaces: (UnresolvedType | TypeReference | IntrinsicTypeReference)[]; + public interfaces: (TypeReference | IntrinsicTypeReference)[] = []; + + public members: { [name: string]: InterfaceMember } = Object.create(null); + + constructor(name: string, public astNode: ts.Node, public description: string, public generics: string[], public parameters: Parameter[], baseType: UnresolvedType | TypeReference | IntrinsicTypeReference, interfaces: (UnresolvedType | TypeReference | IntrinsicTypeReference)[], public isAbstract: boolean, public isPrivate: boolean) { + super(name); + + this.unresolvedBaseType = baseType; + this.unresolvedInterfaces = interfaces; + } +} + +export type InterfaceMember = Property | Function; + +export class Interface extends HasParent { + public parent: Module | Namespace = null; + + public unresolvedBaseTypes: (UnresolvedType | TypeReference | IntrinsicTypeReference)[]; + public baseTypes: (TypeReference | IntrinsicTypeReference)[] = []; + + public members: { [name: string]: InterfaceMember } = Object.create(null); + + constructor(name: string, public astNode: ts.Node, public description: string, public generics: string[], baseTypes: (UnresolvedType | TypeReference | IntrinsicTypeReference)[], public isPrivate: boolean) { + super(name); + + this.unresolvedBaseTypes = baseTypes; + } +} + +export class Function extends HasParent { + public parent: Module | Namespace | Class | Interface = null; + + constructor(name: string, public astNode: ts.Node, public description: string, public generics: string[], public parameters: Parameter[], public returnType: ReturnType, public isAbstract: boolean, public isPrivate: boolean, public isProtected: boolean, public isStatic: boolean) { + super(name); + } +} + +export class Property extends HasParent { + public parent: Module | Namespace | Class | Interface = null; + + public getter: Getter = null; + public setter: Setter = null; + + constructor(name: string) { + super(name); + } +} + +export class Getter { + constructor(public astNode: ts.Node, public description: string, public type: string, public isPrivate: boolean) { } +} + +export class Setter { + constructor(public astNode: ts.Node, public description: string, public type: string, public isPrivate: boolean) { } +} + +export class Parameter { + public subParameters: Parameter[] = []; + + constructor(public name: string, public description: string, public type: string) { } +} + +export class ReturnType { + constructor(public description: string, public type: string) { } +} + +export class Enum extends HasParent { + public parent: Module | Namespace = null; + + public members: EnumMember[] = []; + + constructor(name: string, public astNode: ts.Node, public description: string, public isPrivate: boolean) { + super(name); + } +} + +export class EnumMember extends HasParent { + public parent: Enum = null; + + constructor(name: string, public description: string, public value: number) { + super(name); + } +} + +export class TypeReference { + constructor(public type: NamespaceMember, public generics: (TypeReference | IntrinsicTypeReference)[]) { } + + get name(): string { + return this.type.name; + } + + get fullName(): string { + return this.type.fullName; + } +} + +export class IntrinsicTypeReference { + public fullName: string; + + constructor(public name: string) { + this.fullName = name; + } +} + +export class UnresolvedType { + constructor(public symbol: ts.Symbol, public generics: (UnresolvedType | IntrinsicTypeReference)[]) { } +} + +export type HasStringGenerics = Class | Interface | Function; + +export function hasStringGenerics(item: NamespaceMember): item is HasStringGenerics { + return (item as HasGenerics).generics !== undefined; +} + +export type HasGenerics = HasStringGenerics | TypeReference; + +export function hasGenerics(item: ModuleMember | EnumMember | TypeReference): item is HasGenerics { + return (item as HasGenerics).generics !== undefined; +} + +export type CanBePrivate = Class | Interface | Function | Getter | Setter | Enum | Reference; +export type CanBeProtected = Function; +export type CanBeStatic = Function; diff --git a/negromate/web/static/js/libjass/build/typescript/compiler.ts b/negromate/web/static/js/libjass/build/typescript/compiler.ts new file mode 100644 index 0000000..86ff04c --- /dev/null +++ b/negromate/web/static/js/libjass/build/typescript/compiler.ts @@ -0,0 +1,308 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import path = require("path"); +import ts = require("typescript"); + +import { File, FileTransform } from "async-build"; + +import * as AST from "./ast"; +import { walk } from "./walker"; + +export interface StreamingCompilerHost extends ts.CompilerHost { + setOutputStream(outputStream: FileTransform): void; +} + +function createCompilerHost(options: ts.CompilerOptions): StreamingCompilerHost { + const host = ts.createCompilerHost(options) as StreamingCompilerHost; + + let _outputStream: FileTransform = null; + host.setOutputStream = outputStream => _outputStream = outputStream; + + host.writeFile = (fileName, data, writeByteOrderMark, onError?, sourceFiles?): void => { + _outputStream.push({ + path: fileName, + contents: new Buffer(data) + }); + }; + + host.useCaseSensitiveFileNames = () => true; + + host.getNewLine = () => "\n"; + + return host; +} + +export class Compiler { + private _projectRoot: string = null; + private _host: StreamingCompilerHost; + private _program: ts.Program = null; + + compile(projectConfigFile: File) { + this._projectRoot = path.dirname(projectConfigFile.path); + + const projectConfig = ts.parseJsonConfigFileContent(JSON.parse(projectConfigFile.contents.toString()), ts.sys, this._projectRoot); + + this._host = createCompilerHost(projectConfig.options); + this._program = ts.createProgram(projectConfig.fileNames, projectConfig.options, this._host); + + const syntacticDiagnostics = this._program.getSyntacticDiagnostics(); + if (syntacticDiagnostics.length > 0) { + this._reportDiagnostics(syntacticDiagnostics); + throw new Error("There were one or more syntactic diagnostics."); + } + + const optionsDiagnostics = this._program.getOptionsDiagnostics(); + if (optionsDiagnostics.length > 0) { + this._reportDiagnostics(optionsDiagnostics); + throw new Error("There were one or more options diagnostics."); + } + + const globalDiagnostics = this._program.getGlobalDiagnostics(); + if (globalDiagnostics.length > 0) { + this._reportDiagnostics(globalDiagnostics); + throw new Error("There were one or more global diagnostics."); + } + + const semanticDiagnostics = this._program.getSemanticDiagnostics(); + if (semanticDiagnostics.length > 0) { + this._reportDiagnostics(semanticDiagnostics); + throw new Error("There were one or more semantic diagnostics."); + } + }; + + writeFiles(outputStream: FileTransform) { + this._host.setOutputStream(outputStream); + + const emitDiagnostics = this._program.emit().diagnostics; + if (emitDiagnostics.length > 0) { + this._reportDiagnostics(emitDiagnostics); + throw new Error("There were one or more emit diagnostics."); + } + }; + + get projectRoot(): string { + return this._projectRoot; + } + + get typeChecker(): ts.TypeChecker { + return this._program.getTypeChecker(); + } + + get sourceFiles(): ts.SourceFile[] { + return this._program.getSourceFiles(); + } + + private _reportDiagnostics(diagnostics: ts.Diagnostic[]) { + for (const diagnostic of diagnostics) { + let message = ""; + + if (diagnostic.file) { + const location = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + message = `${ diagnostic.file.fileName }(${ location.line + 1 },${ location.character }): `; + } + + message += + ts.DiagnosticCategory[diagnostic.category].toLowerCase() + + ` TS${ diagnostic.code }: ` + + ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); + + console.error(message); + } + }; +} + +export function build(root: string, rootNamespaceName: string): FileTransform { + const compiler = new Compiler(); + + return new FileTransform(function (projectConfigFile): void { + console.log("Compiling " + projectConfigFile.path + "..."); + + compiler.compile(projectConfigFile); + + const walkResult = walk(compiler, root, rootNamespaceName); + addJSDocComments(walkResult.modules); + + compiler.writeFiles(this); + + console.log("Compile succeeded."); + }); +} + +function addJSDocComments(modules: { [name: string]: AST.Module }): void { + function visitor(current: AST.Module | AST.ModuleMember | AST.InterfaceMember) { + if (current instanceof AST.Module) { + for (const memberName of Object.keys(current.members)) { + visitor(current.members[memberName]); + } + + return; + } + + const newComments: string[] = []; + + if (current instanceof AST.Class) { + newComments.push("@constructor"); + + if (current.baseType !== null) { + const baseType = current.baseType; + newComments.push( + "@extends {" + + baseType.fullName + ( + (baseType instanceof AST.TypeReference && baseType.generics.length) > 0 ? + (".<" + (baseType as AST.TypeReference).generics.map(generic => generic.fullName).join(", ") + ">") : + "" + ) + + "}" + ); + } + + if (current.interfaces.length > 0) { + current.interfaces.forEach(interfase => { + newComments.push( + "@implements {" + + interfase.fullName + ( + (interfase instanceof AST.TypeReference && interfase.generics.length > 0) ? + (".<" + interfase.generics.map(generic => generic.fullName).join(", ") + ">") : + "" + ) + + "}" + ); + }); + } + + Object.keys(current.members).forEach(memberName => visitor(current.members[memberName])); + } + else if (current instanceof AST.Enum) { + newComments.push("@enum"); + } + else if (current instanceof AST.Reference) { + return; + } + + if (current.parent instanceof AST.Namespace) { + newComments.push("@memberOf " + current.parent.fullName); + } + + if (AST.hasStringGenerics(current) && current.generics.length > 0) { + newComments.push("@template " + current.generics.join(", ")); + } + + if ((current as AST.CanBePrivate).isPrivate) { + newComments.push("@private"); + } + + if ((current as AST.CanBeProtected).isProtected) { + newComments.push("@protected"); + } + + if ((current as AST.CanBeStatic).isStatic) { + newComments.push("@static"); + } + + if (newComments.length > 0) { + if (current instanceof AST.Property) { + const nodes: ts.Node[] = []; + if (current.getter !== null) { nodes.push(current.getter.astNode); } + if (current.setter !== null && nodes[0] !== current.setter.astNode) { nodes.push(current.setter.astNode); } + for (const node of nodes) { + (node as any)["typescript-new-comment"] = newComments; + } + } + else { + (current.astNode as any)["typescript-new-comment"] = newComments; + } + } + } + + for (const moduleName of Object.keys(modules)) { + visitor(modules[moduleName]); + } +} + +class FakeSourceFile { + public text: string; + public lineMap: number[]; + + constructor(originalSourceFile: ts.SourceFile) { + this.text = originalSourceFile.text; + this.lineMap = ts.getLineStarts(originalSourceFile).slice(); + } + + addComment(originalComment: ts.CommentRange, newComments: string[]): ts.CommentRange & { sourceFile: FakeSourceFile } { + var pos = this.text.length; + + this.text += "/**\n"; + this.lineMap.push(this.text.length); + + var originalCommentLines = this.text.substring(originalComment.pos, originalComment.end).split("\n"); + originalCommentLines.shift(); + + originalCommentLines = originalCommentLines.map(line => line.replace(/^\s+/, " ")); + + if (originalCommentLines.length > 1) { + originalCommentLines.splice(originalCommentLines.length - 1, 0, " *"); + } + + for (const newComment of newComments) { + originalCommentLines.splice(originalCommentLines.length - 1, 0, " * " + newComment); + } + + for (const newCommentLine of originalCommentLines) { + this.text += newCommentLine + "\n"; + this.lineMap.push(this.text.length); + } + + var end = this.text.length; + + return { pos, end, hasTrailingNewLine: originalComment.hasTrailingNewLine, kind: ts.SyntaxKind.MultiLineCommentTrivia, sourceFile: this }; + } +} + +var fakeSourceFiles: { [name: string]: FakeSourceFile } = Object.create(null); + +export const oldGetLeadingCommentRangesOfNodeFromText: typeof ts.getLeadingCommentRangesOfNodeFromText = ts.getLeadingCommentRangesOfNodeFromText.bind(ts); + +ts.getLeadingCommentRangesOfNodeFromText = (node: ts.Node, text: string) => { + const originalComments = oldGetLeadingCommentRangesOfNodeFromText(node, text); + + if (originalComments !== undefined && (node)["typescript-new-comment"] !== undefined) { + const sourceFileOfNode = ts.getSourceFileOfNode(node); + let fakeSourceFile = fakeSourceFiles[sourceFileOfNode.fileName]; + if (fakeSourceFile === undefined) { + fakeSourceFile = fakeSourceFiles[sourceFileOfNode.fileName] = new FakeSourceFile(sourceFileOfNode); + } + + originalComments[originalComments.length - 1] = fakeSourceFile.addComment(originalComments[originalComments.length - 1], (node)["typescript-new-comment"]); + } + + return originalComments; +}; + +var oldWriteCommentRange: typeof ts.writeCommentRange = ts.writeCommentRange.bind(ts); +ts.writeCommentRange = (text: string, lineMap: number[], writer: ts.EmitTextWriter, comment: ts.CommentRange, newLine: string) => { + if ((<{ sourceFile: ts.SourceFile }>comment).sourceFile) { + const currentSourceFile = (<{ sourceFile: ts.SourceFile }>comment).sourceFile; + text = currentSourceFile.text; + lineMap = currentSourceFile.lineMap; + } + + return oldWriteCommentRange(text, lineMap, writer, comment, newLine); +}; diff --git a/negromate/web/static/js/libjass/build/typescript/extras.d.ts b/negromate/web/static/js/libjass/build/typescript/extras.d.ts new file mode 100644 index 0000000..acd6eb8 --- /dev/null +++ b/negromate/web/static/js/libjass/build/typescript/extras.d.ts @@ -0,0 +1,22 @@ +declare namespace ts { + interface EmitTextWriter { } + + interface IntrinsicType extends Type { + intrinsicName: string; + } + + interface SourceFile { + lineMap: number[]; + } + + function forEachProperty(map: Map, callback: (value: T, key: string) => U): U; + function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration | InterfaceDeclaration): ExpressionWithTypeArguments; + function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration): ExpressionWithTypeArguments[]; + function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): ExpressionWithTypeArguments[]; + function getLeadingCommentRangesOfNodeFromText(node: Node, text: string): CommentRange[]; + function getLineStarts(sourceFile: SourceFile): number[]; + function getSourceFileOfNode(node: Node): SourceFile; + function getTextOfNode(node: Node, includeTrivia?: boolean): string; + function normalizeSlashes(path: string): string; + function writeCommentRange(text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string): void; +} diff --git a/negromate/web/static/js/libjass/build/typescript/index.ts b/negromate/web/static/js/libjass/build/typescript/index.ts new file mode 100644 index 0000000..4518681 --- /dev/null +++ b/negromate/web/static/js/libjass/build/typescript/index.ts @@ -0,0 +1,21 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { build } from "./compiler"; diff --git a/negromate/web/static/js/libjass/build/typescript/walker.ts b/negromate/web/static/js/libjass/build/typescript/walker.ts new file mode 100644 index 0000000..2b8943b --- /dev/null +++ b/negromate/web/static/js/libjass/build/typescript/walker.ts @@ -0,0 +1,888 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import path = require("path"); +import ts = require("typescript"); + +import { Compiler, oldGetLeadingCommentRangesOfNodeFromText } from "./compiler"; + +import * as AST from "./ast"; + +function hasModifier(node: ts.Node, flags: ts.NodeFlags): boolean { + return (node.flags & flags) !== 0; +} + +interface JSDoc { + description: string; + isAbstract: boolean; + parameters: { [name: string]: AST.Parameter }; + returnType: AST.ReturnType; + typeAnnotation: string; +} + +class WalkerScope { + private _scopes: AST.HasParent[] = []; + + get current(): AST.HasParent { + return (this._scopes.length > 0) ? this._scopes[this._scopes.length - 1] : null; + } + + enter(scope: T): T { + scope.parent = this.current; + this._scopes.push(scope); + return scope; + } + + leave(): void { + this._scopes.pop(); + } +} + +class Walker { + private _typeChecker: ts.TypeChecker; + private _globalNS: AST.Namespace = new AST.Namespace("Global"); + private _scope: WalkerScope = new WalkerScope(); + + private _currentSourceFile: ts.SourceFile; + + public modules: { [name: string]: AST.Module } = Object.create(null); + public namespaces: { [name: string]: AST.Namespace } = Object.create(null); + + constructor(private _compiler: Compiler) { + this._typeChecker = _compiler.typeChecker; + + this._globalNS.getMemberFullName = member => member.name; + } + + walk(sourceFile: ts.SourceFile): void { + const moduleName = this._moduleNameFromFileName(sourceFile.fileName); + + if (!(moduleName in this.modules)) { + this.modules[moduleName] = new AST.Module(moduleName); + } + + const module = this._scope.enter(this.modules[moduleName]); + this._currentSourceFile = sourceFile; + + for (const statement of sourceFile.statements) { + this._walk(statement, module); + } + + this._scope.leave(); + } + + private _walk(node: ts.Node, parent: AST.Module): void { + switch (node.kind) { + case ts.SyntaxKind.VariableStatement: + this._visitVariableStatement(node as ts.VariableStatement, parent); + break; + + case ts.SyntaxKind.FunctionDeclaration: + this._visitFunctionDeclaration(node as ts.FunctionDeclaration, parent); + break; + + case ts.SyntaxKind.ClassDeclaration: + this._visitClassDeclaration(node as ts.ClassDeclaration, parent); + break; + + case ts.SyntaxKind.InterfaceDeclaration: + this._visitInterfaceDeclaration(node as ts.InterfaceDeclaration, parent); + break; + + case ts.SyntaxKind.EnumDeclaration: + this._visitEnumDeclaration(node as ts.EnumDeclaration, parent); + break; + + case ts.SyntaxKind.ImportDeclaration: + this._visitImportDeclaration(node as ts.ImportDeclaration, parent); + break; + + case ts.SyntaxKind.ExportDeclaration: + this._visitExportDeclaration(node as ts.ExportDeclaration, parent); + break; + + case ts.SyntaxKind.ExpressionStatement: + case ts.SyntaxKind.ForOfStatement: + case ts.SyntaxKind.IfStatement: + case ts.SyntaxKind.TypeAliasDeclaration: + break; + + default: + console.error(node.kind, ts.SyntaxKind[node.kind], node); + throw new Error("Unrecognized node."); + } + } + + private _walkClassMember(node: ts.Node, clazz: AST.Class): void { + switch (node.kind) { + case ts.SyntaxKind.PropertySignature: + case ts.SyntaxKind.PropertyDeclaration: + this._visitProperty(node as ts.PropertyDeclaration, clazz); + break; + + case ts.SyntaxKind.MethodSignature: + case ts.SyntaxKind.MethodDeclaration: + this._visitMethod(node as ts.MethodDeclaration, clazz); + break; + + case ts.SyntaxKind.GetAccessor: + this._visitGetAccessor(node as ts.AccessorDeclaration, clazz); + break; + + case ts.SyntaxKind.SetAccessor: + this._visitSetAccessor(node as ts.AccessorDeclaration, clazz); + break; + + case ts.SyntaxKind.TypeParameter: + case ts.SyntaxKind.Parameter: + case ts.SyntaxKind.Constructor: + break; + + default: + console.error(node.kind, ts.SyntaxKind[node.kind], node); + throw new Error("Unrecognized node."); + } + } + + private _walkInterfaceMember(node: ts.Node, interfase: AST.Interface): void { + switch (node.kind) { + case ts.SyntaxKind.PropertySignature: + case ts.SyntaxKind.PropertyDeclaration: + this._visitProperty(node as ts.PropertyDeclaration, interfase); + break; + + case ts.SyntaxKind.MethodSignature: + case ts.SyntaxKind.MethodDeclaration: + this._visitMethod(node as ts.MethodDeclaration, interfase); + break; + + case ts.SyntaxKind.TypeParameter: + case ts.SyntaxKind.CallSignature: + case ts.SyntaxKind.ConstructSignature: + case ts.SyntaxKind.IndexSignature: + break; + + default: + console.error(node.kind, ts.SyntaxKind[node.kind], node); + throw new Error("Unrecognized node."); + } + } + + private _visitProperty(node: ts.PropertyDeclaration, parent: AST.Class | AST.Interface) { + if (hasModifier(node, ts.NodeFlags.Private)) { + return; + } + + const jsDoc = this._parseJSDoc(node); + + if (jsDoc.typeAnnotation === null) { + this._notifyIncorrectJsDoc(`Field ${ ts.getTextOfNode(node.name) } has no @type annotation.`); + jsDoc.typeAnnotation = "*"; + } + + const property = this._scope.enter(new AST.Property(ts.getTextOfNode(node.name))); + parent.members[property.name] = property; + property.getter = new AST.Getter(node, jsDoc.description, jsDoc.typeAnnotation, false); + property.setter = new AST.Setter(node, jsDoc.description, jsDoc.typeAnnotation, false); + this._scope.leave(); + } + + private _visitMethod(node: ts.MethodDeclaration, parent: AST.Class | AST.Interface) { + const jsDoc = this._parseJSDoc(node); + + const parameters = this._connectParameters(node.parameters, jsDoc.parameters, + parameterName => `Could not find @param annotation for ${ parameterName } on method ${ ts.getTextOfNode(node.name) }` + ); + + if (jsDoc.returnType === null && (node.type === undefined || node.type.kind !== ts.SyntaxKind.VoidKeyword)) { + this._notifyIncorrectJsDoc(`Missing @return annotation for method ${ ts.getTextOfNode(node.name) }`); + jsDoc.returnType = new AST.ReturnType("", "*"); + } + + const isPrivate = hasModifier(node, ts.NodeFlags.Private); + const isProtected = hasModifier(node, ts.NodeFlags.Protected); + const isStatic = hasModifier(node, ts.NodeFlags.Static); + + const generics = this._getGenericsOfSignatureDeclaration(node); + + const method = this._scope.enter(new AST.Function(ts.getTextOfNode(node.name), node, jsDoc.description, generics, parameters, jsDoc.returnType, jsDoc.isAbstract, isPrivate, isProtected, isStatic)); + parent.members[method.name] = method; + this._scope.leave(); + } + + private _visitGetAccessor(node: ts.AccessorDeclaration, clazz: AST.Class): void { + const jsDoc = this._parseJSDoc(node); + + const name = ts.getTextOfNode(node.name); + + const isPrivate = hasModifier(node, ts.NodeFlags.Private); + + let property = clazz.members[name] as AST.Property; + if (property === undefined) { + this._scope.enter(property = new AST.Property(name)); + + clazz.members[property.name] = property; + + this._scope.leave(); + } + + if (jsDoc.typeAnnotation === null) { + this._notifyIncorrectJsDoc(`Getter ${ name } has no @type annotation.`); + } + + property.getter = new AST.Getter(node, jsDoc.description, jsDoc.typeAnnotation, isPrivate); + } + + private _visitSetAccessor(node: ts.AccessorDeclaration, clazz: AST.Class): void { + const jsDoc = this._parseJSDoc(node); + + const name = ts.getTextOfNode(node.name); + + const isPrivate = hasModifier(node, ts.NodeFlags.Private); + + let property = clazz.members[name] as AST.Property; + if (property === undefined) { + this._scope.enter(property = new AST.Property(name)); + + clazz.members[property.name] = property; + + this._scope.leave(); + } + + if (jsDoc.typeAnnotation === null) { + this._notifyIncorrectJsDoc(`Setter ${ name } has no @type annotation.`); + } + + property.setter = new AST.Setter(node, jsDoc.description, jsDoc.typeAnnotation, isPrivate); + } + + private _visitVariableStatement(node: ts.VariableStatement, parent: AST.Module): void { + if (node.declarationList.declarations.length > 1) { + return; + } + + const declaration = node.declarationList.declarations[0]; + if (hasModifier(declaration, ts.NodeFlags.Ambient)) { + return; + } + + const jsDoc = this._parseJSDoc(node); + if (jsDoc.typeAnnotation === null) { + return; + } + + const property = this._scope.enter(new AST.Property(ts.getTextOfNode(declaration.name))); + property.getter = new AST.Getter(node, jsDoc.description, jsDoc.typeAnnotation, false); + + parent.members[property.name] = property; + + this._scope.leave(); + } + + private _visitFunctionDeclaration(node: ts.FunctionDeclaration, parent: AST.Module): void { + const jsDoc = this._parseJSDoc(node); + + const isPrivate = !hasModifier(node, ts.NodeFlags.Export); + + const generics = this._getGenericsOfSignatureDeclaration(node); + + const parameters = this._connectParameters(node.parameters, jsDoc.parameters, + parameterName => `Could not find @param annotation for ${ parameterName } on function ${ node.name.text }` + ); + + if (node.type === undefined) { + this._notifyIncorrectJsDoc(`Missing return type annotation for function ${ node.name.text }`); + jsDoc.returnType = new AST.ReturnType("", "*"); + } + else if (jsDoc.returnType === null && node.type.kind !== ts.SyntaxKind.VoidKeyword) { + this._notifyIncorrectJsDoc(`Missing @return annotation for function ${ node.name.text }`); + jsDoc.returnType = new AST.ReturnType("", "*"); + } + + const freeFunction = this._scope.enter(new AST.Function(node.name.text, node, jsDoc.description, generics, parameters, jsDoc.returnType, jsDoc.isAbstract, isPrivate, false, false)); + + parent.members[freeFunction.name] = freeFunction; + + this._scope.leave(); + } + + private _visitClassDeclaration(node: ts.ClassDeclaration, parent: AST.Module): void { + const jsDoc = this._parseJSDoc(node); + + const type = this._typeChecker.getTypeAtLocation(node) as ts.InterfaceType; + + const generics = this._getGenericsOfInterfaceType(type); + + const baseTypeHeritageClauseElement = ts.getClassExtendsHeritageClauseElement(node) || null; + let baseType: AST.UnresolvedType = null; + if (baseTypeHeritageClauseElement !== null) { + baseType = new AST.UnresolvedType( + this._typeChecker.getTypeAtLocation(baseTypeHeritageClauseElement).symbol, + this._getGenericsOfTypeReferenceNode(baseTypeHeritageClauseElement, generics) + ); + } + + const interfaces = (ts.getClassImplementsHeritageClauseElements(node) || []).map(type => new AST.UnresolvedType( + this._typeChecker.getTypeAtLocation(type).symbol, + this._getGenericsOfTypeReferenceNode(type, generics) + )); + + const isPrivate = !hasModifier(node, ts.NodeFlags.Export); + + let parameters: AST.Parameter[] = []; + + if (type.symbol.members["__constructor"] !== undefined) { + parameters = this._connectParameters((type.symbol.members["__constructor"].declarations[0] as ts.ConstructorDeclaration).parameters, jsDoc.parameters, + parameterName => `Could not find @param annotation for ${ parameterName } on constructor in class ${ node.name.text }` + ); + } + else if (Object.keys(jsDoc.parameters).length > 0) { + this._notifyIncorrectJsDoc("There are @param annotations on this class but it has no constructors."); + } + + const clazz = this._scope.enter(new AST.Class(node.name.text, node, jsDoc.description, generics, parameters, baseType, interfaces, jsDoc.isAbstract, isPrivate)); + + parent.members[clazz.name] = clazz; + + ts.forEachProperty(type.symbol.exports, symbol => { + if (symbol.name === "prototype") { + return; + } + + for (const declaration of symbol.declarations) { + this._walkClassMember(declaration, clazz); + } + }); + + ts.forEachProperty(type.symbol.members, symbol => { + for (const declaration of symbol.declarations) { + this._walkClassMember(declaration, clazz); + } + }); + + this._scope.leave(); + } + + private _visitInterfaceDeclaration(node: ts.InterfaceDeclaration, parent: AST.Module): void { + const jsDoc = this._parseJSDoc(node); + + const type = this._typeChecker.getTypeAtLocation(node) as ts.InterfaceType; + + const generics = this._getGenericsOfInterfaceType(type); + + const baseTypes = (ts.getInterfaceBaseTypeNodes(node) || []).map(type => new AST.UnresolvedType( + this._typeChecker.getTypeAtLocation(type).symbol, + this._getGenericsOfTypeReferenceNode(type, generics) + )); + + const existingInterfaceType = parent.members[node.name.text]; + if (existingInterfaceType !== undefined) { + return; + } + + const isPrivate = !hasModifier(node, ts.NodeFlags.Export); + + const interfase = this._scope.enter(new AST.Interface(node.name.text, node, jsDoc.description, generics, baseTypes, isPrivate)); + parent.members[interfase.name] = interfase; + + ts.forEachProperty(type.symbol.members, symbol => { + for (const declaration of symbol.declarations) { + this._walkInterfaceMember(declaration, interfase); + } + }); + + this._scope.leave(); + } + + private _visitEnumDeclaration(node: ts.EnumDeclaration, parent: AST.Module): void { + const jsDoc = this._parseJSDoc(node); + + const existingEnumType = parent.members[node.name.text]; + if (existingEnumType !== undefined) { + return; + } + + const isPrivate = !hasModifier(node, ts.NodeFlags.Export); + + const type = this._typeChecker.getTypeAtLocation(node); + + const enumType = this._scope.enter(new AST.Enum(node.name.text, node, jsDoc.description, isPrivate)); + parent.members[enumType.name] = enumType; + + ts.forEachProperty(type.symbol.exports, symbol => { + this._visitEnumMember(symbol.declarations[0] as ts.EnumMember, enumType); + }); + + this._scope.leave(); + } + + private _visitEnumMember(node: ts.EnumMember, parent: AST.Enum): void { + const jsDoc = this._parseJSDoc(node); + + const value = (node.initializer === undefined) ? null : parseInt((node.initializer as ts.LiteralExpression).text); + + const enumMember = this._scope.enter(new AST.EnumMember(ts.getTextOfNode(node.name), (jsDoc === null) ? "" : jsDoc.description, value)); + + parent.members.push(enumMember); + + this._scope.leave(); + } + + private _visitImportDeclaration(node: ts.ImportDeclaration, parent: AST.Module): void { + if (node.importClause === undefined) { + // import "foo"; + return; + } + + if (node.importClause.namedBindings === undefined) { + throw new Error("Default import is not supported."); + } + + const moduleName = this._resolve((node.moduleSpecifier as ts.LiteralExpression).text, parent); + + if ((node.importClause.namedBindings as ts.NamespaceImport).name !== undefined) { + // import * as foo from "baz"; + parent.members[(node.importClause.namedBindings as ts.NamespaceImport).name.text] = new AST.Reference(moduleName, "*", true); + } + else if ((node.importClause.namedBindings as ts.NamedImports).elements !== undefined) { + // import { foo, bar } from "baz"; + for (const element of (node.importClause.namedBindings as ts.NamedImports).elements) { + const importedName = element.propertyName && element.propertyName.text || element.name.text; + parent.members[element.name.text] = new AST.Reference(moduleName, importedName, true); + } + } + else { + throw new Error("Unrecognized import declaration syntax."); + } + } + + private _visitExportDeclaration(node: ts.ExportDeclaration, parent: AST.Module): void { + if (node.moduleSpecifier !== undefined) { + // export { foo } from "bar"; + const moduleName = this._resolve((node.moduleSpecifier as ts.LiteralExpression).text, parent); + for (const element of node.exportClause.elements) { + const importedName = element.propertyName && element.propertyName.text || element.name.text; + parent.members[element.name.text] = new AST.Reference(moduleName, importedName, false); + } + } + else { + // export { foo }; + for (const element of node.exportClause.elements) { + (parent.members[element.name.text] as AST.CanBePrivate).isPrivate = false; + } + } + } + + private _resolve(relativeModuleName: string, currentModule: AST.Module): string { + let result = ts.normalizeSlashes(path.join(currentModule.name, `../${ relativeModuleName }`)); + + if (result[0] !== ".") { + result = `./${ result }`; + } + + return result; + } + + private _parseJSDoc(node: ts.Node): JSDoc { + let comments = oldGetLeadingCommentRangesOfNodeFromText(node, this._currentSourceFile.text); + + if (comments === undefined) { + comments = []; + } + + if (comments.length > 1) { + comments = [comments[comments.length - 1]]; + } + + const comment = + (comments.length === 0) ? + "" : + this._currentSourceFile.text.substring(comments[0].pos, comments[0].end); + + const commentStartIndex = comment.indexOf("/**"); + const commentEndIndex = comment.lastIndexOf("*/"); + + const lines = + (commentStartIndex === -1 || commentEndIndex === -1) ? + [] : + comment.substring(commentStartIndex + 2, commentEndIndex).split("\n").map(line => { + const match = line.match(/^[ \t]*\* (.*)/); + if (match === null) { + return ""; + } + return match[1]; + }); + + let rootDescription = ""; + + const parameters: { [name: string]: AST.Parameter } = Object.create(null); + + let typeAnnotation: string = null; + + let returnType: AST.ReturnType = null; + + let isAbstract = false; + + let lastRead: { description: string } = null; + + for (const line of lines) { + const firstWordMatch = line.match(/^\s*(\S+)(\s*)/); + const firstWord = (firstWordMatch !== null) ? firstWordMatch[1] : ""; + let remainingLine = (firstWordMatch !== null) ? line.substring(firstWordMatch[0].length) : ""; + + if (firstWord[0] === "@") { + lastRead = null; + } + + switch (firstWord) { + case "@abstract": + isAbstract = true; + break; + + case "@param": { + let type: string; + [type, remainingLine] = this._readType(remainingLine); + + const [, name, description] = remainingLine.match(/(\S+)\s*(.*)/); + + const subParameterMatch = name.match(/^(?:(.+)\.([^\.]+))|(?:(.+)\[("[^\[\]"]+")\])$/); + if (subParameterMatch === null) { + parameters[name] = lastRead = new AST.Parameter(name, description, type); + } + else { + const parentName = subParameterMatch[1] || subParameterMatch[3]; + const childName = subParameterMatch[2] || subParameterMatch[4]; + const parentParameter = parameters[parentName]; + parentParameter.subParameters.push(lastRead = new AST.Parameter(childName, description, type)); + } + + break; + } + + case "@return": { + const [type, description] = this._readType(remainingLine); + + returnType = lastRead = new AST.ReturnType(description, type); + + break; + } + + case "@type": + [typeAnnotation] = this._readType(remainingLine); + break; + + default: + if (lastRead !== null) { + lastRead.description += "\n" + line; + } + else { + rootDescription += ((rootDescription.length > 0) ? "\n" : "") + line; + } + break; + } + } + + return { + description: rootDescription, + isAbstract: isAbstract, + parameters: parameters, + returnType: returnType, + typeAnnotation: typeAnnotation, + }; + } + + private _readType(remainingLine: string): [string, string] { + if (remainingLine[0] !== "{") { + return ["*", remainingLine]; + } + + let index = -1; + let numberOfUnterminatedBraces = 0; + for (let i = 0; i < remainingLine.length; i++) { + if (remainingLine[i] === "{") { + numberOfUnterminatedBraces++; + } + else if (remainingLine[i] === "}") { + numberOfUnterminatedBraces--; + + if (numberOfUnterminatedBraces === 0) { + index = i; + break; + } + } + } + + if (index === -1) { + throw new Error("Unterminated type specifier."); + } + + const type = remainingLine.substr(1, index - 1); + remainingLine = remainingLine.substr(index + 1).replace(/^\s+/, ""); + + return [type, remainingLine]; + } + + private _getGenericsOfSignatureDeclaration(signatureDeclaration: ts.SignatureDeclaration): string[] { + if (signatureDeclaration.typeParameters === undefined) { + return []; + } + + return signatureDeclaration.typeParameters.map(typeParameter => typeParameter.name.text); + } + + private _getGenericsOfTypeReferenceNode(typeReferenceNode: ts.ExpressionWithTypeArguments, intrinsicGenerics: string[]): (AST.UnresolvedType | AST.IntrinsicTypeReference)[] { + if (typeReferenceNode.typeArguments === undefined) { + return []; + } + + const typeReference = this._typeChecker.getTypeAtLocation(typeReferenceNode) as ts.TypeReference; + + return typeReference.typeArguments.map(typeArgument => { + if ((typeArgument as ts.IntrinsicType).intrinsicName !== undefined) { + return new AST.IntrinsicTypeReference((typeArgument as ts.IntrinsicType).intrinsicName); + } + + if (typeArgument.flags & ts.TypeFlags.TypeParameter) { + if (intrinsicGenerics.indexOf(typeArgument.symbol.name) !== -1) { + return new AST.IntrinsicTypeReference(typeArgument.symbol.name); + } + + throw new Error(`Unbound type parameter ${ typeArgument.symbol.name }`); + } + + return new AST.UnresolvedType(typeArgument.symbol, []); + }); + } + + private _getGenericsOfInterfaceType(interfaceType: ts.InterfaceType): string[] { + if (interfaceType.typeParameters === undefined) { + return []; + } + + return interfaceType.typeParameters.map(typeParameter => { + return typeParameter.symbol.name; + }); + } + + private _connectParameters(astParameters: ts.ParameterDeclaration[], jsDocParameters: { [name: string]: AST.Parameter }, onMissingMessageCallback: (parameterName: string) => string) { + return astParameters.map(parameter => { + let parameterName = (parameter.name as ts.Identifier).text; + if (parameterName[0] === "_") { + parameterName = parameterName.substr(1); + } + + let jsDocParameter = jsDocParameters[parameterName]; + + if (jsDocParameter === undefined) { + this._notifyIncorrectJsDoc(onMissingMessageCallback.call(this, parameterName)); + jsDocParameter = new AST.Parameter(parameterName, "*", ""); + } + + return jsDocParameter; + }); + } + + private _notifyIncorrectJsDoc(message: string): void { + const fileName = path.basename(this._currentSourceFile.fileName); + if (fileName === "lib.es5.d.ts" || fileName === "lib.dom.d.ts") { + return; + } + + throw new Error(`${ fileName }: ${ this._scope.current.fullName }: ${ message }`); + } + + link(rootNamespaceName: string): void { + for (const moduleName of Object.keys(this.modules)) { + const module = this.modules[moduleName]; + + for (const memberName of Object.keys(module.members)) { + const member = module.members[memberName]; + + if (member instanceof AST.Class) { + if (member.unresolvedBaseType instanceof AST.UnresolvedType) { + member.baseType = this._resolveTypeReference(member.unresolvedBaseType); + } + else { + member.baseType = member.unresolvedBaseType; + } + + member.interfaces = member.unresolvedInterfaces.map(interfase => { + if (interfase instanceof AST.UnresolvedType) { + return this._resolveTypeReference(interfase); + } + + return interfase; + }); + } + + else if (member instanceof AST.Interface) { + member.baseTypes = member.unresolvedBaseTypes.map(baseType => { + if (baseType instanceof AST.UnresolvedType) { + return this._resolveTypeReference(baseType); + } + + return baseType; + }); + } + + else if (member instanceof AST.Enum) { + let value = 0; + for (const enumMember of member.members) { + if (enumMember.value === null) { + enumMember.value = value; + } + else { + value = enumMember.value; + } + + value++; + } + } + } + } + + this.namespaces[rootNamespaceName] = this._scope.enter(new AST.Namespace(rootNamespaceName)); + this._moduleToNamespace(this.modules["./index"]); + this._scope.leave(); + } + + private _moduleToNamespace(module: AST.Module): void { + for (const memberName of Object.keys(module.members)) { + let member = module.members[memberName]; + + if (member instanceof AST.Reference) { + if (member.isPrivate) { + continue; + } + + if (member.name === "*") { + const newNamespace = this._scope.enter(new AST.Namespace(memberName)); + + const existingNamespace = this.namespaces[newNamespace.fullName]; + if (existingNamespace !== undefined) { + this._scope.leave(); + this._scope.enter(existingNamespace); + } + else { + this.namespaces[newNamespace.fullName] = newNamespace; + } + + let referencedModuleName = member.moduleName; + let referencedModule = this.modules[referencedModuleName]; + if (referencedModule === undefined && ((referencedModuleName + "/index") in this.modules)) { + member.moduleName = referencedModuleName = referencedModuleName + "/index"; + referencedModule = this.modules[referencedModuleName]; + } + this._moduleToNamespace(referencedModule); + + this._scope.leave(); + } + else { + while (member instanceof AST.Reference) { + member = this.modules[member.moduleName].members[member.name]; + } + + this._scope.enter(member); + this._scope.leave(); + (this._scope.current as AST.Namespace).members[member.name] = member; + } + } + else if (!(member as AST.CanBePrivate).isPrivate) { + this._scope.enter(member); + this._scope.leave(); + (this._scope.current as AST.Namespace).members[member.name] = member; + } + } + } + + private _resolveTypeReference(unresolvedType: AST.UnresolvedType): AST.TypeReference | AST.IntrinsicTypeReference { + let node: ts.Node = unresolvedType.symbol.declarations[0]; + while (node.kind !== ts.SyntaxKind.SourceFile) { + node = node.parent; + } + + const sourceFile = node as ts.SourceFile; + + if (sourceFile.fileName.substr(-"globals.d.ts".length) === "globals.d.ts") { + return new AST.IntrinsicTypeReference(unresolvedType.symbol.name); + } + else { + const moduleName = this._moduleNameFromFileName(sourceFile.fileName); + const module = this.modules[moduleName]; + + let result = module.members[unresolvedType.symbol.name]; + + if (result === undefined) { + throw new Error(`Type ${unresolvedType.symbol.name} could not be resolved.`); + } + + while (result instanceof AST.Reference) { + result = this.modules[result.moduleName].members[result.name]; + } + + const resultGenerics = unresolvedType.generics.map(generic => { + if (generic instanceof AST.UnresolvedType) { + return this._resolveTypeReference(generic); + } + + return generic; + }); + + return new AST.TypeReference(result, resultGenerics); + } + } + + private _moduleNameFromFileName(fileName: string): string { + let result = ts.normalizeSlashes(path.relative(this._compiler.projectRoot, fileName)); + + result = result.substr(0, result.length - ".ts".length); + + if (result[0] !== ".") { + result = `./${ result }`; + } + + return result; + } +} + +export function walk(compiler: Compiler, root: string, rootNamespaceName: string) { + const sourceFiles = compiler.sourceFiles; + + const walker = new Walker(compiler); + + // Walk + for (const sourceFile of sourceFiles) { + if ( + path.basename(sourceFile.fileName) === "lib.es5.d.ts" || + path.basename(sourceFile.fileName) === "lib.dom.d.ts" || + sourceFile.fileName.substr(-"globals.d.ts".length) === "globals.d.ts" + ) { + continue; + } + + walker.walk(sourceFile); + } + + // Link base types and set enum member values if unspecified. + walker.link(rootNamespaceName); + + // Return types + return { namespaces: walker.namespaces, modules: walker.modules }; +} diff --git a/negromate/web/static/js/libjass/build/uglify.js b/negromate/web/static/js/libjass/build/uglify.js new file mode 100644 index 0000000..78e9cde --- /dev/null +++ b/negromate/web/static/js/libjass/build/uglify.js @@ -0,0 +1,447 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var fs = require("fs"); +var path = require("path"); + +var UglifyJS = require("uglify-js"); + +var FileTransform = require("async-build").FileTransform; + +var Run = (function () { + function Run(outputLibraryName, unusedVarsToIgnore) { + this._outputLibraryName = outputLibraryName; + this._unusedVarsToIgnore = unusedVarsToIgnore; + + this._root = UglifyJS.parse(fs.readFileSync(path.resolve(__filename, "..", "umd-wrapper.js"), "utf8")); + + this._root.figure_out_scope({ screw_ie8: true }); + + this._toInsert = null; + + this._rootSourceMap = null; + } + + Run.prototype.addFile = function (file) { + switch (path.extname(file.path)) { + case ".js": + try { + this._toInsert = UglifyJS.parse(file.contents.toString(), { + filename: path.basename(file.path), + toplevel: null, + }).body; + } + catch (ex) { + if (ex instanceof UglifyJS.JS_Parse_Error) { + throw new Error("UglifyJS parse error: " + ex.toString() + "\n"); + } + + throw ex; + } + break; + + case ".map": + var rawSourceMap = JSON.parse(file.contents.toString()); + + this._rootSourceMap = UglifyJS.SourceMap({ + file: this._outputLibraryName + ".js", + root: "", + orig: rawSourceMap, + }); + + var generator = this._rootSourceMap.get(); + + rawSourceMap.sources.forEach(function (sourceRelativePath, index) { + generator.setSourceContent(sourceRelativePath, rawSourceMap.sourcesContent[index]); + }); + + break; + } + }; + + Run.prototype.build = function (outputStream) { + var _this = this; + + + // Splice in the TS output into the UMD wrapper. + var insertionParent = this._root.body[0].body.args[1].body; + + this._toInsert.reverse(); + for (var i = this._toInsert.length - 1; i >= 0; i--) { + var node = this._toInsert[i]; + if (node instanceof UglifyJS.AST_Var) { + for (var j = 0; j < node.definitions.length; j++) { + var definition = node.definitions[j]; + if (definition.name.name === "__extends" || definition.name.name === "__decorate") { + definition.value = definition.value.right; + } + } + + insertionParent.splice(-1, 0, node); + this._toInsert.splice(i, 1); + } + } + + insertionParent.splice.apply(insertionParent, [-1, 0].concat(this._toInsert)); + + + // Fixups + for (var i = 0; i < this._toInsert.length; i++) { + var node = this._toInsert[i]; + if (node instanceof UglifyJS.AST_Statement && node.body instanceof UglifyJS.AST_Call && node.body.expression.name === "define") { + var defineCall = node.body; + + defineCall.expression.name = "def"; + + if (defineCall.args[1].elements[0].value !== "require") { + throw new Error("Expected first dep to be require"); + } + defineCall.args[1].elements.shift(); + defineCall.args[2].argnames.shift(); + + if (defineCall.args[1].elements[0].value !== "exports") { + throw new Error("Expected second dep to be exports"); + } + defineCall.args[1].elements.shift(); + defineCall.args[2].argnames.push(defineCall.args[2].argnames.shift()); + } + } + + + // Remove all license headers except the one from the UMD wrapper + var firstLicenseHeader = null; + this._root.walk(new UglifyJS.TreeWalker(function (node, descend) { + if (node.start) { + (node.start.comments_before || []).some(function (comment, i) { + if (comment.value.indexOf("Copyright") !== -1) { + if (firstLicenseHeader === null) { + firstLicenseHeader = comment; + } + else if (comment !== firstLicenseHeader) { + node.start.comments_before.splice(i, 1); + } + + return true; + } + + return false; + }); + } + })); + + + // Fixup anonymous functions to print a space after "function" + this._root.walk(new UglifyJS.TreeWalker(function (node, descend) { + if (node instanceof UglifyJS.AST_Lambda && !node.name) { + node.name = Object.create(UglifyJS.AST_Node.prototype); + node.name.print = function () { }; + } + })); + + + // Fix alignment of multi-line block comments + this._root.walk(new UglifyJS.TreeWalker(function (node, descend) { + if (node.start && node.start.comments_before) { + node.start.comments_before.forEach(function (comment) { + if (comment.value.indexOf("Copyright") !== -1) { + return; + } + + var lines = comment.value.split("\n"); + if (lines.length < 2) { + return; + } + + var indent = " "; // 5 spaces + for (var i = 0; i < comment.col; i++) { + indent += " "; + } + lines[lines.length - 1] = lines[lines.length - 1].replace(/\s+$/, indent); + comment.value = [lines[0]].concat(lines.slice(1).map(function (line) { return line.replace(/^\s+/, indent); })).join("\n"); + }); + } + })); + + + this._root.figure_out_scope({ screw_ie8: true }); + + + // Remove some things from the AST + var nodesToRemove = []; + + // Set if there are any unused variables apart from the ones in unusedVarsToIgnore + var haveUnusedVars = false; + + // Repeat because removing some declarations may make others unreferenced + for (;;) { + this._root.figure_out_scope({ screw_ie8: true }); + + // Unreferenced variable and function declarations, and unreferenced terminal function arguments + this._root.walk(new UglifyJS.TreeWalker(function (node, descend) { + if (node instanceof UglifyJS.AST_SymbolDeclaration && node.unreferenced()) { + if (node instanceof UglifyJS.AST_SymbolFunarg) { + if (this.parent().argnames.indexOf(node) === this.parent().argnames.length - 1) { + nodesToRemove.push({ node: node, parent: this.parent().argnames }); + } + } + else if (node instanceof UglifyJS.AST_SymbolVar) { + if (_this._unusedVarsToIgnore.indexOf(node.name) !== -1) { + nodesToRemove.push({ node: this.parent(), parent: this.parent(1).definitions }); + if (this.parent(1).definitions.length === 1) { + nodesToRemove.push({ node: this.parent(1), parent: this.parent(2).body }); + } + } + else { + haveUnusedVars = true; + } + } + else if (node instanceof UglifyJS.AST_SymbolDefun) { + nodesToRemove.push({ node: this.parent(), parent: this.parent(1).body }); + } + } + })); + + if (nodesToRemove.length === 0) { + break; + } + + nodesToRemove.forEach(function (tuple) { + tuple.parent.splice(tuple.parent.indexOf(tuple.node), 1); + }); + + nodesToRemove = []; + } + + + // Move var statements at the end of blocks (generated by TS for rest parameters) to the start of the block. + // This is needed to prevent unreachable-code warnings from UJS + this._root.walk(new UglifyJS.TreeWalker(function (node, descend) { + if ( + node instanceof UglifyJS.AST_Block && + node.body[node.body.length - 1] instanceof UglifyJS.AST_Var + ) { + node.body.unshift(node.body.pop()); + } + })); + + + // Split multiple vars per declaration into one var per declaration + this._root.walk(new UglifyJS.TreeWalker(function (node, descend) { + if ( + node instanceof UglifyJS.AST_Var && + node.definitions.length > 1 && + this.parent() instanceof UglifyJS.AST_Block + ) { + var parent = this.parent().body; + parent.splice.apply(parent, [parent.indexOf(node), 1].concat(node.definitions.map(function (definition) { + return new UglifyJS.AST_Var({ start: node.start, end: node.end, definitions: [definition] }); + }))); + } + })); + + + // Rename all function arguments that begin with _ to not have the _. + // This converts the TypeScript syntax of declaring private members in the constructor declaration `function Color(private _red: number, ...)` to `function Color(red, ...)` + // so that it matches the JSDoc (and looks nicer). + this._root.walk(new UglifyJS.TreeWalker(function (node, descend) { + if ( + node instanceof UglifyJS.AST_SymbolFunarg && + node.thedef.name[0] === "_" && + node.thedef.name[1] !== "_" && + node.thedef.name !== "_super" // Don't rename _super (used in TypeScript's inheritance shim) to super. super is a reserved word. + ) { + node.thedef.name = node.thedef.name.slice(1); + } + })); + + + // Output + var output = { + source_map: this._rootSourceMap, + ascii_only: true, + beautify: true, + comments: function (node, comment) { + return comment.value.indexOf("tslint") === -1; + }, + }; + + var stream = UglifyJS.OutputStream(output); + this._root.print(stream); + + outputStream.push({ + path: this._outputLibraryName + ".js", + contents: Buffer.concat([new Buffer(stream.toString()), new Buffer("\n//# sourceMappingURL=" + this._outputLibraryName + ".js.map")]) + }); + + outputStream.push({ + path: this._outputLibraryName + ".js.map", + contents: new Buffer(this._rootSourceMap.get().toString()) + }); + + // Print unused variables + if (haveUnusedVars) { + this._root.walk(new UglifyJS.TreeWalker(function (node, descend) { + if (node instanceof UglifyJS.AST_SymbolVar && node.unreferenced()) { + if (_this._unusedVarsToIgnore.indexOf(node.name) === -1) { + console.warn("Unused variable %s at %s:%s:%s", node.name, node.start.file, node.start.line, node.start.col); + } + } + })); + } + }; + + return Run; +})(); + +module.exports = { + build: function (outputLibraryName, unusedVarsToIgnore) { + var run = new Run(outputLibraryName, unusedVarsToIgnore); + + return new FileTransform(function (file) { + run.addFile(file); + }, function () { + run.build(this); + }); + }, + + watch: function (outputLibraryName, unusedVarsToIgnore) { + var files = Object.create(null); + + return new FileTransform(function (file) { + if (file.path !== "END") { + files[file.path] = file; + } + else { + var run = new Run(outputLibraryName, unusedVarsToIgnore); + Object.keys(files).forEach(function (filename) { + run.addFile(files[filename]); + }); + run.build(this); + } + }); + }, + + minify: function () { + var codeFile = null; + var sourceMapFile = null; + + return new FileTransform(function (file) { + switch (path.extname(file.path)) { + case ".js": + codeFile = file; + break; + case ".map": + sourceMapFile = file; + break; + } + + if (codeFile !== null && sourceMapFile !== null) { + UglifyJS.base54.reset(); + + + // Parse + var root = null; + root = UglifyJS.parse(codeFile.contents.toString(), { + filename: path.basename(codeFile.path), + toplevel: root + }); + + root.figure_out_scope({ screw_ie8: true }); + + + // Warnings + root.scope_warnings({ + func_arguments: false + }); + + + // Compress + var compressor = UglifyJS.Compressor({ + warnings: true, + screw_ie8: true + }); + root = root.transform(compressor); + + + // Mangle + root.figure_out_scope({ screw_ie8: true }); + root.compute_char_frequency(); + root.mangle_names({ screw_ie8: true }); + root = UglifyJS.mangle_properties(root, { + regex: /^_/ + }); + + + // Output + var firstLicenseHeaderFound = false; // To detect and preserve the first license header + + var output = { + source_map: UglifyJS.SourceMap({ + file: path.basename(sourceMapFile.path), + orig: sourceMapFile.contents.toString() + }), + ascii_only: true, + comments: function (node, comment) { + if (!firstLicenseHeaderFound && comment.value.indexOf("Copyright") !== -1) { + firstLicenseHeaderFound = true; + + return true; + } + + return false; + }, + screw_ie8: true + }; + + var stream = UglifyJS.OutputStream(output); + root.print(stream); + + codeFile.path = codeFile.path.replace(/\.js$/, ".min.js"); + sourceMapFile.path = sourceMapFile.path.replace(/\.js\.map$/, ".min.js.map"); + + codeFile.contents = Buffer.concat([new Buffer(stream.toString()), new Buffer("\n//# sourceMappingURL="), new Buffer(sourceMapFile.path)]); + this.push(codeFile); + + var inputSourceMapObject = JSON.parse(sourceMapFile.contents.toString()); + var outputSourceMapObject = output.source_map.get(); + outputSourceMapObject._sources.toArray().forEach(function (filename, i) { + outputSourceMapObject.setSourceContent(filename, inputSourceMapObject.sourcesContent[i]); + }); + + sourceMapFile.contents = new Buffer(output.source_map.toString()); + this.push(sourceMapFile); + + codeFile = null; + sourceMapFile = null; + } + }); + } +}; + +var originalSymbolUnreferenced = UglifyJS.AST_Symbol.prototype.unreferenced; + +// Workaround for https://github.com/mishoo/UglifyJS2/issues/789 - Nodes explicitly marked with ujs:unreferenced will not be warned for. +UglifyJS.AST_Symbol.prototype.unreferenced = function () { + if (this.start.comments_before.length > 0 && this.start.comments_before[0].value.trim() === "ujs:unreferenced") { + return false; + } + + return originalSymbolUnreferenced.call(this); +}; diff --git a/negromate/web/static/js/libjass/build/umd-wrapper.js b/negromate/web/static/js/libjass/build/umd-wrapper.js new file mode 100644 index 0000000..9bb3c8e --- /dev/null +++ b/negromate/web/static/js/libjass/build/umd-wrapper.js @@ -0,0 +1,65 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @license + */ + +(function (root, factory) { + var global = this; + + if (typeof define === "function" && define.amd) { + define([], function() { + return factory(global); + }); + } + else if (typeof exports === "object" && typeof module === "object") { + module.exports = factory(global); + } + else if (typeof exports === "object") { + exports.libjass = factory(global); + } + else { + root.libjass = factory(global); + } +})(this, function (global) { + "use strict"; + + var registeredModules = Object.create(null); + var installedModules = Object.create(null); + + function def(moduleId, deps, body) { + installedModules[moduleId] = { deps: deps, body: body, }; + } + + function req(moduleId) { + if (moduleId in registeredModules) { + return registeredModules[moduleId]; + } + + var exports = registeredModules[moduleId] = Object.create(null); + var deps = installedModules[moduleId].deps.map(req); + deps.push(exports); + + installedModules[moduleId].body.apply(null, deps); + + return exports; + } + + return req("index"); +}); diff --git a/negromate/web/static/js/libjass/package.json b/negromate/web/static/js/libjass/package.json new file mode 100644 index 0000000..ff89065 --- /dev/null +++ b/negromate/web/static/js/libjass/package.json @@ -0,0 +1,44 @@ +{ + "name": "libjass", + "version": "0.12.0", + "description": "A library to render ASS subtitles on HTML5 video in the browser.", + "keywords": [ + "browser", + "html5", + "subtitles" + ], + "homepage": "https://github.com/Arnavion/libjass", + "bugs": "https://github.com/Arnavion/libjass/issues", + "license": "Apache-2.0", + "contributors": [ + { + "name": "Arnav Singh", + "email": "arnavion@gmail.com" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/Arnavion/libjass" + }, + "main": "lib/libjass.js", + "scripts": { + "prepublish": "node ./build.js clean default", + "build": "tsc -p ./build/tsconfig.json", + "test": "node ./build.js test", + "test-lib": "intern-client config=tests/intern reporters=Pretty", + "test-minified": "intern-client config=tests/intern reporters=Pretty minified=true", + "test-browser": "intern-runner config=tests/intern", + "test-doc": "intern-client config=tests/intern-doc reporters=Pretty" + }, + "devDependencies": { + "async": "1.x >=1.4", + "async-build": "0.3.1", + "intern": "3.x >=3.2.0", + "npm": "4.x", + "pngjs": "3.x", + "sax": "1.x", + "typescript": "2.0.10", + "uglify-js": "2.x >=2.4.24" + }, + "private": true +} diff --git a/negromate/web/static/js/libjass/src/globals.d.ts b/negromate/web/static/js/libjass/src/globals.d.ts new file mode 100644 index 0000000..1e5b1b5 --- /dev/null +++ b/negromate/web/static/js/libjass/src/globals.d.ts @@ -0,0 +1,163 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface Array { + filter(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; +} + +interface WorkerGlobalScope { + postMessage(message: any): void; + addEventListener(type: string, listener: (message: any) => void, useCapture: boolean): void; +} + +interface FontFace { + family: string; + load(): Promise; +} + +interface FontFaceSet { + add(fontFace: FontFace): FontFaceSet; + forEach(callbackfn: (fontFace: FontFace, index: FontFace, set: FontFaceSet) => void, thisArg?: any): void; +} + +interface Map { + size: number; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; + delete(key: K): boolean; + clear(): void; + forEach(callbackfn: (value: V, index: K, map: this) => void, thisArg?: any): void; +} + +interface Node { + cloneNode(deep?: boolean): this; +} + +interface Promise extends Thenable { + then(onFulfilled: (value: T) => Thenable, onRejected?: (reason: any) => U | Thenable): Promise; + /* tslint:disable-next-line:unified-signatures */ + then(onFulfilled: (value: T) => U, onRejected?: (reason: any) => U | Thenable): Promise; + catch(onRejected: (reason: any) => T | Thenable): Promise; +} + +interface ReadableStream { + getReader(): ReadableStreamReader; +} + +interface ReadableStreamReader { + read(): Promise<{ value: Uint8Array; done: boolean; }>; +} + +interface Set { + size: number; + add(value: T): this; + clear(): void; + has(value: T): boolean; + forEach(callbackfn: (value: T, index: T, set: this) => void, thisArg?: any): void; +} + +interface SVGFEComponentTransferElement { + appendChild(newChild: SVGFEFuncAElement): SVGFEFuncAElement; + appendChild(newChild: SVGFEFuncBElement): SVGFEFuncBElement; + appendChild(newChild: SVGFEFuncGElement): SVGFEFuncGElement; + appendChild(newChild: SVGFEFuncRElement): SVGFEFuncRElement; +} + +interface SVGFEMergeElement { + appendChild(newChild: SVGFEMergeNodeElement): SVGFEMergeNodeElement; +} + +interface TextDecoder { + decode(input: ArrayBuffer | ArrayBufferView, options: { stream: boolean }): string; +} + +interface Thenable { + then: ThenableThen; +} + +type ThenableThen = (this: Thenable, resolve: ((resolution: T | Thenable) => void) | undefined, reject: ((reason: any) => void) | undefined) => void; + +/** + * The interface implemented by a communication channel to the other side. + */ +interface WorkerCommunication { + addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void; + addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; + postMessage(message: any): void; +} + +declare const exports: any; + +declare const global: (WorkerGlobalScope) & { + FontFace?: { + new (family: string, source: string): FontFace; + }; + + Map?: { + new (iterable?: [K, V][]): Map; + /* tslint:disable-next-line:member-ordering */ + prototype: Map | { forEach: undefined }; + }; + + MutationObserver?: typeof MutationObserver; + + Promise?: { + new (init: (resolve: (value: T | Thenable) => void, reject: (reason: any) => void) => void): Promise; + /* tslint:disable-next-line:member-ordering */ + prototype: Promise; + resolve(value: T | Thenable): Promise; + reject(reason: any): Promise; + all(values: (T | Thenable)[]): Promise; + race(values: (T | Thenable)[]): Promise; + }; + + ReadableStream?: { + prototype: ReadableStream | { getReader: undefined; }; + }; + + Set?: { + new (iterable?: T[]): Set; + /* tslint:disable-next-line:member-ordering */ + prototype: Set | { forEach: undefined }; + }; + + TextDecoder?: { new (encoding: string, options: { ignoreBOM: boolean }): TextDecoder }; + + WebkitMutationObserver?: typeof MutationObserver; + + Worker?: typeof Worker, + + WorkerGlobalScope?: { + prototype: WorkerGlobalScope; + new (): WorkerGlobalScope; + }; + + document?: { + currentScript?: HTMLScriptElement; + fonts?: FontFaceSet; + }; + + fetch?(url: string): Promise<{ body: ReadableStream; ok?: boolean; status?: number; }>; + + process?: { + nextTick?(callback: () => void): void; + } +}; diff --git a/negromate/web/static/js/libjass/src/index.ts b/negromate/web/static/js/libjass/src/index.ts new file mode 100644 index 0000000..27f13b0 --- /dev/null +++ b/negromate/web/static/js/libjass/src/index.ts @@ -0,0 +1,137 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as settings from "./settings"; +export { debugMode, verboseMode } from "./settings"; + +import * as set from "./utility/set"; +export { Set } from "./utility/set"; + +import * as map from "./utility/map"; +export { Map } from "./utility/map"; + +import * as promise from "./utility/promise"; +export { Promise, DeferredPromise } from "./utility/promise"; + +import * as webworker from "./webworker"; +export { webworker }; + +import * as parts from "./parts"; +export { parts }; + +import * as parser from "./parser"; +export { parser }; + +import * as renderers from "./renderers"; +export { renderers }; + +export { serialize, deserialize } from "./serialization"; + +export { ASS } from "./types/ass"; +export { Attachment, AttachmentType } from "./types/attachment"; +export { Dialogue } from "./types/dialogue"; +export { ScriptProperties } from "./types/script-properties"; +export { Style } from "./types/style"; + +export { BorderStyle, Format, WrappingStyle } from "./types/misc"; + +export { version } from "./version"; + +/** + * Configures libjass with the given properties. + * + * @param {!*} newConfig + * @param {?boolean} newConfig["debugMode"] When true, libjass logs some debug messages. + * @param {?boolean} newConfig["verboseMode"] When true, libjass logs some more debug messages. This setting is independent of {@link libjass.debugMode} + * @param {?function(new:Set, !Array.=)} newConfig["Set"] Sets the Set implementation used by libjass to the provided one. If null, {@link ./utility/set.SimpleSet} is used. + * @param {?function(new:Map, !Array.>=)} newConfig["Map"] Sets the Map implementation used by libjass to the provided one. If null, {@link ./utility/map.SimpleMap} is used. + * @param {?function(new:Promise)} newConfig["Promise"] Sets the Promise implementation used by libjass to the provided one. If null, {@link ./utility/promise.SimplePromise} is used. + */ +export function configure(newConfig: { + debugMode?: boolean, + verboseMode?: boolean, + Set?: typeof set.Set | null, + Map?: typeof map.Map | null, + Promise?: typeof promise.Promise | null, +}): void { + if (typeof newConfig.debugMode === "boolean") { + settings.setDebugMode(newConfig.debugMode); + } + + if (typeof newConfig.verboseMode === "boolean") { + settings.setVerboseMode(newConfig.verboseMode); + } + + if (typeof newConfig.Set === "function" || newConfig.Set === null) { + set.setImplementation(newConfig.Set); + } + + if (typeof newConfig.Map === "function" || newConfig.Map === null) { + map.setImplementation(newConfig.Map); + } + + if (typeof newConfig.Promise === "function" || newConfig.Promise === null) { + promise.setImplementation(newConfig.Promise); + } +} + +// Getters below are to work around https://github.com/Microsoft/TypeScript/issues/6366 + +Object.defineProperties(exports, { + debugMode: { + get: () => settings.debugMode, + set: value => { + console.warn("Setter `libjass.debugMode = value` has been deprecated. Use `libjass.configure({ debugMode: value })` instead."); + settings.setDebugMode(value); + }, + }, + + verboseMode: { + get: () => settings.verboseMode, + set: value => { + console.warn("Setter `libjass.verboseMode = value` has been deprecated. Use `libjass.configure({ verboseMode: value })` instead."); + settings.setVerboseMode(value); + }, + }, + + Set: { + get: () => set.Set, + set: value => { + console.warn("Setter `libjass.Set = value` has been deprecated. Use `libjass.configure({ Set: value })` instead."); + set.setImplementation(value); + }, + }, + + Map: { + get: () => map.Map, + set: value => { + console.warn("Setter `libjass.Map = value` has been deprecated. Use `libjass.configure({ Map: value })` instead."); + map.setImplementation(value); + }, + }, + + Promise: { + get: () => promise.Promise, + set: value => { + console.warn("Setter `libjass.Promise = value` has been deprecated. Use `libjass.configure({ Promise: value })` instead."); + promise.setImplementation(value); + }, + }, +}); diff --git a/negromate/web/static/js/libjass/src/parser/index.ts b/negromate/web/static/js/libjass/src/parser/index.ts new file mode 100644 index 0000000..c2ecadb --- /dev/null +++ b/negromate/web/static/js/libjass/src/parser/index.ts @@ -0,0 +1,23 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { parse } from "./parse"; +export { BrowserReadableStream, Stream, StringStream, XhrStream } from "./streams"; +export { StreamParser, SrtStreamParser } from "./stream-parsers"; diff --git a/negromate/web/static/js/libjass/src/parser/misc.ts b/negromate/web/static/js/libjass/src/parser/misc.ts new file mode 100644 index 0000000..cf475b2 --- /dev/null +++ b/negromate/web/static/js/libjass/src/parser/misc.ts @@ -0,0 +1,68 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Property, TypedTemplate } from "../types/misc"; + +import { Map } from "../utility/map"; + +/** + * Parses a line into a {@link ./types/misc.Property}. + * + * @param {string} line + * @return {Property} + */ +export function parseLineIntoProperty(line: string): Property | null { + const colonPos = line.indexOf(":"); + if (colonPos === -1) { + return null; + } + + const name = line.substr(0, colonPos); + const value = line.substr(colonPos + 1).replace(/^\s+/, ""); + + return { name, value }; +} + +/** + * Parses a line into a {@link ./types/misc.TypedTemplate} according to the given format specifier. + * + * @param {string} line + * @param {!Array.} formatSpecifier + * @return {TypedTemplate} + */ +export function parseLineIntoTypedTemplate(line: string, formatSpecifier: string[]): TypedTemplate | null { + const property = parseLineIntoProperty(line); + if (property === null) { + return null; + } + + const value = property.value.split(","); + + if (value.length > formatSpecifier.length) { + value[formatSpecifier.length - 1] = value.slice(formatSpecifier.length - 1).join(","); + } + + const template = new Map(); + formatSpecifier.forEach((formatKey, index) => { + template.set(formatKey, value[index]); + }); + + return { type: property.name, template }; +} diff --git a/negromate/web/static/js/libjass/src/parser/parse.ts b/negromate/web/static/js/libjass/src/parser/parse.ts new file mode 100644 index 0000000..1f61812 --- /dev/null +++ b/negromate/web/static/js/libjass/src/parser/parse.ts @@ -0,0 +1,2094 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as parts from "../parts"; + +import { debugMode } from "../settings"; + +import { Map } from "../utility/map"; + +const rules = new Map ParseNode>(); + +/** + * Parses a given string with the specified rule. + * + * @param {string} input The string to be parsed. + * @param {string} rule The rule to parse the string with + * @return {*} The value returned depends on the rule used. + */ +export function parse(input: string, rule: string): any { + /* tslint:disable-next-line:no-use-before-declare */ + const { result } = new ParserRun(input, rule); + + if (result === null || result.end !== input.length) { + if (debugMode) { + console.error("Parse failed. %s %s %o", rule, input, result); + } + + throw new Error("Parse failed."); + } + + return result.value; +} + +/** + * This class represents a single parse node. It has a start and end position, and an optional value object. + * + * @param {ParseNode} parent The parent of this parse node. + * @param {*=null} value If provided, it is assigned as the value of the node. + */ +class ParseNode { + private _children: ParseNode[] = []; + + private _start: number; + private _end: number; + private _value: any; + + constructor(private _parent: ParseNode | null, value: any = null) { + if (_parent !== null) { + _parent.children.push(this); + } + + this._start = ((_parent !== null) ? _parent.end : 0); + this._end = this._start; + + this.value = value; + } + + /** + * The start position of this parse node. + * + * @type {number} + */ + get start(): number { + return this._start; + } + + /** + * The end position of this parse node. + * + * @type {number} + */ + get end(): number { + return this._end; + } + + /** + * @type {ParseNode} + */ + get parent(): ParseNode | null { + return this._parent; + } + + /** + * @type {!Array.} + */ + get children(): ParseNode[] { + return this._children; + } + + /** + * An optional object associated with this parse node. + * + * @type {*} + */ + get value(): any { + return this._value; + } + + /** + * An optional object associated with this parse node. + * + * If the value is a string, then the end property is updated to be the length of the string. + * + * @type {*} + */ + set value(newValue: any) { + this._value = newValue; + + if (this._value !== null && this._value.constructor === String && this._children.length === 0) { + this._setEnd(this._start + (this._value as string).length); + } + } + + /** + * Removes the last child of this node and updates the end position to be end position of the new last child. + */ + pop(): void { + this._children.splice(this._children.length - 1, 1); + + if (this._children.length > 0) { + this._setEnd(this._children[this._children.length - 1].end); + } + else { + this._setEnd(this.start); + } + } + + /** + * Updates the end property of this node and its parent recursively to the root node. + * + * @param {number} newEnd + */ + private _setEnd(newEnd: number): void { + this._end = newEnd; + + if (this._parent !== null && this._parent.end !== this._end) { + this._parent._setEnd(this._end); + } + } +} + +/** + * This class represents a single run of the parser. + * + * @param {string} input + * @param {string} rule + */ +class ParserRun { + private _parseTree: ParseNode; + private _result: ParseNode; + + constructor(private _input: string, rule: string) { + const ruleFunction = rules.get(rule); + if (ruleFunction === undefined) { + throw new Error(`Could not find parser rule named ${ rule }`); + } + + this._parseTree = new ParseNode(null); + + this._result = ruleFunction.call(this, this._parseTree); + } + + /** + * @type {ParseNode} + */ + get result(): ParseNode | null { + return this._result; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_dialogueParts(parent: ParseNode): ParseNode { + const current = new ParseNode(parent); + + current.value = []; + + while (this._haveMore()) { + const enclosedTagsNode = this.parse_enclosedTags(current); + + if (enclosedTagsNode !== null) { + current.value.push(...enclosedTagsNode.value); + } + + else { + const whiteSpaceOrTextNode = this.parse_newline(current) || this.parse_soft_newline(current) || this.parse_hardspace(current) || this.parse_text(current); + + if (whiteSpaceOrTextNode.value instanceof parts.Text && current.value[current.value.length - 1] instanceof parts.Text) { + // Merge consecutive text parts into one part + const previousTextPart = current.value[current.value.length - 1] as parts.Text; + current.value[current.value.length - 1] = new parts.Text(previousTextPart.value + (whiteSpaceOrTextNode.value as parts.Text).value); + } + else { + current.value.push(whiteSpaceOrTextNode.value); + } + } + } + + let inDrawingMode = false; + + current.value.forEach((part: parts.Part, i: number) => { + if (part instanceof parts.DrawingMode) { + inDrawingMode = part.scale !== 0; + } + + else if (part instanceof parts.Text && inDrawingMode) { + current.value[i] = new parts.DrawingInstructions(parse(part.value, "drawingInstructions") as parts.drawing.Instruction[]); + } + }); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_enclosedTags(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + current.value = []; + + if (this.read(current, "{") === null) { + parent.pop(); + return null; + } + + for (let next = this._peek(); this._haveMore() && next !== "}"; next = this._peek()) { + let childNode: ParseNode | null = null; + + if (this.read(current, "\\") !== null) { + childNode = + this.parse_tag_alpha(current) || + this.parse_tag_iclip(current) || + this.parse_tag_xbord(current) || + this.parse_tag_ybord(current) || + this.parse_tag_xshad(current) || + this.parse_tag_yshad(current) || + + this.parse_tag_blur(current) || + this.parse_tag_bord(current) || + this.parse_tag_clip(current) || + this.parse_tag_fade(current) || + this.parse_tag_fscx(current) || + this.parse_tag_fscy(current) || + this.parse_tag_move(current) || + this.parse_tag_shad(current) || + + this.parse_tag_fad(current) || + this.parse_tag_fax(current) || + this.parse_tag_fay(current) || + this.parse_tag_frx(current) || + this.parse_tag_fry(current) || + this.parse_tag_frz(current) || + this.parse_tag_fsp(current) || + this.parse_tag_fsplus(current) || + this.parse_tag_fsminus(current) || + this.parse_tag_org(current) || + this.parse_tag_pbo(current) || + this.parse_tag_pos(current) || + + this.parse_tag_an(current) || + this.parse_tag_be(current) || + this.parse_tag_fn(current) || + this.parse_tag_fr(current) || + this.parse_tag_fs(current) || + this.parse_tag_kf(current) || + this.parse_tag_ko(current) || + this.parse_tag_1a(current) || + this.parse_tag_1c(current) || + this.parse_tag_2a(current) || + this.parse_tag_2c(current) || + this.parse_tag_3a(current) || + this.parse_tag_3c(current) || + this.parse_tag_4a(current) || + this.parse_tag_4c(current) || + + this.parse_tag_a(current) || + this.parse_tag_b(current) || + this.parse_tag_c(current) || + this.parse_tag_i(current) || + this.parse_tag_k(current) || + this.parse_tag_K(current) || + this.parse_tag_p(current) || + this.parse_tag_q(current) || + this.parse_tag_r(current) || + this.parse_tag_s(current) || + this.parse_tag_t(current) || + this.parse_tag_u(current); + + if (childNode === null) { + current.pop(); // Unread backslash + } + } + + if (childNode === null) { + childNode = this.parse_comment(current); + } + + if (childNode.value instanceof parts.Comment && current.value[current.value.length - 1] instanceof parts.Comment) { + // Merge consecutive comment parts into one part + current.value[current.value.length - 1] = + new parts.Comment( + (current.value[current.value.length - 1] as parts.Comment).value + + (childNode.value as parts.Comment).value, + ); + } + else { + current.value.push(childNode.value); + } + } + + if (this.read(current, "}") === null) { + parent.pop(); + return null; + } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_newline(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "\\N") === null) { + parent.pop(); + return null; + } + + current.value = new parts.NewLine(); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_soft_newline(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "\\n") === null) { + parent.pop(); + return null; + } + + current.value = new parts.SoftNewLine(); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_hardspace(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "\\h") === null) { + parent.pop(); + return null; + } + + current.value = new parts.Text("\u00A0"); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_text(parent: ParseNode): ParseNode { + const value = this._peek(); + + const current = new ParseNode(parent); + const valueNode = new ParseNode(current, value); + + current.value = new parts.Text(valueNode.value); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_comment(parent: ParseNode): ParseNode { + const value = this._peek(); + + const current = new ParseNode(parent); + const valueNode = new ParseNode(current, value); + + current.value = new parts.Comment(valueNode.value); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_a(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "a") === null) { + parent.pop(); + return null; + } + + let next = this._peek(); + + switch (next) { + case "1": + const next2 = this._peek(2); + + switch (next2) { + case "10": + case "11": + next = next2; + break; + } + + break; + + case "2": + case "3": + case "5": + case "6": + case "7": + case "9": + break; + + default: + parent.pop(); + return null; + } + + const valueNode = new ParseNode(current, next); + + let value: number = -1; + switch ((valueNode.value)) { + case "1": + value = 1; + break; + + case "2": + value = 2; + break; + + case "3": + value = 3; + break; + + case "5": + value = 7; + break; + + case "6": + value = 8; + break; + + case "7": + value = 9; + break; + + case "9": + value = 4; + break; + + case "10": + value = 5; + break; + + case "11": + value = 6; + break; + } + + current.value = new parts.Alignment(value); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_alpha(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_an(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "an") === null) { + parent.pop(); + return null; + } + + const next = this._peek(); + + if (next < "1" || next > "9") { + parent.pop(); + return null; + } + + const valueNode = new ParseNode(current, next); + + current.value = new parts.Alignment(parseInt(valueNode.value)); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_b(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "b") === null) { + parent.pop(); + return null; + } + + let valueNode: ParseNode | null = null; + + let next = this._peek(); + + if (next >= "1" && next <= "9") { + next = this._peek(3); + if (next.substr(1) === "00") { + valueNode = new ParseNode(current, next); + valueNode.value = parseInt(valueNode.value); + } + } + + if (valueNode === null) { + valueNode = this.parse_enableDisable(current); + } + + if (valueNode !== null) { + current.value = new parts.Bold(valueNode.value); + } + else { + current.value = new parts.Bold(null); + } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_be(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_blur(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_bord(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_c(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_clip(parent: ParseNode): ParseNode | null { + return this._parse_tag_clip_or_iclip("clip", parent); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fad(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "fad") === null) { + parent.pop(); + return null; + } + + if (this.read(current, "(") === null) { + parent.pop(); + return null; + } + + const startNode = this.parse_decimal(current); + if (startNode === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const endNode = this.parse_decimal(current); + if (endNode === null) { + parent.pop(); + return null; + } + + if (this.read(current, ")") === null) { + parent.pop(); + return null; + } + + current.value = new parts.Fade(startNode.value / 1000, endNode.value / 1000); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fade(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "fade") === null) { + parent.pop(); + return null; + } + + if (this.read(current, "(") === null) { + parent.pop(); + return null; + } + + const a1Node = this.parse_decimal(current); + if (a1Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const a2Node = this.parse_decimal(current); + if (a2Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const a3Node = this.parse_decimal(current); + if (a3Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const t1Node = this.parse_decimal(current); + if (t1Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const t2Node = this.parse_decimal(current); + if (t2Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const t3Node = this.parse_decimal(current); + if (t3Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const t4Node = this.parse_decimal(current); + if (t4Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ")") === null) { + parent.pop(); + return null; + } + + current.value = + new parts.ComplexFade( + 1 - a1Node.value / 255, 1 - a2Node.value / 255, 1 - a3Node.value / 255, + t1Node.value / 1000, t2Node.value / 1000, t3Node.value / 1000, t4Node.value / 1000, + ); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fax(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fay(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fn(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "fn") === null) { + parent.pop(); + return null; + } + + const valueNode = new ParseNode(current, ""); + + for (let next = this._peek(); this._haveMore() && next !== "\\" && next !== "}"; next = this._peek()) { + valueNode.value += next; + } + + if (valueNode.value.length > 0) { + current.value = new parts.FontName(valueNode.value); + } + else { + current.value = new parts.FontName(null); + } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fr(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_frx(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fry(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_frz(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fs(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fsplus(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "fs+") === null) { + parent.pop(); + return null; + } + + const valueNode = this.parse_decimal(current); + + if (valueNode === null) { + parent.pop(); + return null; + } + + current.value = new parts.FontSizePlus(valueNode.value / 10); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fsminus(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "fs-") === null) { + parent.pop(); + return null; + } + + const valueNode = this.parse_decimal(current); + + if (valueNode === null) { + parent.pop(); + return null; + } + + current.value = new parts.FontSizeMinus(valueNode.value / 10); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fscx(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "fscx") === null) { + parent.pop(); + return null; + } + + const valueNode = this.parse_decimal(current); + + if (valueNode !== null) { + current.value = new parts.FontScaleX(valueNode.value / 100); + } + else { + current.value = new parts.FontScaleX(null); + } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fscy(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "fscy") === null) { + parent.pop(); + return null; + } + + const valueNode = this.parse_decimal(current); + + if (valueNode !== null) { + current.value = new parts.FontScaleY(valueNode.value / 100); + } + else { + current.value = new parts.FontScaleY(null); + } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_fsp(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_i(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_iclip(parent: ParseNode): ParseNode | null { + return this._parse_tag_clip_or_iclip("iclip", parent); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_k(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "k") === null) { + parent.pop(); + return null; + } + + const valueNode = this.parse_decimal(current); + + if (valueNode === null) { + parent.pop(); + return null; + } + + current.value = new parts.ColorKaraoke(valueNode.value / 100); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_K(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "K") === null) { + parent.pop(); + return null; + } + + const valueNode = this.parse_decimal(current); + + if (valueNode === null) { + parent.pop(); + return null; + } + + current.value = new parts.SweepingColorKaraoke(valueNode.value / 100); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_kf(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "kf") === null) { + parent.pop(); + return null; + } + + const valueNode = this.parse_decimal(current); + + if (valueNode === null) { + parent.pop(); + return null; + } + + current.value = new parts.SweepingColorKaraoke(valueNode.value / 100); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_ko(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "ko") === null) { + parent.pop(); + return null; + } + + const valueNode = this.parse_decimal(current); + + if (valueNode === null) { + parent.pop(); + return null; + } + + current.value = new parts.OutlineKaraoke(valueNode.value / 100); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_move(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "move") === null) { + parent.pop(); + return null; + } + + if (this.read(current, "(") === null) { + parent.pop(); + return null; + } + + const x1Node = this.parse_decimal(current); + if (x1Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const y1Node = this.parse_decimal(current); + if (y1Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const x2Node = this.parse_decimal(current); + if (x2Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const y2Node = this.parse_decimal(current); + if (y2Node === null) { + parent.pop(); + return null; + } + + let t1Node: ParseNode | null = null; + let t2Node: ParseNode | null = null; + + if (this.read(current, ",") !== null) { + t1Node = this.parse_decimal(current); + if (t1Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + t2Node = this.parse_decimal(current); + if (t2Node === null) { + parent.pop(); + return null; + } + } + + if (this.read(current, ")") === null) { + parent.pop(); + return null; + } + + current.value = new parts.Move( + x1Node.value, y1Node.value, x2Node.value, y2Node.value, + (t1Node !== null) ? (t1Node.value / 1000) : null, (t2Node !== null) ? (t2Node.value / 1000) : null, + ); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_org(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "org") === null) { + parent.pop(); + return null; + } + + if (this.read(current, "(") === null) { + parent.pop(); + return null; + } + + const xNode = this.parse_decimal(current); + if (xNode === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const yNode = this.parse_decimal(current); + if (yNode === null) { + parent.pop(); + return null; + } + + if (this.read(current, ")") === null) { + parent.pop(); + return null; + } + + current.value = new parts.RotationOrigin(xNode.value, yNode.value); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_p(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_pbo(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_pos(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "pos") === null) { + parent.pop(); + return null; + } + + if (this.read(current, "(") === null) { + parent.pop(); + return null; + } + + const xNode = this.parse_decimal(current); + if (xNode === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const yNode = this.parse_decimal(current); + if (yNode === null) { + parent.pop(); + return null; + } + + if (this.read(current, ")") === null) { + parent.pop(); + return null; + } + + current.value = new parts.Position(xNode.value, yNode.value); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_q(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "q") === null) { + parent.pop(); + return null; + } + + const next = this._peek(); + + if (next < "0" || next > "3") { + parent.pop(); + return null; + } + + const valueNode = new ParseNode(current, next); + + current.value = new parts.WrappingStyle(parseInt(valueNode.value)); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_r(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "r") === null) { + parent.pop(); + return null; + } + + const valueNode = new ParseNode(current, ""); + + for (let next = this._peek(); this._haveMore() && next !== "\\" && next !== "}"; next = this._peek()) { + valueNode.value += next; + } + + if (valueNode.value.length > 0) { + current.value = new parts.Reset(valueNode.value); + } + else { + current.value = new parts.Reset(null); + } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_s(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_shad(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_t(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, "t") === null) { + parent.pop(); + return null; + } + + if (this.read(current, "(") === null) { + parent.pop(); + return null; + } + + let startNode: ParseNode | null = null; + let endNode: ParseNode | null = null; + let accelNode: ParseNode | null = null; + + const firstNode = this.parse_decimal(current); + if (firstNode !== null) { + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const secondNode = this.parse_decimal(current); + if (secondNode !== null) { + startNode = firstNode; + endNode = secondNode; + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const thirdNode = this.parse_decimal(current); + if (thirdNode !== null) { + accelNode = thirdNode; + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + } + } + else { + accelNode = firstNode; + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + } + } + + const transformTags: parts.Part[] = []; + + for (let next = this._peek(); this._haveMore() && next !== ")" && next !== "}"; next = this._peek()) { + let childNode: ParseNode | null = null; + + if (this.read(current, "\\") !== null) { + childNode = + this.parse_tag_alpha(current) || + this.parse_tag_iclip(current) || + this.parse_tag_xbord(current) || + this.parse_tag_ybord(current) || + this.parse_tag_xshad(current) || + this.parse_tag_yshad(current) || + + this.parse_tag_blur(current) || + this.parse_tag_bord(current) || + this.parse_tag_clip(current) || + this.parse_tag_fscx(current) || + this.parse_tag_fscy(current) || + this.parse_tag_shad(current) || + + this.parse_tag_fax(current) || + this.parse_tag_fay(current) || + this.parse_tag_frx(current) || + this.parse_tag_fry(current) || + this.parse_tag_frz(current) || + this.parse_tag_fsp(current) || + this.parse_tag_fsplus(current) || + this.parse_tag_fsminus(current) || + + this.parse_tag_be(current) || + this.parse_tag_fr(current) || + this.parse_tag_fs(current) || + this.parse_tag_1a(current) || + this.parse_tag_1c(current) || + this.parse_tag_2a(current) || + this.parse_tag_2c(current) || + this.parse_tag_3a(current) || + this.parse_tag_3c(current) || + this.parse_tag_4a(current) || + this.parse_tag_4c(current) || + + this.parse_tag_c(current); + + if (childNode === null) { + current.pop(); // Unread backslash + } + } + + if (childNode === null) { + childNode = this.parse_comment(current); + } + + if (childNode.value instanceof parts.Comment && transformTags[transformTags.length - 1] instanceof parts.Comment) { + // Merge consecutive comment parts into one part + transformTags[transformTags.length - 1] = + new parts.Comment( + (transformTags[transformTags.length - 1] as parts.Comment).value + + (childNode.value as parts.Comment).value, + ); + } + else { + transformTags.push(childNode.value); + } + } + + this.read(current, ")"); + + current.value = + new parts.Transform( + (startNode !== null) ? (startNode.value / 1000) : null, + (endNode !== null) ? (endNode.value / 1000) : null, + (accelNode !== null) ? (accelNode.value / 1000) : null, + transformTags, + ); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_u(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_xbord(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_xshad(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_ybord(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_yshad(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_1a(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_1c(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_2a(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_2c(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_3a(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_3c(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_4a(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_tag_4c(_parent: ParseNode): ParseNode | null { + throw new Error("unreachable"); + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_drawingInstructions(parent: ParseNode): ParseNode { + const current = new ParseNode(parent); + + let currentType: string | null = null; + const numberParts: ParseNode[] = []; + + current.value = []; + + while (this._haveMore()) { + while (this.read(current, " ") !== null) { } + if (!this._haveMore()) { + break; + } + + if (currentType !== null) { + const numberPart = this.parse_decimal(current); + if (numberPart !== null) { + numberParts.push(numberPart); + + if (currentType === "m" && numberParts.length === 2) { + current.value.push(new parts.drawing.MoveInstruction(numberParts[0].value, numberParts[1].value)); + numberParts.splice(0, numberParts.length); + } + else if (currentType === "l" && numberParts.length === 2) { + current.value.push(new parts.drawing.LineInstruction(numberParts[0].value, numberParts[1].value)); + numberParts.splice(0, numberParts.length); + } + else if (currentType === "b" && numberParts.length === 6) { + current.value.push(new parts.drawing.CubicBezierCurveInstruction( + numberParts[0].value, numberParts[1].value, + numberParts[2].value, numberParts[3].value, + numberParts[4].value, numberParts[5].value)); + numberParts.splice(0, numberParts.length); + } + + continue; + } + } + + const typePart = this.parse_text(current); + const newType = (typePart.value as parts.Text).value; + switch (newType) { + case "m": + case "l": + case "b": + currentType = newType; + numberParts.splice(0, numberParts.length); + break; + } + } + + while (this.read(current, " ") !== null) { } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_decimalInt32(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + const isNegative = this.read(current, "-") !== null; + + const numberNode = new ParseNode(current, ""); + for (let next = this._peek(); this._haveMore() && next >= "0" && next <= "9"; next = this._peek()) { + numberNode.value += next; + } + + if (numberNode.value.length === 0) { + parent.pop(); + return null; + } + + let value = parseInt(numberNode.value); + if (value >= 0xFFFFFFFF) { + value = 0xFFFFFFFF; + } + else if (isNegative) { + value = -value; + } + + current.value = value; + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_hexInt32(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + const isNegative = this.read(current, "-") !== null; + + const numberNode = new ParseNode(current, ""); + for ( + let next = this._peek(); + this._haveMore() && ( + (next >= "0" && next <= "9") || + (next >= "a" && next <= "f") || + (next >= "A" && next <= "F") + ); + next = this._peek()) { + + numberNode.value += next; + } + + if (numberNode.value.length === 0) { + parent.pop(); + return null; + } + + let value = parseInt(numberNode.value, 16); + if (value >= 0xFFFFFFFF) { + value = 0xFFFFFFFF; + } + else if (isNegative) { + value = -value; + } + + current.value = value; + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_decimalOrHexInt32(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + const valueNode = + (this.read(current, "&H") !== null || this.read(current, "&h") !== null) ? + this.parse_hexInt32(current) : + this.parse_decimalInt32(current); + + if (valueNode === null) { + parent.pop(); + return null; + } + + current.value = valueNode.value; + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_decimal(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + const negative = (this.read(current, "-") !== null); + + const numericalPart = this.parse_unsignedDecimal(current); + + if (numericalPart === null) { + parent.pop(); + return null; + } + + current.value = numericalPart.value; + + if (negative) { + current.value = -current.value; + } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_unsignedDecimal(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + const characteristicNode = new ParseNode(current, ""); + + let mantissaNode: ParseNode | null = null; + + for (let next = this._peek(); this._haveMore() && next >= "0" && next <= "9"; next = this._peek()) { + characteristicNode.value += next; + } + + if (characteristicNode.value.length === 0) { + parent.pop(); + return null; + } + + if (this.read(current, ".") !== null) { + mantissaNode = new ParseNode(current, ""); + + for (let next = this._peek(); this._haveMore() && next >= "0" && next <= "9"; next = this._peek()) { + mantissaNode.value += next; + } + + if (mantissaNode.value.length === 0) { + parent.pop(); + return null; + } + } + + current.value = parseFloat((characteristicNode.value as string) + ((mantissaNode !== null) ? ("." + (mantissaNode.value as string)) : "")); + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_enableDisable(parent: ParseNode): ParseNode | null { + const next = this._peek(); + + if (next === "0" || next === "1") { + const result = new ParseNode(parent, next); + result.value = (result.value === "1"); + + return result; + } + + return null; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_color(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + while (this.read(current, "&") !== null || this.read(current, "H") !== null) { } + + const valueNode = this.parse_hexInt32(current); + if (valueNode === null) { + parent.pop(); + return null; + } + + const value = valueNode.value; + + /* tslint:disable:no-bitwise */ + + current.value = new parts.Color( + value & 0xFF, + (value >> 8) & 0xFF, + (value >> 16) & 0xFF, + ); + + /* tslint:enable:no-bitwise */ + + while (this.read(current, "&") !== null || this.read(current, "H") !== null) { } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_alpha(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + while (this.read(current, "&") !== null || this.read(current, "H") !== null) { } + + const valueNode = this.parse_hexInt32(current); + if (valueNode === null) { + parent.pop(); + return null; + } + + const value = valueNode.value; + + /* tslint:disable-next-line:no-bitwise */ + current.value = 1 - (value & 0xFF) / 0xFF; + + while (this.read(current, "&") !== null || this.read(current, "H") !== null) { } + + return current; + } + + /** + * @param {!ParseNode} parent + * @return {ParseNode} + */ + parse_colorWithAlpha(parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + const valueNode = this.parse_decimalOrHexInt32(current); + if (valueNode === null) { + parent.pop(); + return null; + } + + const value = valueNode.value; + + /* tslint:disable:no-bitwise */ + + current.value = new parts.Color( + value & 0xFF, + (value >> 8) & 0xFF, + (value >> 16) & 0xFF, + 1 - ((value >> 24) & 0xFF) / 0xFF, + ); + + /* tslint:enable:no-bitwise */ + + return current; + } + + /** + * @param {!ParseNode} parent + * @param {string} next + * @return {ParseNode} + */ + read(parent: ParseNode, next: string): ParseNode | null { + if (this._peek(next.length) !== next) { + return null; + } + + return new ParseNode(parent, next); + } + + /** + * @param {number=1} count + * @return {string} + */ + private _peek(count: number = 1): string { + // Fastpath for count === 1. http://jsperf.com/substr-vs-indexer + if (count === 1) { return this._input[this._parseTree.end]; } + + return this._input.substr(this._parseTree.end, count); + } + + /** + * @return {boolean} + */ + private _haveMore(): boolean { + return this._parseTree.end < this._input.length; + } + + /** + * @param {string} tagName One of "clip" and "iclip" + * @param {!ParseNode} parent + * @return {ParseNode} + */ + private _parse_tag_clip_or_iclip(tagName: "clip" | "iclip", parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, tagName) === null) { + parent.pop(); + return null; + } + + if (this.read(current, "(") === null) { + parent.pop(); + return null; + } + + let x1Node: ParseNode | null = null; + let x2Node: ParseNode | null = null; + let y1Node: ParseNode | null = null; + let y2Node: ParseNode | null = null; + let scaleNode: ParseNode | null = null; + let commandsNode: ParseNode | null = null; + + const firstNode = this.parse_decimal(current); + + if (firstNode !== null) { + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + const secondNode = this.parse_decimal(current); + + if (secondNode !== null) { + x1Node = firstNode; + y1Node = secondNode; + } + else { + scaleNode = firstNode; + } + } + + if (x1Node !== null && y1Node !== null) { + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + x2Node = this.parse_decimal(current); + if (x2Node === null) { + parent.pop(); + return null; + } + + if (this.read(current, ",") === null) { + parent.pop(); + return null; + } + + y2Node = this.parse_decimal(current); + if (y2Node === null) { + parent.pop(); + return null; + } + + current.value = new parts.RectangularClip(x1Node.value, y1Node.value, x2Node.value, y2Node.value, tagName === "clip"); + } + else { + commandsNode = new ParseNode(current, ""); + + for (let next = this._peek(); this._haveMore() && next !== ")" && next !== "}"; next = this._peek()) { + commandsNode.value += next; + } + + current.value = new parts.VectorClip((scaleNode !== null) ? scaleNode.value : 1, parse(commandsNode.value, "drawingInstructions") as parts.drawing.Instruction[], tagName === "clip"); + } + + if (this.read(current, ")") === null) { + parent.pop(); + return null; + } + + return current; + } +} + +/** + * Constructs a simple tag parser function and sets it on the prototype of the {@link ./parser/parse.ParserRun} class. + * + * @param {string} tagName The name of the tag to generate the parser function for + * @param {function(new: !libjass.parts.Part, *)} tagConstructor The type of tag to be returned by the generated parser function + * @param {function(!ParseNode): ParseNode} valueParser The parser for the tag's value + * @param {boolean} required Whether the tag's value is required or optional + */ +function makeTagParserFunction( + tagName: string, + tagConstructor: { new (value: any): parts.Part }, + valueParser: (current: ParseNode) => ParseNode | null, + required: boolean, +): void { + (ParserRun.prototype as any)[`parse_tag_${ tagName }`] = function (this: ParserRun, parent: ParseNode): ParseNode | null { + const current = new ParseNode(parent); + + if (this.read(current, tagName) === null) { + parent.pop(); + return null; + } + + const valueNode: ParseNode | null = valueParser.call(this, current); + + if (valueNode !== null) { + current.value = new tagConstructor(valueNode.value); + } + else if (!required) { + current.value = new tagConstructor(null); + } + else { + parent.pop(); + return null; + } + + return current; + }; +} + +makeTagParserFunction("alpha", parts.Alpha, ParserRun.prototype.parse_alpha, false); +makeTagParserFunction("be", parts.Blur, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("blur", parts.GaussianBlur, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("bord", parts.Border, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("c", parts.PrimaryColor, ParserRun.prototype.parse_color, false); +makeTagParserFunction("fax", parts.SkewX, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("fay", parts.SkewY, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("fr", parts.RotateZ, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("frx", parts.RotateX, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("fry", parts.RotateY, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("frz", parts.RotateZ, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("fs", parts.FontSize, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("fsp", parts.LetterSpacing, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("i", parts.Italic, ParserRun.prototype.parse_enableDisable, false); +makeTagParserFunction("p", parts.DrawingMode, ParserRun.prototype.parse_decimal, true); +makeTagParserFunction("pbo", parts.DrawingBaselineOffset, ParserRun.prototype.parse_decimal, true); +makeTagParserFunction("s", parts.StrikeThrough, ParserRun.prototype.parse_enableDisable, false); +makeTagParserFunction("shad", parts.Shadow, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("u", parts.Underline, ParserRun.prototype.parse_enableDisable, false); +makeTagParserFunction("xbord", parts.BorderX, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("xshad", parts.ShadowX, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("ybord", parts.BorderY, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("yshad", parts.ShadowY, ParserRun.prototype.parse_decimal, false); +makeTagParserFunction("1a", parts.PrimaryAlpha, ParserRun.prototype.parse_alpha, false); +makeTagParserFunction("1c", parts.PrimaryColor, ParserRun.prototype.parse_color, false); +makeTagParserFunction("2a", parts.SecondaryAlpha, ParserRun.prototype.parse_alpha, false); +makeTagParserFunction("2c", parts.SecondaryColor, ParserRun.prototype.parse_color, false); +makeTagParserFunction("3a", parts.OutlineAlpha, ParserRun.prototype.parse_alpha, false); +makeTagParserFunction("3c", parts.OutlineColor, ParserRun.prototype.parse_color, false); +makeTagParserFunction("4a", parts.ShadowAlpha, ParserRun.prototype.parse_alpha, false); +makeTagParserFunction("4c", parts.ShadowColor, ParserRun.prototype.parse_color, false); + +for (const key of Object.keys(ParserRun.prototype)) { + if (key.indexOf("parse_") === 0 && typeof (ParserRun.prototype as any)[key] === "function") { + rules.set(key.substr("parse_".length), (ParserRun.prototype as any)[key]); + } +} + +import { Promise } from "../utility/promise"; + +import { WorkerCommands } from "../webworker/commands"; +import { registerWorkerCommand } from "../webworker/misc"; + +registerWorkerCommand(WorkerCommands.Parse, parameters => new Promise(resolve => { + resolve(parse(parameters.input, parameters.rule)); +})); diff --git a/negromate/web/static/js/libjass/src/parser/stream-parsers.ts b/negromate/web/static/js/libjass/src/parser/stream-parsers.ts new file mode 100644 index 0000000..028c35a --- /dev/null +++ b/negromate/web/static/js/libjass/src/parser/stream-parsers.ts @@ -0,0 +1,438 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { debugMode } from "../settings"; + +import { ASS } from "../types/ass"; +import { Attachment, AttachmentType } from "../types/attachment"; +import { Dialogue } from "../types/dialogue"; +import { Style } from "../types/style"; + +import { Map } from "../utility/map"; + +import { DeferredPromise } from "../utility/promise"; + +import { parseLineIntoProperty } from "./misc"; +import { Stream } from "./streams"; + +enum Section { + ScriptInfo, + Styles, + Events, + Fonts, + Graphics, + Other, + EOF, +} + +/** + * A parser that parses an {@link libjass.ASS} object from a {@link libjass.parser.Stream}. + * + * @param {!libjass.parser.Stream} stream The {@link libjass.parser.Stream} to parse + */ +export class StreamParser { + private _ass: ASS = new ASS(); + private _minimalDeferred: DeferredPromise = new DeferredPromise(); + private _deferred: DeferredPromise = new DeferredPromise(); + + private _shouldSwallowBom: boolean = true; + private _currentSection: Section = Section.ScriptInfo; + private _currentAttachment: Attachment | null = null; + + constructor(private _stream: Stream) { + /* tslint:disable-next-line:no-floating-promises */ + this._stream.nextLine().then(line => this._onNextLine(line), reason => { + this._minimalDeferred.reject(reason); + this._deferred.reject(reason); + }); + } + + /** + * @type {!Promise.} A promise that will be resolved when the script properties of the ASS script have been parsed from the stream. Styles and events have not necessarily been + * parsed at the point this promise becomes resolved. + */ + get minimalASS(): Promise { + return this._minimalDeferred.promise; + } + + /** + * @type {!Promise.} A promise that will be resolved when the entire stream has been parsed. + */ + get ass(): Promise { + return this._deferred.promise; + } + + /** + * @type {number} + */ + private get currentSection(): Section { + return this._currentSection; + } + + /** + * @type {number} + */ + private set currentSection(value: Section) { + if (this._currentAttachment !== null) { + this._ass.addAttachment(this._currentAttachment); + this._currentAttachment = null; + } + + if (this._currentSection === Section.ScriptInfo && value !== Section.ScriptInfo) { + // Exiting script info section + this._minimalDeferred.resolve(this._ass); + } + + if (value === Section.EOF) { + const scriptProperties = this._ass.properties; + /* tslint:disable-next-line:strict-type-predicates */ + if (scriptProperties.resolutionX === undefined || scriptProperties.resolutionY === undefined) { + // Malformed script. + this._minimalDeferred.reject("Malformed ASS script."); + this._deferred.reject("Malformed ASS script."); + } + else { + this._minimalDeferred.resolve(this._ass); + this._deferred.resolve(this._ass); + } + } + + this._currentSection = value; + } + + /** + * @param {string} line + */ + private _onNextLine(line: string | null): void { + if (line === null) { + this.currentSection = Section.EOF; + return; + } + + if (line[line.length - 1] === "\r") { + line = line.substr(0, line.length - 1); + } + + if (line.charCodeAt(0) === 0xfeff && this._shouldSwallowBom) { + line = line.substr(1); + } + + this._shouldSwallowBom = false; + + if (line === "") { + // Ignore empty lines. + } + + else if (line[0] === ";" && this._currentAttachment === null) { + // Lines starting with ; are comments, unless reading an attachment. + } + + else if (line === "[Script Info]") { + this.currentSection = Section.ScriptInfo; + } + else if (line === "[V4+ Styles]" || line === "[V4 Styles]") { + this.currentSection = Section.Styles; + } + else if (line === "[Events]") { + this.currentSection = Section.Events; + } + else if (line === "[Fonts]") { + this.currentSection = Section.Fonts; + } + else if (line === "[Graphics]") { + this.currentSection = Section.Graphics; + } + else { + if (this._currentAttachment === null && line[0] === "[" && line[line.length - 1] === "]") { + /* This looks like the start of a new section. The section name is unrecognized if it is. + * Since there's no current attachment being parsed it's definitely the start of a new section. + * If an attachment is being parsed, this might be part of the attachment. + */ + this.currentSection = Section.Other; + } + + switch (this.currentSection) { + case Section.ScriptInfo: + const property = parseLineIntoProperty(line); + if (property !== null) { + switch (property.name) { + case "PlayResX": + this._ass.properties.resolutionX = parseInt(property.value); + break; + case "PlayResY": + this._ass.properties.resolutionY = parseInt(property.value); + break; + case "WrapStyle": + this._ass.properties.wrappingStyle = parseInt(property.value); + break; + case "ScaledBorderAndShadow": + this._ass.properties.scaleBorderAndShadow = (property.value === "yes"); + break; + } + } + break; + + case Section.Styles: + if (this._ass.stylesFormatSpecifier === null) { + const property = parseLineIntoProperty(line); + if (property !== null && property.name === "Format") { + this._ass.stylesFormatSpecifier = property.value.split(",").map(str => str.trim()); + } + else { + // Ignore any non-format lines + } + } + else { + try { + this._ass.addStyle(line); + } + catch (ex) { + if (debugMode) { + console.error(`Could not parse style from line ${ line } - ${ ex.stack || ex }`); + } + } + } + break; + + case Section.Events: + if (this._ass.dialoguesFormatSpecifier === null) { + const property = parseLineIntoProperty(line); + if (property !== null && property.name === "Format") { + this._ass.dialoguesFormatSpecifier = property.value.split(",").map(str => str.trim()); + } + else { + // Ignore any non-format lines + } + } + else { + try { + this._ass.addEvent(line); + } + catch (ex) { + if (debugMode) { + console.error(`Could not parse event from line ${ line } - ${ ex.stack || ex }`); + } + } + } + break; + + case Section.Fonts: + case Section.Graphics: + const startOfNewAttachmentRegex = (this.currentSection === Section.Fonts) ? /^fontname:(.+)/ : /^filename:(.+)/; + const startOfNewAttachment = startOfNewAttachmentRegex.exec(line); + + if (startOfNewAttachment !== null) { + // Start of new attachment + + if (this._currentAttachment !== null) { + this._ass.addAttachment(this._currentAttachment); + this._currentAttachment = null; + } + + this._currentAttachment = new Attachment(startOfNewAttachment[1].trim(), (this.currentSection === Section.Fonts) ? AttachmentType.Font : AttachmentType.Graphic); + } + else if (this._currentAttachment !== null) { + try { + this._currentAttachment.contents += uuencodedToBase64(line); + } + catch (ex) { + if (debugMode) { + console.error(`Encountered error while reading font ${ this._currentAttachment.filename }: %o`, ex); + } + + this._currentAttachment = null; + } + } + else { + // Ignore. + } + break; + + case Section.Other: + // Ignore other sections. + break; + + default: + throw new Error(`Unhandled state ${ this.currentSection }`); + } + } + + /* tslint:disable-next-line:no-floating-promises */ + this._stream.nextLine().then(line => this._onNextLine(line), reason => { + this._minimalDeferred.reject(reason); + this._deferred.reject(reason); + }); + } +} + +/** + * A parser that parses an {@link libjass.ASS} object from a {@link libjass.parser.Stream} of an SRT script. + * + * @param {!libjass.parser.Stream} stream The {@link libjass.parser.Stream} to parse + */ +export class SrtStreamParser { + private _ass: ASS = new ASS(); + private _deferred: DeferredPromise = new DeferredPromise(); + + private _shouldSwallowBom: boolean = true; + + private _currentDialogueNumber: string | null = null; + private _currentDialogueStart: string | null = null; + private _currentDialogueEnd: string | null = null; + private _currentDialogueText: string | null = null; + + constructor(private _stream: Stream) { + /* tslint:disable-next-line:no-floating-promises */ + this._stream.nextLine().then(line => this._onNextLine(line), reason => { + this._deferred.reject(reason); + }); + + this._ass.properties.resolutionX = 1280; + this._ass.properties.resolutionY = 720; + this._ass.properties.wrappingStyle = 1; + this._ass.properties.scaleBorderAndShadow = true; + + const newStyle = new Style(new Map([["Name", "Default"], ["FontSize", "36"]])); + this._ass.styles.set(newStyle.name, newStyle); + } + + /** + * @type {!Promise.} A promise that will be resolved when the entire stream has been parsed. + */ + get ass(): Promise { + return this._deferred.promise; + } + + /** + * @param {string} line + */ + private _onNextLine(line: string | null): void { + if (line === null) { + if (this._currentDialogueNumber !== null && this._currentDialogueStart !== null && this._currentDialogueEnd !== null && this._currentDialogueText !== null) { + this._ass.dialogues.push(new Dialogue(new Map([ + ["Style", "Default"], + ["Start", this._currentDialogueStart], + ["End", this._currentDialogueEnd], + ["Text", this._currentDialogueText], + ]), this._ass)); + } + + this._deferred.resolve(this._ass); + return; + } + + if (line[line.length - 1] === "\r") { + line = line.substr(0, line.length - 1); + } + + if (line.charCodeAt(0) === 0xfeff && this._shouldSwallowBom) { + line = line.substr(1); + } + + this._shouldSwallowBom = false; + + if (line === "") { + if (this._currentDialogueNumber !== null && this._currentDialogueStart !== null && this._currentDialogueEnd !== null && this._currentDialogueText !== null) { + this._ass.dialogues.push(new Dialogue(new Map([ + ["Style", "Default"], + ["Start", this._currentDialogueStart], + ["End", this._currentDialogueEnd], + ["Text", this._currentDialogueText], + ]), this._ass)); + } + + this._currentDialogueNumber = this._currentDialogueStart = this._currentDialogueEnd = this._currentDialogueText = null; + } + else { + if (this._currentDialogueNumber === null) { + if (/^\d+$/.test(line)) { + this._currentDialogueNumber = line; + } + } + else if (this._currentDialogueStart === null && this._currentDialogueEnd === null) { + const match = /^(\d\d:\d\d:\d\d,\d\d\d) --> (\d\d:\d\d:\d\d,\d\d\d)/.exec(line); + if (match !== null) { + this._currentDialogueStart = match[1].replace(",", "."); + this._currentDialogueEnd = match[2].replace(",", "."); + } + } + else { + line = line + .replace(//g, "{\\b1}").replace(/\{b\}/g, "{\\b1}") + .replace(/<\/b>/g, "{\\b0}").replace(/\{\/b\}/g, "{\\b0}") + .replace(//g, "{\\i1}").replace(/\{i\}/g, "{\\i1}") + .replace(/<\/i>/g, "{\\i0}").replace(/\{\/i\}/g, "{\\i0}") + .replace(//g, "{\\u1}").replace(/\{u\}/g, "{\\u1}") + .replace(/<\/u>/g, "{\\u0}").replace(/\{\/u\}/g, "{\\u0}") + .replace( + //g, + (/* ujs:unreferenced */ _substring: string, red: string, green: string, blue: string) => `{\c&H${ blue }${ green }${ red }&}`, + ).replace(/<\/font>/g, "{\\c}"); + + if (this._currentDialogueText !== null) { + this._currentDialogueText += "\\N" + line; + } + else { + this._currentDialogueText = line; + } + } + } + + /* tslint:disable-next-line:no-floating-promises */ + this._stream.nextLine().then(line => this._onNextLine(line), reason => { + this._deferred.reject(reason); + }); + } +} + +/** + * Converts a uuencoded string to a base64 string. + * + * @param {string} str + * @return {string} + */ +function uuencodedToBase64(str: string): string { + let result = ""; + + for (let i = 0; i < str.length; i++) { + const charCode = str.charCodeAt(i) - 33; + + if (charCode < 0 || charCode > 63) { + throw new Error(`Out-of-range character code ${ charCode } at index ${ i } in string ${ str }`); + } + if (charCode < 26) { + result += String.fromCharCode("A".charCodeAt(0) + charCode); + } + else if (charCode < 52) { + result += String.fromCharCode("a".charCodeAt(0) + charCode - 26); + } + else if (charCode < 62) { + result += String.fromCharCode("0".charCodeAt(0) + charCode - 52); + } + else if (charCode === 62) { + result += "+"; + } + else { + result += "/"; + } + } + + return result; +} diff --git a/negromate/web/static/js/libjass/src/parser/streams.ts b/negromate/web/static/js/libjass/src/parser/streams.ts new file mode 100644 index 0000000..3c2aa43 --- /dev/null +++ b/negromate/web/static/js/libjass/src/parser/streams.ts @@ -0,0 +1,251 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { DeferredPromise, Promise } from "../utility/promise"; + +/** + * An interface for a stream. + */ +export interface Stream { + /** + * @return {!Promise.} A promise that will be resolved with the next line, or null if the stream is exhausted. + */ + nextLine(): Promise; +} + +/** + * A {@link libjass.parser.Stream} that reads from a string in memory. + * + * @param {string} str The string + */ +export class StringStream implements Stream { + private _readTill: number = 0; + + constructor(private _str: string) { } + + /** + * @return {!Promise.} A promise that will be resolved with the next line, or null if the string has been completely read. + */ + nextLine(): Promise { + let result: Promise; + + if (this._readTill < this._str.length) { + const nextNewLinePos = this._str.indexOf("\n", this._readTill); + if (nextNewLinePos !== -1) { + result = Promise.resolve(this._str.substring(this._readTill, nextNewLinePos)); + this._readTill = nextNewLinePos + 1; + } + else { + result = Promise.resolve(this._str.substr(this._readTill)); + this._readTill = this._str.length; + } + } + else { + result = Promise.resolve(null); + } + + return result; + } +} + +/** + * A {@link libjass.parser.Stream} that reads from an XMLHttpRequest object. + * + * @param {!XMLHttpRequest} xhr The XMLHttpRequest object. Make sure to not call .open() on this object before passing it in here, + * since event handlers cannot be registered after open() has been called. + */ +export class XhrStream implements Stream { + private _readTill: number = 0; + private _pendingDeferred: DeferredPromise | null = null; + private _failedError: ErrorEvent | null = null; + + constructor(private _xhr: XMLHttpRequest) { + _xhr.addEventListener("progress", () => this._onXhrProgress(), false); + _xhr.addEventListener("load", () => this._onXhrLoad(), false); + _xhr.addEventListener("error", event => this._onXhrError(event), false); + } + + /** + * @return {!Promise.} A promise that will be resolved with the next line, or null if the stream is exhausted. + */ + nextLine(): Promise { + if (this._pendingDeferred !== null) { + throw new Error("XhrStream only supports one pending unfulfilled read at a time."); + } + + const deferred = this._pendingDeferred = new DeferredPromise(); + + this._tryResolveNextLine(); + + return deferred.promise; + } + + /** + */ + private _onXhrProgress(): void { + if (this._pendingDeferred === null) { + return; + } + + if (this._xhr.readyState === XMLHttpRequest.DONE) { + /* Suppress resolving next line here. Let the "load" or "error" event handlers do it. + * + * This is required because a failed XHR fires the progress event with readyState === DONE before it fires the error event. + * This would confuse _tryResolveNextLine() into thinking the request succeeded with no data if it was called here. + */ + return; + } + + this._tryResolveNextLine(); + } + + /** + */ + private _onXhrLoad(): void { + if (this._pendingDeferred === null) { + return; + } + + this._tryResolveNextLine(); + } + + /** + * @param {!ErrorEvent} event + */ + private _onXhrError(event: ErrorEvent): void { + this._failedError = event; + + if (this._pendingDeferred === null) { + return; + } + + this._tryResolveNextLine(); + } + + /** + */ + private _tryResolveNextLine(): void { + if (this._failedError !== null) { + this._pendingDeferred!.reject(this._failedError); + return; + } + + const response = this._xhr.responseText; + + const nextNewLinePos = response.indexOf("\n", this._readTill); + if (nextNewLinePos !== -1) { + this._pendingDeferred!.resolve(response.substring(this._readTill, nextNewLinePos)); + this._readTill = nextNewLinePos + 1; + this._pendingDeferred = null; + } + + else if (this._xhr.readyState === XMLHttpRequest.DONE) { + // No more data. This is the last line. + if (this._readTill < response.length) { + this._pendingDeferred!.resolve(response.substr(this._readTill)); + this._readTill = response.length; + } + else { + this._pendingDeferred!.resolve(null); + } + + this._pendingDeferred = null; + } + } +} + +/** + * A {@link libjass.parser.Stream} that reads from a ReadableStream object. + * + * @param {!ReadableStream} stream + * @param {string} encoding + */ +export class BrowserReadableStream implements Stream { + /** + * @return {boolean} Whether BrowserReadableStream is supported in this environment. + */ + static isSupported(): boolean { + return ( + global.ReadableStream !== undefined && + typeof global.ReadableStream.prototype.getReader === "function" && + typeof global.TextDecoder === "function" + ); + } + + private _reader: ReadableStreamReader; + private _decoder: TextDecoder; + private _buffer: string = ""; + private _pendingDeferred: DeferredPromise | null = null; + + constructor(stream: ReadableStream, encoding: string) { + this._reader = stream.getReader(); + this._decoder = new global.TextDecoder!(encoding, { ignoreBOM: true }); + } + + /** + * @return {!Promise.} A promise that will be resolved with the next line, or null if the stream is exhausted. + */ + nextLine(): Promise { + if (this._pendingDeferred !== null) { + throw new Error("BrowserReadableStream only supports one pending unfulfilled read at a time."); + } + + const deferred = this._pendingDeferred = new DeferredPromise(); + + this._tryResolveNextLine(); + + return deferred.promise; + } + + /** + */ + private _tryResolveNextLine(): void { + const nextNewLinePos = this._buffer.indexOf("\n"); + if (nextNewLinePos !== -1) { + this._pendingDeferred!.resolve(this._buffer.substr(0, nextNewLinePos)); + this._buffer = this._buffer.substr(nextNewLinePos + 1); + this._pendingDeferred = null; + } + + else { + /* tslint:disable-next-line:no-floating-promises */ + this._reader.read().then(next => { + const { value, done } = next; + + if (!done) { + this._buffer += this._decoder.decode(value, { stream: true }); + this._tryResolveNextLine(); + } + else { + // No more data. + if (this._buffer.length === 0) { + this._pendingDeferred!.resolve(null); + } + else { + this._pendingDeferred!.resolve(this._buffer); + this._buffer = ""; + } + + this._pendingDeferred = null; + } + }); + } + } +} diff --git a/negromate/web/static/js/libjass/src/parser/ttf.ts b/negromate/web/static/js/libjass/src/parser/ttf.ts new file mode 100644 index 0000000..fdd8d8c --- /dev/null +++ b/negromate/web/static/js/libjass/src/parser/ttf.ts @@ -0,0 +1,228 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Attachment } from "../types/attachment"; + +import { Map } from "../utility/map"; +import { Set } from "../utility/set"; + +type DataReader = { dataView: DataView; position: number; }; + +enum DataType { + Char, + Uint16, + Uint32, +} + +type StructMemberDefinition = { type: DataType; field: string; }; + +const fieldDecorators = new Map void>(); + +@struct +class OffsetTable { + /** @type {function(!{ dataView: DataView, position: number }): OffsetTable} */ + static read: (reader: DataReader) => OffsetTable; + + /** @type {number} */ @field(DataType.Uint16) majorVersion: number; + /** @type {number} */ @field(DataType.Uint16) minorVersion: number; + /** @type {number} */ @field(DataType.Uint16) numTables: number; + /** @type {number} */ @field(DataType.Uint16) searchRange: number; + /** @type {number} */ @field(DataType.Uint16) entrySelector: number; + /** @type {number} */ @field(DataType.Uint16) rangeShift: number; +} + +@struct +class TableRecord { + /** @type {function(!{ dataView: DataView, position: number }): TableRecord} */ + static read: (reader: DataReader) => TableRecord; + + /** @type {string} */ @field(DataType.Char) c1: string; + /** @type {string} */ @field(DataType.Char) c2: string; + /** @type {string} */ @field(DataType.Char) c3: string; + /** @type {string} */ @field(DataType.Char) c4: string; + /** @type {number} */ @field(DataType.Uint32) checksum: number; + /** @type {number} */ @field(DataType.Uint32) offset: number; + /** @type {number} */ @field(DataType.Uint32) length: number; +} + +@struct +class NameTableHeader { + /** @type {function(!{ dataView: DataView, position: number }): NameTableHeader} */ + static read: (reader: DataReader) => NameTableHeader; + + /** @type {number} */ @field(DataType.Uint16) formatSelector: number; + /** @type {number} */ @field(DataType.Uint16) count: number; + /** @type {number} */ @field(DataType.Uint16) stringOffset: number; +} + +@struct +class NameRecord { + /** @type {function(!{ dataView: DataView, position: number }): NameRecord} */ + static read: (reader: DataReader) => NameRecord; + + /** @type {number} */ @field(DataType.Uint16) platformId: number; + /** @type {number} */ @field(DataType.Uint16) encodingId: number; + /** @type {number} */ @field(DataType.Uint16) languageId: number; + /** @type {number} */ @field(DataType.Uint16) nameId: number; + /** @type {number} */ @field(DataType.Uint16) length: number; + /** @type {number} */ @field(DataType.Uint16) offset: number; +} + +/** + * Gets all the font names from the given font attachment. + * + * @param {!libjass.Attachment} attachment + * @return {!libjass.Set.} + */ +export function getTtfNames(attachment: Attachment): Set { + const decoded = atob(attachment.contents); + + const bytes = new Uint8Array(new ArrayBuffer(decoded.length)); + + for (let i = 0; i < decoded.length; i++) { + bytes[i] = decoded.charCodeAt(i); + } + + const reader = { dataView: new DataView(bytes.buffer), position: 0 }; + + const offsetTable = OffsetTable.read(reader); + let nameTableRecord: TableRecord | null = null; + for (let i = 0; i < offsetTable.numTables; i++) { + const tableRecord = TableRecord.read(reader); + if (tableRecord.c1 + tableRecord.c2 + tableRecord.c3 + tableRecord.c4 === "name") { + nameTableRecord = tableRecord; + break; + } + } + if (nameTableRecord === null) { + throw new Error('Could not find "name" table record.'); + } + + reader.position = nameTableRecord.offset; + const nameTableHeader = NameTableHeader.read(reader); + + const result = new Set(); + for (let i = 0; i < nameTableHeader.count; i++) { + const nameRecord = NameRecord.read(reader); + + switch (nameRecord.nameId) { + case 1: + case 4: + case 6: + const recordOffset = nameTableRecord.offset + nameTableHeader.stringOffset + nameRecord.offset; + const nameBytes = bytes.subarray(recordOffset, recordOffset + nameRecord.length); + + switch (nameRecord.platformId) { + case 1: { + let name = ""; + + /* tslint:disable-next-line:prefer-for-of */ + for (let j = 0; j < nameBytes.length; j++) { + name += String.fromCharCode(nameBytes[j]); + } + + result.add(name); + + break; + } + + case 3: { + let name = ""; + + for (let j = 0; j < nameBytes.length; j += 2) { + /* tslint:disable-next-line:no-bitwise */ + name += String.fromCharCode((nameBytes[j] << 8) + nameBytes[j + 1]); + } + + result.add(name); + + break; + } + } + + break; + + default: + break; + } + } + + return result; +} + +/** + * @param {!function(new(): T)} clazz + * @return {!function(new(): T)} + */ +function struct(clazz: { new (): T; read(reader: DataReader): T; }): { new (): T; read(reader: DataReader): T; } { + const fields: StructMemberDefinition[] = (clazz as any).__fields; + + clazz.read = (reader: DataReader) => { + const result: any = new clazz(); + + for (const field of fields) { + let value: any; + switch (field.type) { + case DataType.Char: + value = String.fromCharCode(reader.dataView.getInt8(reader.position)); + reader.position += 1; + break; + + case DataType.Uint16: + value = reader.dataView.getUint16(reader.position); + reader.position += 2; + break; + + case DataType.Uint32: + value = reader.dataView.getUint32(reader.position); + reader.position += 4; + break; + } + + result[field.field] = value; + } + + return result; + }; + + return clazz; +} + +/** + * @param {number} type + * @return {function(T, string)} + */ +function field(type: DataType): (proto: T, field: string) => void { + let existingDecorator = fieldDecorators.get(type); + if (existingDecorator === undefined) { + existingDecorator = (proto: T, field: string) => { + const ctor: { __fields?: StructMemberDefinition[] } = proto.constructor; + if (ctor.__fields === undefined) { + ctor.__fields = []; + } + + ctor.__fields.push({ type, field }); + }; + + fieldDecorators.set(type, existingDecorator); + } + + return existingDecorator; +} diff --git a/negromate/web/static/js/libjass/src/parts/drawing.ts b/negromate/web/static/js/libjass/src/parts/drawing.ts new file mode 100644 index 0000000..62bb2e7 --- /dev/null +++ b/negromate/web/static/js/libjass/src/parts/drawing.ts @@ -0,0 +1,148 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The base interface of the drawing instructions. + */ +export interface Instruction { } + +/** + * An instruction to move to a particular position. + * + * @param {number} x + * @param {number} y + */ +export class MoveInstruction implements Instruction { + constructor(private _x: number, private _y: number) { } + + /** + * The X position of this move instruction. + * + * @type {number} + */ + get x(): number { + return this._x; + } + + /** + * The Y position of this move instruction. + * + * @type {number} + */ + get y(): number { + return this._y; + } +} + +/** + * An instruction to draw a line to a particular position. + * + * @param {number} x + * @param {number} y + */ +export class LineInstruction implements Instruction { + constructor(private _x: number, private _y: number) { } + + /** + * The X position of this line instruction. + * + * @type {number} + */ + get x(): number { + return this._x; + } + + /** + * The Y position of this line instruction. + * + * @type {number} + */ + get y(): number { + return this._y; + } +} + +/** + * An instruction to draw a cubic bezier curve to a particular position, with two given control points. + * + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {number} x3 + * @param {number} y3 + */ +export class CubicBezierCurveInstruction implements Instruction { + constructor(private _x1: number, private _y1: number, private _x2: number, private _y2: number, private _x3: number, private _y3: number) { } + + /** + * The X position of the first control point of this cubic bezier curve instruction. + * + * @type {number} + */ + get x1(): number { + return this._x1; + } + + /** + * The Y position of the first control point of this cubic bezier curve instruction. + * + * @type {number} + */ + get y1(): number { + return this._y1; + } + + /** + * The X position of the second control point of this cubic bezier curve instruction. + * + * @type {number} + */ + get x2(): number { + return this._x2; + } + + /** + * The Y position of the second control point of this cubic bezier curve instruction. + * + * @type {number} + */ + get y2(): number { + return this._y2; + } + + /** + * The ending X position of this cubic bezier curve instruction. + * + * @type {number} + */ + get x3(): number { + return this._x3; + } + + /** + * The ending Y position of this cubic bezier curve instruction. + * + * @type {number} + */ + get y3(): number { + return this._y3; + } +} diff --git a/negromate/web/static/js/libjass/src/parts/index.ts b/negromate/web/static/js/libjass/src/parts/index.ts new file mode 100644 index 0000000..c226024 --- /dev/null +++ b/negromate/web/static/js/libjass/src/parts/index.ts @@ -0,0 +1,1326 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { WrappingStyle as WrappingStyleType } from "../types/misc"; + +import * as drawing from "./drawing"; +export { drawing }; + +/** + * Represents a CSS color with red, green, blue and alpha components. + * + * Instances of this class are immutable. + * + * @param {number} red + * @param {number} green + * @param {number} blue + * @param {number=1} alpha + */ +export class Color { + constructor(private _red: number, private _green: number, private _blue: number, private _alpha: number = 1) { } + + /** + * The red component of this color as a number between 0 and 255. + * + * @type {number} + */ + get red(): number { + return this._red; + } + + /** + * The green component of this color as a number between 0 and 255. + * + * @type {number} + */ + get green(): number { + return this._green; + } + + /** + * The blue component of this color as a number between 0 and 255. + * + * @type {number} + */ + get blue(): number { + return this._blue; + } + + /** + * The alpha component of this color as a number between 0 and 1, where 0 means transparent and 1 means opaque. + * + * @type {number} + */ + get alpha(): number { + return this._alpha; + } + + /** + * @param {?number} value The new alpha. If null, the existing alpha is used. + * @return {!libjass.parts.Color} Returns a new Color instance with the same color but the provided alpha. + */ + withAlpha(value: number): Color { + return new Color(this._red, this._green, this._blue, value); + } + + /** + * @return {string} The CSS representation "rgba(...)" of this color. + */ + toString(): string { + return `rgba(${ this._red }, ${ this._green }, ${ this._blue }, ${ this._alpha.toFixed(3) })`; + } + + /** + * Returns a new Color by interpolating the current color to the final color by the given progression. + * + * @param {!libjass.parts.Color} final + * @param {number} progression + * @return {!libjass.parts.Color} + */ + interpolate(final: Color, progression: number): Color { + return new Color( + this._red + progression * (final.red - this._red), + this._green + progression * (final.green - this._green), + this._blue + progression * (final.blue - this._blue), + this._alpha + progression * (final.alpha - this._alpha), + ); + } +} + +/** + * The base interface of the ASS tag classes. + */ +export interface Part { } + +/** + * A comment, i.e., any text enclosed in {} that is not understood as an ASS tag. + * + * @param {string} value The text of this comment + */ +export class Comment { + constructor(private _value: string) { } + + /** + * The value of this comment. + * + * @type {string} + */ + get value(): string { + return this._value; + } +} + +/** + * A block of text, i.e., any text not enclosed in {}. Also includes \h. + * + * @param {string} value The content of this block of text + */ +export class Text { + constructor(private _value: string) { } + + /** + * The value of this text part. + * + * @type {string} + */ + get value(): string { + return this._value; + } + + /** + * @return {string} + */ + toString(): string { + return `Text { value: ${ this._value.replace(/\u00A0/g, "\\h") } }`; + } +} + +/** + * A newline character \N. + */ +export class NewLine { +} + +/** + * A soft newline character \n. + */ +export class SoftNewLine { +} + +/** + * An italic tag {\i} + * + * @param {?boolean} value {\i1} -> true, {\i0} -> false, {\i} -> null + */ +export class Italic { + constructor(private _value: boolean | null) { } + + /** + * The value of this italic tag. + * + * @type {?boolean} + */ + get value(): boolean | null { + return this._value; + } +} + +/** + * A bold tag {\b} + * + * @param {?boolean|?number} value {\b1} -> true, {\b0} -> false, {\b###} -> weight of the bold (number), {\b} -> null + */ +export class Bold { + constructor(private _value: boolean | number | null) { } + + /** + * The value of this bold tag. + * + * @type {?boolean|?number} + */ + get value(): boolean | number | null { + return this._value; + } +} + +/** + * An underline tag {\u} + * + * @param {?boolean} value {\u1} -> true, {\u0} -> false, {\u} -> null + */ +export class Underline { + constructor(private _value: boolean | null) { } + + /** + * The value of this underline tag. + * + * @type {?boolean} + */ + get value(): boolean | null { + return this._value; + } +} + +/** + * A strike-through tag {\s} + * + * @param {?boolean} value {\s1} -> true, {\s0} -> false, {\s} -> null + */ +export class StrikeThrough { + constructor(private _value: boolean | null) { } + + /** + * The value of this strike-through tag. + * + * @type {?boolean} + */ + get value(): boolean | null { + return this._value; + } +} + +/** + * A border tag {\bord} + * + * @param {?number} value {\bord###} -> width (number), {\bord} -> null + */ +export class Border { + constructor(private _value: number | null) { } + + /** + * The value of this border tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A horizontal border tag {\xbord} + * + * @param {?number} value {\xbord###} -> width (number), {\xbord} -> null + */ +export class BorderX { + constructor(private _value: number | null) { } + + /** + * The value of this horizontal border tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A vertical border tag {\ybord} + * + * @param {?number} value {\ybord###} -> height (number), {\ybord} -> null + */ +export class BorderY { + constructor(private _value: number | null) { } + + /** + * The value of this vertical border tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A shadow tag {\shad} + * + * @param {?number} value {\shad###} -> depth (number), {\shad} -> null + */ +export class Shadow { + constructor(private _value: number | null) { } + + /** + * The value of this shadow tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A horizontal shadow tag {\xshad} + * + * @param {?number} value {\xshad###} -> depth (number), {\xshad} -> null + */ +export class ShadowX { + constructor(private _value: number | null) { } + + /** + * The value of this horizontal shadow tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A vertical shadow tag {\yshad} + * + * @param {?number} value {\yshad###} -> depth (number), {\yshad} -> null + */ +export class ShadowY { + constructor(private _value: number | null) { } + + /** + * The value of this vertical shadow tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A blur tag {\be} + * + * @param {?number} value {\be###} -> strength (number), {\be} -> null + */ +export class Blur { + constructor(private _value: number | null) { } + + /** + * The value of this blur tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A Gaussian blur tag {\blur} + * + * @param {?number} value {\blur###} -> strength (number), {\blur} -> null + */ +export class GaussianBlur { + constructor(private _value: number | null) { } + + /** + * The value of this Gaussian blur tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A font name tag {\fn} + * + * @param {?string} value {\fn###} -> name (string), {\fn} -> null + */ +export class FontName { + constructor(private _value: string | null) { } + + /** + * The value of this font name tag. + * + * @type {?string} + */ + get value(): string | null { + return this._value; + } +} + +/** + * A font size tag {\fs} + * + * @param {?number} value {\fs###} -> size (number), {\fs} -> null + */ +export class FontSize { + constructor(private _value: number | null) { } + + /** + * The value of this font size tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A font size increase tag {\fs+} + * + * @param {number} value {\fs+###} -> relative difference (number, percentage) + */ +export class FontSizePlus { + constructor(private _value: number) { } + + /** + * The value of this font size increase tag. + * + * @type {number} + */ + get value(): number { + return this._value; + } +} + +/** + * A font size decrease tag {\fs-} + * + * @param {number} value {\fs-###} -> relative difference (number, percentage) + */ +export class FontSizeMinus { + constructor(private _value: number) { } + + /** + * The value of this font size decrease tag. + * + * @type {number} + */ + get value(): number { + return this._value; + } +} + +/** + * A horizontal font scaling tag {\fscx} + * + * @param {?number} value {\fscx###} -> scale (number), {\fscx} -> null + */ +export class FontScaleX { + constructor(private _value: number | null) { } + + /** + * The value of this horizontal font scaling tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A vertical font scaling tag {\fscy} + * + * @param {?number} value {\fscy###} -> scale (number), {\fscy} -> null + */ +export class FontScaleY { + constructor(private _value: number | null) { } + + /** + * The value of this vertical font scaling tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A letter-spacing tag {\fsp} + * + * @param {?number} value {\fsp###} -> spacing (number), {\fsp} -> null + */ +export class LetterSpacing { + constructor(private _value: number | null) { } + + /** + * The value of this letter-spacing tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * An X-axis rotation tag {\frx} + * + * @param {?number} value {\frx###} -> angle (number), {\frx} -> null + */ +export class RotateX { + constructor(private _value: number | null) { } + + /** + * The value of this X-axis rotation tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A Y-axis rotation tag {\fry} + * + * @param {?number} value {\fry###} -> angle (number), {\fry} -> null + */ +export class RotateY { + constructor(private _value: number | null) { } + + /** + * The value of this Y-axis rotation tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A Z-axis rotation tag {\fr} or {\frz} + * + * @param {?number} value {\frz###} -> angle (number), {\frz} -> null + */ +export class RotateZ { + constructor(private _value: number | null) { } + + /** + * The value of this Z-axis rotation tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * An X-axis shearing tag {\fax} + * + * @param {?number} value {\fax###} -> angle (number), {\fax} -> null + */ +export class SkewX { + constructor(private _value: number | null) { } + + /** + * The value of this X-axis shearing tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A Y-axis shearing tag {\fay} + * + * @param {?number} value {\fay###} -> angle (number), {\fay} -> null + */ +export class SkewY { + constructor(private _value: number | null) { } + + /** + * The value of this Y-axis shearing tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A primary color tag {\c} or {\1c} + * + * @param {libjass.parts.Color} value {\1c###} -> color (Color), {\1c} -> null + */ +export class PrimaryColor { + constructor(private _value: Color | null) { } + + /** + * The value of this primary color tag. + * + * @type {libjass.parts.Color} + */ + get value(): Color | null { + return this._value; + } +} + +/** + * A secondary color tag {\2c} + * + * @param {libjass.parts.Color} value {\2c###} -> color (Color), {\2c} -> null + */ +export class SecondaryColor { + constructor(private _value: Color | null) { } + + /** + * The value of this secondary color tag. + * + * @type {libjass.parts.Color} + */ + get value(): Color | null { + return this._value; + } +} + +/** + * An outline color tag {\3c} + * + * @param {libjass.parts.Color} value {\3c###} -> color (Color), {\3c} -> null + */ +export class OutlineColor { + constructor(private _value: Color | null) { } + + /** + * The value of this outline color tag. + * + * @type {libjass.parts.Color} + */ + get value(): Color | null { + return this._value; + } +} + +/** + * A shadow color tag {\4c} + * + * @param {libjass.parts.Color} value {\4c###} -> color (Color), {\4c} -> null + */ +export class ShadowColor { + constructor(private _value: Color | null) { } + + /** + * The value of this shadow color tag. + * + * @type {libjass.parts.Color} + */ + get value(): Color | null { + return this._value; + } +} + +/** + * An alpha tag {\alpha} + * + * @param {?number} value {\alpha###} -> alpha (number), {\alpha} -> null + */ +export class Alpha { + constructor(private _value: number | null) { } + + /** + * The value of this alpha tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A primary alpha tag {\1a} + * + * @param {?number} value {\1a###} -> alpha (number), {\1a} -> null + */ +export class PrimaryAlpha { + constructor(private _value: number | null) { } + + /** + * The value of this primary alpha tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A secondary alpha tag {\2a} + * + * @param {?number} value {\2a###} -> alpha (number), {\2a} -> null + */ +export class SecondaryAlpha { + constructor(private _value: number | null) { } + + /** + * The value of this secondary alpha tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * An outline alpha tag {\3a} + * + * @param {?number} value {\3a###} -> alpha (number), {\3a} -> null + */ +export class OutlineAlpha { + constructor(private _value: number | null) { } + + /** + * The value of this outline alpha tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * A shadow alpha tag {\4a} + * + * @param {?number} value {\4a###} -> alpha (number), {\4a} -> null + */ +export class ShadowAlpha { + constructor(private _value: number | null) { } + + /** + * The value of this shadow alpha tag. + * + * @type {?number} + */ + get value(): number | null { + return this._value; + } +} + +/** + * An alignment tag {\an} or {\a} + * + * @param {number} value {\an###} -> alignment (number) + */ +export class Alignment { + constructor(private _value: number) { } + + /** + * The value of this alignment tag. + * + * @type {number} + */ + get value(): number { + return this._value; + } +} + +/** + * A color karaoke tag {\k} + * + * @param {number} duration {\k###} -> duration (number) + */ +export class ColorKaraoke { + constructor(private _duration: number) { } + + /** + * The duration of this color karaoke tag. + * + * @type {number} + */ + get duration(): number { + return this._duration; + } +} + +/** + * A sweeping color karaoke tag {\K} or {\kf} + * + * @param {number} duration {\kf###} -> duration (number) + */ +export class SweepingColorKaraoke { + constructor(private _duration: number) { } + + /** + * The duration of this sweeping color karaoke tag. + * + * @type {number} + */ + get duration(): number { + return this._duration; + } +} + +/** + * An outline karaoke tag {\ko} + * + * @param {number} duration {\ko###} -> duration (number) + */ +export class OutlineKaraoke { + constructor(private _duration: number) { } + + /** + * The duration of this outline karaoke tag. + * + * @type {number} + */ + get duration(): number { + return this._duration; + } +} + +/** + * A wrapping style tag {\q} + * + * @param {number} value {\q###} -> style (number) + */ +export class WrappingStyle { + constructor(private _value: WrappingStyleType) { } + + /** + * The value of this wrapping style tag. + * + * @type {number} + */ + get value(): WrappingStyleType { + return this._value; + } +} + +/** + * A style reset tag {\r} + * + * @param {?string} value {\r###} -> style name (string), {\r} -> null + */ +export class Reset { + constructor(private _value: string | null) { } + + /** + * The value of this style reset tag. + * + * @type {?string} + */ + get value(): string | null { + return this._value; + } +} + +/** + * A position tag {\pos} + * + * @param {number} x + * @param {number} y + */ +export class Position { + constructor(private _x: number, private _y: number) { } + + /** + * The x value of this position tag. + * + * @type {number} + */ + get x(): number { + return this._x; + } + + /** + * The y value of this position tag. + * + * @type {number} + */ + get y(): number { + return this._y; + } +} + +/** + * A movement tag {\move} + * + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {?number} t1 + * @param {?number} t2 + */ +export class Move { + constructor(private _x1: number, private _y1: number, private _x2: number, private _y2: number, private _t1: number | null, private _t2: number | null) { } + + /** + * The starting x value of this move tag. + * + * @type {number} + */ + get x1(): number { + return this._x1; + } + + /** + * The starting y value of this move tag. + * + * @type {number} + */ + get y1(): number { + return this._y1; + } + + /** + * The ending x value of this move tag. + * + * @type {number} + */ + get x2(): number { + return this._x2; + } + + /** + * The ending y value of this move tag. + * + * @type {number} + */ + get y2(): number { + return this._y2; + } + + /** + * The start time of this move tag. + * + * @type {?number} + */ + get t1(): number | null { + return this._t1; + } + + /** + * The end time value of this move tag. + * + * @type {?number} + */ + get t2(): number | null { + return this._t2; + } +} + +/** + * A rotation origin tag {\org} + * + * @param {number} x + * @param {number} y + */ +export class RotationOrigin { + constructor(private _x: number, private _y: number) { } + + /** + * The x value of this rotation origin tag. + * + * @type {number} + */ + get x(): number { + return this._x; + } + + /** + * The y value of this rotation origin tag. + * + * @type {number} + */ + get y(): number { + return this._y; + } +} + +/** + * A simple fade tag {\fad} + * + * @param {number} start + * @param {number} end + */ +export class Fade { + constructor(private _start: number, private _end: number) { } + + /** + * The start time of this fade tag. + * + * @type {number} + */ + get start(): number { + return this._start; + } + + /** + * The end time of this fade tag. + * + * @type {number} + */ + get end(): number { + return this._end; + } +} + +/** + * A complex fade tag {\fade} + * + * @param {number} a1 + * @param {number} a2 + * @param {number} a3 + * @param {number} t1 + * @param {number} t2 + * @param {number} t3 + * @param {number} t4 + */ +export class ComplexFade { + constructor( + private _a1: number, private _a2: number, private _a3: number, + private _t1: number, private _t2: number, private _t3: number, private _t4: number, + ) { } + + /** + * The alpha value of this complex fade tag at time t2. + * + * @type {number} + */ + get a1(): number { + return this._a1; + } + + /** + * The alpha value of this complex fade tag at time t3. + * + * @type {number} + */ + get a2(): number { + return this._a2; + } + + /** + * The alpha value of this complex fade tag at time t4. + * + * @type {number} + */ + get a3(): number { + return this._a3; + } + + /** + * The starting time of this complex fade tag. + * + * @type {number} + */ + get t1(): number { + return this._t1; + } + + /** + * The first intermediate time of this complex fade tag. + * + * @type {number} + */ + get t2(): number { + return this._t2; + } + + /** + * The second intermediate time of this complex fade tag. + * + * @type {number} + */ + get t3(): number { + return this._t3; + } + + /** + * The ending time of this complex fade tag. + * + * @type {number} + */ + get t4(): number { + return this._t4; + } +} + +/** + * A transform tag {\t} + * + * @param {?number} start + * @param {?number} end + * @param {?number} accel + * @param {!Array.} tags + */ +export class Transform { + constructor(private _start: number | null, private _end: number | null, private _accel: number | null, private _tags: Part[]) { } + + /** + * The starting time of this transform tag. + * + * @type {?number} + */ + get start(): number | null { + return this._start; + } + + /** + * The ending time of this transform tag. + * + * @type {?number} + */ + get end(): number | null { + return this._end; + } + + /** + * The acceleration of this transform tag. + * + * @type {?number} + */ + get accel(): number | null { + return this._accel; + } + + /** + * The tags animated by this transform tag. + * + * @type {!Array.} + */ + get tags(): Part[] { + return this._tags; + } +} + +/** + * A rectangular clip tag {\clip} or {\iclip} + * + * @param {number} x1 + * @param {number} y1 + * @param {number} x2 + * @param {number} y2 + * @param {boolean} inside + */ +export class RectangularClip { + constructor(private _x1: number, private _y1: number, private _x2: number, private _y2: number, private _inside: boolean) { } + + /** + * The X coordinate of the starting position of this rectangular clip tag. + * + * @type {number} + */ + get x1(): number { + return this._x1; + } + + /** + * The Y coordinate of the starting position of this rectangular clip tag. + * + * @type {number} + */ + get y1(): number { + return this._y1; + } + + /** + * The X coordinate of the ending position of this rectangular clip tag. + * + * @type {number} + */ + get x2(): number { + return this._x2; + } + + /** + * The Y coordinate of the ending position of this rectangular clip tag. + * + * @type {number} + */ + get y2(): number { + return this._y2; + } + + /** + * Whether this rectangular clip tag clips the region it encloses or the region it excludes. + * + * @type {boolean} + */ + get inside(): boolean { + return this._inside; + } +} + +/** + * A vector clip tag {\clip} or {\iclip} + * + * @param {number} scale + * @param {!Array.} instructions + * @param {boolean} inside + */ +export class VectorClip { + constructor(private _scale: number, private _instructions: drawing.Instruction[], private _inside: boolean) { } + + /** + * The scale of this vector clip tag. + * + * @type {number} + */ + get scale(): number { + return this._scale; + } + + /** + * The clip commands of this vector clip tag. + * + * @type {string} + */ + get instructions(): drawing.Instruction[] { + return this._instructions; + } + + /** + * Whether this vector clip tag clips the region it encloses or the region it excludes. + * + * @type {boolean} + */ + get inside(): boolean { + return this._inside; + } +} + +/** + * A drawing mode tag {\p} + * + * @param {number} scale + */ +export class DrawingMode { + constructor(private _scale: number) { } + + /** + * The scale of this drawing mode tag. + * + * @type {number} + */ + get scale(): number { + return this._scale; + } +} + +/** + * A drawing mode baseline offset tag {\pbo} + * + * @param {number} value + */ +export class DrawingBaselineOffset { + constructor(private _value: number) { } + + /** + * The value of this drawing mode baseline offset tag. + * + * @type {number} + */ + get value(): number { + return this._value; + } +} + +/** + * A pseudo-part representing text interpreted as drawing instructions + * + * @param {!Array.} instructions + */ +export class DrawingInstructions { + constructor(private _instructions: drawing.Instruction[]) { } + + /** + * The instructions contained in this drawing instructions part. + * + * @type {!Array.} + */ + get instructions(): drawing.Instruction[] { + return this._instructions; + } +} + +const addToString = function (ctor: Function, ctorName: string): void { + if (!ctor.prototype.hasOwnProperty("toString")) { + const propertyNames = Object.getOwnPropertyNames(ctor.prototype).filter(property => property !== "constructor"); + + ctor.prototype.toString = function (this: any): string { + return `${ ctorName } { ${ propertyNames.map(name => `${ name }: ${ this[name] }`).join(", ") }${ (propertyNames.length > 0) ? " " : "" }}`; + }; + } +}; + +import { registerClass } from "../serialization"; + +for (const key of Object.keys(exports)) { + const value: any = exports[key]; + if (value instanceof Function) { + addToString(value, key); + registerClass(value); + } +} + +for (const key of Object.keys(drawing)) { + const value: any = (drawing as any)[key]; + if (value instanceof Function) { + addToString(value, `Drawing${ key }`); + registerClass(value); + } +} diff --git a/negromate/web/static/js/libjass/src/renderers/clocks/auto.ts b/negromate/web/static/js/libjass/src/renderers/clocks/auto.ts new file mode 100644 index 0000000..b5d7eee --- /dev/null +++ b/negromate/web/static/js/libjass/src/renderers/clocks/auto.ts @@ -0,0 +1,252 @@ +/** + * libjass + * + * https://github.com/Arnavion/libjass + * + * Copyright 2013 Arnav Singh + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { debugMode } from "../../settings"; + +import { Clock, ClockEvent } from "./base"; +import { ManualClock } from "./manual"; + +/** + * An implementation of {@link libjass.renderers.Clock} that automatically ticks and generates {@link libjass.renderers.ClockEvent}s according to the state of an external driver. + * + * For example, if you're using libjass to render subtitles on a canvas with your own video controls, these video controls will function as the driver to this AutoClock. + * It would call {@link libjass.renderers.AutoClock.play}, {@link libjass.renderers.AutoClock.pause}, etc. when the user pressed the corresponding video controls. + * + * The difference from ManualClock is that AutoClock does not require the driver to call something like {@link libjass.renderers.ManualClock.tick}. Instead it keeps its + * own time with a high-resolution requestAnimationFrame-based timer. + * + * If using libjass with a