Compare commits
435 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3d3ef58d73 | |||
| d2db781f82 | |||
| 11d1b36fc3 | |||
| 509aa3b52d | |||
| d916a8dece | |||
| ff9fa3954d | |||
| 9b0e15cd78 | |||
| 795bef96ac | |||
| 45f081ba54 | |||
| 308715a495 | |||
| abbbd6bf04 | |||
| 569fce4072 | |||
| 5b88230c32 | |||
| 097854f30f | |||
| 6fc6bcc4b2 | |||
| 0045ebe3fb | |||
| 1cefb68b47 | |||
| 78bab74e11 | |||
| a43f2da4c9 | |||
| 7ff81409c7 | |||
| 0661ada8e6 | |||
| ec1c180173 | |||
| d5969cc2f5 | |||
| b23f6e4e9f | |||
| da1e7ed52b | |||
| e6d3195df0 | |||
| 81117ce07b | |||
| 6dbee54f6a | |||
| 5f9890d157 | |||
| db1201d84e | |||
| f3ab2bc57f | |||
| a4c617f1df | |||
| e1b993a0ae | |||
| 42db525b30 | |||
| 76691cc52b | |||
| 82f3706eff | |||
| a0ac2ba83b | |||
| b89b5f76bb | |||
| 2bfdcb582c | |||
| 604129a10d | |||
| 563141f1c4 | |||
| a0d49f4ee5 | |||
| 23445a82c4 | |||
| 0c51760fc5 | |||
| 2ce0d7985a | |||
| f8eb111f89 | |||
| 9e9ba88ede | |||
| 8ed209bba4 | |||
| 0260014524 | |||
| c6cafd10d4 | |||
| e46f0322ed | |||
| 0ecb96c42a | |||
| 191a34d060 | |||
| 484997e3fc | |||
| 7482220201 | |||
| 6606413eef | |||
| 6dce371011 | |||
| 6b2800ef70 | |||
| 29c187f076 | |||
| 7d7217007a | |||
| e783afc43c | |||
| 4183228262 | |||
| b92b63f94f | |||
| 4ddab3a2d9 | |||
| 3b381ac925 | |||
| 1d803dd1b8 | |||
| 074f3ec723 | |||
| caf6701c7b | |||
| 99d72711be | |||
| 7ed52215cb | |||
| 50e9140ee3 | |||
| 6f81c4dc17 | |||
| 7a1dc0582c | |||
| d9f2431414 | |||
| cec2f13361 | |||
| 6939e10c9b | |||
| 2ee04485d6 | |||
| d98f3ea94f | |||
| 83b6ae9f64 | |||
| 92397aa351 | |||
| 5e64329a8c | |||
| c0e0dec1fb | |||
| 90c781c4e2 | |||
| 74636c4098 | |||
| bc989a5761 | |||
| 586ff43bec | |||
| e856423ee1 | |||
| 8e903ba50e | |||
| 68d898764e | |||
| 9bde3b9982 | |||
| c4c935175e | |||
| c7986b0eab | |||
| a1dfc2f79d | |||
| bda06a8385 | |||
| 0dd0df60f5 | |||
| d4956466e4 | |||
| 0b4c66f88a | |||
| f21b90b061 | |||
| 1df6c44007 | |||
| 53f96a2367 | |||
| f6b4b705e0 | |||
| fc3c62af0a | |||
| fe2f7bde9e | |||
| 070ef1aee3 | |||
| d05e8015b4 | |||
| cb52d62158 | |||
| 232dddf6e5 | |||
| 53d9721f18 | |||
| 981132c08a | |||
| ff1739fe67 | |||
| 3df0b5bab7 | |||
| f9a8791280 | |||
| 3140391c16 | |||
| 6fa2b2c581 | |||
| c099015f6a | |||
| 9e039ee13d | |||
| 8a53a56157 | |||
| ff04dbab24 | |||
| a9ec919118 | |||
| 676f167180 | |||
| 3a277f9295 | |||
| c469780107 | |||
| 539fa58daf | |||
| 3df3eb7c11 | |||
| eebbad7fd1 | |||
| 0cd9dbe150 | |||
| 5b783850e8 | |||
| 0c2fecd1cc | |||
| d1b17204e9 | |||
| 0292acc20c | |||
| f1e820819c | |||
| c28c722263 | |||
| 64ac166485 | |||
| 8cabd87c60 | |||
| 6986531992 | |||
| 42282c2807 | |||
| f2765085c4 | |||
| 8e28a95e4e | |||
| 782d34c3eb | |||
| b2d9b757e2 | |||
| 41cb005ec6 | |||
| d84573038d | |||
| e047bed5b9 | |||
| 3a9528479b | |||
| ba7f990190 | |||
| 0c76be560e | |||
| 01214bb3f6 | |||
| 2f183071b6 | |||
| 8e12db7564 | |||
| e2eb93748d | |||
| c8a2ea8a1e | |||
| 124d309a4d | |||
| f407b40abb | |||
| be09db8218 | |||
| 36e99a7853 | |||
| bfe847e3bd | |||
| 87c1050089 | |||
| f3d7d4b681 | |||
| 2d65d19fc6 | |||
| 498a6a7cbe | |||
| 52bd57395d | |||
| 618ca069fc | |||
| f3a07a3984 | |||
| eaf2c40e1d | |||
| aa0f15b348 | |||
| 9c5900ebc0 | |||
| b9e6611b1b | |||
| dd52b024d0 | |||
| 5ec1fd9499 | |||
| 36d881b601 | |||
| e9019bd6c0 | |||
| 798482c3d1 | |||
| 07641a3842 | |||
| b1b59869ec | |||
| 67e963f498 | |||
| b6974ce17f | |||
| b0bbfb3b9b | |||
| 3d383a956a | |||
| 79d5ac7789 | |||
| 91524988b4 | |||
| 39990739bd | |||
| dde42d8d8a | |||
| c11a9900e8 | |||
| e811f8c05f | |||
| f6e5a3fd80 | |||
| 9958465b34 | |||
| a9d6700ad6 | |||
| de6cc6bbc4 | |||
| 292c5c3dee | |||
| 30cffd6725 | |||
| a9275aecd6 | |||
| e670c491c2 | |||
| 8025fa324e | |||
| 51d2715e0a | |||
| 67ecdb8151 | |||
| 84fa5b6423 | |||
| b3290a1bd4 | |||
| d31f459704 | |||
| c401eb4043 | |||
| 5c0140cd95 | |||
| 66557f247c | |||
| b8aca3fc53 | |||
| e4671348c5 | |||
| ef223d83a8 | |||
| aa64b76214 | |||
| 979dec810e | |||
| 866a44d46f | |||
| 4c4eea9b47 | |||
| 696730244c | |||
| 5065ab4658 | |||
| 4f8474aa66 | |||
| f6a9f63213 | |||
| 352b26320e | |||
| aef4466a03 | |||
| bb8c106b5a | |||
| d399ff88f9 | |||
| 2d5534042b | |||
| 83bbe54273 | |||
| f94c95b38a | |||
| 28491b8268 | |||
| b7e3b98a13 | |||
| 7e69289727 | |||
| aabc163160 | |||
| 099c812e4b | |||
| b98eeadcdd | |||
| 83e125fe36 | |||
| 80ff9679cf | |||
| edda987835 | |||
| f48f5736dd | |||
| 463f63c1cb | |||
| 0c425859b9 | |||
| 27136eff07 | |||
| d32da0126e | |||
| 2a53165151 | |||
| e17fb75f6c | |||
| 93a5209e85 | |||
| e22a447cfe | |||
| b6e31a68a2 | |||
| 8a61f500a8 | |||
| b1ebe70f3d | |||
| 6d1d6d7aa3 | |||
| 05fdc87824 | |||
| 8e1ab7ed00 | |||
| b2ff78a037 | |||
| 96c4c09bd7 | |||
| ef8d638494 | |||
| 538543b0e8 | |||
| ed2d262608 | |||
| bbca3726d3 | |||
| 63c258b106 | |||
| 443570baa7 | |||
| b58ec66203 | |||
| a93afd1ffb | |||
| 71151b265d | |||
| 534c2cfc4d | |||
| c505b9cea5 | |||
| 46bd989252 | |||
| 8511c3f39c | |||
| baa9bd58b4 | |||
| c45b647cdd | |||
| 34b067a18e | |||
| 39ee4dfd34 | |||
| 2f2a19ee7e | |||
| 49e70f68af | |||
| 88149e8dc3 | |||
| 0371028b01 | |||
| 04011260f9 | |||
| 12f869effc | |||
| e03f0ea0d6 | |||
| 49562a8920 | |||
| 7e4cf218ff | |||
| 091a39a900 | |||
| 93753bdcde | |||
| 859eddb9af | |||
| 2e7ef509a1 | |||
| 16865b5dd8 | |||
| 5c36832fd0 | |||
| 879d85ac55 | |||
| e6a2f1b6bc | |||
| 5c69780a87 | |||
| b8706a1dcd | |||
| 55d0817352 | |||
| 4bfacf2a79 | |||
| ac0faab286 | |||
| cdf8c59c81 | |||
| 10ad819efc | |||
| 59a4d471cf | |||
| 4d3c37a353 | |||
| 4696467fc1 | |||
| 87e3e25038 | |||
| 46f414aa91 | |||
| f47ec8a5d7 | |||
| 08a9e156d3 | |||
| 106a7872d0 | |||
| 47b6613601 | |||
| 8011022c5e | |||
| b4d3f21b96 | |||
| cc67654d7a | |||
| 08b76b72ef | |||
| b72fd99871 | |||
| ce5895a932 | |||
| 8bccf4c791 | |||
| eb23363bf0 | |||
| 69a981ac3f | |||
| 2f36f34960 | |||
| 18f0d0463c | |||
| 2932fbac12 | |||
| fec7bd504b | |||
| 04699eb800 | |||
| 37fcb59ee8 | |||
| d6c66b41ca | |||
| c05ede82b3 | |||
| 72f221db59 | |||
| 6d1b29628a | |||
| 7111648548 | |||
| 621d2b7efc | |||
| 9c599e4a92 | |||
| 2608d59885 | |||
| 43d3002b63 | |||
| f7fc52a6d7 | |||
| d842e4fa3b | |||
| 985e9c8de8 | |||
| cb2faea9d9 | |||
| 887655c058 | |||
| dc284f9992 | |||
| 062dab65d4 | |||
| 73d0b94459 | |||
| 75ecb533b2 | |||
| c4f04b12ee | |||
| 385d0a7992 | |||
| 6efd6c4202 | |||
| aa05790c8e | |||
| 2916af4972 | |||
| 1c5bf4375e | |||
| 8810ff2076 | |||
| ea4fba1fdb | |||
| 3f5c8b6cfd | |||
| 3dda004d23 | |||
| ff3e85dda1 | |||
| 05e692b380 | |||
| 9a65557adc | |||
| 188a349947 | |||
| 8497fccdb4 | |||
| 199af87d77 | |||
| 49545fbc00 | |||
| 125b2b280b | |||
| 54cf2673f4 | |||
| 8fa92017c5 | |||
| a053e6a44a | |||
| e3ed3e82fb | |||
| 73755e0c8a | |||
| f951475103 | |||
| 77474771e6 | |||
| 55f9cb42fe | |||
| a8addddbd6 | |||
| ccd4a53cfb | |||
| 3928bf57f0 | |||
| dd6d008b74 | |||
| 45aabac358 | |||
| 55c9dc10ca | |||
| 32c232308f | |||
| 2eaa6e451d | |||
| 03ed6091c2 | |||
| 43c3e26596 | |||
| 9e584bb75b | |||
| e62f150f32 | |||
| 24ccc5200c | |||
| c627e72b03 | |||
| 6eeb634a36 | |||
| 2349b82f0f | |||
| 443714878b | |||
| 7a6f956b49 | |||
| 73e464e357 | |||
| 71d58e686c | |||
| adaba54be0 | |||
| 5be310a6ba | |||
| ee45e0379e | |||
| 848898c8d0 | |||
| deda90698b | |||
| 774b218aff | |||
| 6bb4873d67 | |||
| 54b4245482 | |||
| 39d75c189d | |||
| ae56620f91 | |||
| ee07ca1d7c | |||
| b6ca859f4b | |||
| c4f87d54bf | |||
| b662698e0c | |||
| 0198fb235c | |||
| fc5dce86ea | |||
| d918b1256d | |||
| c65305fbe8 | |||
| 111c4199ff | |||
| 8bc205fc01 | |||
| e69221af7d | |||
| 6ba048e55a | |||
| 8dda6d67e6 | |||
| 7c6793be8c | |||
| 123339519d | |||
| 12374765ed | |||
| 255447b147 | |||
| 32507ad644 | |||
| d06777d2b3 | |||
| b727f3c6e2 | |||
| 140393fcca | |||
| 2d308b7130 | |||
| 6a282416a8 | |||
| 40ebcfc6b7 | |||
| d23e57d215 | |||
| 77ca69e1d3 | |||
| c2ff6dc369 | |||
| af9ea7c886 | |||
| e1eb4f8e6f | |||
| 7303fd0f53 | |||
| 96bf8d7f6c | |||
| 74de507782 | |||
| 0155cd7392 | |||
| 974c8f70ff | |||
| e4cd237779 | |||
| 4dec3b36f4 | |||
| e275cfbf2e | |||
| 4d25127617 | |||
| 8f6deb2f8e | |||
| 3958d9f504 | |||
| 120a8e8cbd | |||
| 99dfafeafd | |||
| 379265414a | |||
| e09a34cca6 | |||
| b49bd14e55 | |||
| febd4f18ca | |||
| a633963b9f | |||
| b0db48f28e | |||
| c893984115 | |||
| a4ef8b7ef8 | |||
| a26a238b09 |
@@ -1,7 +1,12 @@
|
||||
build/doc.js
|
||||
build/typescript/typescript.d.ts
|
||||
build/typescript/*.js
|
||||
|
||||
dist/
|
||||
|
||||
lib/
|
||||
!lib/libjass.css
|
||||
|
||||
node_modules/
|
||||
|
||||
libjass.js
|
||||
libjass.min.js
|
||||
*.map
|
||||
|
||||
*.log
|
||||
npm-debug.log
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.10"
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.10"
|
||||
- "0.12"
|
||||
- "4"
|
||||
- "5"
|
||||
before_script:
|
||||
- "node ./build.js doc"
|
||||
sudo: false
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
1. Install node.js from http://nodejs.org/ or via your package manager
|
||||
|
||||
1. Change to the directory where you cloned this repository.
|
||||
|
||||
1. Run the following command
|
||||
|
||||
npm install
|
||||
|
||||
This will install the dependencies - [Gulp](http://gulpjs.com/), [Mocha](http://visionmedia.github.io/mocha/), [TypeScript](http://www.typescriptlang.org/), [UglifyJS2](https://github.com/mishoo/UglifyJS2) and [Vinyl](https://github.com/wearefractal/vinyl). It will then run gulp to build libjass.js and minify it into libjass.min.js
|
||||
|
||||
1. Set the URLs of the video and the ASS file in index.xhtml
|
||||
|
||||
<video id="video" src=" <URL OF VIDEO HERE> " controls="">
|
||||
<track src=" <URL OF SCRIPT HERE> " kind="metadata" data-format="ass" />
|
||||
</video>
|
||||
|
||||
1. Set the URLs of any fonts you want to make available in fonts.css
|
||||
|
||||
@font-face {
|
||||
font-family: " <NAME OF FONT HERE> ";
|
||||
src: url(" <URL OF FONT HERE> ");
|
||||
}
|
||||
for each font. The name of the font is what it's called in the ASS file.
|
||||
|
||||
1. Start your web server and navigate to index.xhtml in a browser.
|
||||
@@ -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<target_style> 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.
|
||||
@@ -1,55 +1,142 @@
|
||||
[](https://travis-ci.org/Arnavion/libjass)
|
||||
|
||||
libjass is a JavaScript library written in TypeScript to render ASS subs on HTML5 video in the browser.
|
||||
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.
|
||||
|
||||
* It's easy to deploy. There is no server-side support required. A static hosting is all that's needed.
|
||||
|
||||
* 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.
|
||||
|
||||
|
||||
### What are all these files?
|
||||
|
||||
* The .ts files are the source of libjass. They are TypeScript files and must be compiled into JavaScript for the browser using the TypeScript compiler.
|
||||
|
||||
* The rest of the files - index.xhtml, index.js, index.css and fonts.css - are a sample implementation of how to use libjass on a web page. They demonstrate the API to call, how to place <div> elements to render the subs, etc.
|
||||
|
||||
|
||||
### I want to use libjass for my website. What do I need to do?
|
||||
|
||||
1. You need to build libjass.js using the instructions in BUILD.md
|
||||
1. You need to load libjass.js and libjass.css on the page with your video.
|
||||
1. You need to call the libjass API.
|
||||
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/<release name>/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.
|
||||
|
||||
|
||||
### Where's the API documentation? What API do I need to call to use libjass?
|
||||
### 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 method [ASS.fromString()](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromString) takes in the raw ASS string and returns an [ASS](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS) object representing the script properties, the line styles and dialogue lines in it. The example index.js uses XHR to get this data using the URL specified in a track tag.
|
||||
* 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.
|
||||
|
||||
* index.js initializes a default renderer that libjass ships with, the [DefaultRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer). This renderer 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.
|
||||
* 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 handles resizing the subtitles when the user clicks the browser's native fullscreen-video button. index.js also contains code to change the size of the subtitles based on user input.
|
||||
* 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 - index.js creates this map from the @font-face rules in fonts.css.
|
||||
* 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 [libjass.renderers.makeFontMapFromStyleElement()](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.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 below and ask any questions.
|
||||
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)
|
||||
|
||||
|
||||
### Links
|
||||
@@ -60,31 +147,6 @@ You can also join the IRC channel below and ask any questions.
|
||||
* [Aegisub's documentation on ASS](http://docs.aegisub.org/3.0/ASS_Tags/)
|
||||
|
||||
|
||||
### 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, \blur, \fn, \fs, \fscx, \fscy, \fsp, \frx, \fry, \frz, \fr, \fax, \fay, \c, \1c, \3c, \4c, \alpha, \1a, \3a, \4a, \an, \a, \r, \pos, \move, \fad, \fade, \p
|
||||
* Custom fonts, using CSS web fonts.
|
||||
|
||||
|
||||
### Known issues
|
||||
|
||||
* Unsupported tags: \be, \fe, \2c, \2a, \k, \K, \kf, \ko, \q, \org, \t, \clip, \iclip
|
||||
* \an4, \an5, \an6 aren't positioned correctly.
|
||||
* Lines scaled using {\fscx} and {\fscy} have their text clip into itself in some situations, and aren't always positioned correctly.
|
||||
* All lines are rendered as wrapping style 1 (end-of-line wrapping).
|
||||
* Lines with multiple rotations aren't rotated the same as VSFilter or libass.
|
||||
* Subtitles aren't styled in IE11 because [it doesn't support SVG filter effects on HTML](http://caniuse.com/svg-html).
|
||||
|
||||
|
||||
### Planned improvements
|
||||
|
||||
* Document browser compatibility. Currently libjass is tested on IE11 (Windows 7), Firefox Nightly and Google Chrome (Dev channel).
|
||||
* Write API documentation. Add more explanatory comments to the code.
|
||||
* Write more parser tests. Also figure out a way to test layout.
|
||||
* Evaluate (document, benchmark) the benefits and drawbacks of DOM+CSS-based drawing over canvas.
|
||||
|
||||
|
||||
### License
|
||||
|
||||
```
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* 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("libjass.js", ["build-tools"], 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("./src/index", "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(["./lib/libjass.js", "./lib/libjass.js.map", "./lib/libjass.min.js", "./lib/libjass.min.js.map"]));
|
||||
|
||||
task("watch", ["build-tools"], 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("./src/index", "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"], 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);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,893 @@
|
||||
/**
|
||||
* 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 fs from "fs";
|
||||
import * as path from "path";
|
||||
import { Transform } from "stream";
|
||||
|
||||
import { File, FileTransform } from "async-build";
|
||||
|
||||
import * as AST from "./typescript/ast";
|
||||
import { Compiler } from "./typescript/compiler";
|
||||
import { walk } from "./typescript/walker";
|
||||
|
||||
function flatten<T>(arr: T[][]): T[] {
|
||||
var result: T[] = [];
|
||||
|
||||
for (const a of arr) {
|
||||
result = result.concat(a);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
var 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;
|
||||
}
|
||||
|
||||
var types = [AST.Property, AST.Function, AST.Interface, AST.Class, AST.Enum];
|
||||
function typeSorter(value1: AST.ModuleMember | AST.NamespaceMember, value2: AST.ModuleMember | AST.NamespaceMember) {
|
||||
var type1Index = -1;
|
||||
var 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);
|
||||
}
|
||||
|
||||
var sorters: ((value1: AST.ModuleMember, value2: AST.ModuleMember) => number)[] = [visibilitySorter, typeSorter, nameSorter];
|
||||
|
||||
return (value1: AST.ModuleMember, value2: AST.ModuleMember) => {
|
||||
for (var i = 0; i < sorters.length; i++) {
|
||||
var result = sorters[i](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, "<").replace(/>/g, ">");
|
||||
}
|
||||
|
||||
function toVariableName(item: { name: string }) {
|
||||
// TODO: Handle non-letters (are both their toLowerCase() and toUpperCase())
|
||||
|
||||
var name = item.name;
|
||||
var result = "";
|
||||
|
||||
for (var 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 ((<AST.Class | AST.Interface | AST.Function | AST.Enum>item).isPrivate) {
|
||||
return item.name;
|
||||
}
|
||||
|
||||
return item.fullName;
|
||||
}
|
||||
|
||||
if ((<AST.Function>item).isStatic) {
|
||||
return toUsageName(<AST.Class | AST.Interface>item.parent) + '.' + 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 {
|
||||
var result = `<a href="#${ toId(item) }">${ sanitize(item.name) }`;
|
||||
|
||||
var itemWithGenerics = <AST.HasGenerics>item;
|
||||
if (itemWithGenerics.generics !== undefined && itemWithGenerics.generics.length > 0) {
|
||||
var generics = <(string | AST.TypeReference | AST.IntrinsicTypeReference)[]>itemWithGenerics.generics;
|
||||
result += sanitize(`.<${ generics.map(generic =>
|
||||
(generic instanceof AST.TypeReference || generic instanceof AST.IntrinsicTypeReference) ? generic.name : <string>generic
|
||||
).join(', ') }>`);
|
||||
}
|
||||
|
||||
result += '</a>';
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function writeDescription(text: string): string {
|
||||
var result = sanitize(text).replace(/\{@link ([^} ]+)\}/g, (substring, linkTarget) => `<a href="#${ linkTarget }">${ linkTarget }</a>`);
|
||||
|
||||
var inCodeBlock = false;
|
||||
result = result.split("\n").map(line => {
|
||||
if (line.substr(0, " ".length) === " ") {
|
||||
line = line.substr(" ".length);
|
||||
|
||||
if (!inCodeBlock) {
|
||||
inCodeBlock = true;
|
||||
line = `<pre class="code"><code>${ line }`;
|
||||
}
|
||||
}
|
||||
else if (line.length > 0 && inCodeBlock) {
|
||||
inCodeBlock = false;
|
||||
line = `</code></pre>${ line }`;
|
||||
}
|
||||
else if (line.length === 0 && !inCodeBlock) {
|
||||
line = "</p><p>";
|
||||
}
|
||||
|
||||
return line;
|
||||
}).join("\n");
|
||||
|
||||
if (inCodeBlock) {
|
||||
result += '</code></pre>';
|
||||
}
|
||||
|
||||
result = `<p>${ result }</p>`.replace(/<p>\s*<\/p>/g, "").replace(/<p>\s+/g, "<p>").replace(/\s+<\/p>/g, "</p>");
|
||||
|
||||
if (result.substr("<p>".length).indexOf("<p>") === -1) {
|
||||
result = result.substring("<p>".length, result.length - "</p>".length);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function writeParameters(parameters: AST.Parameter[]): string[] {
|
||||
if (parameters.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
'<dd class="parameters">',
|
||||
' <dl>'
|
||||
].concat(flatten(parameters.map(parameter => {
|
||||
return [
|
||||
` <dt class="parameter name">${ sanitize(parameter.name) }</dt>`,
|
||||
` <dd class="parameter type">${ sanitize(parameter.type) }</dd>`,
|
||||
` <dd class="parameter description">${ writeDescription(parameter.description) }</dd>`
|
||||
].concat(writeParameters(parameter.subParameters).map(indenter(2)));
|
||||
}))).concat([
|
||||
' </dl>',
|
||||
'</dd>'
|
||||
]);
|
||||
}
|
||||
|
||||
function functionToHtml(func: AST.Function): string[] {
|
||||
return [
|
||||
`<dl id="${ toId(func) }" class="function${
|
||||
func.isAbstract ? ' abstract' : '' }${
|
||||
func.isPrivate ? ' private' : ''}${
|
||||
func.isProtected ? ' protected' : ''}${
|
||||
func.isStatic ? ' static' : ''}">`,
|
||||
` <dt class="name">${ toLink(func) }</dt>`,
|
||||
' <dd class="description">',
|
||||
` ${ writeDescription(func.description) }`,
|
||||
' </dd>',
|
||||
` <dd class="usage"><fieldset><legend /><pre><code>${
|
||||
sanitize(
|
||||
`${ (func.returnType !== null) ? 'var result = ' : '' }${ toUsageName(func) }(${
|
||||
func.parameters.map(parameter => parameter.name).join(', ') });`
|
||||
) }</code></pre></fieldset></dd>`
|
||||
].concat(writeParameters(func.parameters).map(indenter(1))).concat(
|
||||
(func.returnType === null) ? [] : [
|
||||
' <dt>Returns</dt>',
|
||||
` <dd class="return type">${ sanitize(func.returnType.type) }</dd>`,
|
||||
` <dd class="return description">${ writeDescription(func.returnType.description) }</dd>`
|
||||
]
|
||||
).concat([
|
||||
'</dl>',
|
||||
''
|
||||
]);
|
||||
}
|
||||
|
||||
function interfaceToHtml(interfase: AST.Interface): string[] {
|
||||
var members: AST.InterfaceMember[] = [];
|
||||
Object.keys(interfase.members).forEach(memberName => members.push(interfase.members[memberName]));
|
||||
|
||||
members.sort(sorter);
|
||||
|
||||
return [
|
||||
`<dl id="${ toId(interfase) }" class="interface${ interfase.isPrivate ? ' private' : '' }">`,
|
||||
` <dt class="name">interface ${ toLink(interfase) }${ (interfase.baseTypes.length > 0) ? ` extends ${
|
||||
interfase.baseTypes.map(baseType => baseType instanceof AST.TypeReference ? toLink(baseType) : baseType.name).join(', ')
|
||||
}` : '' }</dt>`,
|
||||
' <dd class="description">',
|
||||
` ${ writeDescription(interfase.description) }`,
|
||||
' </dd>',
|
||||
' <dd class="members">'
|
||||
].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: ${ (<any>member.constructor).name }`);
|
||||
}
|
||||
}))).concat([
|
||||
' </dd>',
|
||||
'</dl>',
|
||||
''
|
||||
]);
|
||||
}
|
||||
|
||||
function classToHtml(clazz: AST.Class): string[] {
|
||||
var members: AST.InterfaceMember[] = [];
|
||||
Object.keys(clazz.members).forEach(memberName => members.push(clazz.members[memberName]));
|
||||
|
||||
members.sort(sorter);
|
||||
|
||||
return [
|
||||
`<dl id="${ toId(clazz) }" class="clazz${
|
||||
clazz.isAbstract ? ' abstract' : ''}${
|
||||
clazz.isPrivate ? ' private' : ''}">`,
|
||||
` <dt class="name">class ${ toLink(clazz) }${
|
||||
(clazz.baseType !== null) ? ` extends ${ (clazz.baseType instanceof AST.TypeReference) ? toLink(<AST.TypeReference>clazz.baseType) : clazz.baseType.name }` : '' }${
|
||||
(clazz.interfaces.length > 0) ? ` implements ${ clazz.interfaces.map(interfase => interfase instanceof AST.TypeReference ? toLink(interfase) : interfase.name).join(', ') }` : ''}</dt>`,
|
||||
' <dd class="description">',
|
||||
` ${ writeDescription(clazz.description) }`,
|
||||
' </dd>',
|
||||
` <dd class="usage"><fieldset><legend /><pre><code>${
|
||||
sanitize(
|
||||
`var ${ toVariableName(clazz) } = new ${ toUsageName(clazz) }(${
|
||||
clazz.parameters.map(parameter => parameter.name).join(', ') });`
|
||||
) }</code></pre></fieldset></dd>`
|
||||
].concat(writeParameters(clazz.parameters).map(indenter(1))).concat([
|
||||
' <dd class="members">'
|
||||
]).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: ${ (<any>member.constructor).name }`);
|
||||
}
|
||||
}))).concat([
|
||||
' </dd>',
|
||||
'</dl>',
|
||||
''
|
||||
]);
|
||||
}
|
||||
|
||||
function enumToHtml(enumType: AST.Enum): string[] {
|
||||
return [
|
||||
`<dl id="${ toId(enumType) }" class="enum${ enumType.isPrivate ? ' private' : '' }">`,
|
||||
` <dt class="name">enum <a href="#${ sanitize(enumType.fullName) }">${ sanitize(enumType.name) }</a></dt>`,
|
||||
' <dd class="description">',
|
||||
` ${ writeDescription(enumType.description) }`,
|
||||
' </dd>'
|
||||
].concat([
|
||||
' <dd class="members">'
|
||||
]).concat(flatten(enumType.members.map(member => [
|
||||
` <dl id="${ toId(member) }" class="member">`,
|
||||
` <dt class="name">${ toLink(member) } = ${ member.value }</dt>`,
|
||||
' <dd class="description">',
|
||||
` ${ writeDescription(member.description) }`,
|
||||
' </dd>',
|
||||
' </dl>'
|
||||
]))).concat([
|
||||
' </dd>',
|
||||
'</dl>',
|
||||
''
|
||||
]);
|
||||
}
|
||||
|
||||
function propertyToHtml(property: AST.Property): string[] {
|
||||
return [
|
||||
`<dl id="${ toId(property) }" class="property">`,
|
||||
` <dt class="name">${ toLink(property) }</dt>`
|
||||
].concat((property.getter === null) ? [] : [
|
||||
` <dt class="getter${ property.getter.isPrivate ? ' private' : '' }">Getter</dt>`,
|
||||
' <dd class="description">',
|
||||
` ${ writeDescription(property.getter.description) }`,
|
||||
' </dd>',
|
||||
` <dd class="usage"><fieldset><legend /><pre><code>${ sanitize(`var result = ${ toUsageName(property) };`) }</code></pre></fieldset></dd>`,
|
||||
` <dd class="return type">${ sanitize(property.getter.type) }</dd>`
|
||||
]).concat((property.setter === null) ? [] : [
|
||||
` <dt class="setter${ property.setter.isPrivate ? ' private' : '' }">Setter</dt>`,
|
||||
' <dd class="description">',
|
||||
` ${ writeDescription(property.setter.description) }`,
|
||||
' </dd>',
|
||||
` <dd class="usage"><fieldset><legend /><pre><code>${ sanitize(`${ toUsageName(property) } = value;`) }</code></pre></fieldset></dd>`
|
||||
].concat(writeParameters([new AST.Parameter("value", "", property.setter.type)]).map(indenter(1)))).concat([
|
||||
'</dl>',
|
||||
''
|
||||
]);
|
||||
}
|
||||
|
||||
export function build(outputFilePath: string, root: string, rootNamespaceName: string): FileTransform {
|
||||
var compiler = new Compiler();
|
||||
|
||||
return new FileTransform(function (file: File): void {
|
||||
var self: FileTransform = this;
|
||||
|
||||
// Compile
|
||||
compiler.compile(file);
|
||||
|
||||
// Walk
|
||||
var walkResult = walk(compiler, root, rootNamespaceName);
|
||||
var namespaces = walkResult.namespaces;
|
||||
var modules = walkResult.modules;
|
||||
|
||||
// Make HTML
|
||||
|
||||
var namespaceNames = Object.keys(namespaces)
|
||||
.filter(namespaceName => namespaceName.substr(0, rootNamespaceName.length) === rootNamespaceName)
|
||||
.sort((ns1, ns2) => ns1.localeCompare(ns2));
|
||||
|
||||
var moduleNames = Object.keys(modules).sort((ns1, ns2) => ns1.localeCompare(ns2));
|
||||
|
||||
moduleNames = moduleNames.filter(moduleName => Object.keys(modules[moduleName].members).length > 0);
|
||||
|
||||
self.push({
|
||||
path: outputFilePath,
|
||||
contents: Buffer.concat([new Buffer(
|
||||
`<?xml version="1.0" encoding="utf-8" ?>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
|
||||
<head>
|
||||
<title>${ rootNamespaceName } API Documentation</title>
|
||||
<style type="text/css">
|
||||
<![CDATA[
|
||||
html, body, .navigation, .content {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.navigation, .content {
|
||||
overflow-y: scroll;
|
||||
}
|
||||
|
||||
.navigation {
|
||||
float: left;
|
||||
background-color: white;
|
||||
padding: 0 20px;
|
||||
margin-right: 20px;
|
||||
}
|
||||
|
||||
.navigation .namespace, .navigation .module {
|
||||
margin-top: 1em;
|
||||
}
|
||||
|
||||
.navigation .elements {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.content > section:not(:last-child) {
|
||||
border-bottom: 1px solid black;
|
||||
}
|
||||
|
||||
.clazz, .enum, .function, .interface, .property {
|
||||
margin-left: 30px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.getter, .setter {
|
||||
font-size: large;
|
||||
}
|
||||
|
||||
section > .clazz:nth-child(2n), section > .enum:nth-child(2n), section > .function:nth-child(2n), section > .interface:nth-child(2n), section > .property:nth-child(2n) {
|
||||
background-color: rgb(221, 250, 238);
|
||||
}
|
||||
|
||||
section > .clazz:nth-child(2n + 1), section > .enum:nth-child(2n + 1), section > .function:nth-child(2n + 1), section > .interface:nth-child(2n + 1), section > .property:nth-child(2n + 1) {
|
||||
background-color: rgb(244, 250, 221);
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: x-large;
|
||||
}
|
||||
|
||||
.usage {
|
||||
font-size: large;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.usage legend:before {
|
||||
content: "Usage";
|
||||
}
|
||||
|
||||
.usage fieldset {
|
||||
min-width: initial;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.usage pre {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.clazz .function, .clazz .property, .interface .function, .interface .property, .enum .member {
|
||||
background-color: rgb(250, 241, 221);
|
||||
}
|
||||
|
||||
.parameter.name {
|
||||
font-size: large;
|
||||
}
|
||||
|
||||
.type {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.type:before {
|
||||
content: "Type: ";
|
||||
}
|
||||
|
||||
.abstract > .name:before {
|
||||
content: "abstract ";
|
||||
}
|
||||
|
||||
.clazz .private > .name:before {
|
||||
content: "private ";
|
||||
}
|
||||
|
||||
.clazz .protected > .name:before {
|
||||
content: "protected ";
|
||||
}
|
||||
|
||||
.static > .name:before {
|
||||
content: "static ";
|
||||
}
|
||||
|
||||
.abstract.private > .name:before {
|
||||
content: "abstract private ";
|
||||
}
|
||||
|
||||
.private.static > .name:before {
|
||||
content: "static private ";
|
||||
}
|
||||
|
||||
.abstract.protected > .name:before {
|
||||
content: "abstract protected ";
|
||||
}
|
||||
|
||||
.protected.static > .name:before {
|
||||
content: "static protected ";
|
||||
}
|
||||
|
||||
body:not(.show-private) .clazz .private, body:not(.show-private) .clazz .protected, body:not(.show-private) .module {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.description .code {
|
||||
margin-left: 30px;
|
||||
}
|
||||
]]>
|
||||
</style>
|
||||
<script>
|
||||
<![CDATA[
|
||||
addEventListener("DOMContentLoaded", function () {
|
||||
document.querySelector("#show-private").addEventListener("change", function (event) {
|
||||
document.body.className = (event.target.checked ? "show-private" : "");
|
||||
}, false);
|
||||
|
||||
showPrivateIfNecessary();
|
||||
}, false);
|
||||
|
||||
function showPrivateIfNecessary() {
|
||||
var jumpToElement = document.querySelector("[id=\\"" + location.hash.substr(1) + "\\"]");
|
||||
if (jumpToElement !== null && jumpToElement.offsetHeight === 0) {
|
||||
document.querySelector("#show-private").click()
|
||||
jumpToElement.scrollIntoView();
|
||||
}
|
||||
}
|
||||
|
||||
addEventListener("hashchange", showPrivateIfNecessary, false);
|
||||
]]>
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="navigation">
|
||||
<label><input type="checkbox" id="show-private" />Show private</label>
|
||||
`
|
||||
)].concat(namespaceNames.map(namespaceName => {
|
||||
var namespace = namespaces[namespaceName];
|
||||
|
||||
var namespaceMembers: AST.NamespaceMember[] = [];
|
||||
for (const memberName of Object.keys(namespace.members)) {
|
||||
namespaceMembers.push(namespace.members[memberName]);
|
||||
}
|
||||
|
||||
namespaceMembers.sort(sorter);
|
||||
|
||||
return Buffer.concat([new Buffer(
|
||||
` <fieldset class="namespace">
|
||||
<legend><a href="#${ sanitize(namespaceName) }">${ sanitize(namespaceName) }</a></legend>
|
||||
<ul class="elements">
|
||||
`
|
||||
)].concat(namespaceMembers.map(member => new Buffer(
|
||||
` <li><a href="#${ sanitize(member.fullName) }">${ sanitize(member.name) }</a></li>
|
||||
`
|
||||
))).concat([new Buffer(
|
||||
` </ul>
|
||||
</fieldset>
|
||||
|
||||
`
|
||||
)]));
|
||||
})).concat(moduleNames.map(moduleName => {
|
||||
var module = modules[moduleName];
|
||||
|
||||
var moduleMembers: AST.ModuleMemberWithoutReference[] = [];
|
||||
for (const memberName of Object.keys(module.members)) {
|
||||
var member = module.members[memberName];
|
||||
if ((<AST.HasParent><any>member).parent === module) {
|
||||
moduleMembers.push(<AST.ModuleMemberWithoutReference>member);
|
||||
}
|
||||
}
|
||||
|
||||
if (moduleMembers.length === 0) {
|
||||
return new Buffer("");
|
||||
}
|
||||
|
||||
moduleMembers.sort(sorter);
|
||||
|
||||
return Buffer.concat([new Buffer(
|
||||
` <fieldset class="module">
|
||||
<legend><a href="#${ sanitize(moduleName) }">${ sanitize(moduleName) }</a></legend>
|
||||
<ul class="elements">
|
||||
`
|
||||
)].concat(moduleMembers.map(member => new Buffer(
|
||||
` <li><a href="#${ sanitize(member.fullName) }">${ sanitize(member.name) }</a></li>
|
||||
`
|
||||
))).concat([new Buffer(
|
||||
` </ul>
|
||||
</fieldset>
|
||||
|
||||
`
|
||||
)]));
|
||||
})).concat([new Buffer(
|
||||
` </nav>
|
||||
|
||||
<div class="content">
|
||||
`
|
||||
)]).concat(flatten(namespaceNames.map(namespaceName => {
|
||||
var namespace = namespaces[namespaceName];
|
||||
|
||||
var namespaceMembers: AST.NamespaceMember[] = [];
|
||||
for (const memberName of Object.keys(namespace.members)) {
|
||||
namespaceMembers.push(namespace.members[memberName]);
|
||||
}
|
||||
|
||||
namespaceMembers.sort(sorter);
|
||||
|
||||
var properties = <AST.Property[]>namespaceMembers.filter(member => member instanceof AST.Property);
|
||||
var functions = <AST.Function[]>namespaceMembers.filter(member => member instanceof AST.Function);
|
||||
var interfaces = <AST.Interface[]>namespaceMembers.filter(member => member instanceof AST.Interface);
|
||||
var classes = <AST.Class[]>namespaceMembers.filter(member => member instanceof AST.Class);
|
||||
var enums = <AST.Enum[]>namespaceMembers.filter(member => member instanceof AST.Enum);
|
||||
|
||||
var result = [new Buffer(
|
||||
` <section class="namespace">
|
||||
<h1 id="${ sanitize(namespaceName) }">Namespace ${ sanitize(namespaceName) }</h1>
|
||||
`
|
||||
)];
|
||||
|
||||
if (properties.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Properties</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const property of properties) {
|
||||
result.push(new Buffer(propertyToHtml(property).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
if (functions.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Free functions</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const func of functions) {
|
||||
result.push(new Buffer(functionToHtml(func).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
if (interfaces.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Interfaces</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const interfase of interfaces) {
|
||||
result.push(new Buffer(interfaceToHtml(interfase).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
if (classes.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Classes</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const clazz of classes) {
|
||||
result.push(new Buffer(classToHtml(clazz).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
if (enums.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Enums</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const enumType of enums) {
|
||||
result.push(new Buffer(enumToHtml(enumType).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
|
||||
return result;
|
||||
}))).concat(flatten(moduleNames.map(moduleName => {
|
||||
var module = modules[moduleName];
|
||||
|
||||
var moduleMembers: AST.ModuleMember[] = [];
|
||||
for (const memberName of Object.keys(module.members)) {
|
||||
var member = module.members[memberName];
|
||||
if ((<AST.HasParent><any>member).parent === module) {
|
||||
moduleMembers.push(<AST.ModuleMember>member);
|
||||
}
|
||||
}
|
||||
|
||||
if (moduleMembers.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
moduleMembers.sort(sorter);
|
||||
|
||||
var properties = <AST.Property[]>moduleMembers.filter(member => member instanceof AST.Property);
|
||||
var functions = <AST.Function[]>moduleMembers.filter(member => member instanceof AST.Function);
|
||||
var interfaces = <AST.Interface[]>moduleMembers.filter(member => member instanceof AST.Interface);
|
||||
var classes = <AST.Class[]>moduleMembers.filter(member => member instanceof AST.Class);
|
||||
var enums = <AST.Enum[]>moduleMembers.filter(member => member instanceof AST.Enum);
|
||||
|
||||
var result = [new Buffer(
|
||||
` <section class="module">
|
||||
<h1 id="${ sanitize(moduleName) }">Module ${ sanitize(moduleName) }</h1>
|
||||
`
|
||||
)];
|
||||
|
||||
if (properties.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Properties</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const property of properties) {
|
||||
result.push(new Buffer(propertyToHtml(property).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
if (functions.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Free functions</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const func of functions) {
|
||||
result.push(new Buffer(functionToHtml(func).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
if (interfaces.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Interfaces</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const interfase of interfaces) {
|
||||
result.push(new Buffer(interfaceToHtml(interfase).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
if (classes.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Classes</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const clazz of classes) {
|
||||
result.push(new Buffer(classToHtml(clazz).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
if (enums.length > 0) {
|
||||
result.push(new Buffer(
|
||||
` <section>
|
||||
<h2>Enums</h2>
|
||||
`
|
||||
));
|
||||
|
||||
for (const enumType of enums) {
|
||||
result.push(new Buffer(enumToHtml(enumType).map(indenter(5)).join("\n")));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
}
|
||||
|
||||
result.push(new Buffer(
|
||||
` </section>
|
||||
`
|
||||
));
|
||||
|
||||
return result;
|
||||
}))).concat([new Buffer(
|
||||
` </div>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
)]))
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Type definitions for Node.js v0.12.0
|
||||
// Project: http://nodejs.org/
|
||||
// Definitions by: Microsoft TypeScript <http://typescriptlang.org>, DefinitelyTyped <https://github.com/borisyankov/DefinitelyTyped>
|
||||
// Definitions: https://github.com/borisyankov/DefinitelyTyped
|
||||
|
||||
declare var require: {
|
||||
resolve(id: string): string;
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* 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 ts from "typescript";
|
||||
|
||||
export class HasParent {
|
||||
public parent: HasParent = null;
|
||||
|
||||
constructor(public name: string) { }
|
||||
|
||||
get fullName(): string {
|
||||
if (this.parent === null) {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
var 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 type HasGenerics = HasStringGenerics | TypeReference;
|
||||
export type CanBePrivate = Class | Interface | Function | Getter | Setter | Enum | Reference;
|
||||
export type CanBeProtected = Function;
|
||||
export type CanBeStatic = Function;
|
||||
@@ -0,0 +1,427 @@
|
||||
/**
|
||||
* 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 fs from "fs";
|
||||
import * as path from "path";
|
||||
import { Transform } from "stream";
|
||||
import * as ts from "typescript";
|
||||
|
||||
import { File, FileTransform, FileWatcher } from "async-build";
|
||||
|
||||
import * as AST from "./ast";
|
||||
import { walk } from "./walker";
|
||||
|
||||
export interface StreamingCompilerHost extends ts.CompilerHost, ts.ParseConfigHost {
|
||||
setOutputStream(outputStream: FileTransform): void;
|
||||
}
|
||||
|
||||
export class Compiler {
|
||||
private _projectRoot: string = null;
|
||||
private _program: ts.Program = null;
|
||||
|
||||
constructor(private _host: StreamingCompilerHost = new CompilerHost()) { }
|
||||
|
||||
compile(projectConfigFile: File) {
|
||||
this._projectRoot = path.dirname(projectConfigFile.path);
|
||||
|
||||
var projectConfig = ts.parseJsonConfigFileContent(JSON.parse(projectConfigFile.contents.toString()), this._host, this._projectRoot);
|
||||
|
||||
this._program = ts.createProgram(projectConfig.fileNames, projectConfig.options, this._host);
|
||||
|
||||
var syntacticDiagnostics = this._program.getSyntacticDiagnostics();
|
||||
if (syntacticDiagnostics.length > 0) {
|
||||
this._reportDiagnostics(syntacticDiagnostics);
|
||||
throw new Error("There were one or more syntactic diagnostics.");
|
||||
}
|
||||
|
||||
var globalDiagnostics = this._program.getGlobalDiagnostics();
|
||||
if (globalDiagnostics.length > 0) {
|
||||
this._reportDiagnostics(globalDiagnostics);
|
||||
throw new Error("There were one or more global diagnostics.");
|
||||
}
|
||||
|
||||
var 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);
|
||||
|
||||
var 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) {
|
||||
var message = "";
|
||||
|
||||
if (diagnostic.file) {
|
||||
var 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);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const typeScriptModulePath = path.dirname(require.resolve("typescript"));
|
||||
|
||||
class CompilerHost implements StreamingCompilerHost {
|
||||
protected _sourceFiles = Object.create(null);
|
||||
|
||||
private _outputStream: FileTransform = null;
|
||||
|
||||
setOutputStream(outputStream: FileTransform): void {
|
||||
this._outputStream = outputStream;
|
||||
}
|
||||
|
||||
// ts.ModuleResolutionHost members
|
||||
|
||||
fileExists(fileName: string): boolean {
|
||||
return fs.existsSync(fileName);
|
||||
}
|
||||
|
||||
readFile(fileName: string): string {
|
||||
if (!this.fileExists(fileName)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return fs.readFileSync(fileName, { encoding: "utf8" });
|
||||
}
|
||||
|
||||
// ts.CompilerHost members
|
||||
|
||||
getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError: (message: string) => void): ts.SourceFile {
|
||||
if (fileName in this._sourceFiles) {
|
||||
return this._sourceFiles[fileName];
|
||||
}
|
||||
|
||||
try {
|
||||
var text = fs.readFileSync(fileName, { encoding: "utf8" });
|
||||
var result = ts.createSourceFile(fileName, text, ts.ScriptTarget.ES5);
|
||||
this._sourceFiles[fileName] = result;
|
||||
}
|
||||
catch (ex) {
|
||||
if (onError) {
|
||||
onError(ex.message);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
getDefaultLibFileName(): string {
|
||||
return path.join(typeScriptModulePath, "lib.dom.d.ts");
|
||||
}
|
||||
|
||||
writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError: (message?: string) => void): void {
|
||||
this._outputStream.push({
|
||||
path: fileName,
|
||||
contents: new Buffer(data)
|
||||
});
|
||||
}
|
||||
|
||||
getCurrentDirectory(): string {
|
||||
return path.resolve(".");
|
||||
}
|
||||
|
||||
getCanonicalFileName(fileName: string): string {
|
||||
return ts.normalizeSlashes(path.resolve(fileName));
|
||||
}
|
||||
|
||||
useCaseSensitiveFileNames(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
getNewLine(): string {
|
||||
return "\n";
|
||||
}
|
||||
|
||||
// ts.ParseConfigHost members
|
||||
|
||||
readDirectory(rootDir: string, extension: string, exclude: string[]): string[] {
|
||||
return ts.sys.readDirectory(rootDir, extension, exclude).map(fileName => this.getCanonicalFileName(fileName));
|
||||
}
|
||||
}
|
||||
|
||||
class WatchCompilerHost extends CompilerHost {
|
||||
private _fileWatcher = new FileWatcher(fileNames => this._onFilesChanged(fileNames));
|
||||
|
||||
private _filesChangedSinceLast: string[] = [];
|
||||
|
||||
constructor(private _onChangeCallback: () => void) {
|
||||
super();
|
||||
}
|
||||
|
||||
getSourceFile(fileName: string, languageVersion: ts.ScriptTarget, onError: (message: string) => void): ts.SourceFile {
|
||||
var result = super.getSourceFile(fileName, languageVersion, onError);
|
||||
if (result !== undefined) {
|
||||
this._fileWatcher.watchFile(fileName);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
private _onFilesChanged(fileNames: string[]) {
|
||||
for (const fileName of fileNames) {
|
||||
delete this._sourceFiles[fileName];
|
||||
}
|
||||
|
||||
this._onChangeCallback();
|
||||
}
|
||||
}
|
||||
|
||||
export function build(root: string, rootNamespaceName: string): FileTransform {
|
||||
var compiler = new Compiler();
|
||||
|
||||
return new FileTransform(function (projectConfigFile: File): void {
|
||||
var self: FileTransform = this;
|
||||
|
||||
console.log("Compiling " + projectConfigFile.path + "...");
|
||||
|
||||
compiler.compile(projectConfigFile);
|
||||
|
||||
var walkResult = walk(compiler, root, rootNamespaceName);
|
||||
addJSDocComments(walkResult.modules);
|
||||
|
||||
compiler.writeFiles(self);
|
||||
|
||||
console.log("Compile succeeded.");
|
||||
});
|
||||
}
|
||||
|
||||
export function watch(root: string, rootNamespaceName: string): FileTransform {
|
||||
return new FileTransform(function (projectConfigFile: File): void {
|
||||
var self: FileTransform = this;
|
||||
|
||||
function compile() {
|
||||
console.log("Compiling " + projectConfigFile.path + "...");
|
||||
|
||||
compiler.compile(projectConfigFile);
|
||||
|
||||
compiler.writeFiles(self);
|
||||
|
||||
console.log("Compile succeeded.");
|
||||
|
||||
self.push({
|
||||
path: "END",
|
||||
contents: ""
|
||||
});
|
||||
};
|
||||
|
||||
var compilerHost = new WatchCompilerHost(() => {
|
||||
try {
|
||||
compile();
|
||||
}
|
||||
catch (ex) {
|
||||
console.error("Compile failed." + ex.stack);
|
||||
}
|
||||
});
|
||||
|
||||
var compiler = new Compiler(compilerHost);
|
||||
|
||||
compile();
|
||||
|
||||
console.log("Listening for changes...");
|
||||
}, callback => { });
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
var newComments: string[] = [];
|
||||
|
||||
if (current instanceof AST.Class) {
|
||||
newComments.push("@constructor");
|
||||
|
||||
if (current.baseType !== null) {
|
||||
var baseType = current.baseType;
|
||||
newComments.push(
|
||||
"@extends {" +
|
||||
baseType.fullName + (
|
||||
(baseType instanceof AST.TypeReference && baseType.generics.length) > 0 ?
|
||||
(".<" + (<AST.TypeReference>baseType).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 ((<AST.HasParent><any>current).parent instanceof AST.Namespace) {
|
||||
newComments.push("@memberOf " + (<AST.HasParent><any>current).parent.fullName);
|
||||
}
|
||||
|
||||
if ((<AST.HasStringGenerics>current).generics !== undefined && (<AST.HasStringGenerics>current).generics.length > 0) {
|
||||
newComments.push("@template " + (<AST.HasStringGenerics>current).generics.join(", "));
|
||||
}
|
||||
|
||||
if ((<AST.CanBePrivate><any>current).isPrivate) {
|
||||
newComments.push("@private");
|
||||
}
|
||||
|
||||
if ((<AST.CanBeProtected>current).isProtected) {
|
||||
newComments.push("@protected");
|
||||
}
|
||||
|
||||
if ((<AST.CanBeStatic>current).isStatic) {
|
||||
newComments.push("@static");
|
||||
}
|
||||
|
||||
if (newComments.length > 0) {
|
||||
if (current instanceof AST.Property) {
|
||||
var 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) {
|
||||
(<any>node)["typescript-new-comment"] = newComments;
|
||||
}
|
||||
}
|
||||
else {
|
||||
(<any>(<AST.Class | AST.Interface | AST.Function | AST.Enum>current).astNode)["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 var oldGetLeadingCommentRangesOfNode: typeof ts.getLeadingCommentRangesOfNode = ts.getLeadingCommentRangesOfNode.bind(ts);
|
||||
ts.getLeadingCommentRangesOfNode = (node: ts.Node, sourceFileOfNode: ts.SourceFile) => {
|
||||
sourceFileOfNode = sourceFileOfNode || ts.getSourceFileOfNode(node);
|
||||
|
||||
var originalComments = oldGetLeadingCommentRangesOfNode(node, sourceFileOfNode);
|
||||
|
||||
if (originalComments !== undefined && (<any>node)["typescript-new-comment"] !== undefined) {
|
||||
var fakeSourceFile = fakeSourceFiles[sourceFileOfNode.fileName];
|
||||
if (fakeSourceFile === undefined) {
|
||||
fakeSourceFile = fakeSourceFiles[sourceFileOfNode.fileName] = new FakeSourceFile(sourceFileOfNode);
|
||||
}
|
||||
|
||||
originalComments[originalComments.length - 1] = fakeSourceFile.addComment(originalComments[originalComments.length - 1], (<any>node)["typescript-new-comment"]);
|
||||
}
|
||||
|
||||
return originalComments;
|
||||
};
|
||||
|
||||
var oldWriteCommentRange: typeof ts.writeCommentRange = ts.writeCommentRange.bind(ts);
|
||||
ts.writeCommentRange = (currentSourceFile: ts.SourceFile, writer: ts.EmitTextWriter, comment: ts.CommentRange, newLine: string) => {
|
||||
if ((<{ sourceFile: ts.SourceFile }><any>comment).sourceFile) {
|
||||
currentSourceFile = (<{ sourceFile: ts.SourceFile }><any>comment).sourceFile;
|
||||
}
|
||||
|
||||
return oldWriteCommentRange(currentSourceFile, writer, comment, newLine);
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
declare namespace ts {
|
||||
export interface EmitTextWriter { }
|
||||
|
||||
export interface IntrinsicType extends Type {
|
||||
intrinsicName: string;
|
||||
}
|
||||
|
||||
export function forEachValue<T, U>(map: Map<T>, callback: (value: T) => U): U;
|
||||
export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration): ExpressionWithTypeArguments;
|
||||
export function getClassImplementsHeritageClauseElements(node: ClassDeclaration): NodeArray<ExpressionWithTypeArguments>;
|
||||
export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray<ExpressionWithTypeArguments>;
|
||||
export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[];
|
||||
export function getLineStarts(sourceFile: SourceFile): number[];
|
||||
export function getSourceFileOfNode(node: Node): SourceFile;
|
||||
export function getTextOfNode(node: Node, includeTrivia?: boolean): string;
|
||||
export function normalizeSlashes(path: string): string;
|
||||
export function writeCommentRange(currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string): void;
|
||||
}
|
||||
@@ -18,8 +18,4 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
///<reference path="utility.ts" />
|
||||
///<reference path="parts.ts" />
|
||||
///<reference path="parser.ts" />
|
||||
///<reference path="renderer.ts" />
|
||||
///<reference path="types.ts" />
|
||||
export { build, watch } from "./compiler";
|
||||
@@ -0,0 +1,871 @@
|
||||
/**
|
||||
* 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 path from "path";
|
||||
import * as ts from "typescript";
|
||||
|
||||
import { Compiler, oldGetLeadingCommentRangesOfNode } from "./compiler";
|
||||
|
||||
import * as AST from "./ast";
|
||||
|
||||
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<T extends AST.HasParent>(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 {
|
||||
var moduleName = this._moduleNameFromFileName(sourceFile.fileName);
|
||||
|
||||
if (!(moduleName in this.modules)) {
|
||||
this.modules[moduleName] = new AST.Module(moduleName);
|
||||
}
|
||||
|
||||
var 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(<ts.VariableStatement>node, parent);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.FunctionDeclaration:
|
||||
this._visitFunctionDeclaration(<ts.FunctionDeclaration>node, parent);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.ClassDeclaration:
|
||||
this._visitClassDeclaration(<ts.ClassDeclaration>node, parent);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.InterfaceDeclaration:
|
||||
this._visitInterfaceDeclaration(<ts.InterfaceDeclaration>node, parent);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.EnumDeclaration:
|
||||
this._visitEnumDeclaration(<ts.EnumDeclaration>node, parent);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.ImportDeclaration:
|
||||
this._visitImportDeclaration(<ts.ImportDeclaration>node, parent);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.ExportDeclaration:
|
||||
this._visitExportDeclaration(<ts.ExportDeclaration>node, parent);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.ExpressionStatement:
|
||||
case ts.SyntaxKind.ForOfStatement:
|
||||
case ts.SyntaxKind.IfStatement:
|
||||
case ts.SyntaxKind.TypeAliasDeclaration:
|
||||
break;
|
||||
|
||||
default:
|
||||
console.error(node.kind, (<any>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(<ts.PropertyDeclaration>node, clazz);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.MethodSignature:
|
||||
case ts.SyntaxKind.MethodDeclaration:
|
||||
this._visitMethod(<ts.MethodDeclaration>node, clazz);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.GetAccessor:
|
||||
this._visitGetAccessor(<ts.AccessorDeclaration>node, clazz);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.SetAccessor:
|
||||
this._visitSetAccessor(<ts.AccessorDeclaration>node, clazz);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.TypeParameter:
|
||||
case ts.SyntaxKind.Parameter:
|
||||
case ts.SyntaxKind.Constructor:
|
||||
break;
|
||||
|
||||
default:
|
||||
console.error(node.kind, (<any>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(<ts.PropertyDeclaration>node, interfase);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.MethodSignature:
|
||||
case ts.SyntaxKind.MethodDeclaration:
|
||||
this._visitMethod(<ts.MethodDeclaration>node, interfase);
|
||||
break;
|
||||
|
||||
case ts.SyntaxKind.TypeParameter:
|
||||
case ts.SyntaxKind.CallSignature:
|
||||
case ts.SyntaxKind.ConstructSignature:
|
||||
case ts.SyntaxKind.IndexSignature:
|
||||
break;
|
||||
|
||||
default:
|
||||
console.error(node.kind, (<any>ts).SyntaxKind[node.kind], node);
|
||||
throw new Error("Unrecognized node.");
|
||||
}
|
||||
}
|
||||
|
||||
private _visitProperty(node: ts.PropertyDeclaration, parent: AST.Class | AST.Interface) {
|
||||
if ((node.flags & ts.NodeFlags.Private) === ts.NodeFlags.Private) {
|
||||
return;
|
||||
}
|
||||
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
if (jsDoc.typeAnnotation === null) {
|
||||
this._notifyIncorrectJsDoc(`Field ${ ts.getTextOfNode(node.name) } has no @type annotation.`);
|
||||
jsDoc.typeAnnotation = "*";
|
||||
}
|
||||
|
||||
var 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) {
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
var 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("", "*");
|
||||
}
|
||||
|
||||
var isPrivate = (node.flags & ts.NodeFlags.Private) === ts.NodeFlags.Private;
|
||||
var isProtected = (node.flags & ts.NodeFlags.Protected) === ts.NodeFlags.Protected;
|
||||
var isStatic = (node.flags & ts.NodeFlags.Static) === ts.NodeFlags.Static;
|
||||
|
||||
var generics = this._getGenericsOfSignatureDeclaration(node);
|
||||
|
||||
var 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 {
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
var name = ts.getTextOfNode(node.name);
|
||||
|
||||
var isPrivate = (node.flags & ts.NodeFlags.Private) === ts.NodeFlags.Private;
|
||||
|
||||
var property = <AST.Property>clazz.members[name];
|
||||
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 {
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
var name = ts.getTextOfNode(node.name);
|
||||
|
||||
var isPrivate = (node.flags & ts.NodeFlags.Private) === ts.NodeFlags.Private;
|
||||
|
||||
var property = <AST.Property>clazz.members[name];
|
||||
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;
|
||||
}
|
||||
|
||||
var declaration = node.declarationList.declarations[0];
|
||||
if ((declaration.flags & ts.NodeFlags.Ambient) === ts.NodeFlags.Ambient) {
|
||||
return;
|
||||
}
|
||||
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
if (jsDoc.typeAnnotation === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
var property = this._scope.enter(new AST.Property(ts.getTextOfNode(declaration.name)));
|
||||
property.getter = new AST.Getter(node, jsDoc.description, jsDoc.typeAnnotation, false);
|
||||
property.setter = new AST.Setter(node, jsDoc.description, jsDoc.typeAnnotation, false);
|
||||
|
||||
parent.members[property.name] = property;
|
||||
|
||||
this._scope.leave();
|
||||
}
|
||||
|
||||
private _visitFunctionDeclaration(node: ts.FunctionDeclaration, parent: AST.Module): void {
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
var isPrivate = (node.flags & ts.NodeFlags.Export) !== ts.NodeFlags.Export;
|
||||
|
||||
var generics = this._getGenericsOfSignatureDeclaration(node);
|
||||
|
||||
var 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("", "*");
|
||||
}
|
||||
|
||||
var 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 {
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
var baseTypeHeritageClauseElement = ts.getClassExtendsHeritageClauseElement(node) || null;
|
||||
var baseType: AST.UnresolvedType = null;
|
||||
if (baseTypeHeritageClauseElement !== null) {
|
||||
baseType = new AST.UnresolvedType(
|
||||
this._typeChecker.getTypeAtLocation(baseTypeHeritageClauseElement).symbol,
|
||||
this._getGenericsOfTypeReferenceNode(baseTypeHeritageClauseElement)
|
||||
);
|
||||
}
|
||||
|
||||
var interfaces = (ts.getClassImplementsHeritageClauseElements(node) || []).map(type => new AST.UnresolvedType(
|
||||
this._typeChecker.getTypeAtLocation(type).symbol,
|
||||
this._getGenericsOfTypeReferenceNode(type)
|
||||
));
|
||||
|
||||
var isPrivate = (node.flags & ts.NodeFlags.Export) !== ts.NodeFlags.Export;
|
||||
|
||||
var type = <ts.InterfaceType>this._typeChecker.getTypeAtLocation(node);
|
||||
|
||||
var generics = this._getGenericsOfInterfaceType(type);
|
||||
|
||||
var parameters: AST.Parameter[] = [];
|
||||
|
||||
if (type.symbol.members["__constructor"] !== undefined) {
|
||||
parameters = this._connectParameters((<ts.ConstructorDeclaration>type.symbol.members["__constructor"].declarations[0]).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.");
|
||||
}
|
||||
|
||||
var 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.forEachValue(type.symbol.exports, symbol => {
|
||||
if (symbol.name === "prototype") {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const declaration of symbol.declarations) {
|
||||
this._walkClassMember(declaration, clazz);
|
||||
}
|
||||
});
|
||||
|
||||
ts.forEachValue(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 {
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
var baseTypes = (ts.getInterfaceBaseTypeNodes(node) || []).map(type => new AST.UnresolvedType(
|
||||
this._typeChecker.getTypeAtLocation(type).symbol,
|
||||
this._getGenericsOfTypeReferenceNode(type)
|
||||
));
|
||||
|
||||
var existingInterfaceType = parent.members[node.name.text];
|
||||
if (existingInterfaceType !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
var isPrivate = (node.flags & ts.NodeFlags.Export) !== ts.NodeFlags.Export;
|
||||
|
||||
var type = <ts.InterfaceType>this._typeChecker.getTypeAtLocation(node);
|
||||
|
||||
var generics = this._getGenericsOfInterfaceType(type);
|
||||
|
||||
var interfase = this._scope.enter(new AST.Interface(node.name.text, node, jsDoc.description, generics, baseTypes, isPrivate));
|
||||
parent.members[interfase.name] = interfase;
|
||||
|
||||
ts.forEachValue(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 {
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
var existingEnumType = parent.members[node.name.text];
|
||||
if (existingEnumType !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
var isPrivate = (node.flags & ts.NodeFlags.Export) !== ts.NodeFlags.Export;
|
||||
|
||||
var type = this._typeChecker.getTypeAtLocation(node);
|
||||
|
||||
var enumType = this._scope.enter(new AST.Enum(node.name.text, node, jsDoc.description, isPrivate));
|
||||
parent.members[enumType.name] = enumType;
|
||||
|
||||
ts.forEachValue(type.symbol.exports, symbol => {
|
||||
this._visitEnumMember(<ts.EnumMember>symbol.declarations[0], enumType);
|
||||
});
|
||||
|
||||
this._scope.leave();
|
||||
}
|
||||
|
||||
private _visitEnumMember(node: ts.EnumMember, parent: AST.Enum): void {
|
||||
var jsDoc = this._parseJSDoc(node);
|
||||
|
||||
var value = (node.initializer === undefined) ? null : parseInt((<ts.LiteralExpression>node.initializer).text);
|
||||
|
||||
var 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.");
|
||||
}
|
||||
|
||||
var moduleName = this._resolve((<ts.LiteralExpression>node.moduleSpecifier).text, parent);
|
||||
|
||||
if ((<ts.NamespaceImport>node.importClause.namedBindings).name !== undefined) {
|
||||
// import * as foo from "baz";
|
||||
parent.members[(<ts.NamespaceImport>node.importClause.namedBindings).name.text] = new AST.Reference(moduleName, "*", true);
|
||||
}
|
||||
else if ((<ts.NamedImports>node.importClause.namedBindings).elements !== undefined) {
|
||||
// import { foo, bar } from "baz";
|
||||
for (const element of (<ts.NamedImports>node.importClause.namedBindings).elements) {
|
||||
var 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";
|
||||
var moduleName = this._resolve((<ts.LiteralExpression>node.moduleSpecifier).text, parent);
|
||||
for (const element of node.exportClause.elements) {
|
||||
var 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) {
|
||||
(<AST.CanBePrivate><any>parent.members[element.name.text]).isPrivate = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _resolve(relativeModuleName: string, currentModule: AST.Module): string {
|
||||
var result = ts.normalizeSlashes(path.join(currentModule.name, `../${ relativeModuleName }`));
|
||||
|
||||
if (result[0] !== ".") {
|
||||
result = `./${ result }`;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private _parseJSDoc(node: ts.Node): JSDoc {
|
||||
var comments = oldGetLeadingCommentRangesOfNode(node, this._currentSourceFile);
|
||||
|
||||
if (comments === undefined) {
|
||||
comments = [];
|
||||
}
|
||||
|
||||
if (comments.length > 1) {
|
||||
comments = [comments[comments.length - 1]];
|
||||
}
|
||||
|
||||
var comment =
|
||||
(comments.length === 0) ?
|
||||
"" :
|
||||
this._currentSourceFile.text.substring(comments[0].pos, comments[0].end);
|
||||
|
||||
var commentStartIndex = comment.indexOf("/**");
|
||||
var commentEndIndex = comment.lastIndexOf("*/");
|
||||
|
||||
var lines =
|
||||
(commentStartIndex === -1 || commentEndIndex === -1) ?
|
||||
[] :
|
||||
comment.substring(commentStartIndex + 2, commentEndIndex).split("\n").map(line => {
|
||||
var match = line.match(/^[ \t]*\* (.*)/);
|
||||
if (match === null) {
|
||||
return "";
|
||||
}
|
||||
return match[1];
|
||||
});
|
||||
|
||||
var rootDescription = "";
|
||||
|
||||
var parameters: { [name: string]: AST.Parameter } = Object.create(null);
|
||||
|
||||
var typeAnnotation: string = null;
|
||||
|
||||
var returnType: AST.ReturnType = null;
|
||||
|
||||
var isAbstract = false;
|
||||
|
||||
var lastRead: { description: string } = null;
|
||||
|
||||
for (const line of lines) {
|
||||
var firstWordMatch = line.match(/^\s*(\S+)(\s*)/);
|
||||
var firstWord = (firstWordMatch !== null) ? firstWordMatch[1] : "";
|
||||
var remainingLine = (firstWordMatch !== null) ? line.substring(firstWordMatch[0].length) : "";
|
||||
|
||||
if (firstWord[0] === "@") {
|
||||
lastRead = null;
|
||||
}
|
||||
|
||||
switch (firstWord) {
|
||||
case "@abstract":
|
||||
isAbstract = true;
|
||||
break;
|
||||
|
||||
case "@param":
|
||||
var type: string;
|
||||
[type, remainingLine] = this._readType(remainingLine);
|
||||
|
||||
var [, name, description] = remainingLine.match(/(\S+)\s*(.*)/);
|
||||
|
||||
var subParameterMatch = name.match(/^(?:(.+)\.([^\.]+))|(?:(.+)\[("[^\[\]"]+")\])$/);
|
||||
if (subParameterMatch === null) {
|
||||
parameters[name] = lastRead = new AST.Parameter(name, description, type);
|
||||
}
|
||||
else {
|
||||
var parentName = subParameterMatch[1] || subParameterMatch[3];
|
||||
var childName = subParameterMatch[2] || subParameterMatch[4];
|
||||
var parentParameter = parameters[parentName];
|
||||
parentParameter.subParameters.push(lastRead = new AST.Parameter(childName, description, type));
|
||||
}
|
||||
break;
|
||||
|
||||
case "@return":
|
||||
var [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];
|
||||
}
|
||||
|
||||
var index = -1;
|
||||
var numberOfUnterminatedBraces = 0;
|
||||
for (var 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.");
|
||||
}
|
||||
|
||||
var 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): (AST.UnresolvedType | AST.IntrinsicTypeReference)[] {
|
||||
if (typeReferenceNode.typeArguments === undefined) {
|
||||
return [];
|
||||
}
|
||||
|
||||
var typeReference = <ts.TypeReference>this._typeChecker.getTypeAtLocation(typeReferenceNode);
|
||||
|
||||
return typeReference.typeArguments.map(typeArgument => {
|
||||
if ((<ts.IntrinsicType>typeArgument).intrinsicName !== undefined) {
|
||||
return new AST.IntrinsicTypeReference((<ts.IntrinsicType>typeArgument).intrinsicName);
|
||||
}
|
||||
|
||||
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 => {
|
||||
var parameterName = (<ts.Identifier>parameter.name).text;
|
||||
if (parameterName[0] === "_") {
|
||||
parameterName = parameterName.substr(1);
|
||||
}
|
||||
|
||||
var jsDocParameter = jsDocParameters[parameterName];
|
||||
|
||||
if (jsDocParameter === undefined) {
|
||||
this._notifyIncorrectJsDoc(onMissingMessageCallback.call(this, parameterName));
|
||||
jsDocParameter = new AST.Parameter(parameterName, "*", "");
|
||||
}
|
||||
|
||||
return jsDocParameter;
|
||||
});
|
||||
}
|
||||
|
||||
private _notifyIncorrectJsDoc(message: string): void {
|
||||
var fileName = path.basename(this._currentSourceFile.fileName);
|
||||
if (fileName === "lib.core.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)) {
|
||||
var module = this.modules[moduleName];
|
||||
|
||||
for (const memberName of Object.keys(module.members)) {
|
||||
var member = module.members[memberName];
|
||||
|
||||
if (member instanceof AST.Class) {
|
||||
if (member.unresolvedBaseType instanceof AST.UnresolvedType) {
|
||||
member.baseType = this._resolveTypeReference(<AST.UnresolvedType>member.unresolvedBaseType);
|
||||
}
|
||||
else {
|
||||
member.baseType = <AST.TypeReference | AST.IntrinsicTypeReference>member.unresolvedBaseType;
|
||||
}
|
||||
|
||||
member.interfaces = member.unresolvedInterfaces.map(interfase => {
|
||||
if (interfase instanceof AST.UnresolvedType) {
|
||||
return this._resolveTypeReference(interfase);
|
||||
}
|
||||
|
||||
return <AST.TypeReference | AST.IntrinsicTypeReference>interfase;
|
||||
});
|
||||
}
|
||||
|
||||
else if (member instanceof AST.Interface) {
|
||||
member.baseTypes = member.unresolvedBaseTypes.map(baseType => {
|
||||
if (baseType instanceof AST.UnresolvedType) {
|
||||
return this._resolveTypeReference(baseType);
|
||||
}
|
||||
|
||||
return <AST.TypeReference | AST.IntrinsicTypeReference>baseType;
|
||||
});
|
||||
}
|
||||
|
||||
else if (member instanceof AST.Enum) {
|
||||
var 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)) {
|
||||
var member = module.members[memberName];
|
||||
|
||||
if (member instanceof AST.Reference) {
|
||||
if ((<AST.Reference>member).isPrivate) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (member.name === "*") {
|
||||
var newNamespace = this._scope.enter(new AST.Namespace(memberName));
|
||||
|
||||
var existingNamespace = this.namespaces[newNamespace.fullName];
|
||||
if (existingNamespace !== undefined) {
|
||||
this._scope.leave();
|
||||
this._scope.enter(existingNamespace);
|
||||
}
|
||||
else {
|
||||
this.namespaces[newNamespace.fullName] = newNamespace;
|
||||
}
|
||||
|
||||
var referencedModuleName = (<AST.Reference>member).moduleName;
|
||||
var referencedModule = this.modules[referencedModuleName];
|
||||
if (referencedModule === undefined && ((referencedModuleName + "/index") in this.modules)) {
|
||||
(<AST.Reference>member).moduleName = referencedModuleName = referencedModuleName + "/index";
|
||||
referencedModule = this.modules[referencedModuleName];
|
||||
}
|
||||
this._moduleToNamespace(referencedModule);
|
||||
|
||||
this._scope.leave();
|
||||
}
|
||||
else {
|
||||
while (member instanceof AST.Reference) {
|
||||
member = this.modules[(<AST.Reference>member).moduleName].members[member.name];
|
||||
}
|
||||
|
||||
this._scope.enter(<AST.NamespaceMember><any>member);
|
||||
this._scope.leave();
|
||||
(<AST.Namespace>this._scope.current).members[member.name] = <AST.NamespaceMember>member;
|
||||
}
|
||||
}
|
||||
else if (!(<AST.CanBePrivate><any>member).isPrivate) {
|
||||
this._scope.enter(<AST.NamespaceMember>member);
|
||||
this._scope.leave();
|
||||
(<AST.Namespace>this._scope.current).members[member.name] = <AST.NamespaceMember>member;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _resolveTypeReference(unresolvedType: AST.UnresolvedType): AST.TypeReference {
|
||||
var node: ts.Node = unresolvedType.symbol.declarations[0];
|
||||
while (node.kind !== ts.SyntaxKind.SourceFile) {
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
var sourceFile = <ts.SourceFile>node;
|
||||
|
||||
var moduleName = this._moduleNameFromFileName(sourceFile.fileName);
|
||||
var module = this.modules[moduleName];
|
||||
|
||||
var 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[(<AST.Reference>result).moduleName].members[result.name];
|
||||
}
|
||||
|
||||
var resultGenerics = unresolvedType.generics.map(generic => {
|
||||
if (generic instanceof AST.UnresolvedType) {
|
||||
return this._resolveTypeReference(generic);
|
||||
}
|
||||
|
||||
return <AST.IntrinsicTypeReference>generic;
|
||||
});
|
||||
|
||||
return new AST.TypeReference(<AST.NamespaceMember><any>result, resultGenerics);
|
||||
}
|
||||
|
||||
private _moduleNameFromFileName(fileName: string): string {
|
||||
var 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) {
|
||||
var sourceFiles = compiler.sourceFiles;
|
||||
var rootFileName = ts.normalizeSlashes(path.resolve(root));
|
||||
var rootSourceFile = sourceFiles.filter(sourceFile => sourceFile.fileName === rootFileName)[0];
|
||||
|
||||
var walker = new Walker(compiler);
|
||||
|
||||
// Walk
|
||||
for (const sourceFile of sourceFiles) {
|
||||
if (
|
||||
path.basename(sourceFile.fileName) === "lib.core.d.ts" ||
|
||||
path.basename(sourceFile.fileName) === "lib.dom.d.ts" ||
|
||||
sourceFile.fileName.substr(-"references.d.ts".length) === "references.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 };
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
/**
|
||||
* 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(entry, outputLibraryName, unusedVarsToIgnore) {
|
||||
this._entry = path.resolve(entry).replace(/\\/g, "/");
|
||||
this._outputLibraryName = outputLibraryName;
|
||||
this._unusedVarsToIgnore = unusedVarsToIgnore;
|
||||
|
||||
this._root = UglifyJS.parse(
|
||||
'(function (root, factory) {\n' +
|
||||
' var global = this;\n' +
|
||||
'\n' +
|
||||
' if (typeof define === "function" && define.amd) {\n' +
|
||||
' define([], function() {\n' +
|
||||
' return factory(global);\n' +
|
||||
' });\n' +
|
||||
' }\n' +
|
||||
' else if (typeof exports === "object" && typeof module === "object") {\n' +
|
||||
' module.exports = factory(global);\n' +
|
||||
' }\n' +
|
||||
' else if (typeof exports === "object") {\n' +
|
||||
' exports.libjass = factory(global);\n' +
|
||||
' }\n' +
|
||||
' else {\n' +
|
||||
' root.libjass = factory(global);\n' +
|
||||
' }\n' +
|
||||
'})(this, function (global) {\n' +
|
||||
' "use strict";\n' +
|
||||
' return (function (modules) {\n' +
|
||||
' var installedModules = Object.create(null);\n' +
|
||||
' function require(moduleId) {\n' +
|
||||
' if (installedModules[moduleId]) {\n' +
|
||||
' return installedModules[moduleId];\n' +
|
||||
' }\n' +
|
||||
'\n' +
|
||||
' var exports = installedModules[moduleId] = Object.create(null);\n' +
|
||||
' modules[moduleId](exports, require);\n' +
|
||||
' return exports;\n' +
|
||||
' }\n' +
|
||||
'\n' +
|
||||
' return require(0);\n' +
|
||||
' })([\n' +
|
||||
' ]);\n' +
|
||||
'});');
|
||||
|
||||
this._root.figure_out_scope({ screw_ie8: true });
|
||||
|
||||
this._licenseHeader = null;
|
||||
|
||||
this._outputModulesArray = this._root.body[0].body.args[1].body[1].value.args[0].elements;
|
||||
|
||||
this._modules = Object.create(null);
|
||||
|
||||
this._rootSourceMap = UjsSourceMap({ file: this._outputLibraryName + ".js", root: "" });
|
||||
}
|
||||
|
||||
Run.prototype.addFile = function (file) {
|
||||
var _this = this;
|
||||
|
||||
var moduleName = (path.extname(file.path) === ".map") ? file.path.substr(0, file.path.length - ".js.map".length) : file.path.substr(0, file.path.length - ".js".length);
|
||||
if (!(moduleName in this._modules)) {
|
||||
this._modules[moduleName] = { id: null, root: null };
|
||||
}
|
||||
|
||||
var module = this._modules[moduleName];
|
||||
|
||||
var filenameWithoutExtension = path.relative(path.join(this._entry, ".."), moduleName).replace(/\\/g, "/");
|
||||
var tsFilename = filenameWithoutExtension + ".ts";
|
||||
var jsFilename = filenameWithoutExtension + ".js";
|
||||
|
||||
switch (path.extname(file.path)) {
|
||||
case ".js":
|
||||
module.root = UglifyJS.parse(file.contents.toString(), {
|
||||
filename: jsFilename,
|
||||
toplevel: null,
|
||||
});
|
||||
|
||||
if (this._licenseHeader === null) {
|
||||
module.root.walk(new UglifyJS.TreeWalker(function (node, descend) {
|
||||
if (_this._licenseHeader !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (node.start) {
|
||||
(node.start.comments_before || []).some(function (comment, i) {
|
||||
if (comment.value.indexOf("Copyright") !== -1) {
|
||||
_this._licenseHeader = comment;
|
||||
_this._licenseHeader.value = _this._licenseHeader.value.split("\n").map(function (line) { return line.replace(/^\t/, ""); }).join("\n");
|
||||
node.start.comments_before.splice(i, 1);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
}));
|
||||
this._root.start.comments_before = [this._licenseHeader];
|
||||
this._root.start.nlb = true;
|
||||
}
|
||||
break;
|
||||
case ".map":
|
||||
var sourceMapContents = JSON.parse(file.contents.toString());
|
||||
sourceMapContents.sources[0] = tsFilename;
|
||||
sourceMapContents.file = jsFilename;
|
||||
this._rootSourceMap.addInput(sourceMapContents);
|
||||
this._rootSourceMap.get().setSourceContent(tsFilename, fs.readFileSync(moduleName + ".ts", { encoding: "utf8" }));
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
Run.prototype.build = function (outputStream) {
|
||||
var _this = this;
|
||||
|
||||
// Assign IDs to all modules
|
||||
var moduleNames = Object.keys(this._modules);
|
||||
moduleNames.sort(function (name1, name2) { return (name1 === name2) ? 0 : (name1 < name2 ? -1 : 1); });
|
||||
moduleNames.unshift.apply(moduleNames, moduleNames.splice(moduleNames.indexOf(this._entry), 1));
|
||||
|
||||
moduleNames.forEach(function (moduleName, index) {
|
||||
_this._modules[moduleName].id = index;
|
||||
});
|
||||
|
||||
|
||||
// Merge modules
|
||||
moduleNames.forEach(function (moduleName) {
|
||||
var module = _this._modules[moduleName];
|
||||
|
||||
module.root.body.forEach(function (statement) {
|
||||
if (statement instanceof UglifyJS.AST_Var && statement.definitions.length === 1) {
|
||||
if (
|
||||
statement.definitions[0].value instanceof UglifyJS.AST_Call &&
|
||||
statement.definitions[0].value.expression.name === "require"
|
||||
) {
|
||||
var importRelativePath = statement.definitions[0].value.args[0].value;
|
||||
var importAbsolutePath = path.join(moduleName, "..", importRelativePath).replace(/\\/g, "/");
|
||||
var stringArg = statement.definitions[0].value.args[0];
|
||||
var importedModule = _this._modules[importAbsolutePath];
|
||||
if (importedModule === undefined) {
|
||||
importedModule = _this._modules[importAbsolutePath + "/index"];
|
||||
}
|
||||
statement.definitions[0].value.args[0] = new UglifyJS.AST_Number({ start: stringArg.start, end: stringArg.end, value: importedModule.id });
|
||||
}
|
||||
else if (statement.definitions[0].name.name === "__extends") {
|
||||
var importAbsolutePath = path.join(_this._entry, "..", "utility", "ts-helpers").replace(/\\/g, "/");
|
||||
statement.definitions[0].value = UglifyJS.parse('require(' + _this._modules[importAbsolutePath].id + ').__extends').body[0].body;
|
||||
}
|
||||
else if (statement.definitions[0].name.name === "__decorate") {
|
||||
var importAbsolutePath = path.join(_this._entry, "..", "utility", "ts-helpers").replace(/\\/g, "/");
|
||||
statement.definitions[0].value = UglifyJS.parse('require(' + _this._modules[importAbsolutePath].id + ').__decorate').body[0].body;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var wrapper = UglifyJS.parse('/* ' + module.id + ' ./' + path.relative(path.join(_this._entry, ".."), moduleName).replace(/\\/g, "/") + ' */ function x(exports, require) { }');
|
||||
var func = wrapper.body[0];
|
||||
func.body = module.root.body;
|
||||
func.name = null;
|
||||
_this._outputModulesArray.push(func);
|
||||
});
|
||||
|
||||
this._root.figure_out_scope({ screw_ie8: true });
|
||||
|
||||
|
||||
// Set if there are any unused variables apart from the ones in unusedVarsToIgnore
|
||||
var haveUnusedVars = false;
|
||||
|
||||
// Remove some things from the AST
|
||||
var nodesToRemove;
|
||||
|
||||
nodesToRemove = [];
|
||||
|
||||
|
||||
// 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 === _this._licenseHeader) {
|
||||
return;
|
||||
}
|
||||
|
||||
var lines = comment.value.split("\n");
|
||||
if (lines.length < 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
var indent = " "; // 9 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 });
|
||||
|
||||
|
||||
// Repeat because removing some declarations may make others unreferenced
|
||||
for (;;) {
|
||||
// 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 = [];
|
||||
|
||||
this._root.figure_out_scope({ screw_ie8: true });
|
||||
}
|
||||
|
||||
|
||||
// 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,
|
||||
beautify: true,
|
||||
comments: function (node, comment) {
|
||||
// If this is the first license header, keep it.
|
||||
if (comment === _this._licenseHeader) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If this is a license header, remove it.
|
||||
if (comment.value.indexOf("Copyright") !== -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If this is a TypeScript reference comment, strip it.
|
||||
if (comment.value.substr(0, "/<reference path=".length) === "/<reference path=") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
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 (entry, outputLibraryName, unusedVarsToIgnore) {
|
||||
var run = new Run(entry, outputLibraryName, unusedVarsToIgnore);
|
||||
|
||||
return new FileTransform(function (file) {
|
||||
run.addFile(file);
|
||||
}, function () {
|
||||
run.build(this);
|
||||
});
|
||||
},
|
||||
|
||||
watch: function (entry, 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(entry, 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()
|
||||
}),
|
||||
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 SourceMap = require.cache[require.resolve("uglify-js")].require("source-map");
|
||||
|
||||
function UjsSourceMap(options) {
|
||||
var orig_maps = Object.create(null);
|
||||
|
||||
var generator = new SourceMap.SourceMapGenerator({
|
||||
file: options.file,
|
||||
sourceRoot: options.root,
|
||||
});
|
||||
|
||||
return {
|
||||
addInput: function (rawSourceMap) {
|
||||
var consumer = new SourceMap.SourceMapConsumer(rawSourceMap);
|
||||
orig_maps[consumer.file] = consumer;
|
||||
},
|
||||
add: function (source, gen_line, gen_col, orig_line, orig_col, name) {
|
||||
var originalMap = orig_maps[source];
|
||||
if (originalMap === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
var info = originalMap.originalPositionFor({
|
||||
line: orig_line,
|
||||
column: orig_col
|
||||
});
|
||||
|
||||
if (info.source === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
source = info.source;
|
||||
orig_line = info.line;
|
||||
orig_col = info.column;
|
||||
name = info.name || name;
|
||||
|
||||
generator.addMapping({
|
||||
generated : { line: gen_line, column: gen_col },
|
||||
original : { line: orig_line, column: orig_col },
|
||||
source : source,
|
||||
name : name
|
||||
});
|
||||
},
|
||||
get: function () { return generator; },
|
||||
toString: function () { return generator.toString(); },
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
};
|
||||
@@ -1,794 +0,0 @@
|
||||
@font-face {
|
||||
font-family: "???? Pro";
|
||||
src: url("/fonts/Yryr%20minc%20R.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "123 and...";
|
||||
src: url("/fonts/123-and...-Regular.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "123and";
|
||||
src: url("/fonts/123-and...-Regular.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "AmbersHand-Plain";
|
||||
src: url("/fonts/LEHN011.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Amienne";
|
||||
src: url("/fonts/Amienne.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "A-OTF Futo Min A101 Pro";
|
||||
src: url("/fonts/A-OTF-FutoMinA101Pro-Bold.otf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "A-OTF Futo Min A101 Pro Bold";
|
||||
src: url("/fonts/A-OTF-FutoMinA101Pro-Bold.otf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Arial";
|
||||
src: url("/fonts/arial.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "ArialMT";
|
||||
src: url("/fonts/arial.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "ArtificeSSK";
|
||||
src: url("/fonts/ArtificeSSK.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Baar Sophia";
|
||||
src: url("/fonts/BAARS.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "BaarSophia";
|
||||
src: url("/fonts/BAARS.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Babylon 27";
|
||||
src: url("/fonts/Babylon-27-Babylon-27.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Balzano";
|
||||
src: url("/fonts/BALZANO.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Bee Marker Ink";
|
||||
src: url("/fonts/BeeMarkerInk.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "BeeMarkerInk";
|
||||
src: url("/fonts/BeeMarkerInk.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Berlin Sans FB Demi";
|
||||
src: url("/fonts/BRLNSDB.TTF"), url("/fonts/BRLNSDB_0.TTF");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "BerlinSansFBDemi-Bold";
|
||||
src: url("/fonts/BRLNSDB.TTF"), url("/fonts/BRLNSDB_0.TTF");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "BlueBrush";
|
||||
src: url("/fonts/BlueBrush.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Brianne's hand";
|
||||
src: url("/fonts/Brianne_s_hand.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Brianne'shand";
|
||||
src: url("/fonts/Brianne_s_hand.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "bylon 27";
|
||||
src: url("/fonts/Babylon-27-Babylon-27.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "CAC Moose";
|
||||
src: url("/fonts/CAC%20Moose.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "CACMoose";
|
||||
src: url("/fonts/CAC%20Moose.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "CenturyOldStyle-Light";
|
||||
src: url("/fonts/CENTURYO.TTF"), url("/fonts/CenturyOldStyle-Light.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "CenturyOldStyle-Light";
|
||||
src: url("/fonts/CenturyOldStyle-Light%20Bold.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "CenturyOldStyle-Light-Bold";
|
||||
src: url("/fonts/CenturyOldStyle-Light%20Bold.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Charme";
|
||||
src: url("/fonts/CHARME.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Chinacat";
|
||||
src: url("/fonts/chinrg.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Complete in Him";
|
||||
src: url("/fonts/Complete%20in%20Him.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "CompleteinHim";
|
||||
src: url("/fonts/Complete%20in%20Him.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Consolas";
|
||||
src: url("/fonts/consola.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Consolas";
|
||||
src: url("/fonts/consolab.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Consolas-Bold";
|
||||
src: url("/fonts/consolab.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Continuum Bold";
|
||||
src: url("/fonts/contb.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "ContinuumBold";
|
||||
src: url("/fonts/contb.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Designosaur";
|
||||
src: url("/fonts/Designosaur-Regular.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Designosaur";
|
||||
src: url("/fonts/Designosaur-Italic.ttf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Designosaur-Italic";
|
||||
src: url("/fonts/Designosaur-Italic.ttf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Dutch766 BT";
|
||||
src: url("/fonts/Du766Bd.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Dutch766BT-BoldA";
|
||||
src: url("/fonts/Du766Bd.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "EFN Impresja";
|
||||
src: url("/fonts/impresja.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "EFNImpresja";
|
||||
src: url("/fonts/impresja.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Elephant";
|
||||
src: url("/fonts/ELEPHNT.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Elephant-Regular";
|
||||
src: url("/fonts/ELEPHNT.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "EmilysHand-Plain";
|
||||
src: url("/fonts/LEHN084.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "EngraversGothic BT";
|
||||
src: url("/fonts/Engrvgot.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "EngraversGothicBT-Regular";
|
||||
src: url("/fonts/Engrvgot.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Essai";
|
||||
src: url("/fonts/Essai.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Estrangelo Edessa";
|
||||
src: url("/fonts/estre.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "EstrangeloEdessa";
|
||||
src: url("/fonts/estre.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Euphemia";
|
||||
src: url("/fonts/Euphemia_0.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "EuphemiaCAS";
|
||||
src: url("/fonts/Euphemia_0.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "FarrahsHand-Plain";
|
||||
src: url("/fonts/LEHN095.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Fontin Sans";
|
||||
src: url("/fonts/FONTIN_SANS.OTF");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Fontin Sans";
|
||||
src: url("/fonts/FONTIN_SANS_BI.OTF");
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Fontin Sans Rg";
|
||||
src: url("/fonts/FONTIN_SANS.OTF");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Fontin Sans Rg";
|
||||
src: url("/fonts/FONTIN_SANS_BI.OTF");
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "FontinSans-Bold";
|
||||
src: url("/fonts/FONTIN_SANS.OTF");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "FontinSans-BoldItalic";
|
||||
src: url("/fonts/FONTIN_SANS_BI.OTF");
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Forte";
|
||||
src: url("/fonts/FORTE.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "ForteMT";
|
||||
src: url("/fonts/FORTE.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Franchise";
|
||||
src: url("/fonts/Franchise-Bold-hinted.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Franchise-Bold";
|
||||
src: url("/fonts/Franchise-Bold-hinted.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "FutoMinA101Pro-Bold";
|
||||
src: url("/fonts/A-OTF-FutoMinA101Pro-Bold.otf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Gandhi Sans";
|
||||
src: url("/fonts/GandhiSans-Bold.otf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Gandhi Sans";
|
||||
src: url("/fonts/GandhiSans-BoldItalic.otf");
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "GandhiSans-Bold";
|
||||
src: url("/fonts/GandhiSans-Bold.otf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "GandhiSans-BoldItalic";
|
||||
src: url("/fonts/GandhiSans-BoldItalic.otf");
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "HandelGotDBol";
|
||||
src: url("/fonts/HANDGOTB.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "HandelGotD-Bold";
|
||||
src: url("/fonts/HANDGOTB.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "HandelGothic BT";
|
||||
src: url("/fonts/HANDGOTN.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "HandelGothicBT-Regular";
|
||||
src: url("/fonts/HANDGOTN.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "HandVetica";
|
||||
src: url("/fonts/HandVetica.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "HandVetica-Bold";
|
||||
src: url("/fonts/HandVetica.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "HiraginoGyoDS-W4";
|
||||
src: url("/fonts/HiraginoGyoDS-W4.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "HZHandwrite";
|
||||
src: url("/fonts/HZHandwrite.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Impressum Std";
|
||||
src: url("/fonts/ImpressumStd-Roman.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "ImpressumStd-Roman";
|
||||
src: url("/fonts/ImpressumStd-Roman.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "ITC Avant Garde Gothic Std";
|
||||
src: url("/fonts/ITCAvantGardeStd-Md.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "ITC Avant Garde Std Md";
|
||||
src: url("/fonts/ITCAvantGardeStd-Md.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "ITCAvantGardeStd-Md";
|
||||
src: url("/fonts/ITCAvantGardeStd-Md.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "IwaMinPro-Madoka-Lt";
|
||||
src: url("/fonts/IwaMinPro-Lt-Madoka.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "IwaOMinPro-Fate-Bd";
|
||||
src: url("/fonts/IwaOMinPro-Bd-Fate.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Iwata Mincho Old Pro-Fate";
|
||||
src: url("/fonts/IwaOMinPro-Bd-Fate.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Iwata Mincho Old Pro-Fate B";
|
||||
src: url("/fonts/IwaOMinPro-Bd-Fate.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Iwata Mincho Pro-Madoka";
|
||||
src: url("/fonts/IwaMinPro-Lt-Madoka.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Iwata Mincho Pro-Madoka L";
|
||||
src: url("/fonts/IwaMinPro-Lt-Madoka.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "JanieHmkBold";
|
||||
src: url("/fonts/JANIHB.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Kabel LT Std";
|
||||
src: url("/fonts/KabelLTStd-Book.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Kabel LT Std Book";
|
||||
src: url("/fonts/KabelLTStd-Book.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "KabelLTStd-Book";
|
||||
src: url("/fonts/KabelLTStd-Book.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "KozGoPro-Heavy-Madoka";
|
||||
src: url("/fonts/KozGoProH-Madoka.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Kozuka Gothic Pro";
|
||||
src: url("/fonts/KozGoProH-Madoka.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "KozukaGothicProH-Madoka";
|
||||
src: url("/fonts/KozGoProH-Madoka.ttf");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LEHN011";
|
||||
src: url("/fonts/LEHN011.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LEHN084";
|
||||
src: url("/fonts/LEHN084.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LEHN095";
|
||||
src: url("/fonts/LEHN095.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LHF Scriptana";
|
||||
src: url("/fonts/LHF_Scriptana.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LHFScriptana-Regular";
|
||||
src: url("/fonts/LHF_Scriptana.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LinotypeFinnegan-Medium";
|
||||
src: url("/fonts/LT.ttf"), url("/fonts/LT_3.ttf"), url("/fonts/LT_4.ttf"), url("/fonts/macron%20finnetier%200.3.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LinotypeFinnegan-MediumIt";
|
||||
src: url("/fonts/LT_3italic.ttf"), url("/fonts/LT_italic.ttf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LLRubberGrotesqueOTF";
|
||||
src: url("/fonts/LLRUG.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LTFinnegan Medium";
|
||||
src: url("/fonts/LT.ttf"), url("/fonts/LT_3.ttf"), url("/fonts/LT_4.ttf"), url("/fonts/macron%20finnetier%200.3.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "LTFinnegan Medium";
|
||||
src: url("/fonts/LT_3italic.ttf"), url("/fonts/LT_italic.ttf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Macron Finnetier Medium";
|
||||
src: url("/fonts/macron%20finnetier%200.3.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "MacronFinnetier-Medium";
|
||||
src: url("/fonts/macron%20finnetier%200.3.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Mentone";
|
||||
src: url("/fonts/mentone-semibol.otf");
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Mentone Lig";
|
||||
src: url("/fonts/mentone-semibol.otf");
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Mentone-SemiBold";
|
||||
src: url("/fonts/mentone-semibol.otf");
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Montara";
|
||||
src: url("/fonts/Montara-Gothic.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Montara";
|
||||
src: url("/fonts/Montara-Italic.otf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Montara Gothic";
|
||||
src: url("/fonts/Montara-Gothic.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Montara Gothic";
|
||||
src: url("/fonts/Montara-Italic.otf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Montara-Gothic";
|
||||
src: url("/fonts/Montara-Gothic.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Montara-Italic";
|
||||
src: url("/fonts/Montara-Italic.otf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "New";
|
||||
src: url("/fonts/OBGB.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "NewBaskerville";
|
||||
src: url("/fonts/NEWBASK.TTF"), url("/fonts/NewBaskerville.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Old Block";
|
||||
src: url("/fonts/OBGB.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Old Block Black";
|
||||
src: url("/fonts/OBGB.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Old newspaper font";
|
||||
src: url("/fonts/Old_Newspaper_Font.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Oldnewspaperfont";
|
||||
src: url("/fonts/Old_Newspaper_Font.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Painfresco";
|
||||
src: url("/fonts/Painfresco-Regular.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Painfresco";
|
||||
src: url("/fonts/Painfresco-Italic.ttf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Painfresco-Italic";
|
||||
src: url("/fonts/Painfresco-Italic.ttf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Painfresco-Regular";
|
||||
src: url("/fonts/Painfresco-Regular.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "PaintyPaint";
|
||||
src: url("/fonts/PAINP.TTF"), url("/fonts/PAINP_0.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "PaintyPaint1";
|
||||
src: url("/fonts/PAINP.TTF"), url("/fonts/PAINP_0.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Panefresco800wt-Italic";
|
||||
src: url("/fonts/Painfresco-Italic.ttf");
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Panefresco800wtKilllaKill-Regular";
|
||||
src: url("/fonts/Painfresco-Regular.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Pencilfied";
|
||||
src: url("/fonts/pencilfied.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "PencilfiedX";
|
||||
src: url("/fonts/pencilfied.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Profile";
|
||||
src: url("/fonts/Profile-Medium.otf"), url("/fonts/Profile-Regular.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Profile-Medium";
|
||||
src: url("/fonts/Profile-Medium.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Profile-Regular";
|
||||
src: url("/fonts/Profile-Regular.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Prototype";
|
||||
src: url("/fonts/Prototype.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Reswysokr";
|
||||
src: url("/fonts/Reswysokr.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Signika";
|
||||
src: url("/fonts/Signika-Regular.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Signika-Regular";
|
||||
src: url("/fonts/Signika-Regular.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Spectrum MT Std";
|
||||
src: url("/fonts/SpectrumMTStd.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "SpectrumMTStd";
|
||||
src: url("/fonts/SpectrumMTStd.otf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Swis721 Hv BT";
|
||||
src: url("/fonts/SWZ721H.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Swis721 Md BT";
|
||||
src: url("/fonts/SWZ721M.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Swiss721BT-Heavy";
|
||||
src: url("/fonts/SWZ721H.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Swiss721BT-Medium";
|
||||
src: url("/fonts/SWZ721M.TTF");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Unisketchlightlimited";
|
||||
src: url("/fonts/Unisketch-light_limited.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Unisketch-lightlimitedLight";
|
||||
src: url("/fonts/Unisketch-light_limited.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Untitled";
|
||||
src: url("/fonts/Babylon-27-Babylon-27.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Yryr minc R";
|
||||
src: url("/fonts/Yryr%20minc%20R.ttf");
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "YryrmincR";
|
||||
src: url("/fonts/Yryr%20minc%20R.ttf");
|
||||
}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
/**
|
||||
* 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 childProcess = require("child_process");
|
||||
var fs = require("fs");
|
||||
var gulp = require("gulp");
|
||||
var path = require("path");
|
||||
|
||||
var Vinyl = require("vinyl");
|
||||
|
||||
var Transform = require("./gulplib/helpers.js").Transform;
|
||||
|
||||
Object.defineProperties(global, {
|
||||
Doc: { get: function () { return require("./gulplib/doc.js"); } },
|
||||
Mocha: { get: function () { return require("mocha"); } },
|
||||
TypeScript: { get: function () { return require("./gulplib/typescript.js"); } },
|
||||
UglifyJS: { get: function () { return require("./gulplib/uglify.js"); } },
|
||||
});
|
||||
|
||||
gulp.task("default", ["libjass.js", "libjass.min.js"]);
|
||||
|
||||
gulp.task("libjass.js", function (callback) {
|
||||
if (fs.existsSync("./libjass.js")) {
|
||||
return callback(null);
|
||||
}
|
||||
|
||||
return gulp.src("./libjass.ts").pipe(TypeScript.gulp("/libjass.js", "/libjass.js.map")).pipe(UglifyJS.fixup()).pipe(gulp.dest("."));
|
||||
});
|
||||
|
||||
gulp.task("libjass.min.js", ["libjass.js"], function (callback) {
|
||||
if (fs.existsSync("./libjass.min.js")) {
|
||||
return callback(null);
|
||||
}
|
||||
|
||||
var input = Object.create(null);
|
||||
|
||||
return gulp.src(["./libjass.js", "./libjass.js.map"]).pipe(UglifyJS.minify()).pipe(gulp.dest("."));
|
||||
});
|
||||
|
||||
gulp.task("clean", function () {
|
||||
["libjass.js", "libjass.js.map", "libjass.min.js", "libjass.min.js.map"].forEach(function (file) {
|
||||
try {
|
||||
fs.unlinkSync(file);
|
||||
}
|
||||
catch (ex) {
|
||||
if (ex.code !== "ENOENT") {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
gulp.task("test", ["libjass.js"], function (callback) {
|
||||
var mocha = new Mocha({
|
||||
ui: "tdd",
|
||||
reporter: "spec"
|
||||
});
|
||||
|
||||
gulp.src("./tests/test-*.js").pipe(Transform(function (file) {
|
||||
mocha.addFile(file.path);
|
||||
}, function () {
|
||||
mocha.run(function (failures) {
|
||||
if (failures > 0) {
|
||||
callback(new Error(failures + " test(s) failed."));
|
||||
}
|
||||
else {
|
||||
callback(null);
|
||||
}
|
||||
});
|
||||
}));
|
||||
});
|
||||
|
||||
gulp.task("watch", function (callback) {
|
||||
var spawnSubProcess = function () {
|
||||
var pathToGulp = path.resolve("./node_modules/.bin/gulp");
|
||||
var subProcess = childProcess.exec(pathToGulp + " _watch");
|
||||
subProcess.stdout.pipe(process.stdout);
|
||||
subProcess.stderr.pipe(process.stderr);
|
||||
subProcess.addListener("exit", function (code, signal) {
|
||||
spawnSubProcess();
|
||||
});
|
||||
};
|
||||
|
||||
spawnSubProcess();
|
||||
});
|
||||
|
||||
gulp.task("_watch", function () {
|
||||
return gulp.watch(["./*.ts", "./tests/*.js"], ["clean", "libjass.js", "test"]);
|
||||
});
|
||||
|
||||
gulp.task("doc", ["libjass.js"], function () {
|
||||
return gulp.src("./libjass.js").pipe(Doc("/api.xhtml")).pipe(gulp.dest("../libjass-gh-pages/"));
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
/**
|
||||
* 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 stream = require("stream");
|
||||
var util = require("util");
|
||||
|
||||
var Transform = function (transform, flush) {
|
||||
if (!(this instanceof Transform)) {
|
||||
return new Transform(transform, flush);
|
||||
}
|
||||
|
||||
stream.Transform.call(this, { objectMode: true });
|
||||
|
||||
transform = transform || function (chunk, encoding, callback) { callback(); };
|
||||
|
||||
if (transform.length < 3) {
|
||||
this._transform = function (chunk, encoding, callback) {
|
||||
try {
|
||||
transform.call(this, chunk, encoding);
|
||||
callback();
|
||||
}
|
||||
catch (ex) {
|
||||
callback(ex);
|
||||
}
|
||||
};
|
||||
}
|
||||
else {
|
||||
this._transform = transform.bind(this);
|
||||
}
|
||||
|
||||
flush = flush || function (callback) { callback(); };
|
||||
if (flush.length < 1) {
|
||||
this._flush = function (callback) { try { flush.call(this); callback(); } catch (ex) { callback(ex); } };
|
||||
}
|
||||
else {
|
||||
this._flush = flush.bind(this);
|
||||
}
|
||||
};
|
||||
|
||||
util.inherits(Transform, stream.Transform);
|
||||
|
||||
exports.Transform = Transform;
|
||||
@@ -1,205 +0,0 @@
|
||||
/**
|
||||
* 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 vm = require("vm");
|
||||
|
||||
var Vinyl = require("vinyl");
|
||||
|
||||
var Transform = require("./helpers.js").Transform;
|
||||
|
||||
var typeScriptModulePath = path.resolve("./node_modules/typescript/bin");
|
||||
var typeScriptJsPath = path.join(typeScriptModulePath, "typescript.js");
|
||||
|
||||
var TypeScript = {};
|
||||
vm.runInNewContext(fs.readFileSync(typeScriptJsPath, { encoding: "utf8" }) + "module.exports = TypeScript;", {
|
||||
module: Object.defineProperty(Object.create(null), "exports", {
|
||||
get: function () { return TypeScript; },
|
||||
set: function (value) { TypeScript = value; }
|
||||
}),
|
||||
require: require,
|
||||
process: process,
|
||||
__filename: typeScriptJsPath,
|
||||
__dirname: typeScriptModulePath
|
||||
});
|
||||
|
||||
exports.TS = TypeScript;
|
||||
|
||||
var innerCompilerSettings = new TypeScript.CompilationSettings();
|
||||
innerCompilerSettings.codeGenTarget = TypeScript.LanguageVersion.EcmaScript5;
|
||||
innerCompilerSettings.mapSourceFiles = true;
|
||||
innerCompilerSettings.noImplicitAny = true;
|
||||
innerCompilerSettings.outFileOption = "output.js";
|
||||
|
||||
innerCompilerSettings = TypeScript.ImmutableCompilationSettings.fromCompilationSettings(innerCompilerSettings);
|
||||
|
||||
var Compiler = function () {
|
||||
function Compiler() {
|
||||
this._diagnostics = [];
|
||||
|
||||
this._scriptSnapshots = Object.create(null);
|
||||
};
|
||||
|
||||
Compiler.prototype.addFiles = function (files) {
|
||||
var _this = this;
|
||||
|
||||
var resolutionResults = TypeScript.ReferenceResolver.resolve(files, {
|
||||
resolveRelativePath: function (file, directory) {
|
||||
return path.resolve(directory, file);
|
||||
},
|
||||
fileExists: fs.existsSync.bind(fs),
|
||||
getScriptSnapshot: this._getScriptSnapshot.bind(this),
|
||||
getParentDirectory: path.dirname.bind(path)
|
||||
}, true);
|
||||
|
||||
resolutionResults.resolvedFiles.unshift({
|
||||
path: path.resolve(typeScriptModulePath, "lib.d.ts"),
|
||||
referencedFiles: [],
|
||||
importedFiles: []
|
||||
});
|
||||
|
||||
this._addDiagnostics(resolutionResults.diagnostics);
|
||||
|
||||
this._innerCompiler = new TypeScript.TypeScriptCompiler(new TypeScript.NullLogger(), innerCompilerSettings);
|
||||
|
||||
resolutionResults.resolvedFiles.forEach(function (resolvedFile) {
|
||||
_this._innerCompiler.addFile(resolvedFile.path, _this._getScriptSnapshot(resolvedFile.path), 0, 0, false, resolvedFile.referencedFiles);
|
||||
});
|
||||
|
||||
return resolutionResults.resolvedFiles;
|
||||
};
|
||||
|
||||
Compiler.prototype.compile = function (outputCodePath, outputSourceMapPath) {
|
||||
var iterator = this._innerCompiler.compile(path.resolve.bind(path));
|
||||
var outputFiles = [];
|
||||
|
||||
while (iterator.moveNext()) {
|
||||
var result = iterator.current();
|
||||
|
||||
this._addDiagnostics(result.diagnostics);
|
||||
|
||||
result.outputFiles.forEach(function (outputFile) {
|
||||
var outputPath = null;
|
||||
|
||||
switch (outputFile.fileType) {
|
||||
case TypeScript.OutputFileType.JavaScript:
|
||||
outputPath = outputCodePath;
|
||||
break;
|
||||
|
||||
case TypeScript.OutputFileType.SourceMap:
|
||||
outputPath = outputSourceMapPath;
|
||||
break;
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
outputFiles.push(new Vinyl({
|
||||
base: "/",
|
||||
path: outputPath,
|
||||
contents: new Buffer(outputFile.text)
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
if (this._diagnostics.some(function (diagnostic) { return diagnostic.info().category === 1; })) {
|
||||
throw new Error("There were one or more errors.");
|
||||
}
|
||||
|
||||
return outputFiles;
|
||||
};
|
||||
|
||||
Compiler.prototype.getDocument = function (resolvedFilePath) {
|
||||
return this._innerCompiler.getDocument(resolvedFilePath);
|
||||
};
|
||||
|
||||
Compiler.prototype._addDiagnostics = function (newDiagnostics) {
|
||||
newDiagnostics.forEach(function (diagnostic) {
|
||||
var message = diagnostic.message();
|
||||
|
||||
if (diagnostic.fileName()) {
|
||||
message = diagnostic.fileName() + "(" + (diagnostic.line() + 1) + "," + (diagnostic.character() + 1) + "): " + message;
|
||||
}
|
||||
|
||||
console.error(message);
|
||||
});
|
||||
|
||||
this._diagnostics.push.apply(this._diagnostics, newDiagnostics);
|
||||
};
|
||||
|
||||
Compiler.prototype._getScriptSnapshot = function (filename) {
|
||||
var scriptSnapshot = this._scriptSnapshots[filename];
|
||||
|
||||
if (!scriptSnapshot) {
|
||||
var fileContents;
|
||||
|
||||
try {
|
||||
fileContents = fs.readFileSync(filename, { encoding: "utf8" });
|
||||
}
|
||||
catch (ex) {
|
||||
this._addDiagnostics([new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_read_file_0_1, [filename, ex.message])]);
|
||||
fileContents = "";
|
||||
}
|
||||
|
||||
scriptSnapshot = this._scriptSnapshots[filename] = TypeScript.ScriptSnapshot.fromString(fileContents);
|
||||
}
|
||||
|
||||
return scriptSnapshot;
|
||||
};
|
||||
|
||||
return Compiler;
|
||||
}();
|
||||
|
||||
exports.Compiler = Compiler;
|
||||
|
||||
exports.gulp = function (outputCodePath, outputSourceMapPath) {
|
||||
var files = [];
|
||||
|
||||
return Transform(function (file, encoding) {
|
||||
files.push(file.path);
|
||||
}, function () {
|
||||
var _this = this;
|
||||
|
||||
try {
|
||||
console.log("Compiling " + JSON.stringify(files) + "...");
|
||||
|
||||
var compiler = new Compiler();
|
||||
|
||||
compiler.addFiles(files);
|
||||
|
||||
var outputFiles = compiler.compile(outputCodePath, outputSourceMapPath);
|
||||
|
||||
console.log("Compile succeeded.");
|
||||
|
||||
outputFiles.forEach(function (file) {
|
||||
_this.push(file);
|
||||
});
|
||||
}
|
||||
catch (ex) {
|
||||
if (ex instanceof Error) {
|
||||
throw ex;
|
||||
}
|
||||
else {
|
||||
throw new Error("Internal compiler error: " + ex.stack + "\n");
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,338 +0,0 @@
|
||||
/**
|
||||
* 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 Transform = require("./helpers.js").Transform;
|
||||
|
||||
module.exports = {
|
||||
fixup: function () {
|
||||
var codeFile = null;
|
||||
var sourceMapFile = null;
|
||||
|
||||
return Transform(function (file) {
|
||||
switch (path.extname(file.path)) {
|
||||
case ".js":
|
||||
codeFile = file;
|
||||
break;
|
||||
case ".map":
|
||||
sourceMapFile = file;
|
||||
break;
|
||||
}
|
||||
}, function () {
|
||||
UglifyJS.base54.reset();
|
||||
|
||||
|
||||
// Parse
|
||||
var root = UglifyJS.parse(codeFile.contents.toString(), {
|
||||
filename: path.basename(codeFile.path),
|
||||
toplevel: null
|
||||
});
|
||||
|
||||
root = root.wrap_enclose(['((typeof module !== "undefined") && module.exports) || (this.libjass = {}):libjass', '((typeof global !== "undefined") && global) || this:global']);
|
||||
|
||||
root.figure_out_scope({ screw_ie8: true });
|
||||
|
||||
|
||||
// Remove some things from the AST
|
||||
var nodesToRemove;
|
||||
|
||||
nodesToRemove = [];
|
||||
|
||||
// 1. All the top-level "var libjass;"
|
||||
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
|
||||
if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "libjass") {
|
||||
nodesToRemove.push({ node: node, parent: this.parent().body });
|
||||
}
|
||||
}));
|
||||
|
||||
// 2. All but the first top-level "var __extends = ..."
|
||||
var firstVarExtendsFound = false;
|
||||
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
|
||||
if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "__extends") {
|
||||
if (firstVarExtendsFound === false) {
|
||||
firstVarExtendsFound = true;
|
||||
// Remove the check for this.__extends
|
||||
node.definitions[0].value = node.definitions[0].value.right;
|
||||
}
|
||||
else {
|
||||
nodesToRemove.push({ node: node, parent: this.parent().body });
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
// Repeat because removing some declarations may make others unreferenced
|
||||
for (;;) {
|
||||
// 3. Unreferenced variable and function declarations, and unreferenced terminal function arguments
|
||||
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) {
|
||||
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 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 = [];
|
||||
|
||||
root.figure_out_scope({ screw_ie8: true });
|
||||
}
|
||||
|
||||
// 4. 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).
|
||||
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
|
||||
if (
|
||||
node instanceof UglifyJS.AST_SymbolFunarg &&
|
||||
node.thedef.name[0] === "_" &&
|
||||
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 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(),
|
||||
root: ""
|
||||
}),
|
||||
beautify: true,
|
||||
comments: function (node, comment) {
|
||||
// If this is a license header
|
||||
if (comment.value.indexOf("Copyright") !== -1) {
|
||||
if (!firstLicenseHeaderFound) {
|
||||
firstLicenseHeaderFound = true;
|
||||
}
|
||||
else {
|
||||
// This isn't the first license header. Strip it.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// If this is a TypeScript reference comment, strip it.
|
||||
if (comment.value.substr(0, "/<reference path=".length) === "/<reference path=") {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Align multi-line comments correctly.
|
||||
* TypeScript shifts them one space left, and UJS shifts them four spaces left,
|
||||
* so shift each line except the first five spaces right.
|
||||
*/
|
||||
if (comment.type === "comment2") {
|
||||
var lines = comment.value.split("\n");
|
||||
lines = [lines[0]].concat(lines.slice(1).map(function (line) { return ' ' + line; }));
|
||||
comment.value = lines.join('\n');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
var stream = UglifyJS.OutputStream(output);
|
||||
root.print(stream);
|
||||
|
||||
codeFile.contents = Buffer.concat([new Buffer(stream.toString()), new Buffer("\n//# sourceMappingURL=libjass.js.map")]);
|
||||
this.push(codeFile);
|
||||
|
||||
output.source_map.get()._sources.toArray().forEach(function (filename) {
|
||||
output.source_map.get().setSourceContent(filename, fs.readFileSync(filename, { encoding: "utf8"}));
|
||||
});
|
||||
|
||||
sourceMapFile.contents = new Buffer(output.source_map.toString());
|
||||
this.push(sourceMapFile);
|
||||
});
|
||||
},
|
||||
|
||||
minify: function () {
|
||||
var codeFile = null;
|
||||
var sourceMapFile = null;
|
||||
|
||||
return Transform(function (file) {
|
||||
switch (path.extname(file.path)) {
|
||||
case ".js":
|
||||
codeFile = file;
|
||||
break;
|
||||
case ".map":
|
||||
sourceMapFile = file;
|
||||
break;
|
||||
}
|
||||
}, function () {
|
||||
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 });
|
||||
|
||||
|
||||
// Suppress some warnings
|
||||
var originalWarn = UglifyJS.AST_Node.warn;
|
||||
UglifyJS.AST_Node.warn = function (text, properties) {
|
||||
if (
|
||||
(text === "{type} {name} is declared but not referenced [{file}:{line},{col}]" && properties.type === "Symbol" && properties.name === "substring" && properties.file === "libjass.js" && properties.line === 5917)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
originalWarn.call(UglifyJS.AST_Node, text, properties);
|
||||
};
|
||||
|
||||
// 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 });
|
||||
|
||||
|
||||
// Mangle private members
|
||||
var occurrences = Object.create(null);
|
||||
|
||||
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
|
||||
if (
|
||||
node instanceof UglifyJS.AST_PropAccess &&
|
||||
typeof node.property === "string" &&
|
||||
node.property[0] === "_" && node.property[1] !== "_"
|
||||
) {
|
||||
var occurrence = occurrences[node.property];
|
||||
if (occurrence === undefined) {
|
||||
occurrences[node.property] = 1;
|
||||
}
|
||||
else {
|
||||
occurrences[node.property]++;
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
var identifiers = Object.keys(occurrences);
|
||||
identifiers.sort(function (first, second) { return occurrences[second] - occurrences[first]; });
|
||||
|
||||
var generatedIdentifiers = occurrences;
|
||||
|
||||
var validIdentifierCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
|
||||
var toIdentifier = function (index) {
|
||||
var result = validIdentifierCharacters[(index % validIdentifierCharacters.length)];
|
||||
index = (index / validIdentifierCharacters.length) | 0;
|
||||
|
||||
while (index > 0) {
|
||||
index--;
|
||||
result = validIdentifierCharacters[index % validIdentifierCharacters.length] + result;
|
||||
index = (index / validIdentifierCharacters.length) | 0;
|
||||
}
|
||||
|
||||
return "_" + result;
|
||||
};
|
||||
|
||||
identifiers.forEach(function (identifier, index) {
|
||||
generatedIdentifiers[identifier] = toIdentifier(index);
|
||||
});
|
||||
|
||||
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
|
||||
if (
|
||||
node instanceof UglifyJS.AST_PropAccess &&
|
||||
typeof node.property === "string" &&
|
||||
node.property in generatedIdentifiers
|
||||
) {
|
||||
node.property = generatedIdentifiers[node.property];
|
||||
}
|
||||
}));
|
||||
|
||||
|
||||
// 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(),
|
||||
root: ""
|
||||
}),
|
||||
comments: {
|
||||
test: function (comment) {
|
||||
if (!firstLicenseHeaderFound && comment.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");
|
||||
codeFile.contents = Buffer.concat([new Buffer(stream.toString()), new Buffer("\n//# sourceMappingURL=libjass.js.map")]);
|
||||
this.push(codeFile);
|
||||
|
||||
output.source_map.get()._sources.toArray().forEach(function (filename) {
|
||||
output.source_map.get().setSourceContent(filename, fs.readFileSync(filename, { encoding: "utf8"}));
|
||||
});
|
||||
|
||||
sourceMapFile.path = sourceMapFile.path.replace(/\.js\.map$/, ".min.js.map");
|
||||
sourceMapFile.contents = new Buffer(output.source_map.toString());
|
||||
this.push(sourceMapFile);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1,137 +0,0 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
|
||||
libjass.debugMode = (location.search === "?debug") || (location.search === "?verbose");
|
||||
libjass.verboseMode = (location.search === "?verbose");
|
||||
|
||||
addEventListener("DOMContentLoaded", function () {
|
||||
var debug = function () {
|
||||
if (libjass.debugMode) {
|
||||
console.log.apply(console, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
var video = document.querySelector("#video");
|
||||
|
||||
var videoMetadataLoaded = false;
|
||||
var ass = null;
|
||||
|
||||
var testVideoAndASSLoaded = function () {
|
||||
if (videoMetadataLoaded && ass) {
|
||||
var renderer = new libjass.renderers.DefaultRenderer(video, ass, {
|
||||
fontMap: libjass.renderers.RendererSettings.makeFontMapFromStyleElement(document.querySelector("#font-map"))
|
||||
});
|
||||
|
||||
if (libjass.debugMode) {
|
||||
window.renderer = renderer;
|
||||
}
|
||||
|
||||
renderer.addEventListener("ready", function () {
|
||||
debug("All fonts have been preloaded. Beginning autoplay.");
|
||||
video.play();
|
||||
|
||||
subToggleSpanTextNode.textContent = renderer.enabled ? "off" : "on";
|
||||
});
|
||||
|
||||
var subToggleSpanTextNode = document.createTextNode("");
|
||||
document.querySelector("#enable-disable-subs-span").appendChild(subToggleSpanTextNode);
|
||||
|
||||
document.querySelector("#enable-disable-button").addEventListener("click", function (event) {
|
||||
renderer.toggle();
|
||||
subToggleSpanTextNode.textContent = renderer.enabled ? "off" : "on";
|
||||
}, false);
|
||||
|
||||
var changeVideoSizeSelection = function (id) {
|
||||
if (typeof id === "undefined") {
|
||||
[].some.call(videoSizeSelector.querySelectorAll("input[name='video-size']"), function (option) {
|
||||
if (option.checked) {
|
||||
id = option.id;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
if (id === "video-size-video-radio") {
|
||||
video.style.width = video.videoWidth + "px";
|
||||
video.style.height = video.videoHeight + "px";
|
||||
renderer.resize(video.videoWidth, video.videoHeight);
|
||||
}
|
||||
|
||||
else if (id === "video-size-script-radio") {
|
||||
video.style.width = ass.properties.resolutionX + "px";
|
||||
video.style.height = ass.properties.resolutionY + "px";
|
||||
renderer.resize(ass.properties.resolutionX, ass.properties.resolutionY);
|
||||
}
|
||||
};
|
||||
|
||||
var videoSizeSelector = document.querySelector("#video-size-selector");
|
||||
videoSizeSelector.addEventListener("change", function (event) { changeVideoSizeSelection(event.target.id); }, false);
|
||||
|
||||
renderer.addEventListener("fullScreenChange", function (newState) {
|
||||
if (newState === false) {
|
||||
changeVideoSizeSelection();
|
||||
}
|
||||
});
|
||||
|
||||
changeVideoSizeSelection();
|
||||
};
|
||||
}
|
||||
|
||||
if (video.readyState < HTMLMediaElement.HAVE_METADATA) {
|
||||
video.addEventListener("loadedmetadata", function () {
|
||||
debug("Video metadata loaded.");
|
||||
videoMetadataLoaded = true;
|
||||
|
||||
document.querySelector("#video-resolution-label-width").appendChild(document.createTextNode(video.videoWidth));
|
||||
document.querySelector("#video-resolution-label-height").appendChild(document.createTextNode(video.videoHeight));
|
||||
|
||||
testVideoAndASSLoaded();
|
||||
}, false);
|
||||
}
|
||||
else {
|
||||
debug("Video metadata loaded.");
|
||||
videoMetadataLoaded = true;
|
||||
testVideoAndASSLoaded();
|
||||
}
|
||||
|
||||
var track = document.querySelector("#video > track[data-format='ass'], #video > track[data-format='srt']");
|
||||
var subsRequest = new XMLHttpRequest();
|
||||
subsRequest.open("GET", track.src || track.getAttribute("src"), true);
|
||||
subsRequest.addEventListener("readystatechange", function () {
|
||||
if (subsRequest.readyState === XMLHttpRequest.DONE) {
|
||||
debug("Script received.");
|
||||
|
||||
ass = libjass.ASS.fromString(subsRequest.responseText, libjass.Format[track.getAttribute("data-format").toUpperCase()]);
|
||||
if (libjass.debugMode) {
|
||||
window.ass = ass;
|
||||
}
|
||||
|
||||
document.querySelector("#script-resolution-label-width").appendChild(document.createTextNode(ass.properties.resolutionX));
|
||||
document.querySelector("#script-resolution-label-height").appendChild(document.createTextNode(ass.properties.resolutionY));
|
||||
|
||||
testVideoAndASSLoaded();
|
||||
}
|
||||
}, false);
|
||||
subsRequest.send(null);
|
||||
}, false);
|
||||
@@ -1,57 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
|
||||
<head>
|
||||
<title>>2012 >Streaman Animu</title>
|
||||
<link rel="stylesheet" href="libjass.css" />
|
||||
<link rel="stylesheet" href="index.css" />
|
||||
<link rel="stylesheet" href="fonts.css" id="font-map" />
|
||||
|
||||
<!-- Unminified file -->
|
||||
<script src="libjass.js" />
|
||||
|
||||
<!-- Minified file -->
|
||||
<!--
|
||||
<script src="libjass.min.js" />
|
||||
-->
|
||||
|
||||
<script src="index.js" />
|
||||
</head>
|
||||
<body>
|
||||
<h1>Foo</h1>
|
||||
<h2>Bar</h2>
|
||||
<video id="video" src="/video/gc-01.webm" controls="">
|
||||
<track src="/video/gc-01.ass" kind="metadata" data-format="ass" />
|
||||
</video>
|
||||
<form class="settings-form">
|
||||
<div>
|
||||
<button type="button" id="enable-disable-button">Turn subs <span id="enable-disable-subs-span" /></button>
|
||||
</div>
|
||||
<fieldset>
|
||||
<legend>Video size</legend>
|
||||
<div id="video-size-selector">
|
||||
<input type="radio" name="video-size" id="video-size-video-radio" checked="checked" /><label for="video-size-video-radio">Video resolution <span id="video-resolution-label-width" />x<span id="video-resolution-label-height" /></label>
|
||||
<input type="radio" name="video-size" id="video-size-script-radio" /><label for="video-size-script-radio">Script resolution <span id="script-resolution-label-width" />x<span id="script-resolution-label-height" /></label>
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
@@ -23,10 +23,6 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.libjass-wrapper.libjass-full-screen {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.libjass-subs {
|
||||
position: absolute;
|
||||
overflow: hidden;
|
||||
@@ -34,6 +30,8 @@
|
||||
|
||||
.libjass-subs, .libjass-subs * {
|
||||
pointer-events: none;
|
||||
-webkit-animation-fill-mode: both !important;
|
||||
animation-fill-mode: both !important;
|
||||
}
|
||||
|
||||
.libjass-subs.paused * {
|
||||
@@ -64,16 +62,28 @@
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.libjass-subs div {
|
||||
.libjass-subs .an1, .libjass-subs .an4, .libjass-subs .an7 {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.libjass-subs .an2, .libjass-subs .an5, .libjass-subs .an8 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.libjass-subs .an3, .libjass-subs .an6, .libjass-subs .an9 {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.libjass-subs {
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
/* Filter wrapper span */
|
||||
.libjass-subs div[data-dialogue-id] > span {
|
||||
-webkit-perspective-origin: center;
|
||||
-webkit-perspective: 200px;
|
||||
-webkit-perspective: 400px;
|
||||
perspective-origin: center;
|
||||
perspective: 200px;
|
||||
perspective: 400px;
|
||||
}
|
||||
|
||||
.libjass-font-measure {
|
||||
@@ -82,6 +92,7 @@
|
||||
border: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
.libjass-filters {
|
||||
@@ -1,17 +1,12 @@
|
||||
{
|
||||
"name": "libjass",
|
||||
"version": "0.6.0",
|
||||
"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": {
|
||||
"url": "https://github.com/Arnavion/libjass/issues"
|
||||
},
|
||||
"licenses": [{
|
||||
"type": "Apache 2.0",
|
||||
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
|
||||
}],
|
||||
"maintainers": [{
|
||||
"bugs": "https://github.com/Arnavion/libjass/issues",
|
||||
"license": "Apache-2.0",
|
||||
"contributors": [{
|
||||
"name": "Arnav Singh",
|
||||
"email": "arnavion@gmail.com"
|
||||
}],
|
||||
@@ -19,15 +14,26 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/Arnavion/libjass"
|
||||
},
|
||||
"main": "lib/libjass.js",
|
||||
"scripts": {
|
||||
"postinstall": "gulp clean && gulp --trace",
|
||||
"test": "gulp test"
|
||||
"prepublish": "node ./build.js clean default",
|
||||
"build": "tsc ./build/typescript/index.ts ./build/doc.ts ./build/node.d.ts ./build/typescript/typescript.d.ts ./node_modules/async-build/typings.d.ts -m commonjs -t es5 -noImplicitAny --moduleResolution classic",
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"gulp": "latest",
|
||||
"mocha": "1.18.x",
|
||||
"typescript": "0.9.7",
|
||||
"uglify-js": "2.x >=2.4.13",
|
||||
"vinyl": "latest"
|
||||
}
|
||||
"devDependencies": {
|
||||
"async": "1.x >=1.4",
|
||||
"async-build": "0.2.0",
|
||||
"firefox-profile": "0.3.x",
|
||||
"intern": "3.x >=3.0.1",
|
||||
"npm": "3.x",
|
||||
"pngjs": "2.2.0",
|
||||
"sax": "1.x",
|
||||
"typescript": "1.7.5",
|
||||
"uglify-js": "2.x >=2.4.24"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* 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 { 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";
|
||||
|
||||
declare const exports: any;
|
||||
|
||||
Object.defineProperties(exports, {
|
||||
debugMode: {
|
||||
get: () => settings.debugMode,
|
||||
set: settings.setDebugMode,
|
||||
},
|
||||
|
||||
verboseMode: {
|
||||
get: () => settings.verboseMode,
|
||||
set: settings.setVerboseMode,
|
||||
},
|
||||
Set: {
|
||||
get: () => set.Set,
|
||||
set: set.setImplementation,
|
||||
},
|
||||
Map: {
|
||||
get: () => map.Map,
|
||||
set: map.setImplementation,
|
||||
},
|
||||
Promise: {
|
||||
get: () => promise.Promise,
|
||||
set: promise.setImplementation,
|
||||
},
|
||||
});
|
||||
@@ -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";
|
||||
@@ -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 {
|
||||
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.<string>} formatSpecifier
|
||||
* @return {!TypedTemplate}
|
||||
*/
|
||||
export function parseLineIntoTypedTemplate(line: string, formatSpecifier: string[]): TypedTemplate {
|
||||
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<string, string>();
|
||||
formatSpecifier.forEach((formatKey, index) => {
|
||||
template.set(formatKey, value[index]);
|
||||
});
|
||||
|
||||
return { type: property.name, template };
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
/**
|
||||
* 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 { Style } from "../types/style";
|
||||
import { Dialogue } from "../types/dialogue";
|
||||
import { Attachment, AttachmentType } from "../types/attachment";
|
||||
import { Property, TypedTemplate } from "../types/misc";
|
||||
|
||||
import { Map } from "../utility/map";
|
||||
|
||||
import { Promise, 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<ASS> = new DeferredPromise<ASS>();
|
||||
private _deferred: DeferredPromise<ASS> = new DeferredPromise<ASS>();
|
||||
|
||||
private _shouldSwallowBom: boolean = true;
|
||||
private _currentSection: Section = Section.ScriptInfo;
|
||||
private _currentAttachment: Attachment = null;
|
||||
|
||||
constructor(private _stream: Stream) {
|
||||
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
|
||||
this._minimalDeferred.reject(reason);
|
||||
this._deferred.reject(reason);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {!Promise.<!libjass.ASS>} 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<ASS> {
|
||||
return this._minimalDeferred.promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {!Promise.<!libjass.ASS>} A promise that will be resolved when the entire stream has been parsed.
|
||||
*/
|
||||
get ass(): Promise<ASS> {
|
||||
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;
|
||||
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): 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 }`);
|
||||
}
|
||||
}
|
||||
|
||||
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<ASS> = new DeferredPromise<ASS>();
|
||||
|
||||
private _shouldSwallowBom: boolean = true;
|
||||
|
||||
private _currentDialogueNumber: string = null;
|
||||
private _currentDialogueStart: string = null;
|
||||
private _currentDialogueEnd: string = null;
|
||||
private _currentDialogueText: string = null;
|
||||
|
||||
constructor(private _stream: Stream) {
|
||||
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.<!libjass.ASS>} A promise that will be resolved when the entire stream has been parsed.
|
||||
*/
|
||||
get ass(): Promise<ASS> {
|
||||
return this._deferred.promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} line
|
||||
*/
|
||||
private _onNextLine(line: string): 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(/<b>/g, "{\\b1}").replace(/\{b\}/g, "{\\b1}")
|
||||
.replace(/<\/b>/g, "{\\b0}").replace(/\{\/b\}/g, "{\\b0}")
|
||||
.replace(/<i>/g, "{\\i1}").replace(/\{i\}/g, "{\\i1}")
|
||||
.replace(/<\/i>/g, "{\\i0}").replace(/\{\/i\}/g, "{\\i0}")
|
||||
.replace(/<u>/g, "{\\u1}").replace(/\{u\}/g, "{\\u1}")
|
||||
.replace(/<\/u>/g, "{\\u0}").replace(/\{\/u\}/g, "{\\u0}")
|
||||
.replace(
|
||||
/<font color="#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})">/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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
import { Promise, DeferredPromise } from "../utility/promise";
|
||||
|
||||
export interface ReadableStream {
|
||||
/**
|
||||
* @return {!ReadableStreamReader}
|
||||
*/
|
||||
getReader(): ReadableStreamReader;
|
||||
}
|
||||
|
||||
interface ReadableStreamReader {
|
||||
/**
|
||||
* @return {!Promise.<{ value?: Uint8Array, done: boolean }>}
|
||||
*/
|
||||
read(): Promise<{ value: Uint8Array; done: boolean; }>;
|
||||
}
|
||||
|
||||
export interface TextDecoder {
|
||||
/**
|
||||
* @param {!ArrayBuffer|!ArrayBufferView} input
|
||||
* @param {{ stream: boolean }} options
|
||||
* @return {string}
|
||||
*/
|
||||
decode(input: ArrayBuffer | ArrayBufferView, options: { stream: boolean }): string;
|
||||
}
|
||||
export interface TextDecoderConstructor {
|
||||
new (encoding: string, options: { ignoreBOM: boolean }): TextDecoder;
|
||||
|
||||
/**
|
||||
* @type {!TextDecoder}
|
||||
*/
|
||||
prototype: TextDecoder;
|
||||
}
|
||||
|
||||
declare const global: {
|
||||
/**
|
||||
* @type {!TextDecoderConstructor}
|
||||
*/
|
||||
TextDecoder?: TextDecoderConstructor;
|
||||
};
|
||||
|
||||
/**
|
||||
* An interface for a stream.
|
||||
*/
|
||||
export interface Stream {
|
||||
/**
|
||||
* @return {!Promise.<?string>} A promise that will be resolved with the next line, or null if the stream is exhausted.
|
||||
*/
|
||||
nextLine(): Promise<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.<?string>} A promise that will be resolved with the next line, or null if the string has been completely read.
|
||||
*/
|
||||
nextLine(): Promise<string> {
|
||||
let result: Promise<string> = null;
|
||||
|
||||
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<string>(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<string> = null;
|
||||
private _failedError: ErrorEvent = 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.<?string>} A promise that will be resolved with the next line, or null if the stream is exhausted.
|
||||
*/
|
||||
nextLine(): Promise<string> {
|
||||
if (this._pendingDeferred !== null) {
|
||||
throw new Error("XhrStream only supports one pending unfulfilled read at a time.");
|
||||
}
|
||||
|
||||
const deferred = this._pendingDeferred = new DeferredPromise<string>();
|
||||
|
||||
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) {
|
||||
if (this._failedError !== null) {
|
||||
this._pendingDeferred.reject(this._failedError);
|
||||
}
|
||||
|
||||
// No more data. This is the last line.
|
||||
else 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 {
|
||||
private _reader: ReadableStreamReader;
|
||||
private _decoder: TextDecoder;
|
||||
private _buffer: string = "";
|
||||
private _pendingDeferred: DeferredPromise<string> = null;
|
||||
|
||||
constructor(stream: ReadableStream, encoding: string) {
|
||||
this._reader = stream.getReader();
|
||||
this._decoder = new global.TextDecoder(encoding, { ignoreBOM: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {!Promise.<?string>} A promise that will be resolved with the next line, or null if the stream is exhausted.
|
||||
*/
|
||||
nextLine(): Promise<string> {
|
||||
if (this._pendingDeferred !== null) {
|
||||
throw new Error("BrowserReadableStream only supports one pending unfulfilled read at a time.");
|
||||
}
|
||||
|
||||
const deferred = this._pendingDeferred = new DeferredPromise<string>();
|
||||
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* 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<DataType, (proto: any, field: string) => void>();
|
||||
|
||||
@struct
|
||||
class 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;
|
||||
|
||||
/** @type {function(!{ dataView: DataView, position: number }): OffsetTable} */
|
||||
static read: (reader: DataReader) => OffsetTable;
|
||||
}
|
||||
|
||||
@struct
|
||||
class 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;
|
||||
|
||||
/** @type {function(!{ dataView: DataView, position: number }): TableRecord} */
|
||||
static read: (reader: DataReader) => TableRecord;
|
||||
}
|
||||
|
||||
@struct
|
||||
class NameTableHeader {
|
||||
/** @type {number} */ @field(DataType.Uint16) formatSelector: number;
|
||||
/** @type {number} */ @field(DataType.Uint16) count: number;
|
||||
/** @type {number} */ @field(DataType.Uint16) stringOffset: number;
|
||||
|
||||
/** @type {function(!{ dataView: DataView, position: number }): NameTableHeader} */
|
||||
static read: (reader: DataReader) => NameTableHeader;
|
||||
}
|
||||
|
||||
@struct
|
||||
class 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;
|
||||
|
||||
/** @type {function(!{ dataView: DataView, position: number }): NameRecord} */
|
||||
static read: (reader: DataReader) => NameRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all the font names from the given font attachment.
|
||||
*
|
||||
* @param {!libjass.Attachment} attachment
|
||||
* @return {!libjass.Set.<string>}
|
||||
*/
|
||||
export function getTtfNames(attachment: Attachment): Set<string> {
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
reader.position = nameTableRecord.offset;
|
||||
const nameTableHeader = NameTableHeader.read(reader);
|
||||
|
||||
const result = new Set<string>();
|
||||
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 = "";
|
||||
|
||||
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) {
|
||||
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<T>(clazz: { new (): T; read(reader: DataReader): T; }): { new (): T; read(reader: DataReader): T; } {
|
||||
const fields: StructMemberDefinition[] = (<any>clazz).__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<T>(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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 <video> element, consider using {@link libjass.renderers.VideoClock} that uses the video element as a driver.
|
||||
*
|
||||
* @param {function():number} getCurrentTime A callback that will be invoked to get the current time of the external driver.
|
||||
* @param {number} autoPauseAfter If two calls to getCurrentTime are more than autoPauseAfter milliseconds apart but return the same time, then the external driver will be
|
||||
* considered to have paused.
|
||||
*/
|
||||
export class AutoClock implements Clock {
|
||||
private _manualClock: ManualClock = new ManualClock();
|
||||
|
||||
private _nextAnimationFrameRequestId: number = null;
|
||||
|
||||
private _lastKnownExternalTime: number = null;
|
||||
private _lastKnownExternalTimeObtainedAt: number = null;
|
||||
|
||||
constructor(private _getCurrentTime: () => number, private _autoPauseAfter: number) { }
|
||||
|
||||
/**
|
||||
* Tells the clock to start generating ticks.
|
||||
*/
|
||||
play(): void {
|
||||
if (!this._manualClock.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._startTicking();
|
||||
|
||||
this._manualClock.play();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the clock to pause.
|
||||
*/
|
||||
pause(): void {
|
||||
if (!this._manualClock.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._nextAnimationFrameRequestId === null) {
|
||||
if (debugMode) {
|
||||
console.warn("AutoClock.pause: Abnormal state detected. AutoClock._nextAnimationFrameRequestId should not have been null.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this._stopTicking();
|
||||
|
||||
this._manualClock.pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells the clock that the external driver is seeking.
|
||||
*/
|
||||
seeking(): void {
|
||||
this._manualClock.seek(this._getCurrentTime());
|
||||
}
|
||||
|
||||
// Clock members
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
get currentTime(): number {
|
||||
return this._manualClock.currentTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
get enabled(): boolean {
|
||||
return this._manualClock.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
get paused(): boolean {
|
||||
return this._manualClock.paused;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the rate of the clock - how fast the clock ticks compared to real time.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get rate(): number {
|
||||
return this._manualClock.rate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the rate of the clock - how fast the clock ticks compared to real time.
|
||||
*
|
||||
* @param {number} rate The new rate of the clock.
|
||||
*/
|
||||
setRate(rate: number): void {
|
||||
this._manualClock.setRate(rate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the clock.
|
||||
*
|
||||
* @return {boolean} True if the clock is now enabled, false if it was already enabled.
|
||||
*/
|
||||
enable(): boolean {
|
||||
if (!this._manualClock.enable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._startTicking();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the clock.
|
||||
*
|
||||
* @return {boolean} True if the clock is now disabled, false if it was already disabled.
|
||||
*/
|
||||
disable(): boolean {
|
||||
if (!this._manualClock.disable()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._stopTicking();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle the clock.
|
||||
*/
|
||||
toggle(): void {
|
||||
if (this._manualClock.enabled) {
|
||||
this.disable();
|
||||
}
|
||||
else {
|
||||
this.enable();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable or disable the clock.
|
||||
*
|
||||
* @param {boolean} enabled If true, the clock is enabled, otherwise it's disabled.
|
||||
* @return {boolean} True if the clock is now in the given state, false if it was already in that state.
|
||||
*/
|
||||
setEnabled(enabled: boolean): boolean {
|
||||
if (enabled) {
|
||||
return this.enable();
|
||||
}
|
||||
else {
|
||||
return this.disable();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} type
|
||||
* @param {!Function} listener
|
||||
*/
|
||||
addEventListener(type: ClockEvent, listener: Function): void {
|
||||
this._manualClock.addEventListener(type, listener);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {number} timeStamp
|
||||
*/
|
||||
private _onTimerTick(timeStamp: number): void {
|
||||
if (!this._manualClock.enabled) {
|
||||
if (debugMode) {
|
||||
console.warn("AutoClock._onTimerTick: Called when disabled.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const currentTime = this._manualClock.currentTime;
|
||||
const currentExternalTime = this._getCurrentTime();
|
||||
|
||||
if (!this._manualClock.paused) {
|
||||
if (this._lastKnownExternalTime !== null && currentExternalTime === this._lastKnownExternalTime) {
|
||||
if (timeStamp - this._lastKnownExternalTimeObtainedAt > this._autoPauseAfter) {
|
||||
this._lastKnownExternalTimeObtainedAt = null;
|
||||
this._manualClock.pause();
|
||||
}
|
||||
else {
|
||||
this._manualClock.tick((timeStamp - this._lastKnownExternalTimeObtainedAt) / 1000 * this._manualClock.rate + this._lastKnownExternalTime);
|
||||
}
|
||||
}
|
||||
else {
|
||||
this._lastKnownExternalTime = currentExternalTime;
|
||||
this._lastKnownExternalTimeObtainedAt = timeStamp;
|
||||
this._manualClock.tick(currentExternalTime);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (currentTime !== currentExternalTime) {
|
||||
this._lastKnownExternalTime = currentExternalTime;
|
||||
this._lastKnownExternalTimeObtainedAt = timeStamp;
|
||||
this._manualClock.tick(currentExternalTime);
|
||||
}
|
||||
}
|
||||
|
||||
this._nextAnimationFrameRequestId = requestAnimationFrame(timeStamp => this._onTimerTick(timeStamp));
|
||||
}
|
||||
|
||||
private _startTicking(): void {
|
||||
if (this._nextAnimationFrameRequestId === null) {
|
||||
this._nextAnimationFrameRequestId = requestAnimationFrame(timeStamp => this._onTimerTick(timeStamp));
|
||||
}
|
||||
}
|
||||
|
||||
private _stopTicking(): void {
|
||||
if (this._nextAnimationFrameRequestId !== null) {
|
||||
cancelAnimationFrame(this._nextAnimationFrameRequestId);
|
||||
this._nextAnimationFrameRequestId = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 { Map } from "../../utility/map";
|
||||
|
||||
/**
|
||||
* A mixin class that represents an event source.
|
||||
*/
|
||||
export class EventSource<T> {
|
||||
/**
|
||||
* A map from event type to an array of all the listeners registered for that event type.
|
||||
*
|
||||
* @type {!Map.<T, !Array.<Function>>}
|
||||
*/
|
||||
_eventListeners: Map<T, Function[]>;
|
||||
|
||||
/**
|
||||
* Add a listener for the given event.
|
||||
*
|
||||
* @param {!T} type The type of event to attach the listener for
|
||||
* @param {!Function} listener The listener
|
||||
*/
|
||||
addEventListener(type: T, listener: Function): void {
|
||||
let listeners = this._eventListeners.get(type);
|
||||
|
||||
if (listeners === undefined) {
|
||||
this._eventListeners.set(type, listeners = []);
|
||||
}
|
||||
|
||||
listeners.push(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls all listeners registered for the given event type.
|
||||
*
|
||||
* @param {!T} type The type of event to dispatch
|
||||
* @param {!Array.<*>} args Arguments for the listeners of the event
|
||||
*/
|
||||
_dispatchEvent(type: T, args: Object[]): void {
|
||||
const listeners = this._eventListeners.get(type);
|
||||
if (listeners !== undefined) {
|
||||
for (const listener of listeners) {
|
||||
listener.apply(this, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of clock event.
|
||||
*/
|
||||
export enum ClockEvent {
|
||||
Play,
|
||||
Tick,
|
||||
Pause,
|
||||
Stop,
|
||||
RateChange,
|
||||
}
|
||||
|
||||
/**
|
||||
* The clock interface. A clock is used by a renderer as a source of {@link libjass.renderers.ClockEvent}s.
|
||||
*/
|
||||
export interface Clock {
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
currentTime: number;
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
enabled: boolean;
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
paused: boolean;
|
||||
|
||||
/**
|
||||
* Gets the rate of the clock - how fast the clock ticks compared to real time.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
rate: number;
|
||||
|
||||
/**
|
||||
* Enable the clock.
|
||||
*
|
||||
* @return {boolean} True if the clock is now enabled, false if it was already enabled.
|
||||
*/
|
||||
enable(): boolean;
|
||||
|
||||
/**
|
||||
* Disable the clock.
|
||||
*
|
||||
* @return {boolean} True if the clock is now disabled, false if it was already disabled.
|
||||
*/
|
||||
disable(): boolean;
|
||||
|
||||
/**
|
||||
* Toggle the clock.
|
||||
*/
|
||||
toggle(): void;
|
||||
|
||||
/**
|
||||
* Enable or disable the clock.
|
||||
*
|
||||
* @param {boolean} enabled If true, the clock is enabled, otherwise it's disabled.
|
||||
* @return {boolean} True if the clock is now in the given state, false if it was already in that state.
|
||||
*/
|
||||
setEnabled(enabled: boolean): boolean;
|
||||
|
||||
// EventSource members
|
||||
|
||||
/**
|
||||
* @param {number} type
|
||||
* @param {!Function} listener
|
||||
*/
|
||||
addEventListener(type: ClockEvent, listener: Function): void;
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
/**
|
||||
* 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 { mixin } from "../../utility/mixin";
|
||||
import { Map } from "../../utility/map";
|
||||
|
||||
import { Clock, ClockEvent, EventSource } from "./base";
|
||||
|
||||
/**
|
||||
* An implementation of {@link libjass.renderers.Clock} that allows user script to manually trigger {@link libjass.renderers.ClockEvent}s.
|
||||
*/
|
||||
export class ManualClock implements Clock, EventSource<ClockEvent> {
|
||||
private _currentTime: number = -1;
|
||||
private _rate: number = 1;
|
||||
|
||||
private _enabled: boolean = true;
|
||||
private _paused: boolean = true;
|
||||
|
||||
/**
|
||||
* Trigger a {@link libjass.renderers.ClockEvent.Play}
|
||||
*/
|
||||
play(): void {
|
||||
if (!this._enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this._paused) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._paused = false;
|
||||
|
||||
this._dispatchEvent(ClockEvent.Play, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a {@link libjass.renderers.ClockEvent.Tick} with the given time.
|
||||
*
|
||||
* @param {number} currentTime
|
||||
*/
|
||||
tick(currentTime: number): void {
|
||||
if (!this._enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._currentTime === currentTime) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.play();
|
||||
|
||||
this._currentTime = currentTime;
|
||||
this._dispatchEvent(ClockEvent.Tick, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Seek to the given time. Unlike {@link libjass.renderers.ManualClock.tick} this is used to represent a discontinuous jump, such as the user seeking
|
||||
* via the video element's position bar.
|
||||
*
|
||||
* @param {number} time
|
||||
*/
|
||||
seek(time: number): void {
|
||||
if (!this._enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.pause();
|
||||
|
||||
if (this._currentTime === time) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.stop();
|
||||
|
||||
this.tick(time);
|
||||
|
||||
this.pause();
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a {@link libjass.renderers.ClockEvent.Pause}
|
||||
*/
|
||||
pause(): void {
|
||||
if (!this._enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._paused) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._paused = true;
|
||||
|
||||
this._dispatchEvent(ClockEvent.Pause, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger a {@link libjass.renderers.ClockEvent.Stop}
|
||||
*/
|
||||
stop(): void {
|
||||
this._dispatchEvent(ClockEvent.Stop, []);
|
||||
}
|
||||
|
||||
// Clock members
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
get currentTime(): number {
|
||||
return this._currentTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
get enabled(): boolean {
|
||||
return this._enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
get paused(): boolean {
|
||||
return this._paused;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the rate of the clock - how fast the clock ticks compared to real time.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get rate(): number {
|
||||
return this._rate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the rate of the clock - how fast the clock ticks compared to real time.
|
||||
*
|
||||
* @param {number} rate The new rate of the clock.
|
||||
*/
|
||||
setRate(rate: number): void {
|
||||
if (this._rate === rate) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._rate = rate;
|
||||
|
||||
this._dispatchEvent(ClockEvent.RateChange, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the clock.
|
||||
*
|
||||
* @return {boolean} True if the clock is now enabled, false if it was already enabled.
|
||||
*/
|
||||
enable(): boolean {
|
||||
if (this._enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this._enabled = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the clock.
|
||||
*
|
||||
* @return {boolean} True if the clock is now disabled, false if it was already disabled.
|
||||
*/
|
||||
disable(): boolean {
|
||||
if (!this._enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.pause();
|
||||
|
||||
this.stop();
|
||||
|
||||
this._enabled = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle the clock.
|
||||
*/
|
||||
toggle(): void {
|
||||
if (this._enabled) {
|
||||
this.disable();
|
||||
}
|
||||
else {
|
||||
this.enable();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable or disable the clock.
|
||||
*
|
||||
* @param {boolean} enabled If true, the clock is enabled, otherwise it's disabled.
|
||||
* @return {boolean} True if the clock is now in the given state, false if it was already in that state.
|
||||
*/
|
||||
setEnabled(enabled: boolean): boolean {
|
||||
if (enabled) {
|
||||
return this.enable();
|
||||
}
|
||||
else {
|
||||
return this.disable();
|
||||
}
|
||||
}
|
||||
|
||||
// EventSource members
|
||||
|
||||
/**
|
||||
* @type {!Map.<T, !Array.<Function>>}
|
||||
*/
|
||||
_eventListeners: Map<ClockEvent, Function[]> = new Map<ClockEvent, Function[]>();
|
||||
|
||||
/**
|
||||
* @type {function(number, !Function)}
|
||||
*/
|
||||
addEventListener: (type: ClockEvent, listener: Function) => void;
|
||||
|
||||
/**
|
||||
* @type {function(number, Array.<*>)}
|
||||
*/
|
||||
_dispatchEvent: (type: ClockEvent, args: Object[]) => void;
|
||||
}
|
||||
mixin(ManualClock, [EventSource]);
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* 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 { AutoClock } from "./auto";
|
||||
import { Clock, ClockEvent } from "./base";
|
||||
|
||||
/**
|
||||
* An implementation of libjass.renderers.Clock that generates {@link libjass.renderers.ClockEvent}s according to the state of a <video> element.
|
||||
*
|
||||
* @param {!HTMLVideoElement} video
|
||||
*/
|
||||
export class VideoClock implements Clock {
|
||||
private _autoClock: AutoClock;
|
||||
|
||||
constructor(video: HTMLVideoElement) {
|
||||
this._autoClock = new AutoClock(() => video.currentTime, 100);
|
||||
video.addEventListener("playing", () => this._autoClock.play(), false);
|
||||
video.addEventListener("pause", () => this._autoClock.pause(), false);
|
||||
video.addEventListener("seeking", () => this._autoClock.seeking(), false);
|
||||
video.addEventListener("ratechange", () => this._autoClock.setRate(video.playbackRate), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
get currentTime(): number {
|
||||
return this._autoClock.currentTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
get enabled(): boolean {
|
||||
return this._autoClock.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
get paused(): boolean {
|
||||
return this._autoClock.paused;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the rate of the clock - how fast the clock ticks compared to real time.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get rate(): number {
|
||||
return this._autoClock.rate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable the clock.
|
||||
*
|
||||
* @return {boolean} True if the clock is now enabled, false if it was already enabled.
|
||||
*/
|
||||
enable(): boolean {
|
||||
return this._autoClock.enable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the clock.
|
||||
*
|
||||
* @return {boolean} True if the clock is now disabled, false if it was already disabled.
|
||||
*/
|
||||
disable(): boolean {
|
||||
return this._autoClock.disable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle the clock.
|
||||
*/
|
||||
toggle(): void {
|
||||
if (this._autoClock.enabled) {
|
||||
this.disable();
|
||||
}
|
||||
else {
|
||||
this.enable();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable or disable the clock.
|
||||
*
|
||||
* @param {boolean} enabled If true, the clock is enabled, otherwise it's disabled.
|
||||
* @return {boolean} True if the clock is now in the given state, false if it was already in that state.
|
||||
*/
|
||||
setEnabled(enabled: boolean): boolean {
|
||||
if (enabled) {
|
||||
return this.enable();
|
||||
}
|
||||
else {
|
||||
return this.disable();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} type
|
||||
* @param {!Function} listener
|
||||
*/
|
||||
addEventListener(type: ClockEvent, listener: Function): void {
|
||||
this._autoClock.addEventListener(type, listener);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* 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 { VideoClock } from "./clocks/video";
|
||||
import { RendererSettings } from "./settings";
|
||||
import { WebRenderer } from "./web/renderer";
|
||||
|
||||
import { ASS } from "../types/ass";
|
||||
|
||||
/**
|
||||
* A default renderer implementation.
|
||||
*
|
||||
* @param {!HTMLVideoElement} video
|
||||
* @param {!libjass.ASS} ass
|
||||
* @param {libjass.renderers.RendererSettings} settings
|
||||
*/
|
||||
export class DefaultRenderer extends WebRenderer {
|
||||
constructor(private _video: HTMLVideoElement, ass: ASS, settings?: RendererSettings) {
|
||||
super(ass, new VideoClock(_video), document.createElement("div"), settings);
|
||||
|
||||
this._video.parentElement.replaceChild(this.libjassSubsWrapper, this._video);
|
||||
this.libjassSubsWrapper.insertBefore(this._video, this.libjassSubsWrapper.firstElementChild);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resize the subtitles to the dimensions of the video element.
|
||||
*
|
||||
* This method accounts for letterboxing if the video element's size is not the same ratio as the video resolution.
|
||||
*/
|
||||
resize(): void {
|
||||
// Handle letterboxing around the video. If the width or height are greater than the video can be, then consider that dead space.
|
||||
|
||||
const videoWidth = this._video.videoWidth;
|
||||
const videoHeight = this._video.videoHeight;
|
||||
const videoOffsetWidth = this._video.offsetWidth;
|
||||
const videoOffsetHeight = this._video.offsetHeight;
|
||||
|
||||
const ratio = Math.min(videoOffsetWidth / videoWidth, videoOffsetHeight / videoHeight);
|
||||
const subsWrapperWidth = videoWidth * ratio;
|
||||
const subsWrapperHeight = videoHeight * ratio;
|
||||
const subsWrapperLeft = (videoOffsetWidth - subsWrapperWidth) / 2;
|
||||
const subsWrapperTop = (videoOffsetHeight - subsWrapperHeight) / 2;
|
||||
|
||||
super.resize(subsWrapperWidth, subsWrapperHeight, subsWrapperLeft, subsWrapperTop);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
resizeVideo(): void {
|
||||
console.warn("`DefaultRenderer.resizeVideo(width, height)` has been deprecated. Use `DefaultRenderer.resize()` instead.");
|
||||
this.resize();
|
||||
}
|
||||
|
||||
protected _ready(): void {
|
||||
this.resize();
|
||||
|
||||
super._ready();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* 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 { Clock, ClockEvent, EventSource } from "./clocks/base";
|
||||
export { AutoClock } from "./clocks/auto";
|
||||
export { ManualClock } from "./clocks/manual";
|
||||
export { VideoClock } from "./clocks/video";
|
||||
|
||||
export { DefaultRenderer } from "./default";
|
||||
export { NullRenderer } from "./null";
|
||||
export { WebRenderer } from "./web/renderer";
|
||||
|
||||
export { RendererSettings, makeFontMapFromStyleElement } from "./settings";
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* 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 { Clock, ClockEvent } from "./clocks/base";
|
||||
|
||||
import { RendererSettings, toRendererSettings } from "./settings";
|
||||
|
||||
import { verboseMode } from "../settings";
|
||||
|
||||
import { ASS } from "../types/ass";
|
||||
import { Dialogue } from "../types/dialogue";
|
||||
|
||||
/**
|
||||
* A renderer implementation that doesn't output anything.
|
||||
*
|
||||
* @param {!libjass.ASS} ass
|
||||
* @param {!libjass.renderers.Clock} clock
|
||||
* @param {libjass.renderers.RendererSettings} settings
|
||||
*/
|
||||
export class NullRenderer {
|
||||
private static _lastRendererId = -1;
|
||||
|
||||
private _id: number;
|
||||
|
||||
private _settings: RendererSettings;
|
||||
|
||||
constructor(private _ass: ASS, private _clock: Clock, settings?: RendererSettings) {
|
||||
this._id = ++NullRenderer._lastRendererId;
|
||||
|
||||
this._settings = toRendererSettings(settings);
|
||||
|
||||
this._clock.addEventListener(ClockEvent.Play, () => this._onClockPlay());
|
||||
this._clock.addEventListener(ClockEvent.Tick, () => this._onClockTick());
|
||||
this._clock.addEventListener(ClockEvent.Pause, () => this._onClockPause());
|
||||
this._clock.addEventListener(ClockEvent.Stop, () => this._onClockStop());
|
||||
this._clock.addEventListener(ClockEvent.RateChange, () => this._onClockRateChange());
|
||||
}
|
||||
|
||||
/**
|
||||
* The unique ID of this renderer. Auto-generated.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get id(): number {
|
||||
return this._id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {!libjass.ASS}
|
||||
*/
|
||||
get ass(): ASS {
|
||||
return this._ass;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {!libjass.renderers.Clock}
|
||||
*/
|
||||
get clock(): Clock {
|
||||
return this._clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {!libjass.renderers.RendererSettings}
|
||||
*/
|
||||
get settings(): RendererSettings {
|
||||
return this._settings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-render a dialogue. This is a no-op for this type.
|
||||
*
|
||||
* @param {!libjass.Dialogue} dialogue
|
||||
*/
|
||||
preRender(dialogue: Dialogue): void { }
|
||||
|
||||
/**
|
||||
* Draw a dialogue. This is a no-op for this type.
|
||||
*
|
||||
* @param {!libjass.Dialogue} dialogue
|
||||
*/
|
||||
draw(dialogue: Dialogue): void { }
|
||||
|
||||
/**
|
||||
* Enable the renderer.
|
||||
*
|
||||
* @return {boolean} True if the renderer is now enabled, false if it was already enabled.
|
||||
*/
|
||||
enable(): boolean {
|
||||
return this._clock.enable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable the renderer.
|
||||
*
|
||||
* @return {boolean} True if the renderer is now disabled, false if it was already disabled.
|
||||
*/
|
||||
disable(): boolean {
|
||||
return this._clock.disable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle the renderer.
|
||||
*/
|
||||
toggle(): void {
|
||||
this._clock.toggle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable or disable the renderer.
|
||||
*
|
||||
* @param {boolean} enabled If true, the renderer is enabled, otherwise it's disabled.
|
||||
* @return {boolean} True if the renderer is now in the given state, false if it was already in that state.
|
||||
*/
|
||||
setEnabled(enabled: boolean): boolean {
|
||||
return this._clock.setEnabled(enabled);
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
get enabled(): boolean {
|
||||
return this._clock.enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs when the clock is enabled, or starts playing, or is resumed from pause.
|
||||
*/
|
||||
protected _onClockPlay(): void {
|
||||
if (verboseMode) {
|
||||
console.log("NullRenderer._onClockPlay");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs when the clock's current time changed. This might be a result of either regular playback or seeking.
|
||||
*/
|
||||
protected _onClockTick(): void {
|
||||
const currentTime = this._clock.currentTime;
|
||||
|
||||
if (verboseMode) {
|
||||
console.log(`NullRenderer._onClockTick: currentTime = ${ currentTime }`);
|
||||
}
|
||||
|
||||
for (const dialogue of this._ass.dialogues) {
|
||||
if (dialogue.end > currentTime) {
|
||||
if (dialogue.start <= currentTime) {
|
||||
// This dialogue is visible right now. Draw it.
|
||||
this.draw(dialogue);
|
||||
}
|
||||
else if (dialogue.start <= (currentTime + this._settings.preRenderTime)) {
|
||||
// This dialogue will be visible soon. Pre-render it.
|
||||
this.preRender(dialogue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs when the clock is paused.
|
||||
*/
|
||||
protected _onClockPause(): void {
|
||||
if (verboseMode) {
|
||||
console.log("NullRenderer._onClockPause");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs when the clock is disabled.
|
||||
*/
|
||||
protected _onClockStop(): void {
|
||||
if (verboseMode) {
|
||||
console.log("NullRenderer._onClockStop");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs when the clock changes its rate.
|
||||
*/
|
||||
protected _onClockRateChange(): void {
|
||||
if (verboseMode) {
|
||||
console.log("NullRenderer._onClockRateChange");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* 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 { Map } from "../utility/map";
|
||||
|
||||
/**
|
||||
* Settings for the renderer.
|
||||
*/
|
||||
export interface RendererSettings {
|
||||
/**
|
||||
* A map of font name to one or more URLs of that font. If provided, the fonts in this map are pre-loaded by the WebRenderer when it's created.
|
||||
*
|
||||
* The key of each entry of the map is the font name used in the ASS script. There are three choices for the value:
|
||||
*
|
||||
* - A single string that you would use for the src attribute of a @font-face rule. Eg: `'url("/fonts.foo.ttf"), url("/fonts/foo-fallback.ttf"), local("Arial.ttf")'`
|
||||
*
|
||||
* - An array of the individual sources that you would use for the src attribute of a @font-face rule. Eg: `['url("/fonts.foo.ttf")', 'url("/fonts/foo-fallback.ttf")', 'local("Arial")']`
|
||||
*
|
||||
* - An array of URLs. Eg: `["/fonts.foo.ttf", "/fonts/foo-fallback.ttf"]`
|
||||
*
|
||||
* Only the first and second forms allow you to use local fonts. The third form only allows you to use remote fonts.
|
||||
*
|
||||
* If you have a <style> or <link> element on the page containing @font-face rules, you can use the {@link libjass.renderers.makeFontMapFromStyleElement}
|
||||
* convenience method to create a font map.
|
||||
*
|
||||
* Defaults to null.
|
||||
*
|
||||
* @type {!Map.<string, (string|!Array.<string>)>}
|
||||
*/
|
||||
fontMap: Map<string, string | string[]>;
|
||||
|
||||
/**
|
||||
* Subtitles will be pre-rendered for this amount of time (seconds).
|
||||
*
|
||||
* Defaults to 5.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
preRenderTime: number;
|
||||
|
||||
/**
|
||||
* Subtitle outlines will be rendered in full detail. When false, the value of blur is used to draw less outlines for better performance and (hopefully) similar output.
|
||||
*
|
||||
* Defaults to false.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
preciseOutlines: boolean;
|
||||
|
||||
/**
|
||||
* Outlines and blur are implemented using SVG filters by default. When false, they will be rendered using alternative means.
|
||||
*
|
||||
* IE 11 and below do not support SVG filters on HTML elements so this should be set to false there. See http://caniuse.com/svg-html for details.
|
||||
*
|
||||
* Defaults to true.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
enableSvg: boolean;
|
||||
|
||||
/**
|
||||
* Comma-separated list of fonts to be used when font specified in ASS Styles not loaded.
|
||||
*
|
||||
* The value should be a valid CSS font-family property (i.e. comma-separated and individual names in quotes if necessary). Use empty string to disable fallback.
|
||||
*
|
||||
* Defaults to 'Arial, Helvetica, sans-serif, "Segoe UI Symbol"'.
|
||||
*
|
||||
* @type {string}
|
||||
*/
|
||||
fallbackFonts: string;
|
||||
|
||||
/**
|
||||
* If true, attached TTF fonts in the ASS script will be used. The font is loaded as a data: URI. Requires ES6 typed arrays (ArrayBuffer, DataView, Uint8Array, etc).
|
||||
*
|
||||
* The font is naively parsed to extract the strings that will be used as the font family. Do not use this option with untrusted fonts or scripts.
|
||||
*
|
||||
* Defaults to false.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
useAttachedFonts: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an arbitrary object into a {@link libjass.renderers.RendererSettings} object.
|
||||
*
|
||||
* @param {*} object
|
||||
* @return {!libjass.renderers.RendererSettings}
|
||||
*/
|
||||
export function toRendererSettings(object?: any): RendererSettings {
|
||||
if (object === undefined || object === null) {
|
||||
object = {};
|
||||
}
|
||||
|
||||
const {
|
||||
fontMap = null,
|
||||
preRenderTime = 5,
|
||||
preciseOutlines = false,
|
||||
enableSvg = true,
|
||||
fallbackFonts = 'Arial, Helvetica, sans-serif, "Segoe UI Symbol"',
|
||||
useAttachedFonts = false
|
||||
} = <RendererSettings>object;
|
||||
|
||||
return {
|
||||
fontMap,
|
||||
preRenderTime,
|
||||
preciseOutlines,
|
||||
enableSvg,
|
||||
fallbackFonts,
|
||||
useAttachedFonts,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A convenience method to create a font map from a <style> or <link> element that contains @font-face rules. There should be one @font-face rule for each font name, mapping to a font file URL.
|
||||
*
|
||||
* For example:
|
||||
*
|
||||
* @font-face {
|
||||
* font-family: "Helvetica";
|
||||
* src: url("/fonts/helvetica.ttf"), local("Arial");
|
||||
* }
|
||||
*
|
||||
* @param {!LinkStyle} linkStyle
|
||||
* @return {!Map.<string, string>}
|
||||
*/
|
||||
export function makeFontMapFromStyleElement(linkStyle: LinkStyle): Map<string, string> {
|
||||
const fontMap = new Map<string, string>();
|
||||
|
||||
const styleSheet = <CSSStyleSheet>linkStyle.sheet;
|
||||
for (let i = 0; i < styleSheet.cssRules.length; i++) {
|
||||
const rule = styleSheet.cssRules[i];
|
||||
|
||||
if (isFontFaceRule(rule)) {
|
||||
const name = rule.style.getPropertyValue("font-family").match(/^["']?(.*?)["']?$/)[1];
|
||||
|
||||
let src = rule.style.getPropertyValue("src");
|
||||
if (!src) {
|
||||
src = rule.cssText.split("\n")
|
||||
.map(line => line.match(/src:\s*([^;]+?)\s*;/))
|
||||
.filter(matches => matches !== null)
|
||||
.map(matches => matches[1])[0];
|
||||
}
|
||||
|
||||
fontMap.set(name, src);
|
||||
}
|
||||
}
|
||||
|
||||
return fontMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!CSSRule} rule
|
||||
* @return {boolean}
|
||||
*/
|
||||
function isFontFaceRule(rule: CSSRule): rule is CSSFontFaceRule {
|
||||
return rule.type === CSSRule.FONT_FACE_RULE;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* 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 { Keyframe } from "./keyframe";
|
||||
|
||||
import { NullRenderer } from "../null";
|
||||
|
||||
import { Map } from "../../utility/map";
|
||||
|
||||
/**
|
||||
* This class represents a collection of animations. Each animation contains one or more keyframes.
|
||||
* The collection can then be converted to a CSS3 representation.
|
||||
*
|
||||
* @param {!libjass.renderers.NullRenderer} renderer The renderer that this collection is associated with
|
||||
* @param {!HTMLStyleElement} style A <style> element to insert the animation rules into
|
||||
*/
|
||||
export class AnimationCollection {
|
||||
private static _nextId: number = 0;
|
||||
|
||||
private _id: string;
|
||||
private _rate: number;
|
||||
|
||||
private _animationStyle: string = "";
|
||||
private _animationDelays: Map<string, number> = new Map<string, number>();
|
||||
private _numAnimations: number = 0;
|
||||
|
||||
constructor(renderer: NullRenderer, private _style: HTMLStyleElement) {
|
||||
this._id = `${ renderer.id }-${ AnimationCollection._nextId++ }`;
|
||||
this._rate = renderer.clock.rate;
|
||||
}
|
||||
|
||||
/**
|
||||
* This string should be set as the "animation" CSS property of the target element.
|
||||
*
|
||||
* @type {string}
|
||||
*/
|
||||
get animationStyle(): string {
|
||||
return this._animationStyle;
|
||||
}
|
||||
|
||||
/**
|
||||
* This array should be used to set the "animation-delay" CSS property of the target element.
|
||||
*
|
||||
* @type {!Array.<number>}
|
||||
*/
|
||||
get animationDelays(): Map<string, number> {
|
||||
return this._animationDelays;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an animation to this collection. The given keyframes together make one animation.
|
||||
*
|
||||
* @param {string} timingFunction One of the acceptable values for the "animation-timing-function" CSS property
|
||||
* @param {!Array.<!libjass.renderers.Keyframe>} keyframes
|
||||
*/
|
||||
add(timingFunction: string, keyframes: Keyframe[]): void {
|
||||
let start: number = null;
|
||||
let end: number = null;
|
||||
|
||||
for (const keyframe of keyframes) {
|
||||
if (start === null) {
|
||||
start = keyframe.time;
|
||||
}
|
||||
|
||||
end = keyframe.time;
|
||||
}
|
||||
|
||||
let ruleCssText = "";
|
||||
|
||||
for (const keyframe of keyframes) {
|
||||
ruleCssText +=
|
||||
` ${ (100 * ((end - start === 0) ? 1 : ((keyframe.time - start) / (end - start)))).toFixed(3) }% {
|
||||
`;
|
||||
|
||||
keyframe.properties.forEach((value, name) => {
|
||||
ruleCssText +=
|
||||
` ${ name }: ${ value };
|
||||
`;
|
||||
});
|
||||
|
||||
ruleCssText +=
|
||||
` }
|
||||
`;
|
||||
}
|
||||
|
||||
const animationName = `animation-${ this._id }-${ this._numAnimations++ }`;
|
||||
|
||||
this._style.appendChild(document.createTextNode(
|
||||
`@-webkit-keyframes ${ animationName } {
|
||||
${ ruleCssText }
|
||||
}`));
|
||||
|
||||
this._style.appendChild(document.createTextNode(
|
||||
`@keyframes ${ animationName } {
|
||||
${ ruleCssText }
|
||||
}`));
|
||||
|
||||
if (this._animationStyle !== "") {
|
||||
this._animationStyle += ",";
|
||||
}
|
||||
|
||||
this._animationStyle += `${ animationName } ${ ((end - start) / this._rate).toFixed(3) }s ${ timingFunction }`;
|
||||
this._animationDelays.set(animationName, start);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* 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";
|
||||
|
||||
/**
|
||||
* This class represents an ASS drawing - a set of drawing instructions between {\p} tags.
|
||||
*
|
||||
* @param {number} outputScaleX
|
||||
* @param {number} outputScaleY
|
||||
*/
|
||||
export class DrawingStyles {
|
||||
private _scale: number = 1;
|
||||
private _baselineOffset: number = 0;
|
||||
|
||||
constructor(private _outputScaleX: number, private _outputScaleY: number) { }
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
set scale(value: number) {
|
||||
this._scale = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
set baselineOffset(value: number) {
|
||||
this._baselineOffset = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts this drawing to an <svg> element.
|
||||
*
|
||||
* @param {!libjass.parts.DrawingInstructions} drawingInstructions
|
||||
* @param {!libjass.parts.Color} fillColor
|
||||
* @return {!SVGSVGElement}
|
||||
*/
|
||||
toSVG(drawingInstructions: parts.DrawingInstructions, fillColor: parts.Color): SVGSVGElement {
|
||||
const scaleFactor = Math.pow(2, this._scale - 1);
|
||||
const scaleX = this._outputScaleX / scaleFactor;
|
||||
const scaleY = this._outputScaleY / scaleFactor;
|
||||
|
||||
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
|
||||
|
||||
let bboxWidth = 0;
|
||||
let bboxHeight = 0;
|
||||
|
||||
for (const instruction of drawingInstructions.instructions) {
|
||||
if (instruction instanceof parts.drawing.MoveInstruction) {
|
||||
path.pathSegList.appendItem(path.createSVGPathSegMovetoAbs(instruction.x, instruction.y + this._baselineOffset));
|
||||
bboxWidth = Math.max(bboxWidth, instruction.x);
|
||||
bboxHeight = Math.max(bboxHeight, instruction.y + this._baselineOffset);
|
||||
}
|
||||
else if (instruction instanceof parts.drawing.LineInstruction) {
|
||||
path.pathSegList.appendItem(path.createSVGPathSegLinetoAbs(instruction.x, instruction.y + this._baselineOffset));
|
||||
bboxWidth = Math.max(bboxWidth, instruction.x);
|
||||
bboxHeight = Math.max(bboxHeight, instruction.y + this._baselineOffset);
|
||||
}
|
||||
else if (instruction instanceof parts.drawing.CubicBezierCurveInstruction) {
|
||||
path.pathSegList.appendItem(path.createSVGPathSegCurvetoCubicAbs(instruction.x3, instruction.y3 + this._baselineOffset, instruction.x1, instruction.y1 + this._baselineOffset, instruction.x2, instruction.y2 + this._baselineOffset));
|
||||
bboxWidth = Math.max(bboxWidth, instruction.x1, instruction.x2, instruction.x3);
|
||||
bboxHeight = Math.max(bboxHeight, instruction.y1 + this._baselineOffset, instruction.y2 + this._baselineOffset, instruction.y3 + this._baselineOffset);
|
||||
}
|
||||
}
|
||||
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("version", "1.1");
|
||||
svg.width.baseVal.valueAsString = `${ (bboxWidth * scaleX).toFixed(3) }px`;
|
||||
svg.height.baseVal.valueAsString = `${ (bboxHeight * scaleY).toFixed(3) }px`;
|
||||
|
||||
const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
|
||||
svg.appendChild(g);
|
||||
g.setAttribute("transform", `scale(${ scaleX.toFixed(3) } ${ scaleY.toFixed(3) })`);
|
||||
|
||||
g.appendChild(path);
|
||||
path.setAttribute("fill", fillColor.toString());
|
||||
|
||||
return svg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* 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 { Map } from "../../utility/map";
|
||||
import { Promise } from "../../utility/promise";
|
||||
|
||||
/**
|
||||
* @param {string} fontFamily
|
||||
* @param {number} fontSize
|
||||
* @param {string} fallbackFonts
|
||||
* @param {!HTMLDivElement} fontSizeElement
|
||||
*/
|
||||
function prepareFontSizeElement(fontFamily: string, fontSize: number, fallbackFonts: string, fontSizeElement: HTMLDivElement): void {
|
||||
let fonts = `"${ fontFamily }"`;
|
||||
if (fallbackFonts !== "") {
|
||||
fonts += `, ${ fallbackFonts }`;
|
||||
}
|
||||
|
||||
fontSizeElement.style.fontFamily = fonts;
|
||||
fontSizeElement.style.fontSize = `${ fontSize }px`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} fontFamily
|
||||
* @param {number} fontSize
|
||||
* @param {string} fallbackFonts
|
||||
* @param {!HTMLDivElement} fontSizeElement
|
||||
* @return {!Promise.<number>}
|
||||
*/
|
||||
function lineHeightForFontSize(fontFamily: string, fontSize: number, fallbackFonts: string, fontSizeElement: HTMLDivElement): Promise<number> {
|
||||
prepareFontSizeElement(fontFamily, fontSize, fallbackFonts, fontSizeElement);
|
||||
|
||||
return new Promise(resolve => setTimeout(() => resolve(fontSizeElement.offsetHeight), 1000));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} fontFamily
|
||||
* @param {number} fontSize
|
||||
* @param {string} fallbackFonts
|
||||
* @param {!HTMLDivElement} fontSizeElement
|
||||
* @return {number}
|
||||
*/
|
||||
function lineHeightForFontSizeSync(fontFamily: string, fontSize: number, fallbackFonts: string, fontSizeElement: HTMLDivElement): number {
|
||||
prepareFontSizeElement(fontFamily, fontSize, fallbackFonts, fontSizeElement);
|
||||
|
||||
return fontSizeElement.offsetHeight;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} lowerLineHeight
|
||||
* @param {number} upperLineHeight
|
||||
* @return {[number, number]}
|
||||
*/
|
||||
function fontMetricsFromLineHeights(lowerLineHeight: number, upperLineHeight: number): [number, number] {
|
||||
return [lowerLineHeight, (360 - 180) / (upperLineHeight - lowerLineHeight)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates font metrics for the given font family.
|
||||
*
|
||||
* @param {string} fontFamily
|
||||
* @param {string} fallbackFonts
|
||||
* @param {!HTMLDivElement} fontSizeElement
|
||||
* @return {!Promise.<number>}
|
||||
*/
|
||||
export function calculateFontMetrics(fontFamily: string, fallbackFonts: string, fontSizeElement: HTMLDivElement): Promise<[number, number]> {
|
||||
return lineHeightForFontSize(fontFamily, 180, fallbackFonts, fontSizeElement).then(lowerLineHeight =>
|
||||
lineHeightForFontSize(fontFamily, 360, fallbackFonts, fontSizeElement).then(upperLineHeight =>
|
||||
fontMetricsFromLineHeights(lowerLineHeight, upperLineHeight)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} lineHeight
|
||||
* @param {number} lowerLineHeight
|
||||
* @param {number} factor
|
||||
* @return {number}
|
||||
*/
|
||||
function fontSizeFromMetrics(lineHeight: number, lowerLineHeight: number, factor: number): number {
|
||||
return 180 + (lineHeight - lowerLineHeight) * factor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses linear interpolation to calculate the CSS font size that would give the specified line height for the specified font family.
|
||||
*
|
||||
* WARNING: If fontMetricsCache doesn't already contain a cached value for this font family, and it is not a font already installed on the user's device, then this function
|
||||
* may return wrong values. To avoid this, make sure to preload the font using the {@link libjass.renderers.RendererSettings.fontMap} property when constructing the renderer.
|
||||
*
|
||||
* @param {string} fontFamily
|
||||
* @param {number} lineHeight
|
||||
* @param {string} fallbackFonts
|
||||
* @param {!HTMLDivElement} fontSizeElement
|
||||
* @param {!Map.<string, [number, number]>} fontMetricsCache
|
||||
* @return {number}
|
||||
*/
|
||||
export function fontSizeForLineHeight(fontFamily: string, lineHeight: number, fallbackFonts: string, fontSizeElement: HTMLDivElement, fontMetricsCache: Map<string, [number, number]>): number {
|
||||
let existingMetrics = fontMetricsCache.get(fontFamily);
|
||||
if (existingMetrics === undefined) {
|
||||
const lowerLineHeight = lineHeightForFontSizeSync(fontFamily, 180, fallbackFonts, fontSizeElement);
|
||||
const upperLineHeight = lineHeightForFontSizeSync(fontFamily, 360, fallbackFonts, fontSizeElement);
|
||||
fontMetricsCache.set(fontFamily, existingMetrics = fontMetricsFromLineHeights(lowerLineHeight, upperLineHeight));
|
||||
}
|
||||
|
||||
const [lowerLineHeight, factor] = existingMetrics;
|
||||
return fontSizeFromMetrics(lineHeight, lowerLineHeight, factor);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* 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 { Map } from "../../utility/map";
|
||||
|
||||
/**
|
||||
* This class represents a single keyframe. It has a list of CSS properties (names and values) associated with a point in time. Multiple keyframes make up an animation.
|
||||
*
|
||||
* @param {number} time
|
||||
* @param {!Map.<string, string>} properties
|
||||
*/
|
||||
export class Keyframe {
|
||||
constructor(private _time: number, private _properties: Map<string, string>) { }
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
get time(): number {
|
||||
return this._time;
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {!Map.<string, string>}
|
||||
*/
|
||||
get properties(): Map<string, string> {
|
||||
return this._properties;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,983 @@
|
||||
/**
|
||||
* 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 { AnimationCollection } from "./animation-collection";
|
||||
|
||||
import { fontSizeForLineHeight } from "./font-size";
|
||||
|
||||
import { WebRenderer } from "./renderer";
|
||||
|
||||
import { RendererSettings } from "../settings";
|
||||
|
||||
import { Color } from "../../parts";
|
||||
|
||||
import { Style } from "../../types/style";
|
||||
import { Dialogue } from "../../types/dialogue";
|
||||
|
||||
import { Map } from "../../utility/map";
|
||||
|
||||
/**
|
||||
* This class represents the style attribute of a span.
|
||||
* As a Dialogue's div is rendered, individual parts are added to span's, and this class is used to maintain the style attribute of those.
|
||||
*
|
||||
* @param {!libjass.renderers.NullRenderer} renderer The renderer that this set of styles is associated with
|
||||
* @param {!libjass.Dialogue} dialogue The Dialogue that this set of styles is associated with
|
||||
* @param {number} scaleX The horizontal scaling of the subtitles
|
||||
* @param {number} scaleY The vertical scaling of the subtitles
|
||||
* @param {!libjass.renderers.RendererSettings} settings The renderer settings
|
||||
* @param {!HTMLDivElement} fontSizeElement A <div> element to measure font sizes with
|
||||
* @param {!SVGDefsElement} svgDefsElement An SVG <defs> element to append filter definitions to
|
||||
* @param {!Map<string, [number, number]>} fontMetricsCache Font metrics cache
|
||||
*/
|
||||
export class SpanStyles {
|
||||
private _id: string;
|
||||
private _defaultStyle: Style;
|
||||
|
||||
private _italic: boolean;
|
||||
private _bold: Object;
|
||||
private _underline: boolean;
|
||||
private _strikeThrough: boolean;
|
||||
|
||||
private _outlineWidth: number;
|
||||
private _outlineHeight: number;
|
||||
|
||||
private _shadowDepthX: number;
|
||||
private _shadowDepthY: number;
|
||||
|
||||
private _fontName: string;
|
||||
private _fontSize: number;
|
||||
|
||||
private _fontScaleX: number;
|
||||
private _fontScaleY: number;
|
||||
|
||||
private _letterSpacing: number;
|
||||
|
||||
private _rotationX: number;
|
||||
private _rotationY: number;
|
||||
private _rotationZ: number;
|
||||
|
||||
private _skewX: number;
|
||||
private _skewY: number;
|
||||
|
||||
private _primaryColor: Color;
|
||||
private _secondaryColor: Color;
|
||||
private _outlineColor: Color;
|
||||
private _shadowColor: Color;
|
||||
|
||||
private _primaryAlpha: number;
|
||||
private _secondaryAlpha: number;
|
||||
private _outlineAlpha: number;
|
||||
private _shadowAlpha: number;
|
||||
|
||||
private _blur: number;
|
||||
private _gaussianBlur: number;
|
||||
|
||||
private _nextFilterId = 0;
|
||||
|
||||
constructor(renderer: WebRenderer, dialogue: Dialogue, private _scaleX: number, private _scaleY: number, private _settings: RendererSettings, private _fontSizeElement: HTMLDivElement, private _svgDefsElement: SVGDefsElement, private _fontMetricsCache: Map<string, [number, number]>) {
|
||||
this._id = `${ renderer.id }-${ dialogue.id }`;
|
||||
this._defaultStyle = dialogue.style;
|
||||
|
||||
this.reset(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the styles to the defaults provided by the argument.
|
||||
*
|
||||
* @param {libjass.Style} newStyle The new defaults to reset the style to. If null, the styles are reset to the default style of the Dialogue.
|
||||
*/
|
||||
reset(newStyle: Style): void {
|
||||
if (newStyle === undefined || newStyle === null) {
|
||||
newStyle = this._defaultStyle;
|
||||
}
|
||||
|
||||
this.italic = newStyle.italic;
|
||||
this.bold = newStyle.bold;
|
||||
this.underline = newStyle.underline;
|
||||
this.strikeThrough = newStyle.strikeThrough;
|
||||
|
||||
this.outlineWidth = newStyle.outlineThickness;
|
||||
this.outlineHeight = newStyle.outlineThickness;
|
||||
|
||||
this.shadowDepthX = newStyle.shadowDepth;
|
||||
this.shadowDepthY = newStyle.shadowDepth;
|
||||
|
||||
this.fontName = newStyle.fontName;
|
||||
this.fontSize = newStyle.fontSize;
|
||||
|
||||
this.fontScaleX = newStyle.fontScaleX;
|
||||
this.fontScaleY = newStyle.fontScaleY;
|
||||
|
||||
this.letterSpacing = newStyle.letterSpacing;
|
||||
|
||||
this._rotationX = null;
|
||||
this._rotationY = null;
|
||||
this._rotationZ = newStyle.rotationZ;
|
||||
|
||||
this._skewX = null;
|
||||
this._skewY = null;
|
||||
|
||||
this.primaryColor = newStyle.primaryColor;
|
||||
this.secondaryColor = newStyle.secondaryColor;
|
||||
this.outlineColor = newStyle.outlineColor;
|
||||
this.shadowColor = newStyle.shadowColor;
|
||||
|
||||
this.primaryAlpha = newStyle.primaryColor.alpha;
|
||||
this.secondaryAlpha = newStyle.secondaryColor.alpha;
|
||||
this.outlineAlpha = newStyle.outlineColor.alpha;
|
||||
this.shadowAlpha = newStyle.shadowColor.alpha;
|
||||
|
||||
this.blur = null;
|
||||
this.gaussianBlur = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the style attribute on the given span element.
|
||||
*
|
||||
* @param {!HTMLSpanElement} span
|
||||
* @param {!AnimationCollection} animationCollection
|
||||
* @return {!HTMLSpanElement} The resulting <span> with the CSS styles applied. This may be a wrapper around the input <span> if the styles were applied using SVG filters.
|
||||
*/
|
||||
setStylesOnSpan(span: HTMLSpanElement, animationCollection: AnimationCollection): HTMLSpanElement {
|
||||
const isTextOnlySpan = span.childNodes[0] instanceof Text;
|
||||
|
||||
let fontStyleOrWeight = "";
|
||||
if (this._italic) {
|
||||
fontStyleOrWeight += "italic ";
|
||||
}
|
||||
if (this._bold === true) {
|
||||
fontStyleOrWeight += "bold ";
|
||||
}
|
||||
else if (this._bold !== false) {
|
||||
fontStyleOrWeight += this._bold + " ";
|
||||
}
|
||||
const fontSize = (
|
||||
this._scaleY *
|
||||
fontSizeForLineHeight(this._fontName, this._fontSize * (isTextOnlySpan ? this._fontScaleX : 1), this._settings.fallbackFonts, this._fontSizeElement, this._fontMetricsCache)
|
||||
).toFixed(3);
|
||||
const lineHeight = (this._scaleY * this._fontSize).toFixed(3);
|
||||
|
||||
let fonts = this._fontName;
|
||||
|
||||
// Quote the font family unless it's a generic family, as those must never be quoted
|
||||
switch (fonts) {
|
||||
case "cursive":
|
||||
case "fantasy":
|
||||
case "monospace":
|
||||
case "sans-serif":
|
||||
case "serif":
|
||||
break;
|
||||
default:
|
||||
fonts = `"${ fonts }"`;
|
||||
break;
|
||||
}
|
||||
|
||||
if (this._settings.fallbackFonts !== "") {
|
||||
fonts += `, ${ this._settings.fallbackFonts }`;
|
||||
}
|
||||
|
||||
span.style.font = `${ fontStyleOrWeight }${ fontSize }px/${ lineHeight }px ${ fonts }`;
|
||||
|
||||
let textDecoration = "";
|
||||
if (this._underline) {
|
||||
textDecoration = "underline";
|
||||
}
|
||||
if (this._strikeThrough) {
|
||||
textDecoration += " line-through";
|
||||
}
|
||||
span.style.textDecoration = textDecoration.trim();
|
||||
|
||||
let transform = "";
|
||||
if (isTextOnlySpan) {
|
||||
if (this._fontScaleY !== this._fontScaleX) {
|
||||
transform += `scaleY(${ (this._fontScaleY / this._fontScaleX).toFixed(3) }) `;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (this._fontScaleX !== 1) {
|
||||
transform += `scaleX(${ this._fontScaleX }) `;
|
||||
}
|
||||
if (this._fontScaleY !== 1) {
|
||||
transform += `scaleY(${ this._fontScaleY }) `;
|
||||
}
|
||||
}
|
||||
if (this._rotationY !== null) {
|
||||
transform += `rotateY(${ this._rotationY }deg) `;
|
||||
}
|
||||
if (this._rotationX !== null) {
|
||||
transform += `rotateX(${ this._rotationX }deg) `;
|
||||
}
|
||||
if (this._rotationZ !== 0) {
|
||||
transform += `rotateZ(${ -1 * this._rotationZ }deg) `;
|
||||
}
|
||||
if (this._skewX !== null || this._skewY !== null) {
|
||||
const skewX = SpanStyles._valueOrDefault(this._skewX, 0);
|
||||
const skewY = SpanStyles._valueOrDefault(this._skewY, 0);
|
||||
transform += `matrix(1, ${ skewY }, ${ skewX }, 1, 0, 0) `;
|
||||
}
|
||||
if (transform !== "") {
|
||||
span.style.webkitTransform = transform;
|
||||
span.style.webkitTransformOrigin = "50% 50%";
|
||||
span.style.transform = transform;
|
||||
span.style.transformOrigin = "50% 50%";
|
||||
span.style.display = "inline-block";
|
||||
}
|
||||
|
||||
span.style.letterSpacing = `${ (this._scaleX * this._letterSpacing).toFixed(3) }px`;
|
||||
|
||||
const outlineWidth = this._scaleX * this._outlineWidth;
|
||||
const outlineHeight = this._scaleY * this._outlineHeight;
|
||||
|
||||
const filterWrapperSpan = document.createElement("span");
|
||||
filterWrapperSpan.appendChild(span);
|
||||
|
||||
let primaryColor = this._primaryColor.withAlpha(this._primaryAlpha);
|
||||
let outlineColor = this._outlineColor.withAlpha(this._outlineAlpha);
|
||||
let shadowColor = this._shadowColor.withAlpha(this._shadowAlpha);
|
||||
|
||||
// If we're in non-SVG mode and all colors have the same alpha, then set all colors to alpha === 1 and set the common alpha as the span's opacity property instead
|
||||
if (
|
||||
!this._settings.enableSvg &&
|
||||
((outlineWidth === 0 && outlineHeight === 0) || outlineColor.alpha === primaryColor.alpha) &&
|
||||
((this._shadowDepthX === 0 && this._shadowDepthY === 0) || shadowColor.alpha === primaryColor.alpha)
|
||||
) {
|
||||
primaryColor = this._primaryColor.withAlpha(1);
|
||||
outlineColor = this._outlineColor.withAlpha(1);
|
||||
shadowColor = this._shadowColor.withAlpha(1);
|
||||
|
||||
span.style.opacity = this._primaryAlpha.toFixed(3);
|
||||
}
|
||||
|
||||
span.style.color = primaryColor.toString();
|
||||
|
||||
if (this._settings.enableSvg) {
|
||||
this._setSvgOutlineOnSpan(filterWrapperSpan, outlineWidth, outlineHeight, outlineColor, this._primaryAlpha);
|
||||
}
|
||||
else {
|
||||
this._setTextShadowOutlineOnSpan(span, outlineWidth, outlineHeight, outlineColor);
|
||||
}
|
||||
|
||||
if (this._shadowDepthX !== 0 || this._shadowDepthY !== 0) {
|
||||
const shadowCssString = `${ shadowColor.toString() } ${ (this._shadowDepthX * this._scaleX).toFixed(3) }px ${ (this._shadowDepthY * this._scaleY).toFixed(3) }px 0px`;
|
||||
if (span.style.textShadow === "") {
|
||||
span.style.textShadow = shadowCssString;
|
||||
}
|
||||
else {
|
||||
span.style.textShadow += ", " + shadowCssString;
|
||||
}
|
||||
}
|
||||
|
||||
if (this._rotationX !== 0 || this._rotationY !== 0) {
|
||||
// Perspective needs to be set on a "transformable element"
|
||||
filterWrapperSpan.style.display = "inline-block";
|
||||
}
|
||||
|
||||
span.style.webkitAnimation = animationCollection.animationStyle;
|
||||
span.style.animation = animationCollection.animationStyle;
|
||||
|
||||
return filterWrapperSpan;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!HTMLSpanElement} filterWrapperSpan
|
||||
* @param {number} outlineWidth
|
||||
* @param {number} outlineHeight
|
||||
* @param {!libjass.parts.Color} outlineColor
|
||||
* @param {number} primaryAlpha
|
||||
*/
|
||||
private _setSvgOutlineOnSpan(filterWrapperSpan: HTMLSpanElement, outlineWidth: number, outlineHeight: number, outlineColor: Color, primaryAlpha: number): void {
|
||||
const filterId = `svg-filter-${ this._id }-${ this._nextFilterId++ }`;
|
||||
|
||||
const filterElement = document.createElementNS("http://www.w3.org/2000/svg", "filter");
|
||||
filterElement.id = filterId;
|
||||
filterElement.x.baseVal.valueAsString = "-50%";
|
||||
filterElement.width.baseVal.valueAsString = "200%";
|
||||
filterElement.y.baseVal.valueAsString = "-50%";
|
||||
filterElement.height.baseVal.valueAsString = "200%";
|
||||
|
||||
if (outlineWidth > 0 || outlineHeight > 0) {
|
||||
/* Construct an elliptical border by merging together many rectangles. The border is creating using dilate morphology filters, but these only support
|
||||
* generating rectangles. http://lists.w3.org/Archives/Public/public-fx/2012OctDec/0003.html
|
||||
*/
|
||||
|
||||
let outlineNumber = 0;
|
||||
|
||||
const increment = (!this._settings.preciseOutlines && this._gaussianBlur > 0) ? this._gaussianBlur : 1;
|
||||
|
||||
((addOutline: (x: number, y: number) => void) => {
|
||||
if (outlineWidth <= outlineHeight) {
|
||||
if (outlineWidth > 0) {
|
||||
let x: number;
|
||||
for (x = 0; x <= outlineWidth; x += increment) {
|
||||
addOutline(x, outlineHeight / outlineWidth * Math.sqrt(outlineWidth * outlineWidth - x * x));
|
||||
}
|
||||
if (x !== outlineWidth + increment) {
|
||||
addOutline(outlineWidth, 0);
|
||||
}
|
||||
}
|
||||
else {
|
||||
addOutline(0, outlineHeight);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (outlineHeight > 0) {
|
||||
let y: number;
|
||||
for (y = 0; y <= outlineHeight; y += increment) {
|
||||
addOutline(outlineWidth / outlineHeight * Math.sqrt(outlineHeight * outlineHeight - y * y), y);
|
||||
}
|
||||
if (y !== outlineHeight + increment) {
|
||||
addOutline(0, outlineHeight);
|
||||
}
|
||||
}
|
||||
else {
|
||||
addOutline(outlineWidth, 0);
|
||||
}
|
||||
}
|
||||
})((x: number, y: number): void => {
|
||||
const outlineFilter = document.createElementNS("http://www.w3.org/2000/svg", "feMorphology");
|
||||
filterElement.appendChild(outlineFilter);
|
||||
outlineFilter.in1.baseVal = "source";
|
||||
outlineFilter.operator.baseVal = SVGFEMorphologyElement.SVG_MORPHOLOGY_OPERATOR_DILATE;
|
||||
outlineFilter.radiusX.baseVal = x;
|
||||
outlineFilter.radiusY.baseVal = y;
|
||||
outlineFilter.result.baseVal = `outline${ outlineNumber }`;
|
||||
|
||||
outlineNumber++;
|
||||
});
|
||||
|
||||
// Start with SourceAlpha. Leave the alpha as 0 if it's 0, and set it to 1 if it's greater than 0
|
||||
const source = document.createElementNS("http://www.w3.org/2000/svg", "feComponentTransfer");
|
||||
filterElement.insertBefore(source, filterElement.firstElementChild);
|
||||
source.in1.baseVal = "SourceAlpha";
|
||||
source.result.baseVal = "source";
|
||||
|
||||
const sourceAlphaTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncA");
|
||||
source.appendChild(sourceAlphaTransferNode);
|
||||
sourceAlphaTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
|
||||
|
||||
/* The alphas of all colored pixels of the SourceAlpha should be made as close to 1 as possible. This way the summed outlines below will be uniformly dark.
|
||||
* Multiply the pixels by 1 / primaryAlpha so that the primaryAlpha pixels become 1. A higher value would make the outline larger and too sharp,
|
||||
* leading to jagged outer edge and transparent space around the inner edge between itself and the SourceGraphic.
|
||||
*/
|
||||
sourceAlphaTransferNode.slope.baseVal = (primaryAlpha === 0) ? 1 : (1 / primaryAlpha);
|
||||
|
||||
sourceAlphaTransferNode.intercept.baseVal = 0;
|
||||
|
||||
// Merge the individual outlines
|
||||
const mergedOutlines = document.createElementNS("http://www.w3.org/2000/svg", "feMerge");
|
||||
filterElement.appendChild(mergedOutlines);
|
||||
|
||||
for (let i = 0; i < outlineNumber; i++) {
|
||||
const outlineReferenceNode = document.createElementNS("http://www.w3.org/2000/svg", "feMergeNode");
|
||||
mergedOutlines.appendChild(outlineReferenceNode);
|
||||
outlineReferenceNode.in1.baseVal = `outline${ i }`;
|
||||
}
|
||||
|
||||
// Color it with the outline color
|
||||
const coloredSource = document.createElementNS("http://www.w3.org/2000/svg", "feComponentTransfer");
|
||||
filterElement.appendChild(coloredSource);
|
||||
coloredSource.setAttribute("color-interpolation-filters", "sRGB");
|
||||
|
||||
const outlineRedTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncR");
|
||||
coloredSource.appendChild(outlineRedTransferNode);
|
||||
outlineRedTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
|
||||
outlineRedTransferNode.slope.baseVal = 0;
|
||||
outlineRedTransferNode.intercept.baseVal = outlineColor.red / 255 * outlineColor.alpha;
|
||||
|
||||
const outlineGreenTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncG");
|
||||
coloredSource.appendChild(outlineGreenTransferNode);
|
||||
outlineGreenTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
|
||||
outlineGreenTransferNode.slope.baseVal = 0;
|
||||
outlineGreenTransferNode.intercept.baseVal = outlineColor.green / 255 * outlineColor.alpha;
|
||||
|
||||
const outlineBlueTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncB");
|
||||
coloredSource.appendChild(outlineBlueTransferNode);
|
||||
outlineBlueTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
|
||||
outlineBlueTransferNode.slope.baseVal = 0;
|
||||
outlineBlueTransferNode.intercept.baseVal = outlineColor.blue / 255 * outlineColor.alpha;
|
||||
|
||||
const outlineAlphaTransferNode = document.createElementNS("http://www.w3.org/2000/svg", "feFuncA");
|
||||
coloredSource.appendChild(outlineAlphaTransferNode);
|
||||
outlineAlphaTransferNode.type.baseVal = SVGComponentTransferFunctionElement.SVG_FECOMPONENTTRANSFER_TYPE_LINEAR;
|
||||
outlineAlphaTransferNode.slope.baseVal = outlineColor.alpha;
|
||||
outlineAlphaTransferNode.intercept.baseVal = 0;
|
||||
|
||||
// Blur the merged outline
|
||||
if (this._gaussianBlur > 0) {
|
||||
const gaussianBlurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
|
||||
filterElement.appendChild(gaussianBlurFilter);
|
||||
gaussianBlurFilter.stdDeviationX.baseVal = this._gaussianBlur;
|
||||
gaussianBlurFilter.stdDeviationY.baseVal = this._gaussianBlur;
|
||||
}
|
||||
for (let i = 0; i < this._blur; i++) {
|
||||
const blurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feConvolveMatrix");
|
||||
filterElement.appendChild(blurFilter);
|
||||
blurFilter.setAttribute("kernelMatrix", "1 2 1 2 4 2 1 2 1");
|
||||
blurFilter.edgeMode.baseVal = SVGFEConvolveMatrixElement.SVG_EDGEMODE_NONE;
|
||||
}
|
||||
|
||||
// Cut out the source, so only the outline remains
|
||||
const outlineCutoutNode = document.createElementNS("http://www.w3.org/2000/svg", "feComposite");
|
||||
filterElement.appendChild(outlineCutoutNode);
|
||||
outlineCutoutNode.in2.baseVal = "source";
|
||||
outlineCutoutNode.operator.baseVal = SVGFECompositeElement.SVG_FECOMPOSITE_OPERATOR_OUT;
|
||||
|
||||
// Merge the outline with the SourceGraphic
|
||||
const mergedOutlineAndSourceGraphic = document.createElementNS("http://www.w3.org/2000/svg", "feMerge");
|
||||
filterElement.appendChild(mergedOutlineAndSourceGraphic);
|
||||
|
||||
const outlineReferenceNode = document.createElementNS("http://www.w3.org/2000/svg", "feMergeNode");
|
||||
mergedOutlineAndSourceGraphic.appendChild(outlineReferenceNode);
|
||||
|
||||
const sourceGraphicReferenceNode = document.createElementNS("http://www.w3.org/2000/svg", "feMergeNode");
|
||||
mergedOutlineAndSourceGraphic.appendChild(sourceGraphicReferenceNode);
|
||||
sourceGraphicReferenceNode.in1.baseVal = "SourceGraphic";
|
||||
}
|
||||
else {
|
||||
// Blur the source graphic directly
|
||||
if (this._gaussianBlur > 0) {
|
||||
const gaussianBlurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
|
||||
filterElement.appendChild(gaussianBlurFilter);
|
||||
gaussianBlurFilter.stdDeviationX.baseVal = this._gaussianBlur;
|
||||
gaussianBlurFilter.stdDeviationY.baseVal = this._gaussianBlur;
|
||||
}
|
||||
for (let i = 0; i < this._blur; i++) {
|
||||
const blurFilter = document.createElementNS("http://www.w3.org/2000/svg", "feConvolveMatrix");
|
||||
filterElement.appendChild(blurFilter);
|
||||
blurFilter.setAttribute("kernelMatrix", "1 2 1 2 4 2 1 2 1");
|
||||
blurFilter.edgeMode.baseVal = SVGFEConvolveMatrixElement.SVG_EDGEMODE_NONE;
|
||||
}
|
||||
}
|
||||
|
||||
if (filterElement.childElementCount > 0) {
|
||||
this._svgDefsElement.appendChild(filterElement);
|
||||
|
||||
filterWrapperSpan.style.webkitFilter = `url("#${ filterId }")`;
|
||||
filterWrapperSpan.style.filter = `url("#${ filterId }")`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!HTMLSpanElement} span
|
||||
* @param {number} outlineWidth
|
||||
* @param {number} outlineHeight
|
||||
* @param {!libjass.parts.Color} outlineColor
|
||||
*/
|
||||
private _setTextShadowOutlineOnSpan(span: HTMLSpanElement, outlineWidth: number, outlineHeight: number, outlineColor: Color): void {
|
||||
if (outlineWidth > 0 || outlineHeight > 0) {
|
||||
let outlineCssString = "";
|
||||
|
||||
((addOutline: (x: number, y: number) => void) => {
|
||||
for (let x = 0; x <= outlineWidth; x++) {
|
||||
const maxY = (outlineWidth === 0) ? outlineHeight : outlineHeight * Math.sqrt(1 - ((x * x) / (outlineWidth * outlineWidth)));
|
||||
for (let y = 0; y <= maxY; y++) {
|
||||
addOutline(x, y);
|
||||
|
||||
if (x !== 0) {
|
||||
addOutline(-x, y);
|
||||
}
|
||||
|
||||
if (y !== 0) {
|
||||
addOutline(x, -y);
|
||||
}
|
||||
|
||||
if (x !== 0 && y !== 0) {
|
||||
addOutline(-x, -y);
|
||||
}
|
||||
}
|
||||
}
|
||||
})((x: number, y: number): void => {
|
||||
outlineCssString += `, ${ outlineColor.toString() } ${ x }px ${ y }px ${ this._gaussianBlur.toFixed(3) }px`;
|
||||
});
|
||||
|
||||
span.style.textShadow = outlineCssString.substr(", ".length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {!HTMLBRElement}
|
||||
*/
|
||||
makeNewLine(): HTMLBRElement {
|
||||
const result = document.createElement("br");
|
||||
result.style.lineHeight = `${ (this._scaleY * this._fontSize).toFixed(3) }px`;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the italic property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {?boolean}
|
||||
*/
|
||||
set italic(value: boolean) {
|
||||
this._italic = SpanStyles._valueOrDefault(value, this._defaultStyle.italic);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the bold property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {(?number|?boolean)}
|
||||
*/
|
||||
set bold(value: Object) {
|
||||
this._bold = SpanStyles._valueOrDefault(value, this._defaultStyle.bold);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the underline property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {?boolean}
|
||||
*/
|
||||
set underline(value: boolean) {
|
||||
this._underline = SpanStyles._valueOrDefault(value, this._defaultStyle.underline);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the strike-through property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {?boolean}
|
||||
*/
|
||||
set strikeThrough(value: boolean) {
|
||||
this._strikeThrough = SpanStyles._valueOrDefault(value, this._defaultStyle.strikeThrough);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the outline width property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get outlineWidth() {
|
||||
return this._outlineWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the outline width property. null defaults it to the style's original outline width value.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set outlineWidth(value: number) {
|
||||
this._outlineWidth = SpanStyles._valueOrDefault(value, this._defaultStyle.outlineThickness);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the outline width property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get outlineHeight() {
|
||||
return this._outlineWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the outline height property. null defaults it to the style's original outline height value.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set outlineHeight(value: number) {
|
||||
this._outlineHeight = SpanStyles._valueOrDefault(value, this._defaultStyle.outlineThickness);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the shadow width property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get shadowDepthX() {
|
||||
return this._shadowDepthX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the shadow width property. null defaults it to the style's original shadow depth value.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set shadowDepthX(value: number) {
|
||||
this._shadowDepthX = SpanStyles._valueOrDefault(value, this._defaultStyle.shadowDepth);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the shadow height property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get shadowDepthY() {
|
||||
return this._shadowDepthY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the shadow height property. null defaults it to the style's original shadow depth value.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set shadowDepthY(value: number) {
|
||||
this._shadowDepthY = SpanStyles._valueOrDefault(value, this._defaultStyle.shadowDepth);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the blur property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get blur() {
|
||||
return this._blur;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the blur property. null defaults it to 0.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set blur(value: number) {
|
||||
this._blur = SpanStyles._valueOrDefault(value, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Gaussian blur property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get gaussianBlur() {
|
||||
return this._gaussianBlur;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Gaussian blur property. null defaults it to 0.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set gaussianBlur(value: number) {
|
||||
this._gaussianBlur = SpanStyles._valueOrDefault(value, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the font name property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {?string}
|
||||
*/
|
||||
set fontName(value: string) {
|
||||
this._fontName = SpanStyles._valueOrDefault(value, this._defaultStyle.fontName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the font size property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get fontSize() {
|
||||
return this._fontSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the font size property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set fontSize(value: number) {
|
||||
this._fontSize = SpanStyles._valueOrDefault(value, this._defaultStyle.fontSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the horizontal font scaling property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get fontScaleX() {
|
||||
return this._fontScaleX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the horizontal font scaling property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set fontScaleX(value: number) {
|
||||
this._fontScaleX = SpanStyles._valueOrDefault(value, this._defaultStyle.fontScaleX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the vertical font scaling property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get fontScaleY() {
|
||||
return this._fontScaleY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the vertical font scaling property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set fontScaleY(value: number) {
|
||||
this._fontScaleY = SpanStyles._valueOrDefault(value, this._defaultStyle.fontScaleY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the letter spacing property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get letterSpacing() {
|
||||
return this._letterSpacing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the letter spacing property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set letterSpacing(value: number) {
|
||||
this._letterSpacing = SpanStyles._valueOrDefault(value, this._defaultStyle.letterSpacing);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the X-axis rotation property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
get rotationX() {
|
||||
return this._rotationX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the X-axis rotation property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set rotationX(value: number) {
|
||||
this._rotationX = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Y-axis rotation property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
get rotationY() {
|
||||
return this._rotationY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Y-axis rotation property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set rotationY(value: number) {
|
||||
this._rotationY = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Z-axis rotation property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
get rotationZ() {
|
||||
return this._rotationZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Z-axis rotation property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set rotationZ(value: number) {
|
||||
this._rotationZ = SpanStyles._valueOrDefault(value, this._defaultStyle.rotationZ);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the X-axis skew property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
get skewX() {
|
||||
return this._skewX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the X-axis skew property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set skewX(value: number) {
|
||||
this._skewX = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the Y-axis skew property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
get skewY() {
|
||||
return this._skewY;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Y-axis skew property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set skewY(value: number) {
|
||||
this._skewY = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the primary color property.
|
||||
*
|
||||
* @type {!libjass.Color}
|
||||
*/
|
||||
get primaryColor(): Color {
|
||||
return this._primaryColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the primary color property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {libjass.Color}
|
||||
*/
|
||||
set primaryColor(value: Color) {
|
||||
this._primaryColor = SpanStyles._valueOrDefault(value, this._defaultStyle.primaryColor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the secondary color property.
|
||||
*
|
||||
* @type {!libjass.Color}
|
||||
*/
|
||||
get secondaryColor(): Color {
|
||||
return this._secondaryColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the secondary color property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {libjass.Color}
|
||||
*/
|
||||
set secondaryColor(value: Color) {
|
||||
this._secondaryColor = SpanStyles._valueOrDefault(value, this._defaultStyle.secondaryColor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the outline color property.
|
||||
*
|
||||
* @type {!libjass.Color}
|
||||
*/
|
||||
get outlineColor(): Color {
|
||||
return this._outlineColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the outline color property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {libjass.Color}
|
||||
*/
|
||||
set outlineColor(value: Color) {
|
||||
this._outlineColor = SpanStyles._valueOrDefault(value, this._defaultStyle.outlineColor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the shadow color property.
|
||||
*
|
||||
* @type {!libjass.Color}
|
||||
*/
|
||||
get shadowColor(): Color {
|
||||
return this._shadowColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the shadow color property. null defaults it to the default style's value.
|
||||
*
|
||||
* @type {libjass.Color}
|
||||
*/
|
||||
set shadowColor(value: Color) {
|
||||
this._shadowColor = SpanStyles._valueOrDefault(value, this._defaultStyle.shadowColor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the primary alpha property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get primaryAlpha(): number {
|
||||
return this._primaryAlpha;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the primary alpha property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set primaryAlpha(value: number) {
|
||||
this._primaryAlpha = SpanStyles._valueOrDefault(value, this._defaultStyle.primaryColor.alpha);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the secondary alpha property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get secondaryAlpha(): number {
|
||||
return this._secondaryAlpha;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the secondary alpha property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set secondaryAlpha(value: number) {
|
||||
this._secondaryAlpha = SpanStyles._valueOrDefault(value, this._defaultStyle.secondaryColor.alpha);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the outline alpha property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get outlineAlpha(): number {
|
||||
return this._outlineAlpha;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the outline alpha property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set outlineAlpha(value: number) {
|
||||
this._outlineAlpha = SpanStyles._valueOrDefault(value, this._defaultStyle.outlineColor.alpha);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the shadow alpha property.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get shadowAlpha(): number {
|
||||
return this._shadowAlpha;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the shadow alpha property.
|
||||
*
|
||||
* @type {?number}
|
||||
*/
|
||||
set shadowAlpha(value: number) {
|
||||
this._shadowAlpha = SpanStyles._valueOrDefault(value, this._defaultStyle.shadowColor.alpha);
|
||||
}
|
||||
|
||||
private static _valueOrDefault = <T>(newValue: T, defaultValue: T): T => ((newValue !== null) ? newValue : defaultValue);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 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 Document {
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "defs"): SVGDefsElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComponentTransfer"): SVGFEComponentTransferElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feComposite"): SVGFECompositeElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feConvolveMatrix"): SVGFEConvolveMatrixElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncA"): SVGFEFuncAElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncB"): SVGFEFuncBElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncG"): SVGFEFuncGElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feFuncR"): SVGFEFuncRElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feGaussianBlur"): SVGFEGaussianBlurElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMerge"): SVGFEMergeElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMergeNode"): SVGFEMergeNodeElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "feMorphology"): SVGFEMorphologyElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "filter"): SVGFilterElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "g"): SVGGElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "path"): SVGPathElement;
|
||||
createElementNS(namespaceURI: "http://www.w3.org/2000/svg", qualifiedName: "svg"): SVGSVGElement;
|
||||
}
|
||||
|
||||
interface SVGFEComponentTransferElement {
|
||||
appendChild(newChild: SVGFEFuncAElement): SVGFEFuncAElement;
|
||||
appendChild(newChild: SVGFEFuncBElement): SVGFEFuncBElement;
|
||||
appendChild(newChild: SVGFEFuncGElement): SVGFEFuncGElement;
|
||||
appendChild(newChild: SVGFEFuncRElement): SVGFEFuncRElement;
|
||||
}
|
||||
|
||||
interface SVGFEMergeElement {
|
||||
appendChild(newChild: SVGFEMergeNodeElement): SVGFEMergeNodeElement;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Debug mode. When true, libjass logs some debug messages.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
export let debugMode: boolean = false;
|
||||
|
||||
/**
|
||||
* Verbose debug mode. When true, libjass logs some more debug messages. This setting is independent of {@link libjass.debugMode}
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
export let verboseMode: boolean = false;
|
||||
|
||||
/**
|
||||
* Sets the debug mode.
|
||||
*
|
||||
* @param {boolean} value
|
||||
*/
|
||||
export function setDebugMode(value: boolean): void {
|
||||
debugMode = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the verbose debug mode.
|
||||
*
|
||||
* @param {boolean} value
|
||||
*/
|
||||
export function setVerboseMode(value: boolean): void {
|
||||
verboseMode = value;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "CommonJS",
|
||||
"noImplicitAny": true,
|
||||
"sourceMap": true,
|
||||
"target": "ES5",
|
||||
"experimentalDecorators": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* 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 "./attachment";
|
||||
import { Dialogue } from "./dialogue";
|
||||
import { Style } from "./style";
|
||||
import { ScriptProperties } from "./script-properties";
|
||||
|
||||
import { Format } from "./misc";
|
||||
|
||||
import { verboseMode } from "../settings";
|
||||
|
||||
import * as parser from "../parser";
|
||||
import { parseLineIntoTypedTemplate } from "../parser/misc";
|
||||
import { ReadableStream, TextDecoder, TextDecoderConstructor } from "../parser/streams";
|
||||
|
||||
import { Map } from "../utility/map";
|
||||
import { Promise } from "../utility/promise";
|
||||
|
||||
declare const global: {
|
||||
fetch?(url: string): Promise<{ body: ReadableStream; ok?: boolean; status?: number; }>;
|
||||
ReadableStream?: { prototype: ReadableStream; };
|
||||
TextDecoder?: TextDecoderConstructor;
|
||||
};
|
||||
|
||||
/**
|
||||
* This class represents an ASS script. It contains the {@link libjass.ScriptProperties}, an array of {@link libjass.Style}s, and an array of {@link libjass.Dialogue}s.
|
||||
*/
|
||||
export class ASS {
|
||||
private _properties: ScriptProperties = new ScriptProperties();
|
||||
private _styles: Map<string, Style> = new Map<string, Style>();
|
||||
private _dialogues: Dialogue[] = [];
|
||||
private _attachments: Attachment[] = [];
|
||||
|
||||
private _stylesFormatSpecifier: string[] = null;
|
||||
private _dialoguesFormatSpecifier: string[] = null;
|
||||
|
||||
/**
|
||||
* The properties of this script.
|
||||
*
|
||||
* @type {!libjass.ScriptProperties}
|
||||
*/
|
||||
get properties(): ScriptProperties {
|
||||
return this._properties;
|
||||
}
|
||||
|
||||
/**
|
||||
* The styles in this script.
|
||||
*
|
||||
* @type {!Map.<string, !libjass.Style>}
|
||||
*/
|
||||
get styles(): Map<string, Style> {
|
||||
return this._styles;
|
||||
}
|
||||
|
||||
/**
|
||||
* The dialogues in this script.
|
||||
*
|
||||
* @type {!Array.<!libjass.Dialogue>}
|
||||
*/
|
||||
get dialogues(): Dialogue[] {
|
||||
return this._dialogues;
|
||||
}
|
||||
|
||||
/**
|
||||
* The attachments of this script.
|
||||
*
|
||||
* @type {!Array.<!libjass.Attachment>}
|
||||
*/
|
||||
get attachments(): Attachment[] {
|
||||
return this._attachments;
|
||||
}
|
||||
|
||||
/**
|
||||
* The format specifier for the styles section.
|
||||
*
|
||||
* @type {!Array.<string>}
|
||||
*/
|
||||
get stylesFormatSpecifier(): string[] {
|
||||
return this._stylesFormatSpecifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* The format specifier for the styles section.
|
||||
*
|
||||
* @type {!Array.<string>}
|
||||
*/
|
||||
get dialoguesFormatSpecifier(): string[] {
|
||||
return this._dialoguesFormatSpecifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* The format specifier for the events section.
|
||||
*
|
||||
* @type {!Array.<string>}
|
||||
*/
|
||||
set stylesFormatSpecifier(value: string[]) {
|
||||
this._stylesFormatSpecifier = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The format specifier for the events section.
|
||||
*
|
||||
* @type {!Array.<string>}
|
||||
*/
|
||||
set dialoguesFormatSpecifier(value: string[]) {
|
||||
this._dialoguesFormatSpecifier = value;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
// Deprecated constructor argument
|
||||
if (arguments.length === 1) {
|
||||
throw new Error("Constructor `new ASS(rawASS)` has been deprecated. Use `ASS.fromString(rawASS)` instead.");
|
||||
}
|
||||
|
||||
this._styles.set("Default", new Style(new Map([["Name", "Default"]])));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a style to this ASS script.
|
||||
*
|
||||
* @param {string} line The line from the script that contains the new style.
|
||||
*/
|
||||
addStyle(line: string): void {
|
||||
const styleLine = parseLineIntoTypedTemplate(line, this._stylesFormatSpecifier);
|
||||
if (styleLine === null || styleLine.type !== "Style") {
|
||||
return;
|
||||
}
|
||||
|
||||
const styleTemplate = styleLine.template;
|
||||
|
||||
if (verboseMode) {
|
||||
let repr = "";
|
||||
styleTemplate.forEach((value, key) => repr += `${ key } = ${ value }, `);
|
||||
console.log(`Read style: ${ repr }`);
|
||||
}
|
||||
|
||||
// Create the dialogue and add it to the dialogues array
|
||||
const style = new Style(styleTemplate);
|
||||
this._styles.set(style.name, style);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an event to this ASS script.
|
||||
*
|
||||
* @param {string} line The line from the script that contains the new event.
|
||||
*/
|
||||
addEvent(line: string): void {
|
||||
const dialogueLine = parseLineIntoTypedTemplate(line, this._dialoguesFormatSpecifier);
|
||||
if (dialogueLine === null || dialogueLine.type !== "Dialogue") {
|
||||
return;
|
||||
}
|
||||
|
||||
const dialogueTemplate = dialogueLine.template;
|
||||
|
||||
if (verboseMode) {
|
||||
let repr = "";
|
||||
dialogueTemplate.forEach((value, key) => repr += `${ key } = ${ value }, `);
|
||||
console.log(`Read dialogue: ${ repr }`);
|
||||
}
|
||||
|
||||
// Create the dialogue and add it to the dialogues array
|
||||
this.dialogues.push(new Dialogue(dialogueTemplate, this));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an attachment to this ASS script.
|
||||
*
|
||||
* @param {!libjass.Attachment} attachment
|
||||
*/
|
||||
addAttachment(attachment: Attachment): void {
|
||||
this._attachments.push(attachment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an ASS object from the raw text of an ASS script.
|
||||
*
|
||||
* @param {string} raw The raw text of the script.
|
||||
* @param {number=0} type The type of the script. One of the {@link libjass.Format} constants.
|
||||
* @return {!Promise.<!libjass.ASS>}
|
||||
*/
|
||||
static fromString(raw: string, type: Format = Format.ASS): Promise<ASS> {
|
||||
return ASS.fromStream(new parser.StringStream(raw), type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an ASS object from the given {@link libjass.parser.Stream}.
|
||||
*
|
||||
* @param {!libjass.parser.Stream} stream The stream to parse the script from
|
||||
* @param {number=0} type The type of the script. One of the {@link libjass.Format} constants.
|
||||
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
|
||||
*/
|
||||
static fromStream(stream: parser.Stream, type: Format = Format.ASS): Promise<ASS> {
|
||||
switch (type) {
|
||||
case Format.ASS:
|
||||
return new parser.StreamParser(stream).ass;
|
||||
case Format.SRT:
|
||||
return new parser.SrtStreamParser(stream).ass;
|
||||
default:
|
||||
throw new Error(`Illegal value of type: ${ type }`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an ASS object from the given URL.
|
||||
*
|
||||
* @param {string} url The URL of the script.
|
||||
* @param {number=0} type The type of the script. One of the {@link libjass.Format} constants.
|
||||
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
|
||||
*/
|
||||
static fromUrl(url: string, type: Format = Format.ASS): Promise<ASS> {
|
||||
let fetchPromise: Promise<ASS>;
|
||||
|
||||
if (
|
||||
typeof global.fetch === "function" &&
|
||||
typeof global.ReadableStream === "function" && typeof global.ReadableStream.prototype.getReader === "function" &&
|
||||
typeof global.TextDecoder === "function"
|
||||
) {
|
||||
fetchPromise = global.fetch(url).then(response => {
|
||||
if (response.ok === false || (response.ok === undefined && (response.status < 200 || response.status > 299))) {
|
||||
throw new Error(`HTTP request for ${ url } failed with status code ${ response.status }`);
|
||||
}
|
||||
|
||||
return ASS.fromReadableStream(response.body, "utf-8", type);
|
||||
});
|
||||
}
|
||||
else {
|
||||
fetchPromise = Promise.reject<ASS>(new Error("Not supported."));
|
||||
}
|
||||
|
||||
return fetchPromise.catch(reason => {
|
||||
console.warn("fetch() failed, falling back to XHR: %o", reason);
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
const result = ASS.fromStream(new parser.XhrStream(xhr), type);
|
||||
xhr.open("GET", url, true);
|
||||
xhr.send();
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an ASS object from the given ReadableStream.
|
||||
*
|
||||
* @param {!ReadableStream} stream
|
||||
* @param {string="utf-8"} encoding
|
||||
* @param {number=0} type The type of the script. One of the {@link libjass.Format} constants.
|
||||
* @return {!Promise.<!libjass.ASS>} A promise that will be resolved with the ASS object when it has been fully parsed
|
||||
*/
|
||||
static fromReadableStream(stream: ReadableStream, encoding: string = "utf-8", type: Format = Format.ASS): Promise<ASS> {
|
||||
return ASS.fromStream(new parser.BrowserReadableStream(stream, encoding), type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* 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 type of an attachment.
|
||||
*/
|
||||
export enum AttachmentType {
|
||||
Font,
|
||||
Graphic,
|
||||
}
|
||||
|
||||
/**
|
||||
* This class represents an attachment in a {@link libjass.ASS} script.
|
||||
*
|
||||
* @param {string} filename The filename of this attachment.
|
||||
* @param {number} type The type of this attachment.
|
||||
*/
|
||||
export class Attachment {
|
||||
private _contents: string = "";
|
||||
|
||||
constructor(private _filename: string, private _type: AttachmentType) { }
|
||||
|
||||
/**
|
||||
* The filename of this attachment.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get filename(): string {
|
||||
return this._filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of this attachment.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get type(): AttachmentType {
|
||||
return this._type;
|
||||
}
|
||||
|
||||
/**
|
||||
* The contents of this attachment in base64 encoding.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get contents(): string {
|
||||
return this._contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* The contents of this attachment in base64 encoding.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
set contents(value: string) {
|
||||
this._contents = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* 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 { ASS } from "./ass";
|
||||
import { Style } from "./style";
|
||||
|
||||
import { valueOrDefault } from "./misc";
|
||||
|
||||
import { parseLineIntoTypedTemplate } from "../parser/misc";
|
||||
|
||||
import { parse } from "../parser/parse";
|
||||
|
||||
import * as parts from "../parts";
|
||||
|
||||
import { debugMode } from "../settings";
|
||||
|
||||
import { Map } from "../utility/map";
|
||||
|
||||
/**
|
||||
* This class represents a dialogue in a {@link libjass.ASS} script.
|
||||
*
|
||||
* @param {!Map.<string, string>} template The template object that contains the dialogue's properties. It is a map of the string values read from the ASS file.
|
||||
* @param {string} template["Style"] The name of the default style of this dialogue
|
||||
* @param {string} template["Start"] The start time
|
||||
* @param {string} template["End"] The end time
|
||||
* @param {string} template["Layer"] The layer number
|
||||
* @param {string} template["Text"] The text of this dialogue
|
||||
* @param {!libjass.ASS} ass The ASS object to which this dialogue belongs
|
||||
*/
|
||||
export class Dialogue {
|
||||
private static _lastDialogueId = -1;
|
||||
|
||||
private _id: number;
|
||||
|
||||
private _style: Style;
|
||||
|
||||
private _start: number;
|
||||
private _end: number;
|
||||
|
||||
private _layer: number;
|
||||
private _alignment: number;
|
||||
|
||||
private _rawPartsString: string;
|
||||
private _parts: parts.Part[] = null;
|
||||
|
||||
private _containsTransformTag: boolean = false;
|
||||
|
||||
constructor(template: Map<string, string>, ass: ASS) {
|
||||
{
|
||||
const normalizedTemplate = new Map<string, string>();
|
||||
template.forEach((value, key) => {
|
||||
normalizedTemplate.set(key.toLowerCase(), value);
|
||||
});
|
||||
template = normalizedTemplate;
|
||||
}
|
||||
|
||||
this._id = ++Dialogue._lastDialogueId;
|
||||
|
||||
let styleName = template.get("style");
|
||||
if (styleName !== undefined && styleName !== null && styleName.constructor === String) {
|
||||
styleName = styleName.replace(/^\*+/, "");
|
||||
if (styleName.match(/^Default$/i) !== null) {
|
||||
styleName = "Default";
|
||||
}
|
||||
}
|
||||
|
||||
this._style = ass.styles.get(styleName);
|
||||
if (this._style === undefined) {
|
||||
if (debugMode) {
|
||||
console.warn(`Unrecognized style ${ styleName }. Falling back to "Default"`);
|
||||
}
|
||||
|
||||
this._style = ass.styles.get("Default");
|
||||
}
|
||||
if (this._style === undefined) {
|
||||
throw new Error(`Unrecognized style ${ styleName }`);
|
||||
}
|
||||
|
||||
this._start = Dialogue._toTime(template.get("start"));
|
||||
this._end = Dialogue._toTime(template.get("end"));
|
||||
|
||||
this._layer = Math.max(valueOrDefault(template, "layer", parseInt, value => !isNaN(value), "0"), 0);
|
||||
|
||||
this._rawPartsString = template.get("text");
|
||||
if (this._rawPartsString === undefined || this._rawPartsString === null || this._rawPartsString.constructor !== String) {
|
||||
throw new Error("Dialogue doesn't have any text.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The unique ID of this dialogue. Auto-generated.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get id(): number {
|
||||
return this._id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The start time of this dialogue.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get start(): number {
|
||||
return this._start;
|
||||
}
|
||||
|
||||
/**
|
||||
* The end time of this dialogue.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get end(): number {
|
||||
return this._end;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default style of this dialogue.
|
||||
*
|
||||
* @type {!libjass.Style}
|
||||
*/
|
||||
get style(): Style {
|
||||
return this._style;
|
||||
}
|
||||
|
||||
/**
|
||||
* The alignment number of this dialogue.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get alignment(): number {
|
||||
if (this._parts === null) {
|
||||
this._parsePartsString();
|
||||
}
|
||||
|
||||
return this._alignment;
|
||||
}
|
||||
|
||||
/**
|
||||
* The layer number of this dialogue.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get layer(): number {
|
||||
return this._layer;
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@link libjass.parts} of this dialogue.
|
||||
*
|
||||
* @type {!Array.<!libjass.parts.Part>}
|
||||
*/
|
||||
get parts(): parts.Part[] {
|
||||
if (this._parts === null) {
|
||||
this._parsePartsString();
|
||||
}
|
||||
|
||||
return this._parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience getter for whether this dialogue contains a {\t} tag.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
get containsTransformTag(): boolean {
|
||||
if (this._parts === null) {
|
||||
this._parsePartsString();
|
||||
}
|
||||
|
||||
return this._containsTransformTag;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {string} A simple representation of this dialogue's properties and parts.
|
||||
*/
|
||||
toString(): string {
|
||||
return `#${ this._id } [${ this._start.toFixed(3) }-${ this._end.toFixed(3) }] ${ (this._parts !== null) ? this._parts.join(", ") : this._rawPartsString }`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses this dialogue's parts from the raw parts string.
|
||||
*/
|
||||
private _parsePartsString(): void {
|
||||
this._parts = <parts.Part[]>parse(this._rawPartsString, "dialogueParts");
|
||||
|
||||
this._alignment = this._style.alignment;
|
||||
|
||||
this._parts.forEach((part, index) => {
|
||||
if (part instanceof parts.Alignment) {
|
||||
this._alignment = part.value;
|
||||
}
|
||||
else if (part instanceof parts.Move) {
|
||||
if (part.t1 === null || part.t2 === null) {
|
||||
this._parts[index] =
|
||||
new parts.Move(
|
||||
part.x1, part.y1, part.x2, part.y2,
|
||||
0, this._end - this._start
|
||||
);
|
||||
}
|
||||
}
|
||||
else if (part instanceof parts.Transform) {
|
||||
if (part.start === null || part.end === null || part.accel === null) {
|
||||
this._parts[index] =
|
||||
new parts.Transform(
|
||||
(part.start === null) ? 0 : part.start,
|
||||
(part.end === null) ? (this._end - this._start) : part.end,
|
||||
(part.accel === null) ? 1 : part.accel,
|
||||
part.tags
|
||||
);
|
||||
}
|
||||
|
||||
this._containsTransformTag = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (debugMode) {
|
||||
const possiblyIncorrectParses = this._parts.filter(part => part instanceof parts.Comment && part.value.indexOf("\\") !== -1);
|
||||
if (possiblyIncorrectParses.length > 0) {
|
||||
console.warn(
|
||||
`Possible incorrect parse:
|
||||
${ this._rawPartsString }
|
||||
was parsed as
|
||||
${ this.toString() }
|
||||
The possibly incorrect parses are:
|
||||
${ possiblyIncorrectParses.join("\n") }`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts this string into the number of seconds it represents. This string must be in the form of hh:mm:ss.MMM
|
||||
*
|
||||
* @param {string} str
|
||||
* @return {number}
|
||||
*/
|
||||
private static _toTime(str: string): number {
|
||||
return str.split(":").reduce<number>((previousValue, currentValue) => previousValue * 60 + parseFloat(currentValue), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* 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 { Map } from "../utility/map";
|
||||
|
||||
/**
|
||||
* The format of the string passed to {@link libjass.ASS.fromString}
|
||||
*/
|
||||
export enum Format {
|
||||
ASS,
|
||||
SRT,
|
||||
}
|
||||
|
||||
/**
|
||||
* The wrapping style defined in the {@link libjass.ScriptProperties}
|
||||
*/
|
||||
export enum WrappingStyle {
|
||||
SmartWrappingWithWiderTopLine = 0,
|
||||
SmartWrappingWithWiderBottomLine = 3,
|
||||
EndOfLineWrapping = 1,
|
||||
NoLineWrapping = 2,
|
||||
}
|
||||
|
||||
/**
|
||||
* The border style defined in the {@link libjass.Style} properties.
|
||||
*/
|
||||
export enum BorderStyle {
|
||||
Outline = 1,
|
||||
OpaqueBox = 3,
|
||||
}
|
||||
|
||||
/**
|
||||
* A property.
|
||||
*/
|
||||
export interface Property {
|
||||
/**
|
||||
* @type {string}
|
||||
*/
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* @type {string}
|
||||
*/
|
||||
value: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A template object with a particular type.
|
||||
*/
|
||||
export interface TypedTemplate {
|
||||
/**
|
||||
* @type {string}
|
||||
*/
|
||||
type: string;
|
||||
|
||||
/**
|
||||
* @type {!Map.<string, string>}
|
||||
*/
|
||||
template: Map<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!Map.<string, string>} template
|
||||
* @param {string} key
|
||||
* @param {function(string):T} converter
|
||||
* @param {?function(T):boolean} validator
|
||||
* @param {T} defaultValue
|
||||
* @return {T}
|
||||
*/
|
||||
export function valueOrDefault<T>(template: Map<string, string>, key: string, converter: (str: string) => T, validator: (value: T) => boolean, defaultValue: string): T {
|
||||
const value = template.get(key);
|
||||
if (value === undefined) {
|
||||
return converter(defaultValue);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = converter(value);
|
||||
|
||||
if (validator !== null && !validator(result)) {
|
||||
throw new Error("Validation failed.");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (ex) {
|
||||
throw new Error(`Property ${ key } has invalid value ${ value } - ${ ex.stack }`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* 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 } from "./misc";
|
||||
|
||||
/**
|
||||
* This class represents the properties of a {@link libjass.ASS} script.
|
||||
*/
|
||||
export class ScriptProperties {
|
||||
private _resolutionX: number;
|
||||
private _resolutionY: number;
|
||||
private _wrappingStyle: WrappingStyle;
|
||||
private _scaleBorderAndShadow: boolean;
|
||||
|
||||
/**
|
||||
* The horizontal script resolution.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get resolutionX(): number {
|
||||
return this._resolutionX;
|
||||
}
|
||||
|
||||
/**
|
||||
* The horizontal script resolution.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
set resolutionX(value: number) {
|
||||
this._resolutionX = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The vertical script resolution.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get resolutionY(): number {
|
||||
return this._resolutionY;
|
||||
}
|
||||
|
||||
/**
|
||||
* The vertical script resolution.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
set resolutionY(value: number) {
|
||||
this._resolutionY = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The wrap style. One of the {@link libjass.WrappingStyle} constants.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get wrappingStyle(): WrappingStyle {
|
||||
return this._wrappingStyle;
|
||||
}
|
||||
|
||||
/**
|
||||
* The wrap style. One of the {@link libjass.WrappingStyle} constants.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
set wrappingStyle(value: WrappingStyle) {
|
||||
this._wrappingStyle = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to scale outline widths and shadow depths from script resolution to video resolution or not. If true, widths and depths are scaled.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
get scaleBorderAndShadow(): boolean {
|
||||
return this._scaleBorderAndShadow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to scale outline widths and shadow depths from script resolution to video resolution or not. If true, widths and depths are scaled.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
set scaleBorderAndShadow(value: boolean) {
|
||||
this._scaleBorderAndShadow = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
/**
|
||||
* 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 { valueOrDefault, BorderStyle } from "./misc";
|
||||
|
||||
import { parse } from "../parser/parse";
|
||||
|
||||
import { Color } from "../parts";
|
||||
|
||||
import { Map } from "../utility/map";
|
||||
|
||||
/**
|
||||
* This class represents a single global style declaration in a {@link libjass.ASS} script. The styles can be obtained via the {@link libjass.ASS.styles} property.
|
||||
*
|
||||
* @param {!Map.<string, string>} template The template object that contains the style's properties. It is a map of the string values read from the ASS file.
|
||||
* @param {string} template["Name"] The name of the style
|
||||
* @param {string} template["Italic"] -1 if the style is italicized
|
||||
* @param {string} template["Bold"] -1 if the style is bold
|
||||
* @param {string} template["Underline"] -1 if the style is underlined
|
||||
* @param {string} template["StrikeOut"] -1 if the style is struck-through
|
||||
* @param {string} template["Fontname"] The name of the font
|
||||
* @param {string} template["Fontsize"] The size of the font
|
||||
* @param {string} template["ScaleX"] The horizontal scaling of the font
|
||||
* @param {string} template["ScaleY"] The vertical scaling of the font
|
||||
* @param {string} template["Spacing"] The letter spacing of the font
|
||||
* @param {string} template["PrimaryColour"] The primary color
|
||||
* @param {string} template["OutlineColour"] The outline color
|
||||
* @param {string} template["BackColour"] The shadow color
|
||||
* @param {string} template["Outline"] The outline thickness
|
||||
* @param {string} template["Shadow"] The shadow depth
|
||||
* @param {string} template["Alignment"] The alignment number
|
||||
* @param {string} template["MarginL"] The left margin
|
||||
* @param {string} template["MarginR"] The right margin
|
||||
* @param {string} template["MarginV"] The vertical margin
|
||||
*/
|
||||
export class Style {
|
||||
private _name: string;
|
||||
|
||||
private _italic: boolean;
|
||||
private _bold: boolean;
|
||||
private _underline: boolean;
|
||||
private _strikeThrough: boolean;
|
||||
|
||||
private _fontName: string;
|
||||
private _fontSize: number;
|
||||
|
||||
private _fontScaleX: number;
|
||||
private _fontScaleY: number;
|
||||
|
||||
private _letterSpacing: number;
|
||||
|
||||
private _rotationZ: number;
|
||||
|
||||
private _primaryColor: Color;
|
||||
private _secondaryColor: Color;
|
||||
private _outlineColor: Color;
|
||||
private _shadowColor: Color;
|
||||
|
||||
private _outlineThickness: number;
|
||||
private _borderStyle: BorderStyle;
|
||||
|
||||
private _shadowDepth: number;
|
||||
|
||||
private _alignment: number;
|
||||
|
||||
private _marginLeft: number;
|
||||
private _marginRight: number;
|
||||
private _marginVertical: number;
|
||||
|
||||
constructor(template: Map<string, string>) {
|
||||
{
|
||||
const normalizedTemplate = new Map<string, string>();
|
||||
template.forEach((value, key) => {
|
||||
normalizedTemplate.set(key.toLowerCase(), value);
|
||||
});
|
||||
template = normalizedTemplate;
|
||||
}
|
||||
|
||||
this._name = template.get("name");
|
||||
if (this._name === undefined || this._name === null || this._name.constructor !== String) {
|
||||
throw new Error("Style doesn't have a name.");
|
||||
}
|
||||
this._name = this._name.replace(/^\*+/, "");
|
||||
|
||||
this._italic = !!valueOrDefault(template, "italic", parseFloat, value => !isNaN(value), "0");
|
||||
this._bold = !!valueOrDefault(template, "bold", parseFloat, value => !isNaN(value), "0");
|
||||
this._underline = !!valueOrDefault(template, "underline", parseFloat, value => !isNaN(value), "0");
|
||||
this._strikeThrough = !!valueOrDefault(template, "strikeout", parseFloat, value => !isNaN(value), "0");
|
||||
|
||||
this._fontName = valueOrDefault(template, "fontname", str => str, value => value.constructor === String, "sans-serif");
|
||||
this._fontSize = valueOrDefault(template, "fontsize", parseFloat, value => !isNaN(value), "18");
|
||||
|
||||
this._fontScaleX = valueOrDefault(template, "scalex", parseFloat, value => value >= 0, "100") / 100;
|
||||
this._fontScaleY = valueOrDefault(template, "scaley", parseFloat, value => value >= 0, "100") / 100;
|
||||
|
||||
this._letterSpacing = valueOrDefault(template, "spacing", parseFloat, value => value >= 0, "0");
|
||||
|
||||
this._rotationZ = valueOrDefault(template, "angle", parseFloat, value => !isNaN(value), "0");
|
||||
|
||||
this._primaryColor = valueOrDefault(template, "primarycolour", str => <Color>parse(str, "colorWithAlpha"), null, "&H00FFFFFF");
|
||||
this._secondaryColor = valueOrDefault(template, "secondarycolour", str => <Color>parse(str, "colorWithAlpha"), null, "&H00FFFF00");
|
||||
this._outlineColor = valueOrDefault(template, "outlinecolour", str => <Color>parse(str, "colorWithAlpha"), null, "&H00000000");
|
||||
this._shadowColor = valueOrDefault(template, "backcolour", str => <Color>parse(str, "colorWithAlpha"), null, "&H80000000");
|
||||
|
||||
this._outlineThickness = valueOrDefault(template, "outline", parseFloat, value => value >= 0, "2");
|
||||
this._borderStyle = valueOrDefault(template, "borderstyle", parseInt, value => (<any>BorderStyle)[(<any>BorderStyle)[value]] === value, "1");
|
||||
|
||||
this._shadowDepth = valueOrDefault(template, "shadow", parseFloat, value => value >= 0, "3");
|
||||
|
||||
this._alignment = valueOrDefault(template, "alignment", parseInt, value => value >= 1 && value <= 9, "2");
|
||||
|
||||
this._marginLeft = valueOrDefault(template, "marginl", parseFloat, value => !isNaN(value), "20");
|
||||
this._marginRight = valueOrDefault(template, "marginr", parseFloat, value => !isNaN(value), "20");
|
||||
this._marginVertical = valueOrDefault(template, "marginv", parseFloat, value => !isNaN(value), "20");
|
||||
}
|
||||
|
||||
/**
|
||||
* The name of this style.
|
||||
*
|
||||
* @type {string}
|
||||
*/
|
||||
get name(): string {
|
||||
return this._name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this style is italicized or not.
|
||||
*
|
||||
* @type {string}
|
||||
*/
|
||||
get italic(): boolean {
|
||||
return this._italic;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this style is bold or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
get bold(): boolean {
|
||||
return this._bold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this style is underlined or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
get underline(): boolean {
|
||||
return this._underline;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this style is struck-through or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
get strikeThrough(): boolean {
|
||||
return this._strikeThrough;
|
||||
}
|
||||
|
||||
/**
|
||||
* The name of this style's font.
|
||||
*
|
||||
* @type {string}
|
||||
*/
|
||||
get fontName(): string {
|
||||
return this._fontName;
|
||||
}
|
||||
|
||||
/**
|
||||
* The size of this style's font.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get fontSize(): number {
|
||||
return this._fontSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* The horizontal scaling of this style's font.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get fontScaleX(): number {
|
||||
return this._fontScaleX;
|
||||
}
|
||||
|
||||
/**
|
||||
* The vertical scaling of this style's font.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get fontScaleY(): number {
|
||||
return this._fontScaleY;
|
||||
}
|
||||
|
||||
/**
|
||||
* The letter spacing scaling of this style's font.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get letterSpacing(): number {
|
||||
return this._letterSpacing;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default Z-rotation of this style.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get rotationZ(): number {
|
||||
return this._rotationZ;
|
||||
}
|
||||
|
||||
/**
|
||||
* The color of this style's font.
|
||||
*
|
||||
* @type {!libjass.parts.Color}
|
||||
*/
|
||||
get primaryColor(): Color {
|
||||
return this._primaryColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* The alternate color of this style's font, used in karaoke.
|
||||
*
|
||||
* @type {!libjass.parts.Color}
|
||||
*/
|
||||
get secondaryColor(): Color {
|
||||
return this._secondaryColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* The color of this style's outline.
|
||||
*
|
||||
* @type {!libjass.parts.Color}
|
||||
*/
|
||||
get outlineColor(): Color {
|
||||
return this._outlineColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* The color of this style's shadow.
|
||||
*
|
||||
* @type {!libjass.parts.Color}
|
||||
*/
|
||||
get shadowColor(): Color {
|
||||
return this._shadowColor;
|
||||
}
|
||||
|
||||
/**
|
||||
* The thickness of this style's outline.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get outlineThickness(): number {
|
||||
return this._outlineThickness;
|
||||
}
|
||||
|
||||
/**
|
||||
* The border style of this style.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get borderStyle(): BorderStyle {
|
||||
return this._borderStyle;
|
||||
}
|
||||
|
||||
/**
|
||||
* The depth of this style's shadow.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get shadowDepth(): number {
|
||||
return this._shadowDepth;
|
||||
}
|
||||
|
||||
/**
|
||||
* The alignment of dialogues of this style.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get alignment(): number {
|
||||
return this._alignment;
|
||||
}
|
||||
|
||||
/**
|
||||
* The left margin of dialogues of this style.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get marginLeft(): number {
|
||||
return this._marginLeft;
|
||||
}
|
||||
|
||||
/**
|
||||
* The right margin of dialogues of this style.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get marginRight(): number {
|
||||
return this._marginRight;
|
||||
}
|
||||
|
||||
/**
|
||||
* The vertical margin of dialogues of this style.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
get marginVertical(): number {
|
||||
return this._marginVertical;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
declare const global: {
|
||||
Map?: typeof Map;
|
||||
};
|
||||
|
||||
export interface Map<K, V> {
|
||||
/**
|
||||
* @param {K} key
|
||||
* @return {V}
|
||||
*/
|
||||
get(key: K): V;
|
||||
|
||||
/**
|
||||
* @param {K} key
|
||||
* @return {boolean}
|
||||
*/
|
||||
has(key: K): boolean;
|
||||
|
||||
/**
|
||||
* @param {K} key
|
||||
* @param {V} value
|
||||
* @return {libjass.Map.<K, V>} This map
|
||||
*/
|
||||
set(key: K, value?: V): Map<K, V>;
|
||||
|
||||
/**
|
||||
* @param {K} key
|
||||
* @return {boolean} true if the key was present before being deleted, false otherwise
|
||||
*/
|
||||
delete(key: K): boolean;
|
||||
|
||||
/**
|
||||
*/
|
||||
clear(): void;
|
||||
|
||||
/**
|
||||
* @param {function(V, K, libjass.Map.<K, V>)} callbackfn A function that is called with each key and value in the map.
|
||||
* @param {*} thisArg
|
||||
*/
|
||||
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
size: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set to the global implementation of Map if the environment has one, else set to {@link ./utility/map.SimpleMap}
|
||||
*
|
||||
* Set it to null to force {@link ./utility/map.SimpleMap} to be used even if a global Map is present.
|
||||
*
|
||||
* @type {function(new:Map, !Array.<!Array.<*>>=)}
|
||||
*/
|
||||
export var Map: {
|
||||
new <K, V>(iterable?: [K, V][]): Map<K, V>;
|
||||
prototype: Map<any, any>;
|
||||
} = global.Map;
|
||||
|
||||
/**
|
||||
* Map implementation for browsers that don't support it. Only supports keys which are of Number or String type, or which have a property called "id".
|
||||
*
|
||||
* Keys and values are stored as properties of an object, with property names derived from the key type.
|
||||
*
|
||||
* @param {!Array.<!Array.<*>>=} iterable Only an array of elements (where each element is a 2-tuple of key and value) is supported.
|
||||
*/
|
||||
class SimpleMap<K, V> {
|
||||
private _keys: { [key: string]: K };
|
||||
private _values: { [key: string]: V };
|
||||
private _size: number;
|
||||
|
||||
constructor(iterable?: [K, V][]) {
|
||||
this.clear();
|
||||
|
||||
if (iterable === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Array.isArray(iterable)) {
|
||||
throw new Error("Non-array iterables are not supported by the SimpleMap constructor.");
|
||||
}
|
||||
|
||||
for (const element of iterable) {
|
||||
this.set(element[0], element[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {K} key
|
||||
* @return {V}
|
||||
*/
|
||||
get(key: K): V {
|
||||
const property = this._keyToProperty(key);
|
||||
|
||||
if (property === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return this._values[property];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {K} key
|
||||
* @return {boolean}
|
||||
*/
|
||||
has(key: K): boolean {
|
||||
const property = this._keyToProperty(key);
|
||||
|
||||
if (property === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return property in this._keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {K} key
|
||||
* @param {V} value
|
||||
* @return {libjass.Map.<K, V>} This map
|
||||
*/
|
||||
set(key: K, value: V): Map<K, V> {
|
||||
const property = this._keyToProperty(key);
|
||||
|
||||
if (property === null) {
|
||||
throw new Error("This Map implementation only supports Number and String keys, or keys with an id property.");
|
||||
}
|
||||
|
||||
if (!(property in this._keys)) {
|
||||
this._size++;
|
||||
}
|
||||
|
||||
this._keys[property] = key;
|
||||
this._values[property] = value;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {K} key
|
||||
* @return {boolean} true if the key was present before being deleted, false otherwise
|
||||
*/
|
||||
delete(key: K): boolean {
|
||||
const property = this._keyToProperty(key);
|
||||
|
||||
if (property === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const result = property in this._keys;
|
||||
|
||||
if (result) {
|
||||
delete this._keys[property];
|
||||
delete this._values[property];
|
||||
this._size--;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
*/
|
||||
clear(): void {
|
||||
this._keys = Object.create(null);
|
||||
this._values = Object.create(null);
|
||||
this._size = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {function(V, K, libjass.Map.<K, V>)} callbackfn A function that is called with each key and value in the map.
|
||||
* @param {*} thisArg
|
||||
*/
|
||||
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void {
|
||||
for (const property of Object.keys(this._keys)) {
|
||||
callbackfn.call(thisArg, this._values[property], this._keys[property], this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
get size(): number {
|
||||
return this._size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given key into a property name for the internal map.
|
||||
*
|
||||
* @param {K} key
|
||||
* @return {string}
|
||||
*/
|
||||
private _keyToProperty(key: K): string {
|
||||
if (typeof key === "number") {
|
||||
return `#${ key }`;
|
||||
}
|
||||
|
||||
if (typeof key === "string") {
|
||||
return `'${ key }`;
|
||||
}
|
||||
|
||||
if ((<any>key).id !== undefined) {
|
||||
return `!${ (<any>key).id }`;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (Map === undefined || typeof Map.prototype.forEach !== "function" || (() => {
|
||||
try {
|
||||
return new Map([[1, "foo"], [2, "bar"]]).size !== 2;
|
||||
}
|
||||
catch (ex) {
|
||||
return true;
|
||||
}
|
||||
})()) {
|
||||
Map = SimpleMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Map implementation used by libjass to the provided one. If null, {@link ./utility/map.SimpleMap} is used.
|
||||
*
|
||||
* @param {?function(new:Map, !Array.<!Array.<*>>=)} value
|
||||
*/
|
||||
export function setImplementation(value: typeof Map): void {
|
||||
if (value !== null) {
|
||||
Map = value;
|
||||
}
|
||||
else {
|
||||
Map = SimpleMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Adds properties of the given mixins' prototypes to the given class's prototype.
|
||||
*
|
||||
* @param {!*} clazz
|
||||
* @param {!Array.<*>} mixins
|
||||
*/
|
||||
export function mixin(clazz: any, mixins: any[]): void {
|
||||
for (const mixin of mixins) {
|
||||
for (const name of Object.getOwnPropertyNames(mixin.prototype)) {
|
||||
clazz.prototype[name] = mixin.prototype[name];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
declare const global: {
|
||||
Promise?: typeof Promise;
|
||||
MutationObserver?: typeof MutationObserver;
|
||||
WebkitMutationObserver?: typeof MutationObserver;
|
||||
process?: {
|
||||
nextTick(callback: () => void): void;
|
||||
}
|
||||
};
|
||||
|
||||
export interface Thenable<T> {
|
||||
/** @type {function(this:!Thenable.<T>, function(T|!Thenable.<T>), function(*))} */
|
||||
then: ThenableThen<T>;
|
||||
}
|
||||
|
||||
export interface ThenableThen<T> {
|
||||
/** @type {function(this:!Thenable.<T>, function(T|!Thenable.<T>), function(*))} */
|
||||
(resolve: (resolution: T | Thenable<T>) => void, reject: (reason: any) => void): void;
|
||||
}
|
||||
|
||||
export interface Promise<T> extends Thenable<T> {
|
||||
/**
|
||||
* @param {?function(T):!Thenable.<U>} onFulfilled
|
||||
* @param {?function(*):(U|!Thenable.<U>)} onRejected
|
||||
* @return {!Promise.<U>}
|
||||
*/
|
||||
then<U>(onFulfilled?: (value: T) => Thenable<U>, onRejected?: (reason: any) => U | Thenable<U>): Promise<U>;
|
||||
|
||||
/**
|
||||
* @param {?function(T):U} onFulfilled
|
||||
* @param {?function(*):(U|!Thenable.<U>)} onRejected
|
||||
* @return {!Promise.<U>}
|
||||
*/
|
||||
then<U>(onFulfilled?: (value: T) => U, onRejected?: (reason: any) => U | Thenable<U>): Promise<U>;
|
||||
|
||||
/**
|
||||
* @param {function(*):(T|!Thenable.<T>)} onRejected
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
catch(onRejected?: (reason: any) => T | Thenable<T>): Promise<T>
|
||||
}
|
||||
|
||||
/**
|
||||
* Set to the global implementation of Promise if the environment has one, else set to {@link ./utility/promise.SimplePromise}
|
||||
*
|
||||
* Set it to null to force {@link ./utility/promise.SimplePromise} to be used even if a global Promise is present.
|
||||
*
|
||||
* @type {function(new:Promise)}
|
||||
*/
|
||||
export var Promise: {
|
||||
new <T>(init: (resolve: (value: T | Thenable<T>) => void, reject: (reason: any) => void) => void): Promise<T>;
|
||||
prototype: Promise<any>;
|
||||
resolve<T>(value: T | Thenable<T>): Promise<T>;
|
||||
reject<T>(reason: any): Promise<T>;
|
||||
all<T>(values: (T | Thenable<T>)[]): Promise<T[]>;
|
||||
race<T>(values: (T | Thenable<T>)[]): Promise<T>;
|
||||
} = global.Promise;
|
||||
|
||||
// Based on https://github.com/petkaantonov/bluebird/blob/1b1467b95442c12378d0ea280ede61d640ab5510/src/schedule.js
|
||||
const enqueueJob: (callback: () => void) => void = (function () {
|
||||
const MutationObserver = global.MutationObserver || global.WebkitMutationObserver;
|
||||
if (global.process !== undefined && typeof global.process.nextTick === "function") {
|
||||
return (callback: () => void) => {
|
||||
global.process.nextTick(callback);
|
||||
};
|
||||
}
|
||||
else if (MutationObserver !== undefined) {
|
||||
const pending: (() => void)[] = [];
|
||||
let currentlyPending = false;
|
||||
|
||||
const div = document.createElement("div");
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
const processing = pending.splice(0, pending.length);
|
||||
|
||||
for (const callback of processing) {
|
||||
callback();
|
||||
}
|
||||
|
||||
currentlyPending = false;
|
||||
|
||||
if (pending.length > 0) {
|
||||
div.classList.toggle("foo");
|
||||
currentlyPending = true;
|
||||
}
|
||||
});
|
||||
|
||||
observer.observe(div, { attributes: true });
|
||||
|
||||
return (callback: () => void) => {
|
||||
pending.push(callback);
|
||||
|
||||
if (!currentlyPending) {
|
||||
div.classList.toggle("foo");
|
||||
currentlyPending = true;
|
||||
}
|
||||
};
|
||||
}
|
||||
else {
|
||||
return (callback: () => void) => setTimeout(callback, 0);
|
||||
}
|
||||
})();
|
||||
|
||||
/**
|
||||
* Promise implementation for browsers that don't support it.
|
||||
*
|
||||
* @param {function(function(T|!Thenable.<T>), function(*))} executor
|
||||
*/
|
||||
class SimplePromise<T> {
|
||||
private _state: SimplePromiseState = SimplePromiseState.PENDING;
|
||||
|
||||
private _fulfillReactions: FulfilledPromiseReaction<T, any>[] = [];
|
||||
private _rejectReactions: RejectedPromiseReaction<any>[] = [];
|
||||
|
||||
private _fulfilledValue: T = null;
|
||||
private _rejectedReason: any = null;
|
||||
|
||||
constructor(executor: (resolve: (resolution: T | Thenable<T>) => void, reject: (reason: any) => void) => void) {
|
||||
if (typeof executor !== "function") {
|
||||
throw new TypeError(`typeof executor !== "function"`);
|
||||
}
|
||||
|
||||
const { resolve, reject } = this._createResolvingFunctions();
|
||||
try {
|
||||
executor(resolve, reject);
|
||||
}
|
||||
catch (ex) {
|
||||
reject(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {?function(T):(U|!Thenable.<U>)} onFulfilled
|
||||
* @param {?function(*):(U|!Thenable.<U>)} onRejected
|
||||
* @return {!Promise.<U>}
|
||||
*/
|
||||
then<U>(onFulfilled: (value: T) => U | Thenable<U>, onRejected: (reason: any) => U | Thenable<U>): Promise<U> {
|
||||
const resultCapability = new DeferredPromise<U>();
|
||||
|
||||
if (typeof onFulfilled !== "function") {
|
||||
onFulfilled = (value: T) => <U><any>value;
|
||||
}
|
||||
|
||||
if (typeof onRejected !== "function") {
|
||||
onRejected = (reason: any): U => { throw reason; };
|
||||
}
|
||||
|
||||
const fulfillReaction: FulfilledPromiseReaction<T, U> = {
|
||||
capabilities: resultCapability,
|
||||
handler: onFulfilled,
|
||||
};
|
||||
|
||||
const rejectReaction: RejectedPromiseReaction<U> = {
|
||||
capabilities: resultCapability,
|
||||
handler: onRejected,
|
||||
};
|
||||
|
||||
switch (this._state) {
|
||||
case SimplePromiseState.PENDING:
|
||||
this._fulfillReactions.push(fulfillReaction);
|
||||
this._rejectReactions.push(rejectReaction);
|
||||
break;
|
||||
|
||||
case SimplePromiseState.FULFILLED:
|
||||
this._enqueueFulfilledReactionJob(fulfillReaction, this._fulfilledValue);
|
||||
break;
|
||||
|
||||
case SimplePromiseState.REJECTED:
|
||||
this._enqueueRejectedReactionJob(rejectReaction, this._rejectedReason);
|
||||
break;
|
||||
}
|
||||
|
||||
return resultCapability.promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {function(*):(T|!Thenable.<T>)} onRejected
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
catch(onRejected?: (reason: any) => T | Thenable<T>): Promise<T> {
|
||||
return this.then(null, onRejected);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {T|!Thenable.<T>} value
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
static resolve<T>(value: T | Thenable<T>): Promise<T> {
|
||||
if (value instanceof SimplePromise) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return new Promise<T>(resolve => resolve(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} reason
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
static reject<T>(reason: any): Promise<T> {
|
||||
return new Promise<T>((/* ujs:unreferenced */ resolve, reject) => reject(reason));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!Array.<T|!Thenable.<T>>} values
|
||||
* @return {!Promise.<!Array.<T>>}
|
||||
*/
|
||||
static all<T>(values: (T | Thenable<T>)[]): Promise<T[]> {
|
||||
return new Promise<T[]>((resolve, reject) => {
|
||||
const result: T[] = [];
|
||||
|
||||
let numUnresolved = values.length;
|
||||
if (numUnresolved === 0) {
|
||||
resolve(result);
|
||||
return;
|
||||
}
|
||||
|
||||
values.forEach((value, index) => Promise.resolve(value).then(value => {
|
||||
result[index] = value;
|
||||
numUnresolved--;
|
||||
|
||||
if (numUnresolved === 0) {
|
||||
resolve(result);
|
||||
}
|
||||
}, reject));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!Array.<T|!Thenable.<T>>} values
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
static race<T>(values: (T | Thenable<T>)[]): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
for (const value of values) {
|
||||
Promise.resolve(value).then(resolve, reject);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {{ resolve(T|!Thenable.<T>), reject(*) }}
|
||||
*/
|
||||
private _createResolvingFunctions(): { resolve(resolution: T | Thenable<T>): void; reject(reason: any): void; } {
|
||||
let alreadyResolved = false;
|
||||
|
||||
const resolve = (resolution: T | Thenable<T>): void => {
|
||||
if (alreadyResolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
alreadyResolved = true;
|
||||
|
||||
if (resolution === this) {
|
||||
this._reject(new TypeError(`resolution === this`));
|
||||
return;
|
||||
}
|
||||
|
||||
if (resolution === null || (typeof resolution !== "object" && typeof resolution !== "function")) {
|
||||
this._fulfill(<T>resolution);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
var then = (<Thenable<T>>resolution).then;
|
||||
}
|
||||
catch (ex) {
|
||||
this._reject(ex);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof then !== "function") {
|
||||
this._fulfill(<T>resolution);
|
||||
return;
|
||||
}
|
||||
|
||||
enqueueJob(() => this._resolveWithThenable(<Thenable<T>>resolution, then));
|
||||
};
|
||||
|
||||
const reject = (reason: any): void => {
|
||||
if (alreadyResolved) {
|
||||
return;
|
||||
}
|
||||
|
||||
alreadyResolved = true;
|
||||
|
||||
this._reject(reason);
|
||||
};
|
||||
|
||||
return { resolve, reject };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!Thenable.<T>} thenable
|
||||
* @param {{function(this:!Thenable.<T>, function(T|!Thenable.<T>), function(*))}} then
|
||||
*/
|
||||
private _resolveWithThenable(thenable: Thenable<T>, then: ThenableThen<T>): void {
|
||||
const { resolve, reject } = this._createResolvingFunctions();
|
||||
|
||||
try {
|
||||
then.call(thenable, resolve, reject);
|
||||
}
|
||||
catch (ex) {
|
||||
reject(ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {T} value
|
||||
*/
|
||||
private _fulfill(value: T): void {
|
||||
const reactions = this._fulfillReactions;
|
||||
|
||||
this._fulfilledValue = value;
|
||||
this._fulfillReactions = undefined;
|
||||
this._rejectReactions = undefined;
|
||||
this._state = SimplePromiseState.FULFILLED;
|
||||
|
||||
for (const reaction of reactions) {
|
||||
this._enqueueFulfilledReactionJob(reaction, value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} reason
|
||||
*/
|
||||
private _reject(reason: any): void {
|
||||
const reactions = this._rejectReactions;
|
||||
|
||||
this._rejectedReason = reason;
|
||||
this._fulfillReactions = undefined;
|
||||
this._rejectReactions = undefined;
|
||||
this._state = SimplePromiseState.REJECTED;
|
||||
|
||||
for (const reaction of reactions) {
|
||||
this._enqueueRejectedReactionJob(reaction, reason);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!FulfilledPromiseReaction.<T, *>} reaction
|
||||
* @param {T} value
|
||||
*/
|
||||
private _enqueueFulfilledReactionJob(reaction: FulfilledPromiseReaction<T, any>, value: T): void {
|
||||
enqueueJob(() => {
|
||||
const { capabilities: { resolve, reject }, handler } = reaction;
|
||||
|
||||
let handlerResult: any | Thenable<any>;
|
||||
|
||||
try {
|
||||
handlerResult = handler(value);
|
||||
}
|
||||
catch (ex) {
|
||||
reject(ex);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(handlerResult);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!RejectedPromiseReaction.<*>} reaction
|
||||
* @param {*} reason
|
||||
*/
|
||||
private _enqueueRejectedReactionJob(reaction: RejectedPromiseReaction<any>, reason: any): void {
|
||||
enqueueJob(() => {
|
||||
const { capabilities: { resolve, reject }, handler } = reaction;
|
||||
|
||||
let handlerResult: any | Thenable<any>;
|
||||
|
||||
try {
|
||||
handlerResult = handler(reason);
|
||||
}
|
||||
catch (ex) {
|
||||
reject(ex);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve(handlerResult);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (Promise === undefined) {
|
||||
Promise = SimplePromise;
|
||||
}
|
||||
|
||||
interface FulfilledPromiseReaction<T, U> {
|
||||
/** @type {!libjass.DeferredPromise.<U>} */
|
||||
capabilities: DeferredPromise<U>;
|
||||
|
||||
/**
|
||||
* @param {T} value
|
||||
* @return {U|!Thenable.<U>}
|
||||
*/
|
||||
handler(value: T): U | Thenable<U>;
|
||||
}
|
||||
|
||||
interface RejectedPromiseReaction<U> {
|
||||
/** @type {!libjass.DeferredPromise.<U>} */
|
||||
capabilities: DeferredPromise<U>;
|
||||
|
||||
/**
|
||||
* @param {*} reason
|
||||
* @return {U|!Thenable.<U>}
|
||||
*/
|
||||
handler(reason: any): U | Thenable<U>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The state of the {@link ./utility/promise.SimplePromise}
|
||||
*/
|
||||
enum SimplePromiseState {
|
||||
PENDING = 0,
|
||||
FULFILLED = 1,
|
||||
REJECTED = 2,
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Promise implementation used by libjass to the provided one. If null, {@link ./utility/promise.SimplePromise} is used.
|
||||
*
|
||||
* @param {?function(new:Promise)} value
|
||||
*/
|
||||
export function setImplementation(value: typeof Promise): void {
|
||||
if (value !== null) {
|
||||
Promise = value;
|
||||
}
|
||||
else {
|
||||
Promise = SimplePromise;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A deferred promise.
|
||||
*/
|
||||
export class DeferredPromise<T> {
|
||||
private _promise: Promise<T>;
|
||||
|
||||
/**
|
||||
* @type {function(T|!Thenable.<T>)}
|
||||
*/
|
||||
resolve: (value: T | Thenable<T>) => void;
|
||||
|
||||
/**
|
||||
* @type {function(*)} reason
|
||||
*/
|
||||
reject: (reason: any) => void;
|
||||
|
||||
constructor() {
|
||||
this._promise = new Promise<T>((resolve, reject) => {
|
||||
Object.defineProperties(this, {
|
||||
resolve: { value: resolve, enumerable: true },
|
||||
reject: { value: reject, enumerable: true },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {!Promise.<T>}
|
||||
*/
|
||||
get promise(): Promise<T> {
|
||||
return this._promise;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a promise that resolves to the first (in iteration order) promise that fulfills, and rejects if all the promises reject.
|
||||
*
|
||||
* @param {!Array.<!Promise.<T>>} promises
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
export function first<T>(promises: Promise<T>[]): Promise<T> {
|
||||
return first_rec(promises, []);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!Array.<!Promise.<T>>} promises
|
||||
* @param {!Array.<*>} previousRejections
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
function first_rec<T>(promises: Promise<T>[], previousRejections: any[]): Promise<T> {
|
||||
if (promises.length === 0) {
|
||||
return Promise.reject(previousRejections);
|
||||
}
|
||||
|
||||
const [head, ...tail] = promises;
|
||||
return head.catch(reason => first_rec(tail, previousRejections.concat(reason)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a promise that resolves to the first (in time order) promise that fulfills, and rejects if all the promises reject.
|
||||
*
|
||||
* @param {!Array.<!Promise.<T>>} promises
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
export function any<T>(promises: Promise<T>[]): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) =>
|
||||
Promise.all<any>(promises.map(promise => promise.then(resolve, reason => reason))).then(reject));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a promise that runs the given callback when the promise has resolved regardless of whether it fulfilled or rejected.
|
||||
*
|
||||
* @param {!Promise.<T>} promise
|
||||
* @param {function()} body
|
||||
* @return {!Promise.<T>}
|
||||
*/
|
||||
export function lastly<T>(promise: Promise<T>, body: () => void): Promise<T> {
|
||||
return promise.then<any>(value => {
|
||||
body();
|
||||
return value;
|
||||
}, reason => {
|
||||
body();
|
||||
throw reason;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
declare const global: {
|
||||
Set?: typeof Set;
|
||||
};
|
||||
|
||||
export interface Set<T> {
|
||||
/**
|
||||
* @param {T} value
|
||||
* @return {libjass.Set.<T>} This set
|
||||
*/
|
||||
add(value: T): Set<T>;
|
||||
|
||||
/**
|
||||
*/
|
||||
clear(): void;
|
||||
|
||||
/**
|
||||
* @param {T} value
|
||||
* @return {boolean}
|
||||
*/
|
||||
has(value: T): boolean;
|
||||
|
||||
/**
|
||||
* @param {function(T, T, libjass.Set.<T>)} callbackfn A function that is called with each value in the set.
|
||||
* @param {*} thisArg
|
||||
*/
|
||||
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
size: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set to the global implementation of Set if the environment has one, else set to {@link ./utility/set.SimpleSet}
|
||||
*
|
||||
* Set it to null to force {@link ./utility/set.SimpleSet} to be used even if a global Set is present.
|
||||
*
|
||||
* @type {function(new:Set, !Array.<T>=)}
|
||||
*/
|
||||
export var Set: {
|
||||
new <T>(iterable?: T[]): Set<T>;
|
||||
prototype: Set<any>;
|
||||
} = global.Set;
|
||||
|
||||
/**
|
||||
* Set implementation for browsers that don't support it. Only supports Number and String elements.
|
||||
*
|
||||
* Elements are stored as properties of an object, with names derived from their type.
|
||||
*
|
||||
* @param {!Array.<T>=} iterable Only an array of values is supported.
|
||||
*/
|
||||
class SimpleSet<T> {
|
||||
private _elements: { [key: string]: T };
|
||||
private _size: number;
|
||||
|
||||
constructor(iterable?: T[]) {
|
||||
this.clear();
|
||||
|
||||
if (iterable === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Array.isArray(iterable)) {
|
||||
throw new Error("Non-array iterables are not supported by the SimpleSet constructor.");
|
||||
}
|
||||
|
||||
for (const value of iterable) {
|
||||
this.add(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {T} value
|
||||
* @return {libjass.Set.<T>} This set
|
||||
*/
|
||||
add(value: T): Set<T> {
|
||||
const property = this._toProperty(value);
|
||||
|
||||
if (property === null) {
|
||||
throw new Error("This Set implementation only supports Number and String values.");
|
||||
}
|
||||
|
||||
if (!(property in this._elements)) {
|
||||
this._size++;
|
||||
}
|
||||
|
||||
this._elements[property] = value;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
*/
|
||||
clear(): void {
|
||||
this._elements = Object.create(null);
|
||||
this._size = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {T} value
|
||||
* @return {boolean}
|
||||
*/
|
||||
has(value: T): boolean {
|
||||
const property = this._toProperty(value);
|
||||
|
||||
if (property === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return property in this._elements;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {function(T, T, libjass.Set.<T>)} callbackfn A function that is called with each value in the set.
|
||||
* @param {*} thisArg
|
||||
*/
|
||||
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void {
|
||||
for (const property of Object.keys(this._elements)) {
|
||||
const element = this._elements[property];
|
||||
callbackfn.call(thisArg, element, element, this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
get size(): number {
|
||||
return this._size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the given value into a property name for the internal map.
|
||||
*
|
||||
* @param {T} value
|
||||
* @return {string}
|
||||
*/
|
||||
private _toProperty(value: T): string {
|
||||
if (typeof value === "number") {
|
||||
return `#${ value }`;
|
||||
}
|
||||
|
||||
if (typeof value === "string") {
|
||||
return `'${ value }`;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (Set === undefined || typeof Set.prototype.forEach !== "function" || (() => {
|
||||
try {
|
||||
return new Set([1, 2]).size !== 2;
|
||||
}
|
||||
catch (ex) {
|
||||
return true;
|
||||
}
|
||||
})()) {
|
||||
Set = SimpleSet;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the Set implementation used by libjass to the provided one. If null, {@link ./utility/set.SimpleSet} is used.
|
||||
*
|
||||
* @param {?function(new:Set, !Array.<T>=)} value
|
||||
*/
|
||||
export function setImplementation(value: typeof Set): void {
|
||||
if (value !== null) {
|
||||
Set = value;
|
||||
}
|
||||
else {
|
||||
Set = SimpleSet;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Class inheritance shim.
|
||||
*
|
||||
* @param {!Function} derived
|
||||
* @param {!Function} base
|
||||
*/
|
||||
export function __extends(derived: any, base: any): void {
|
||||
for (const property in base) {
|
||||
if (base.hasOwnProperty(property)) {
|
||||
derived[property] = base[property];
|
||||
}
|
||||
}
|
||||
|
||||
function __() {
|
||||
this.constructor = derived;
|
||||
}
|
||||
|
||||
__.prototype = base.prototype;
|
||||
|
||||
derived.prototype = new (<any>__)();
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorator shim.
|
||||
*
|
||||
* @param {!Array.<!Function>} decorators
|
||||
* @param {!*} target
|
||||
* @param {string=} key
|
||||
* @return {*}
|
||||
*/
|
||||
export function __decorate(decorators: Function[], target: any, key?: string): any {
|
||||
if (arguments.length < 3) {
|
||||
return decorateClass(<any>decorators.reverse(), target);
|
||||
}
|
||||
else {
|
||||
decorateField(<any>decorators.reverse(), target, key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Class decorator shim.
|
||||
*
|
||||
* @param {!Array.<function(function(new(): T)): function(new(): T)>} decorators
|
||||
* @param {function(new(): T)} clazz
|
||||
* @return {function(new(): T)}
|
||||
*/
|
||||
function decorateClass<T>(decorators: ((clazz: { new (...args: any[]): T }) => { new (...args: any[]): T })[], clazz: { new (...args: any[]): T }): { new (...args: any[]): T } {
|
||||
for (const decorator of decorators) {
|
||||
clazz = decorator(clazz) || clazz;
|
||||
}
|
||||
|
||||
return clazz;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class member decorator shim.
|
||||
*
|
||||
* @param {!Array.<function(T, string)>} decorators
|
||||
* @param {!T} proto
|
||||
* @param {string} name
|
||||
*/
|
||||
function decorateField<T>(decorators: ((proto: T, name: string) => void)[], proto: T, name: string): void {
|
||||
for (const decorator of decorators) {
|
||||
decorator(proto, name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* 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 { Map } from "../utility/map";
|
||||
|
||||
import { Promise, DeferredPromise } from "../utility/promise";
|
||||
|
||||
import { WorkerCommands } from "./commands";
|
||||
|
||||
import { getWorkerCommandHandler, serialize, deserialize, registerWorkerCommand } from "./misc";
|
||||
|
||||
/**
|
||||
* Represents a communication channel between the host and the web worker. An instance of this class is created by calling {@link libjass.webworker.createWorker}
|
||||
*/
|
||||
export interface WorkerChannel {
|
||||
/**
|
||||
* Sends a request to the other side to execute the given command with the given parameters.
|
||||
*
|
||||
* @param {number} command
|
||||
* @param {*} parameters
|
||||
* @return {!Promise.<*>} A promise that will get resolved when the other side computes the result
|
||||
*/
|
||||
request(command: WorkerCommands, parameters: any): Promise<any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The signature of a handler registered to handle a particular command in {@link libjass.webworker.WorkerCommands}
|
||||
*/
|
||||
export interface WorkerCommandHandler {
|
||||
(parameters: any): Promise<any>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface implemented by a communication channel to the other side.
|
||||
*/
|
||||
interface WorkerCommunication {
|
||||
/**
|
||||
* @param {"message"} type
|
||||
* @param {function(!MessageEvent): *} listener
|
||||
* @param {?boolean} useCapture
|
||||
*/
|
||||
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
|
||||
|
||||
/**
|
||||
* @param {string} type
|
||||
* @param {!EventListener} listener
|
||||
* @param {?boolean} useCapture
|
||||
*/
|
||||
addEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
|
||||
|
||||
/**
|
||||
* @param {*} message
|
||||
*/
|
||||
postMessage(message: any): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface implemented by a request sent to the other side of the communication channel.
|
||||
*/
|
||||
interface WorkerRequestMessage {
|
||||
/**
|
||||
* An internal identifier for this request. Used to connect responses to their corresponding requests.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
requestId: number;
|
||||
|
||||
/**
|
||||
* The command type of this request.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
command: WorkerCommands;
|
||||
|
||||
/**
|
||||
* Any parameters serialized with this request.
|
||||
*
|
||||
* @type {*}
|
||||
*/
|
||||
parameters: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface implemented by a response received from the other side of the communication channel.
|
||||
*/
|
||||
interface WorkerResponseMessage {
|
||||
/**
|
||||
* An internal identifier for this response. Used to connect responses to their corresponding requests.
|
||||
*
|
||||
* @type {number}
|
||||
*/
|
||||
requestId: number;
|
||||
|
||||
/**
|
||||
* Set if the computation of this response resulted in an error.
|
||||
*
|
||||
* @type {*}
|
||||
*/
|
||||
error: any;
|
||||
|
||||
/**
|
||||
* The result of computing this response.
|
||||
*
|
||||
* @type {*}
|
||||
*/
|
||||
result: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal implementation of libjass.webworker.WorkerChannel
|
||||
*
|
||||
* @param {!*} comm The object used to talk to the other side of the channel. When created by the main thread, this is the Worker object.
|
||||
* When created by the web worker, this is its global object.
|
||||
*/
|
||||
export class WorkerChannelImpl implements WorkerChannel {
|
||||
private static _lastRequestId: number = -1;
|
||||
|
||||
private _pendingRequests = new Map<number, DeferredPromise<any>>();
|
||||
|
||||
constructor(private _comm: WorkerCommunication) {
|
||||
this._comm.addEventListener("message", ev => this._onMessage(<string>ev.data), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} command
|
||||
* @param {*} parameters
|
||||
* @return {!Promise.<*>}
|
||||
*/
|
||||
request(command: WorkerCommands, parameters: any): Promise<any> {
|
||||
const deferred = new DeferredPromise<any>();
|
||||
const requestId = ++WorkerChannelImpl._lastRequestId;
|
||||
this._pendingRequests.set(requestId, deferred);
|
||||
|
||||
const requestMessage: WorkerRequestMessage = { requestId, command, parameters };
|
||||
this._comm.postMessage(serialize(requestMessage));
|
||||
|
||||
return deferred.promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} requestId
|
||||
*/
|
||||
cancelRequest(requestId: number): void {
|
||||
const deferred = this._pendingRequests.get(requestId);
|
||||
if (deferred === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._pendingRequests.delete(requestId);
|
||||
deferred.reject(new Error("Cancelled."));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {!WorkerResponseMessage} message
|
||||
*/
|
||||
private _respond(message: WorkerResponseMessage): void {
|
||||
let { requestId, error, result } = message;
|
||||
if (error instanceof Error) {
|
||||
error = { message: error.message, stack: error.stack };
|
||||
}
|
||||
this._comm.postMessage(serialize({ command: WorkerCommands.Response, requestId, error, result }));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} rawMessage
|
||||
*/
|
||||
private _onMessage(rawMessage: string): void {
|
||||
const message = <{ command: WorkerCommands }>deserialize(rawMessage);
|
||||
|
||||
if (message.command === WorkerCommands.Response) {
|
||||
const responseMessage = <WorkerResponseMessage><any>message;
|
||||
|
||||
const deferred = this._pendingRequests.get(responseMessage.requestId);
|
||||
if (deferred !== undefined) {
|
||||
this._pendingRequests.delete(responseMessage.requestId);
|
||||
if (responseMessage.error === null) {
|
||||
deferred.resolve(responseMessage.result);
|
||||
}
|
||||
else {
|
||||
deferred.reject(responseMessage.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
const requestMessage = <WorkerRequestMessage>message;
|
||||
const requestId = requestMessage.requestId;
|
||||
|
||||
const commandCallback = getWorkerCommandHandler(requestMessage.command);
|
||||
if (commandCallback === undefined) {
|
||||
this._respond({ requestId, error: new Error(`No handler registered for command ${ requestMessage.command }`), result: null });
|
||||
return;
|
||||
}
|
||||
|
||||
commandCallback(requestMessage.parameters).then<WorkerResponseMessage>(
|
||||
result => ({ requestId, error: null, result }),
|
||||
error => ({ requestId, error, result: null })
|
||||
).then(responseMessage => this._respond(responseMessage));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerWorkerCommand(WorkerCommands.Ping, parameters => new Promise<void>(resolve => resolve(null)));
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* 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 commands that can be sent to or from a web worker.
|
||||
*/
|
||||
export enum WorkerCommands {
|
||||
Response = 0,
|
||||
Parse = 1,
|
||||
Ping = 2,
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 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 { Map } from "../utility/map";
|
||||
|
||||
import { Promise, DeferredPromise } from "../utility/promise";
|
||||
|
||||
import { WorkerChannel, WorkerChannelImpl } from "./channel";
|
||||
export { WorkerChannel } from "./channel";
|
||||
|
||||
export { WorkerCommands } from "./commands";
|
||||
|
||||
declare const exports: any;
|
||||
|
||||
/**
|
||||
* Indicates whether web workers are supposed in this environment or not.
|
||||
*
|
||||
* @type {boolean}
|
||||
*/
|
||||
export const supported = typeof Worker !== "undefined";
|
||||
|
||||
const _scriptNode = (typeof document !== "undefined" && document.currentScript !== undefined) ? document.currentScript : null;
|
||||
|
||||
/**
|
||||
* Create a new web worker and returns a {@link libjass.webworker.WorkerChannel} to it.
|
||||
*
|
||||
* @param {string=} scriptPath The path to libjass.js to be loaded in the web worker. If the browser supports document.currentScript, the parameter is optional and, if not provided,
|
||||
* the path will be determined from the src attribute of the <script> element that contains the currently running copy of libjass.js
|
||||
* @return {!libjass.webworker.WorkerChannel} A communication channel to the new web worker.
|
||||
*/
|
||||
export function createWorker(scriptPath: string = _scriptNode.src): WorkerChannel {
|
||||
return new WorkerChannelImpl(new Worker(scriptPath));
|
||||
}
|
||||
|
||||
declare const global: any;
|
||||
|
||||
if (typeof WorkerGlobalScope !== "undefined" && global instanceof WorkerGlobalScope) {
|
||||
// This is a web worker. Set up a channel to talk back to the main thread.
|
||||
new WorkerChannelImpl(global);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* 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 { Map } from "../utility/map";
|
||||
|
||||
import { WorkerCommands } from "./commands";
|
||||
import { WorkerCommandHandler } from "./channel";
|
||||
|
||||
const workerCommands = new Map<WorkerCommands, WorkerCommandHandler>();
|
||||
|
||||
const classPrototypes = new Map<number, any>();
|
||||
|
||||
/**
|
||||
* Registers a handler for the given worker command.
|
||||
*
|
||||
* @param {number} command The command that this handler will handle. One of the {@link libjass.webworker.WorkerCommands} constants.
|
||||
* @param {function(*, function(*, *))} handler The handler. A function of the form (parameters: *, response: function(error: *, result: *): void): void
|
||||
*/
|
||||
export function registerWorkerCommand(command: WorkerCommands, handler: WorkerCommandHandler): void {
|
||||
workerCommands.set(command, handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the handler for the given worker command.
|
||||
*
|
||||
* @param {number} command
|
||||
* @return {?function(*, function(*, *))}
|
||||
*/
|
||||
export function getWorkerCommandHandler(command: WorkerCommands): WorkerCommandHandler {
|
||||
return workerCommands.get(command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a prototype as a deserializable type.
|
||||
*
|
||||
* @param {!*} prototype
|
||||
*/
|
||||
export function registerClassPrototype(prototype: any): void {
|
||||
prototype._classTag = classPrototypes.size;
|
||||
classPrototypes.set(prototype._classTag, prototype);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} obj
|
||||
* @return {string}
|
||||
*/
|
||||
export function serialize(obj: any): string {
|
||||
return JSON.stringify(obj, (/* ujs:unreferenced */ key: string, value: any) => {
|
||||
if (value && value._classTag !== undefined) {
|
||||
value._classTag = value._classTag;
|
||||
}
|
||||
|
||||
return value;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} str
|
||||
* @return {*}
|
||||
*/
|
||||
export function deserialize(str: string): any {
|
||||
return JSON.parse(str, (/* ujs:unreferenced */ key: string, value: any) => {
|
||||
if (value && value._classTag !== undefined) {
|
||||
const hydratedValue = Object.create(classPrototypes.get(value._classTag));
|
||||
for (const key of Object.keys(value)) {
|
||||
if (key !== "_classTag") {
|
||||
hydratedValue[key] = value[key];
|
||||
}
|
||||
}
|
||||
value = hydratedValue;
|
||||
}
|
||||
|
||||
return value;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* 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 Document {
|
||||
/**
|
||||
* @type {!HTMLScriptElement}
|
||||
*/
|
||||
currentScript: HTMLScriptElement;
|
||||
}
|
||||
|
||||
interface WorkerGlobalScope {
|
||||
/**
|
||||
* @param {*} message
|
||||
*/
|
||||
postMessage(message: any): void;
|
||||
|
||||
/**
|
||||
* @param {string} type
|
||||
* @param {function(*)} listener
|
||||
* @param {boolean} useCapture
|
||||
*/
|
||||
addEventListener(type: string, listener: (message: any) => void, useCapture: boolean): void;
|
||||
}
|
||||
declare var WorkerGlobalScope: {
|
||||
prototype: WorkerGlobalScope;
|
||||
new (): WorkerGlobalScope;
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
define(["intern!tdd", "intern/chai!assert", "intern/dojo/node!fs", "intern/dojo/node!path", "intern/dojo/node!sax"], function (tdd, assert, fs, path, sax) {
|
||||
tdd.suite("Documentation tests", function () {
|
||||
var ids = [];
|
||||
var hrefs = [];
|
||||
|
||||
tdd.before(function () {
|
||||
var parser = sax.parser(true);
|
||||
|
||||
parser.onopentag = function (node) {
|
||||
if (node.name === "a" && node.attributes.href[0] === "#") {
|
||||
hrefs.push(node.attributes.href.substr(1));
|
||||
}
|
||||
|
||||
if (node.attributes.id !== undefined) {
|
||||
ids.push(node.attributes.id);
|
||||
}
|
||||
};
|
||||
|
||||
parser.onerror = function (error) { throw error; };
|
||||
|
||||
parser.write(fs.readFileSync(require.toUrl("../libjass-gh-pages/api.xhtml"), { encoding: "utf8" })).close();
|
||||
});
|
||||
|
||||
tdd.test("api.xhtml", function () {
|
||||
var brokenLinks = hrefs.filter(function (href) {
|
||||
return ids.indexOf(href) === -1;
|
||||
});
|
||||
|
||||
assert.equal(brokenLinks.length, 0, "Broken link(s): " + brokenLinks.map(function (href) { return '"' + href + '"'; }).join(", "));
|
||||
});
|
||||
|
||||
tdd.test("README.md", function () {
|
||||
var regex = /\[[^\]]+\]\(http:\/\/arnavion\.github\.io\/libjass\/api\.xhtml#([^)]+)\)/g;
|
||||
var brokenLinks = [];
|
||||
|
||||
var readme = fs.readFileSync(require.toUrl("./README.md"), { encoding: "utf8" });
|
||||
|
||||
var match;
|
||||
while ((match = regex.exec(readme)) !== null) {
|
||||
if (ids.indexOf(match[1]) === -1) {
|
||||
brokenLinks.push(match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
assert.equal(brokenLinks.length, 0, "Broken link(s): " + brokenLinks.map(function (href) { return '"' + href + '"'; }).join(", "));
|
||||
});
|
||||
|
||||
tdd.test("{@link} tags in the source", function () {
|
||||
var regex = /\{@link ([^}]+)\}/g;
|
||||
var brokenLinks = [];
|
||||
|
||||
var libjassJs = fs.readFileSync(require.toUrl("./lib/libjass.js"), { encoding: "utf8" });
|
||||
|
||||
var match;
|
||||
while ((match = regex.exec(libjassJs)) !== null) {
|
||||
if (ids.indexOf(match[1]) === -1) {
|
||||
brokenLinks.push(match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
assert.equal(brokenLinks.length, 0, "Broken link(s): " + brokenLinks.map(function (href) { return '"' + href + '"'; }).join(", "));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
[Script Info]
|
||||
Title:
|
||||
ScriptType: v4.00+
|
||||
WrapStyle: 0
|
||||
PlayResX: 256
|
||||
PlayResY: 144
|
||||
Scroll Position: 0
|
||||
Active Line: 0
|
||||
Video Zoom Percent: 1
|
||||
ScaledBorderAndShadow: yes
|
||||
|
||||
[V4+ Styles]
|
||||
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
||||
Style: Default,Arial,100,&H7F0000FF,&H00FFFFFF,&H7F000000,&H7F000000,0,0,0,0,100,100,0,0,1,2,0,2,15,15,15,1
|
||||
|
||||
[Events]
|
||||
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
Dialogue: 0,0:00:00.00,0:10:00.00,Default,,0,0,0,,X
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
define(["intern!tdd", "require", "tests/support/test-page"], function (tdd, require, TestPage) {
|
||||
tdd.suite("alpha", function () {
|
||||
tdd.test("Basic", function () {
|
||||
var testPage = new TestPage(this.remote, require.toUrl("tests/support/browser-test-page.html"), "/tests/functional/alpha/alpha.ass", 256, 144, "rgb(47, 163, 254)");
|
||||
return testPage
|
||||
.prepare()
|
||||
.then(function (testPage) { return testPage.seekAndCompareScreenshot(1, require.toUrl("./alpha-1.png")); });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
define(["intern!tdd", "intern/chai!assert", "require", "intern/dojo/node!leadfoot/helpers/pollUntil"], function (tdd, assert, require, pollUntil) {
|
||||
tdd.suite("Auto clock", function () {
|
||||
tdd.test("Operations", function () {
|
||||
this.remote.session.setExecuteAsyncTimeout(10000);
|
||||
|
||||
return this.remote
|
||||
.get(require.toUrl("tests/support/browser-test-page.html"))
|
||||
.then(pollUntil('return (document.readyState === "complete") ? true : null;', 100))
|
||||
.execute(function () {
|
||||
window.driverStartTime = 0;
|
||||
window.driverStartTimeAt = new Date();
|
||||
window.driver = function () {
|
||||
return (new Date() - driverStartTimeAt) / 1000 + driverStartTime;
|
||||
};
|
||||
|
||||
window.clock = new libjass.renderers.AutoClock(driver);
|
||||
|
||||
window.events = [];
|
||||
|
||||
clock.addEventListener(libjass.renderers.ClockEvent.Play, function () {
|
||||
events.push("play");
|
||||
});
|
||||
|
||||
clock.addEventListener(libjass.renderers.ClockEvent.Tick, function () {
|
||||
events.push("tick");
|
||||
});
|
||||
|
||||
clock.addEventListener(libjass.renderers.ClockEvent.Pause, function () {
|
||||
events.push("pause");
|
||||
});
|
||||
|
||||
clock.addEventListener(libjass.renderers.ClockEvent.Stop, function () {
|
||||
events.push("stop");
|
||||
});
|
||||
|
||||
return { enabled: clock.enabled, paused: clock.paused, rate: clock.rate, events: events.slice() };
|
||||
})
|
||||
.then(function (clock) {
|
||||
assert.strictEqual(clock.enabled, true);
|
||||
assert.strictEqual(clock.paused, true);
|
||||
assert.strictEqual(clock.rate, 1);
|
||||
assert.deepEqual(clock.events, []);
|
||||
})
|
||||
.executeAsync(function (callback) {
|
||||
clock.play();
|
||||
|
||||
setTimeout(function () {
|
||||
callback({ enabled: clock.enabled, paused: clock.paused, events: events.slice() });
|
||||
}, 1000);
|
||||
})
|
||||
.then(function (clock) {
|
||||
assert.strictEqual(clock.enabled, true);
|
||||
assert.strictEqual(clock.paused, false);
|
||||
|
||||
assert(clock.events.length >= 2);
|
||||
assert.strictEqual(clock.events[0], "play");
|
||||
for (var i = 1; i < clock.events.length; i++) {
|
||||
assert.strictEqual(clock.events[i], "tick");
|
||||
}
|
||||
})
|
||||
.execute(function () {
|
||||
events = [];
|
||||
|
||||
clock.disable();
|
||||
|
||||
return { enabled: clock.enabled, paused: clock.paused, events: events.slice() };
|
||||
})
|
||||
.then(function (clock) {
|
||||
assert.strictEqual(clock.enabled, false);
|
||||
assert.strictEqual(clock.paused, true);
|
||||
assert.deepEqual(clock.events, ["pause", "stop"]);
|
||||
})
|
||||
.execute(function () {
|
||||
events = [];
|
||||
|
||||
clock.enable();
|
||||
|
||||
return { enabled: clock.enabled, paused: clock.paused, events: events.slice() };
|
||||
})
|
||||
.then(function (clock) {
|
||||
assert.strictEqual(clock.enabled, true);
|
||||
assert.strictEqual(clock.paused, true);
|
||||
assert.deepEqual(clock.events, []);
|
||||
})
|
||||
.executeAsync(function (callback) {
|
||||
setTimeout(function () {
|
||||
callback({ enabled: clock.enabled, paused: clock.paused, events: events.slice() });
|
||||
}, 1000);
|
||||
})
|
||||
.then(function (clock) {
|
||||
assert.strictEqual(clock.enabled, true);
|
||||
assert.strictEqual(clock.paused, false);
|
||||
|
||||
assert(clock.events.length >= 2);
|
||||
assert.strictEqual(clock.events[0], "play");
|
||||
for (var i = 1; i < clock.events.length; i++) {
|
||||
assert.strictEqual(clock.events[i], "tick");
|
||||
}
|
||||
})
|
||||
.execute(function () {
|
||||
events = [];
|
||||
|
||||
driverStartTime = 30000;
|
||||
clock.seeking();
|
||||
|
||||
var result = { enabled: clock.enabled, paused: clock.paused, currentTime: clock.currentTime, events: events.slice() };
|
||||
events = [];
|
||||
return result;
|
||||
})
|
||||
.then(function (clock) {
|
||||
assert.strictEqual(clock.enabled, true);
|
||||
assert.strictEqual(clock.paused, true);
|
||||
assert(clock.currentTime >= 30);
|
||||
assert.deepEqual(clock.events, ["pause", "stop", "play", "tick", "pause"]);
|
||||
})
|
||||
.executeAsync(function (callback) {
|
||||
setTimeout(function () {
|
||||
callback({ enabled: clock.enabled, paused: clock.paused, currentTime: clock.currentTime, events: events.slice() });
|
||||
}, 1000);
|
||||
})
|
||||
.then(function (clock) {
|
||||
assert.strictEqual(clock.enabled, true);
|
||||
assert.strictEqual(clock.paused, false);
|
||||
assert(clock.currentTime >= 31);
|
||||
|
||||
assert(clock.events.length >= 2);
|
||||
assert.strictEqual(clock.events[0], "play");
|
||||
for (var i = 1; i < clock.events.length; i++) {
|
||||
assert.strictEqual(clock.events[i], "tick");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
After Width: | Height: | Size: 8.9 KiB |
|
After Width: | Height: | Size: 7.4 KiB |
@@ -0,0 +1,18 @@
|
||||
[Script Info]
|
||||
Title:
|
||||
ScriptType: v4.00+
|
||||
WrapStyle: 0
|
||||
PlayResX: 256
|
||||
PlayResY: 144
|
||||
Scroll Position: 0
|
||||
Active Line: 0
|
||||
Video Zoom Percent: 1
|
||||
ScaledBorderAndShadow: yes
|
||||
|
||||
[V4+ Styles]
|
||||
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
||||
Style: Default,Arial,36,&H000000FF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,1.2,2,15,15,15,1
|
||||
|
||||
[Events]
|
||||
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
Dialogue: 0,0:00:00.00,0:10:00.00,Default,,0,0,0,,xxx{\fscx50}xxx{\fscx\fscy50}xxx{\fscx50\fscy50}xxx
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
define(["intern!tdd", "require", "tests/support/test-page"], function (tdd, require, TestPage) {
|
||||
tdd.suite("fscx and fscy", function () {
|
||||
tdd.test("Basic", function () {
|
||||
var testPage = new TestPage(this.remote, require.toUrl("tests/support/browser-test-page.html"), "/tests/functional/fsc/fsc.ass", 256, 144);
|
||||
return testPage
|
||||
.prepare()
|
||||
.then(function (testPage) { return testPage.seekAndCompareScreenshot(1, require.toUrl("./fsc-1.png")); });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.2 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 2.9 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 3.5 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 3.7 KiB |
@@ -0,0 +1,18 @@
|
||||
[Script Info]
|
||||
; Script generated by Aegisub 3.2.2
|
||||
; http://www.aegisub.org/
|
||||
Title: Default Aegisub file
|
||||
ScriptType: v4.00+
|
||||
WrapStyle: 0
|
||||
ScaledBorderAndShadow: yes
|
||||
YCbCr Matrix: None
|
||||
PlayResX: 256
|
||||
PlayResY: 144
|
||||
|
||||
[V4+ Styles]
|
||||
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
||||
Style: Default,Arial,36,&H00FFFFFF,&H000000FF,&H00000000,&H96000000,0,0,0,0,100,100,0,0,1,2,1.2,2,15,15,15,1
|
||||
|
||||
[Events]
|
||||
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
||||
Dialogue: 0,0:00:01.00,0:00:07.00,Default,,0,0,0,,{\k100}{\k200}a{\k100}bc{\k200}d
|
||||