dwv 0.26.0 → 0.26.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/decoders/dwv/decode-rle.js +22 -22
  2. package/decoders/dwv/rle.js +103 -103
  3. package/decoders/pdfjs/arithmetic_decoder.js +185 -185
  4. package/decoders/pdfjs/decode-jpeg2000.js +18 -18
  5. package/decoders/pdfjs/decode-jpegbaseline.js +18 -18
  6. package/decoders/pdfjs/jpg.js +1072 -1072
  7. package/decoders/pdfjs/jpx.js +2237 -2237
  8. package/decoders/pdfjs/readme.md +15 -15
  9. package/decoders/pdfjs/util.js +1588 -1588
  10. package/decoders/rii-mango/decode-jpegloss.js +34 -34
  11. package/decoders/rii-mango/lossless.js +1755 -1755
  12. package/decoders/rii-mango/readme.md +12 -12
  13. package/dist/dwv.js +27526 -27512
  14. package/dist/dwv.min.js +3 -3
  15. package/license.txt +674 -674
  16. package/locales/de/overlays.json +62 -62
  17. package/locales/de/translation.json +236 -236
  18. package/locales/en/overlays.json +62 -62
  19. package/locales/en/translation.json +236 -236
  20. package/locales/es/overlays.json +62 -62
  21. package/locales/es/translation.json +236 -236
  22. package/locales/fr/overlays.json +62 -62
  23. package/locales/fr/translation.json +236 -236
  24. package/locales/it/overlays.json +62 -62
  25. package/locales/it/translation.json +236 -236
  26. package/locales/jp/overlays.json +62 -62
  27. package/locales/jp/translation.json +236 -236
  28. package/locales/ro/overlays.json +62 -62
  29. package/locales/ro/translation.json +236 -236
  30. package/locales/ru/overlays.json +62 -62
  31. package/locales/ru/translation.json +236 -236
  32. package/locales/zh/overlays.json +62 -62
  33. package/locales/zh/translation.json +236 -236
  34. package/package.json +50 -50
  35. package/readme.md +66 -66
  36. package/build/dist/dwv.js +0 -27512
  37. package/build/dist/dwv.min.js +0 -3
  38. package/dist/dwv-0.26.0.min.js +0 -3
@@ -1,1588 +1,1588 @@
1
- /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
- /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
3
- /* Copyright 2012 Mozilla Foundation
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
18
- Promise */
19
-
20
- 'use strict';
21
-
22
- var globalScope = (typeof window === 'undefined') ? this : window;
23
-
24
- var isWorker = (typeof window === 'undefined');
25
-
26
- var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
27
-
28
- var TextRenderingMode = {
29
- FILL: 0,
30
- STROKE: 1,
31
- FILL_STROKE: 2,
32
- INVISIBLE: 3,
33
- FILL_ADD_TO_PATH: 4,
34
- STROKE_ADD_TO_PATH: 5,
35
- FILL_STROKE_ADD_TO_PATH: 6,
36
- ADD_TO_PATH: 7,
37
- FILL_STROKE_MASK: 3,
38
- ADD_TO_PATH_FLAG: 4
39
- };
40
-
41
- var ImageKind = {
42
- GRAYSCALE_1BPP: 1,
43
- RGB_24BPP: 2,
44
- RGBA_32BPP: 3
45
- };
46
-
47
- var AnnotationType = {
48
- WIDGET: 1,
49
- TEXT: 2,
50
- LINK: 3
51
- };
52
-
53
- var StreamType = {
54
- UNKNOWN: 0,
55
- FLATE: 1,
56
- LZW: 2,
57
- DCT: 3,
58
- JPX: 4,
59
- JBIG: 5,
60
- A85: 6,
61
- AHX: 7,
62
- CCF: 8,
63
- RL: 9
64
- };
65
-
66
- var FontType = {
67
- UNKNOWN: 0,
68
- TYPE1: 1,
69
- TYPE1C: 2,
70
- CIDFONTTYPE0: 3,
71
- CIDFONTTYPE0C: 4,
72
- TRUETYPE: 5,
73
- CIDFONTTYPE2: 6,
74
- TYPE3: 7,
75
- OPENTYPE: 8,
76
- TYPE0: 9,
77
- MMTYPE1: 10
78
- };
79
-
80
- // The global PDFJS object exposes the API
81
- // In production, it will be declared outside a global wrapper
82
- // In development, it will be declared here
83
- if (!globalScope.PDFJS) {
84
- globalScope.PDFJS = {};
85
- }
86
-
87
- globalScope.PDFJS.pdfBug = false;
88
-
89
- PDFJS.VERBOSITY_LEVELS = {
90
- errors: 0,
91
- warnings: 1,
92
- infos: 5
93
- };
94
-
95
- // All the possible operations for an operator list.
96
- var OPS = PDFJS.OPS = {
97
- // Intentionally start from 1 so it is easy to spot bad operators that will be
98
- // 0's.
99
- dependency: 1,
100
- setLineWidth: 2,
101
- setLineCap: 3,
102
- setLineJoin: 4,
103
- setMiterLimit: 5,
104
- setDash: 6,
105
- setRenderingIntent: 7,
106
- setFlatness: 8,
107
- setGState: 9,
108
- save: 10,
109
- restore: 11,
110
- transform: 12,
111
- moveTo: 13,
112
- lineTo: 14,
113
- curveTo: 15,
114
- curveTo2: 16,
115
- curveTo3: 17,
116
- closePath: 18,
117
- rectangle: 19,
118
- stroke: 20,
119
- closeStroke: 21,
120
- fill: 22,
121
- eoFill: 23,
122
- fillStroke: 24,
123
- eoFillStroke: 25,
124
- closeFillStroke: 26,
125
- closeEOFillStroke: 27,
126
- endPath: 28,
127
- clip: 29,
128
- eoClip: 30,
129
- beginText: 31,
130
- endText: 32,
131
- setCharSpacing: 33,
132
- setWordSpacing: 34,
133
- setHScale: 35,
134
- setLeading: 36,
135
- setFont: 37,
136
- setTextRenderingMode: 38,
137
- setTextRise: 39,
138
- moveText: 40,
139
- setLeadingMoveText: 41,
140
- setTextMatrix: 42,
141
- nextLine: 43,
142
- showText: 44,
143
- showSpacedText: 45,
144
- nextLineShowText: 46,
145
- nextLineSetSpacingShowText: 47,
146
- setCharWidth: 48,
147
- setCharWidthAndBounds: 49,
148
- setStrokeColorSpace: 50,
149
- setFillColorSpace: 51,
150
- setStrokeColor: 52,
151
- setStrokeColorN: 53,
152
- setFillColor: 54,
153
- setFillColorN: 55,
154
- setStrokeGray: 56,
155
- setFillGray: 57,
156
- setStrokeRGBColor: 58,
157
- setFillRGBColor: 59,
158
- setStrokeCMYKColor: 60,
159
- setFillCMYKColor: 61,
160
- shadingFill: 62,
161
- beginInlineImage: 63,
162
- beginImageData: 64,
163
- endInlineImage: 65,
164
- paintXObject: 66,
165
- markPoint: 67,
166
- markPointProps: 68,
167
- beginMarkedContent: 69,
168
- beginMarkedContentProps: 70,
169
- endMarkedContent: 71,
170
- beginCompat: 72,
171
- endCompat: 73,
172
- paintFormXObjectBegin: 74,
173
- paintFormXObjectEnd: 75,
174
- beginGroup: 76,
175
- endGroup: 77,
176
- beginAnnotations: 78,
177
- endAnnotations: 79,
178
- beginAnnotation: 80,
179
- endAnnotation: 81,
180
- paintJpegXObject: 82,
181
- paintImageMaskXObject: 83,
182
- paintImageMaskXObjectGroup: 84,
183
- paintImageXObject: 85,
184
- paintInlineImageXObject: 86,
185
- paintInlineImageXObjectGroup: 87,
186
- paintImageXObjectRepeat: 88,
187
- paintImageMaskXObjectRepeat: 89,
188
- paintSolidColorImageMask: 90,
189
- constructPath: 91
190
- };
191
-
192
- // A notice for devs. These are good for things that are helpful to devs, such
193
- // as warning that Workers were disabled, which is important to devs but not
194
- // end users.
195
- function info(msg) {
196
- if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
197
- console.log('Info: ' + msg);
198
- }
199
- }
200
-
201
- // Non-fatal warnings.
202
- function warn(msg) {
203
- if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
204
- console.log('Warning: ' + msg);
205
- }
206
- }
207
-
208
- // Fatal errors that should trigger the fallback UI and halt execution by
209
- // throwing an exception.
210
- function error(msg) {
211
- // If multiple arguments were passed, pass them all to the log function.
212
- if (arguments.length > 1) {
213
- var logArguments = ['Error:'];
214
- logArguments.push.apply(logArguments, arguments);
215
- console.log.apply(console, logArguments);
216
- // Join the arguments into a single string for the lines below.
217
- msg = [].join.call(arguments, ' ');
218
- } else {
219
- console.log('Error: ' + msg);
220
- }
221
- console.log(backtrace());
222
- UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
223
- throw new Error(msg);
224
- }
225
-
226
- function backtrace() {
227
- try {
228
- throw new Error();
229
- } catch (e) {
230
- return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
231
- }
232
- }
233
-
234
- function assert(cond, msg) {
235
- if (!cond) {
236
- error(msg);
237
- }
238
- }
239
-
240
- var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
241
- unknown: 'unknown',
242
- forms: 'forms',
243
- javaScript: 'javaScript',
244
- smask: 'smask',
245
- shadingPattern: 'shadingPattern',
246
- font: 'font'
247
- };
248
-
249
- var UnsupportedManager = PDFJS.UnsupportedManager =
250
- (function UnsupportedManagerClosure() {
251
- var listeners = [];
252
- return {
253
- listen: function (cb) {
254
- listeners.push(cb);
255
- },
256
- notify: function (featureId) {
257
- warn('Unsupported feature "' + featureId + '"');
258
- for (var i = 0, ii = listeners.length; i < ii; i++) {
259
- listeners[i](featureId);
260
- }
261
- }
262
- };
263
- })();
264
-
265
- // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
266
- // absolute URL, it will be returned as is.
267
- function combineUrl(baseUrl, url) {
268
- if (!url) {
269
- return baseUrl;
270
- }
271
- if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
272
- return url;
273
- }
274
- var i;
275
- if (url.charAt(0) === '/') {
276
- // absolute path
277
- i = baseUrl.indexOf('://');
278
- if (url.charAt(1) === '/') {
279
- ++i;
280
- } else {
281
- i = baseUrl.indexOf('/', i + 3);
282
- }
283
- return baseUrl.substring(0, i) + url;
284
- } else {
285
- // relative path
286
- var pathLength = baseUrl.length;
287
- i = baseUrl.lastIndexOf('#');
288
- pathLength = i >= 0 ? i : pathLength;
289
- i = baseUrl.lastIndexOf('?', pathLength);
290
- pathLength = i >= 0 ? i : pathLength;
291
- var prefixLength = baseUrl.lastIndexOf('/', pathLength);
292
- return baseUrl.substring(0, prefixLength + 1) + url;
293
- }
294
- }
295
-
296
- // Validates if URL is safe and allowed, e.g. to avoid XSS.
297
- function isValidUrl(url, allowRelative) {
298
- if (!url) {
299
- return false;
300
- }
301
- // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
302
- // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
303
- var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
304
- if (!protocol) {
305
- return allowRelative;
306
- }
307
- protocol = protocol[0].toLowerCase();
308
- switch (protocol) {
309
- case 'http':
310
- case 'https':
311
- case 'ftp':
312
- case 'mailto':
313
- case 'tel':
314
- return true;
315
- default:
316
- return false;
317
- }
318
- }
319
- PDFJS.isValidUrl = isValidUrl;
320
-
321
- function shadow(obj, prop, value) {
322
- Object.defineProperty(obj, prop, { value: value,
323
- enumerable: true,
324
- configurable: true,
325
- writable: false });
326
- return value;
327
- }
328
- PDFJS.shadow = shadow;
329
-
330
- var PasswordResponses = PDFJS.PasswordResponses = {
331
- NEED_PASSWORD: 1,
332
- INCORRECT_PASSWORD: 2
333
- };
334
-
335
- var PasswordException = (function PasswordExceptionClosure() {
336
- function PasswordException(msg, code) {
337
- this.name = 'PasswordException';
338
- this.message = msg;
339
- this.code = code;
340
- }
341
-
342
- PasswordException.prototype = new Error();
343
- PasswordException.constructor = PasswordException;
344
-
345
- return PasswordException;
346
- })();
347
- PDFJS.PasswordException = PasswordException;
348
-
349
- var UnknownErrorException = (function UnknownErrorExceptionClosure() {
350
- function UnknownErrorException(msg, details) {
351
- this.name = 'UnknownErrorException';
352
- this.message = msg;
353
- this.details = details;
354
- }
355
-
356
- UnknownErrorException.prototype = new Error();
357
- UnknownErrorException.constructor = UnknownErrorException;
358
-
359
- return UnknownErrorException;
360
- })();
361
- PDFJS.UnknownErrorException = UnknownErrorException;
362
-
363
- var InvalidPDFException = (function InvalidPDFExceptionClosure() {
364
- function InvalidPDFException(msg) {
365
- this.name = 'InvalidPDFException';
366
- this.message = msg;
367
- }
368
-
369
- InvalidPDFException.prototype = new Error();
370
- InvalidPDFException.constructor = InvalidPDFException;
371
-
372
- return InvalidPDFException;
373
- })();
374
- PDFJS.InvalidPDFException = InvalidPDFException;
375
-
376
- var MissingPDFException = (function MissingPDFExceptionClosure() {
377
- function MissingPDFException(msg) {
378
- this.name = 'MissingPDFException';
379
- this.message = msg;
380
- }
381
-
382
- MissingPDFException.prototype = new Error();
383
- MissingPDFException.constructor = MissingPDFException;
384
-
385
- return MissingPDFException;
386
- })();
387
- PDFJS.MissingPDFException = MissingPDFException;
388
-
389
- var UnexpectedResponseException =
390
- (function UnexpectedResponseExceptionClosure() {
391
- function UnexpectedResponseException(msg, status) {
392
- this.name = 'UnexpectedResponseException';
393
- this.message = msg;
394
- this.status = status;
395
- }
396
-
397
- UnexpectedResponseException.prototype = new Error();
398
- UnexpectedResponseException.constructor = UnexpectedResponseException;
399
-
400
- return UnexpectedResponseException;
401
- })();
402
- PDFJS.UnexpectedResponseException = UnexpectedResponseException;
403
-
404
- var NotImplementedException = (function NotImplementedExceptionClosure() {
405
- function NotImplementedException(msg) {
406
- this.message = msg;
407
- }
408
-
409
- NotImplementedException.prototype = new Error();
410
- NotImplementedException.prototype.name = 'NotImplementedException';
411
- NotImplementedException.constructor = NotImplementedException;
412
-
413
- return NotImplementedException;
414
- })();
415
-
416
- var MissingDataException = (function MissingDataExceptionClosure() {
417
- function MissingDataException(begin, end) {
418
- this.begin = begin;
419
- this.end = end;
420
- this.message = 'Missing data [' + begin + ', ' + end + ')';
421
- }
422
-
423
- MissingDataException.prototype = new Error();
424
- MissingDataException.prototype.name = 'MissingDataException';
425
- MissingDataException.constructor = MissingDataException;
426
-
427
- return MissingDataException;
428
- })();
429
-
430
- var XRefParseException = (function XRefParseExceptionClosure() {
431
- function XRefParseException(msg) {
432
- this.message = msg;
433
- }
434
-
435
- XRefParseException.prototype = new Error();
436
- XRefParseException.prototype.name = 'XRefParseException';
437
- XRefParseException.constructor = XRefParseException;
438
-
439
- return XRefParseException;
440
- })();
441
-
442
-
443
- function bytesToString(bytes) {
444
- assert(bytes !== null && typeof bytes === 'object' &&
445
- bytes.length !== undefined, 'Invalid argument for bytesToString');
446
- var length = bytes.length;
447
- var MAX_ARGUMENT_COUNT = 8192;
448
- if (length < MAX_ARGUMENT_COUNT) {
449
- return String.fromCharCode.apply(null, bytes);
450
- }
451
- var strBuf = [];
452
- for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
453
- var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
454
- var chunk = bytes.subarray(i, chunkEnd);
455
- strBuf.push(String.fromCharCode.apply(null, chunk));
456
- }
457
- return strBuf.join('');
458
- }
459
-
460
- function stringToBytes(str) {
461
- assert(typeof str === 'string', 'Invalid argument for stringToBytes');
462
- var length = str.length;
463
- var bytes = new Uint8Array(length);
464
- for (var i = 0; i < length; ++i) {
465
- bytes[i] = str.charCodeAt(i) & 0xFF;
466
- }
467
- return bytes;
468
- }
469
-
470
- function string32(value) {
471
- return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
472
- (value >> 8) & 0xff, value & 0xff);
473
- }
474
-
475
- function log2(x) {
476
- var n = 1, i = 0;
477
- while (x > n) {
478
- n <<= 1;
479
- i++;
480
- }
481
- return i;
482
- }
483
-
484
- function readInt8(data, start) {
485
- return (data[start] << 24) >> 24;
486
- }
487
-
488
- function readUint16(data, offset) {
489
- return (data[offset] << 8) | data[offset + 1];
490
- }
491
-
492
- function readUint32(data, offset) {
493
- return ((data[offset] << 24) | (data[offset + 1] << 16) |
494
- (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
495
- }
496
-
497
- // Lazy test the endianness of the platform
498
- // NOTE: This will be 'true' for simulated TypedArrays
499
- function isLittleEndian() {
500
- var buffer8 = new Uint8Array(2);
501
- buffer8[0] = 1;
502
- var buffer16 = new Uint16Array(buffer8.buffer);
503
- return (buffer16[0] === 1);
504
- }
505
-
506
- Object.defineProperty(PDFJS, 'isLittleEndian', {
507
- configurable: true,
508
- get: function PDFJS_isLittleEndian() {
509
- return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
510
- }
511
- });
512
-
513
- //#if !(FIREFOX || MOZCENTRAL || B2G || CHROME)
514
- //// Lazy test if the userAgant support CanvasTypedArrays
515
- function hasCanvasTypedArrays() {
516
- var canvas = document.createElement('canvas');
517
- canvas.width = canvas.height = 1;
518
- var ctx = canvas.getContext('2d');
519
- var imageData = ctx.createImageData(1, 1);
520
- return (typeof imageData.data.buffer !== 'undefined');
521
- }
522
-
523
- Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
524
- configurable: true,
525
- get: function PDFJS_hasCanvasTypedArrays() {
526
- return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
527
- }
528
- });
529
-
530
- var Uint32ArrayView = (function Uint32ArrayViewClosure() {
531
-
532
- function Uint32ArrayView(buffer, length) {
533
- this.buffer = buffer;
534
- this.byteLength = buffer.length;
535
- this.length = length === undefined ? (this.byteLength >> 2) : length;
536
- ensureUint32ArrayViewProps(this.length);
537
- }
538
- Uint32ArrayView.prototype = Object.create(null);
539
-
540
- var uint32ArrayViewSetters = 0;
541
- function createUint32ArrayProp(index) {
542
- return {
543
- get: function () {
544
- var buffer = this.buffer, offset = index << 2;
545
- return (buffer[offset] | (buffer[offset + 1] << 8) |
546
- (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
547
- },
548
- set: function (value) {
549
- var buffer = this.buffer, offset = index << 2;
550
- buffer[offset] = value & 255;
551
- buffer[offset + 1] = (value >> 8) & 255;
552
- buffer[offset + 2] = (value >> 16) & 255;
553
- buffer[offset + 3] = (value >>> 24) & 255;
554
- }
555
- };
556
- }
557
-
558
- function ensureUint32ArrayViewProps(length) {
559
- while (uint32ArrayViewSetters < length) {
560
- Object.defineProperty(Uint32ArrayView.prototype,
561
- uint32ArrayViewSetters,
562
- createUint32ArrayProp(uint32ArrayViewSetters));
563
- uint32ArrayViewSetters++;
564
- }
565
- }
566
-
567
- return Uint32ArrayView;
568
- })();
569
- //#else
570
- //PDFJS.hasCanvasTypedArrays = true;
571
- //#endif
572
-
573
- var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
574
-
575
- var Util = PDFJS.Util = (function UtilClosure() {
576
- function Util() {}
577
-
578
- var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
579
-
580
- // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
581
- // creating many intermediate strings.
582
- Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
583
- rgbBuf[1] = r;
584
- rgbBuf[3] = g;
585
- rgbBuf[5] = b;
586
- return rgbBuf.join('');
587
- };
588
-
589
- // Concatenates two transformation matrices together and returns the result.
590
- Util.transform = function Util_transform(m1, m2) {
591
- return [
592
- m1[0] * m2[0] + m1[2] * m2[1],
593
- m1[1] * m2[0] + m1[3] * m2[1],
594
- m1[0] * m2[2] + m1[2] * m2[3],
595
- m1[1] * m2[2] + m1[3] * m2[3],
596
- m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
597
- m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
598
- ];
599
- };
600
-
601
- // For 2d affine transforms
602
- Util.applyTransform = function Util_applyTransform(p, m) {
603
- var xt = p[0] * m[0] + p[1] * m[2] + m[4];
604
- var yt = p[0] * m[1] + p[1] * m[3] + m[5];
605
- return [xt, yt];
606
- };
607
-
608
- Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
609
- var d = m[0] * m[3] - m[1] * m[2];
610
- var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
611
- var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
612
- return [xt, yt];
613
- };
614
-
615
- // Applies the transform to the rectangle and finds the minimum axially
616
- // aligned bounding box.
617
- Util.getAxialAlignedBoundingBox =
618
- function Util_getAxialAlignedBoundingBox(r, m) {
619
-
620
- var p1 = Util.applyTransform(r, m);
621
- var p2 = Util.applyTransform(r.slice(2, 4), m);
622
- var p3 = Util.applyTransform([r[0], r[3]], m);
623
- var p4 = Util.applyTransform([r[2], r[1]], m);
624
- return [
625
- Math.min(p1[0], p2[0], p3[0], p4[0]),
626
- Math.min(p1[1], p2[1], p3[1], p4[1]),
627
- Math.max(p1[0], p2[0], p3[0], p4[0]),
628
- Math.max(p1[1], p2[1], p3[1], p4[1])
629
- ];
630
- };
631
-
632
- Util.inverseTransform = function Util_inverseTransform(m) {
633
- var d = m[0] * m[3] - m[1] * m[2];
634
- return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
635
- (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
636
- };
637
-
638
- // Apply a generic 3d matrix M on a 3-vector v:
639
- // | a b c | | X |
640
- // | d e f | x | Y |
641
- // | g h i | | Z |
642
- // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
643
- // with v as [X,Y,Z]
644
- Util.apply3dTransform = function Util_apply3dTransform(m, v) {
645
- return [
646
- m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
647
- m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
648
- m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
649
- ];
650
- };
651
-
652
- // This calculation uses Singular Value Decomposition.
653
- // The SVD can be represented with formula A = USV. We are interested in the
654
- // matrix S here because it represents the scale values.
655
- Util.singularValueDecompose2dScale =
656
- function Util_singularValueDecompose2dScale(m) {
657
-
658
- var transpose = [m[0], m[2], m[1], m[3]];
659
-
660
- // Multiply matrix m with its transpose.
661
- var a = m[0] * transpose[0] + m[1] * transpose[2];
662
- var b = m[0] * transpose[1] + m[1] * transpose[3];
663
- var c = m[2] * transpose[0] + m[3] * transpose[2];
664
- var d = m[2] * transpose[1] + m[3] * transpose[3];
665
-
666
- // Solve the second degree polynomial to get roots.
667
- var first = (a + d) / 2;
668
- var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
669
- var sx = first + second || 1;
670
- var sy = first - second || 1;
671
-
672
- // Scale values are the square roots of the eigenvalues.
673
- return [Math.sqrt(sx), Math.sqrt(sy)];
674
- };
675
-
676
- // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
677
- // For coordinate systems whose origin lies in the bottom-left, this
678
- // means normalization to (BL,TR) ordering. For systems with origin in the
679
- // top-left, this means (TL,BR) ordering.
680
- Util.normalizeRect = function Util_normalizeRect(rect) {
681
- var r = rect.slice(0); // clone rect
682
- if (rect[0] > rect[2]) {
683
- r[0] = rect[2];
684
- r[2] = rect[0];
685
- }
686
- if (rect[1] > rect[3]) {
687
- r[1] = rect[3];
688
- r[3] = rect[1];
689
- }
690
- return r;
691
- };
692
-
693
- // Returns a rectangle [x1, y1, x2, y2] corresponding to the
694
- // intersection of rect1 and rect2. If no intersection, returns 'false'
695
- // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
696
- Util.intersect = function Util_intersect(rect1, rect2) {
697
- function compare(a, b) {
698
- return a - b;
699
- }
700
-
701
- // Order points along the axes
702
- var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
703
- orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
704
- result = [];
705
-
706
- rect1 = Util.normalizeRect(rect1);
707
- rect2 = Util.normalizeRect(rect2);
708
-
709
- // X: first and second points belong to different rectangles?
710
- if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
711
- (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
712
- // Intersection must be between second and third points
713
- result[0] = orderedX[1];
714
- result[2] = orderedX[2];
715
- } else {
716
- return false;
717
- }
718
-
719
- // Y: first and second points belong to different rectangles?
720
- if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
721
- (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
722
- // Intersection must be between second and third points
723
- result[1] = orderedY[1];
724
- result[3] = orderedY[2];
725
- } else {
726
- return false;
727
- }
728
-
729
- return result;
730
- };
731
-
732
- Util.sign = function Util_sign(num) {
733
- return num < 0 ? -1 : 1;
734
- };
735
-
736
- Util.appendToArray = function Util_appendToArray(arr1, arr2) {
737
- Array.prototype.push.apply(arr1, arr2);
738
- };
739
-
740
- Util.prependToArray = function Util_prependToArray(arr1, arr2) {
741
- Array.prototype.unshift.apply(arr1, arr2);
742
- };
743
-
744
- Util.extendObj = function extendObj(obj1, obj2) {
745
- for (var key in obj2) {
746
- obj1[key] = obj2[key];
747
- }
748
- };
749
-
750
- Util.getInheritableProperty = function Util_getInheritableProperty(dict,
751
- name) {
752
- while (dict && !dict.has(name)) {
753
- dict = dict.get('Parent');
754
- }
755
- if (!dict) {
756
- return null;
757
- }
758
- return dict.get(name);
759
- };
760
-
761
- Util.inherit = function Util_inherit(sub, base, prototype) {
762
- sub.prototype = Object.create(base.prototype);
763
- sub.prototype.constructor = sub;
764
- for (var prop in prototype) {
765
- sub.prototype[prop] = prototype[prop];
766
- }
767
- };
768
-
769
- Util.loadScript = function Util_loadScript(src, callback) {
770
- var script = document.createElement('script');
771
- var loaded = false;
772
- script.setAttribute('src', src);
773
- if (callback) {
774
- script.onload = function() {
775
- if (!loaded) {
776
- callback();
777
- }
778
- loaded = true;
779
- };
780
- }
781
- document.getElementsByTagName('head')[0].appendChild(script);
782
- };
783
-
784
- return Util;
785
- })();
786
-
787
- /**
788
- * PDF page viewport created based on scale, rotation and offset.
789
- * @class
790
- * @alias PDFJS.PageViewport
791
- */
792
- var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
793
- /**
794
- * @constructor
795
- * @private
796
- * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
797
- * @param scale {number} scale of the viewport.
798
- * @param rotation {number} rotations of the viewport in degrees.
799
- * @param offsetX {number} offset X
800
- * @param offsetY {number} offset Y
801
- * @param dontFlip {boolean} if true, axis Y will not be flipped.
802
- */
803
- function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
804
- this.viewBox = viewBox;
805
- this.scale = scale;
806
- this.rotation = rotation;
807
- this.offsetX = offsetX;
808
- this.offsetY = offsetY;
809
-
810
- // creating transform to convert pdf coordinate system to the normal
811
- // canvas like coordinates taking in account scale and rotation
812
- var centerX = (viewBox[2] + viewBox[0]) / 2;
813
- var centerY = (viewBox[3] + viewBox[1]) / 2;
814
- var rotateA, rotateB, rotateC, rotateD;
815
- rotation = rotation % 360;
816
- rotation = rotation < 0 ? rotation + 360 : rotation;
817
- switch (rotation) {
818
- case 180:
819
- rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
820
- break;
821
- case 90:
822
- rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
823
- break;
824
- case 270:
825
- rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
826
- break;
827
- //case 0:
828
- default:
829
- rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
830
- break;
831
- }
832
-
833
- if (dontFlip) {
834
- rotateC = -rotateC; rotateD = -rotateD;
835
- }
836
-
837
- var offsetCanvasX, offsetCanvasY;
838
- var width, height;
839
- if (rotateA === 0) {
840
- offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
841
- offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
842
- width = Math.abs(viewBox[3] - viewBox[1]) * scale;
843
- height = Math.abs(viewBox[2] - viewBox[0]) * scale;
844
- } else {
845
- offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
846
- offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
847
- width = Math.abs(viewBox[2] - viewBox[0]) * scale;
848
- height = Math.abs(viewBox[3] - viewBox[1]) * scale;
849
- }
850
- // creating transform for the following operations:
851
- // translate(-centerX, -centerY), rotate and flip vertically,
852
- // scale, and translate(offsetCanvasX, offsetCanvasY)
853
- this.transform = [
854
- rotateA * scale,
855
- rotateB * scale,
856
- rotateC * scale,
857
- rotateD * scale,
858
- offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
859
- offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
860
- ];
861
-
862
- this.width = width;
863
- this.height = height;
864
- this.fontScale = scale;
865
- }
866
- PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
867
- /**
868
- * Clones viewport with additional properties.
869
- * @param args {Object} (optional) If specified, may contain the 'scale' or
870
- * 'rotation' properties to override the corresponding properties in
871
- * the cloned viewport.
872
- * @returns {PDFJS.PageViewport} Cloned viewport.
873
- */
874
- clone: function PageViewPort_clone(args) {
875
- args = args || {};
876
- var scale = 'scale' in args ? args.scale : this.scale;
877
- var rotation = 'rotation' in args ? args.rotation : this.rotation;
878
- return new PageViewport(this.viewBox.slice(), scale, rotation,
879
- this.offsetX, this.offsetY, args.dontFlip);
880
- },
881
- /**
882
- * Converts PDF point to the viewport coordinates. For examples, useful for
883
- * converting PDF location into canvas pixel coordinates.
884
- * @param x {number} X coordinate.
885
- * @param y {number} Y coordinate.
886
- * @returns {Object} Object that contains 'x' and 'y' properties of the
887
- * point in the viewport coordinate space.
888
- * @see {@link convertToPdfPoint}
889
- * @see {@link convertToViewportRectangle}
890
- */
891
- convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
892
- return Util.applyTransform([x, y], this.transform);
893
- },
894
- /**
895
- * Converts PDF rectangle to the viewport coordinates.
896
- * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
897
- * @returns {Array} Contains corresponding coordinates of the rectangle
898
- * in the viewport coordinate space.
899
- * @see {@link convertToViewportPoint}
900
- */
901
- convertToViewportRectangle:
902
- function PageViewport_convertToViewportRectangle(rect) {
903
- var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
904
- var br = Util.applyTransform([rect[2], rect[3]], this.transform);
905
- return [tl[0], tl[1], br[0], br[1]];
906
- },
907
- /**
908
- * Converts viewport coordinates to the PDF location. For examples, useful
909
- * for converting canvas pixel location into PDF one.
910
- * @param x {number} X coordinate.
911
- * @param y {number} Y coordinate.
912
- * @returns {Object} Object that contains 'x' and 'y' properties of the
913
- * point in the PDF coordinate space.
914
- * @see {@link convertToViewportPoint}
915
- */
916
- convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
917
- return Util.applyInverseTransform([x, y], this.transform);
918
- }
919
- };
920
- return PageViewport;
921
- })();
922
-
923
- var PDFStringTranslateTable = [
924
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
925
- 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
926
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
927
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
928
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
929
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
930
- 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
931
- 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
932
- 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
933
- ];
934
-
935
- function stringToPDFString(str) {
936
- var i, n = str.length, strBuf = [];
937
- if (str[0] === '\xFE' && str[1] === '\xFF') {
938
- // UTF16BE BOM
939
- for (i = 2; i < n; i += 2) {
940
- strBuf.push(String.fromCharCode(
941
- (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
942
- }
943
- } else {
944
- for (i = 0; i < n; ++i) {
945
- var code = PDFStringTranslateTable[str.charCodeAt(i)];
946
- strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
947
- }
948
- }
949
- return strBuf.join('');
950
- }
951
-
952
- function stringToUTF8String(str) {
953
- return decodeURIComponent(escape(str));
954
- }
955
-
956
- function isEmptyObj(obj) {
957
- for (var key in obj) {
958
- return false;
959
- }
960
- return true;
961
- }
962
-
963
- function isBool(v) {
964
- return typeof v === 'boolean';
965
- }
966
-
967
- function isInt(v) {
968
- return typeof v === 'number' && ((v | 0) === v);
969
- }
970
-
971
- function isNum(v) {
972
- return typeof v === 'number';
973
- }
974
-
975
- function isString(v) {
976
- return typeof v === 'string';
977
- }
978
-
979
- function isName(v) {
980
- return v instanceof Name;
981
- }
982
-
983
- function isCmd(v, cmd) {
984
- return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
985
- }
986
-
987
- function isDict(v, type) {
988
- if (!(v instanceof Dict)) {
989
- return false;
990
- }
991
- if (!type) {
992
- return true;
993
- }
994
- var dictType = v.get('Type');
995
- return isName(dictType) && dictType.name === type;
996
- }
997
-
998
- function isArray(v) {
999
- return v instanceof Array;
1000
- }
1001
-
1002
- function isStream(v) {
1003
- return typeof v === 'object' && v !== null && v.getBytes !== undefined;
1004
- }
1005
-
1006
- function isArrayBuffer(v) {
1007
- return typeof v === 'object' && v !== null && v.byteLength !== undefined;
1008
- }
1009
-
1010
- function isRef(v) {
1011
- return v instanceof Ref;
1012
- }
1013
-
1014
- /**
1015
- * Promise Capability object.
1016
- *
1017
- * @typedef {Object} PromiseCapability
1018
- * @property {Promise} promise - A promise object.
1019
- * @property {function} resolve - Fullfills the promise.
1020
- * @property {function} reject - Rejects the promise.
1021
- */
1022
-
1023
- /**
1024
- * Creates a promise capability object.
1025
- * @alias PDFJS.createPromiseCapability
1026
- *
1027
- * @return {PromiseCapability} A capability object contains:
1028
- * - a Promise, resolve and reject methods.
1029
- */
1030
- function createPromiseCapability() {
1031
- var capability = {};
1032
- capability.promise = new Promise(function (resolve, reject) {
1033
- capability.resolve = resolve;
1034
- capability.reject = reject;
1035
- });
1036
- return capability;
1037
- }
1038
-
1039
- PDFJS.createPromiseCapability = createPromiseCapability;
1040
-
1041
- /**
1042
- * Polyfill for Promises:
1043
- * The following promise implementation tries to generally implement the
1044
- * Promise/A+ spec. Some notable differences from other promise libaries are:
1045
- * - There currently isn't a seperate deferred and promise object.
1046
- * - Unhandled rejections eventually show an error if they aren't handled.
1047
- *
1048
- * Based off of the work in:
1049
- * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
1050
- */
1051
- (function PromiseClosure() {
1052
- if (globalScope.Promise) {
1053
- // Promises existing in the DOM/Worker, checking presence of all/resolve
1054
- if (typeof globalScope.Promise.all !== 'function') {
1055
- globalScope.Promise.all = function (iterable) {
1056
- var count = 0, results = [], resolve, reject;
1057
- var promise = new globalScope.Promise(function (resolve_, reject_) {
1058
- resolve = resolve_;
1059
- reject = reject_;
1060
- });
1061
- iterable.forEach(function (p, i) {
1062
- count++;
1063
- p.then(function (result) {
1064
- results[i] = result;
1065
- count--;
1066
- if (count === 0) {
1067
- resolve(results);
1068
- }
1069
- }, reject);
1070
- });
1071
- if (count === 0) {
1072
- resolve(results);
1073
- }
1074
- return promise;
1075
- };
1076
- }
1077
- if (typeof globalScope.Promise.resolve !== 'function') {
1078
- globalScope.Promise.resolve = function (value) {
1079
- return new globalScope.Promise(function (resolve) { resolve(value); });
1080
- };
1081
- }
1082
- if (typeof globalScope.Promise.reject !== 'function') {
1083
- globalScope.Promise.reject = function (reason) {
1084
- return new globalScope.Promise(function (resolve, reject) {
1085
- reject(reason);
1086
- });
1087
- };
1088
- }
1089
- if (typeof globalScope.Promise.prototype.catch !== 'function') {
1090
- globalScope.Promise.prototype.catch = function (onReject) {
1091
- return globalScope.Promise.prototype.then(undefined, onReject);
1092
- };
1093
- }
1094
- return;
1095
- }
1096
- //#if !MOZCENTRAL
1097
- var STATUS_PENDING = 0;
1098
- var STATUS_RESOLVED = 1;
1099
- var STATUS_REJECTED = 2;
1100
-
1101
- // In an attempt to avoid silent exceptions, unhandled rejections are
1102
- // tracked and if they aren't handled in a certain amount of time an
1103
- // error is logged.
1104
- var REJECTION_TIMEOUT = 500;
1105
-
1106
- var HandlerManager = {
1107
- handlers: [],
1108
- running: false,
1109
- unhandledRejections: [],
1110
- pendingRejectionCheck: false,
1111
-
1112
- scheduleHandlers: function scheduleHandlers(promise) {
1113
- if (promise._status === STATUS_PENDING) {
1114
- return;
1115
- }
1116
-
1117
- this.handlers = this.handlers.concat(promise._handlers);
1118
- promise._handlers = [];
1119
-
1120
- if (this.running) {
1121
- return;
1122
- }
1123
- this.running = true;
1124
-
1125
- setTimeout(this.runHandlers.bind(this), 0);
1126
- },
1127
-
1128
- runHandlers: function runHandlers() {
1129
- var RUN_TIMEOUT = 1; // ms
1130
- var timeoutAt = Date.now() + RUN_TIMEOUT;
1131
- while (this.handlers.length > 0) {
1132
- var handler = this.handlers.shift();
1133
-
1134
- var nextStatus = handler.thisPromise._status;
1135
- var nextValue = handler.thisPromise._value;
1136
-
1137
- try {
1138
- if (nextStatus === STATUS_RESOLVED) {
1139
- if (typeof handler.onResolve === 'function') {
1140
- nextValue = handler.onResolve(nextValue);
1141
- }
1142
- } else if (typeof handler.onReject === 'function') {
1143
- nextValue = handler.onReject(nextValue);
1144
- nextStatus = STATUS_RESOLVED;
1145
-
1146
- if (handler.thisPromise._unhandledRejection) {
1147
- this.removeUnhandeledRejection(handler.thisPromise);
1148
- }
1149
- }
1150
- } catch (ex) {
1151
- nextStatus = STATUS_REJECTED;
1152
- nextValue = ex;
1153
- }
1154
-
1155
- handler.nextPromise._updateStatus(nextStatus, nextValue);
1156
- if (Date.now() >= timeoutAt) {
1157
- break;
1158
- }
1159
- }
1160
-
1161
- if (this.handlers.length > 0) {
1162
- setTimeout(this.runHandlers.bind(this), 0);
1163
- return;
1164
- }
1165
-
1166
- this.running = false;
1167
- },
1168
-
1169
- addUnhandledRejection: function addUnhandledRejection(promise) {
1170
- this.unhandledRejections.push({
1171
- promise: promise,
1172
- time: Date.now()
1173
- });
1174
- this.scheduleRejectionCheck();
1175
- },
1176
-
1177
- removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
1178
- promise._unhandledRejection = false;
1179
- for (var i = 0; i < this.unhandledRejections.length; i++) {
1180
- if (this.unhandledRejections[i].promise === promise) {
1181
- this.unhandledRejections.splice(i);
1182
- i--;
1183
- }
1184
- }
1185
- },
1186
-
1187
- scheduleRejectionCheck: function scheduleRejectionCheck() {
1188
- if (this.pendingRejectionCheck) {
1189
- return;
1190
- }
1191
- this.pendingRejectionCheck = true;
1192
- setTimeout(function rejectionCheck() {
1193
- this.pendingRejectionCheck = false;
1194
- var now = Date.now();
1195
- for (var i = 0; i < this.unhandledRejections.length; i++) {
1196
- if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
1197
- var unhandled = this.unhandledRejections[i].promise._value;
1198
- var msg = 'Unhandled rejection: ' + unhandled;
1199
- if (unhandled.stack) {
1200
- msg += '\n' + unhandled.stack;
1201
- }
1202
- warn(msg);
1203
- this.unhandledRejections.splice(i);
1204
- i--;
1205
- }
1206
- }
1207
- if (this.unhandledRejections.length) {
1208
- this.scheduleRejectionCheck();
1209
- }
1210
- }.bind(this), REJECTION_TIMEOUT);
1211
- }
1212
- };
1213
-
1214
- function Promise(resolver) {
1215
- this._status = STATUS_PENDING;
1216
- this._handlers = [];
1217
- try {
1218
- resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
1219
- } catch (e) {
1220
- this._reject(e);
1221
- }
1222
- }
1223
- /**
1224
- * Builds a promise that is resolved when all the passed in promises are
1225
- * resolved.
1226
- * @param {array} array of data and/or promises to wait for.
1227
- * @return {Promise} New dependant promise.
1228
- */
1229
- Promise.all = function Promise_all(promises) {
1230
- var resolveAll, rejectAll;
1231
- var deferred = new Promise(function (resolve, reject) {
1232
- resolveAll = resolve;
1233
- rejectAll = reject;
1234
- });
1235
- var unresolved = promises.length;
1236
- var results = [];
1237
- if (unresolved === 0) {
1238
- resolveAll(results);
1239
- return deferred;
1240
- }
1241
- function reject(reason) {
1242
- if (deferred._status === STATUS_REJECTED) {
1243
- return;
1244
- }
1245
- results = [];
1246
- rejectAll(reason);
1247
- }
1248
- for (var i = 0, ii = promises.length; i < ii; ++i) {
1249
- var promise = promises[i];
1250
- var resolve = (function(i) {
1251
- return function(value) {
1252
- if (deferred._status === STATUS_REJECTED) {
1253
- return;
1254
- }
1255
- results[i] = value;
1256
- unresolved--;
1257
- if (unresolved === 0) {
1258
- resolveAll(results);
1259
- }
1260
- };
1261
- })(i);
1262
- if (Promise.isPromise(promise)) {
1263
- promise.then(resolve, reject);
1264
- } else {
1265
- resolve(promise);
1266
- }
1267
- }
1268
- return deferred;
1269
- };
1270
-
1271
- /**
1272
- * Checks if the value is likely a promise (has a 'then' function).
1273
- * @return {boolean} true if value is thenable
1274
- */
1275
- Promise.isPromise = function Promise_isPromise(value) {
1276
- return value && typeof value.then === 'function';
1277
- };
1278
-
1279
- /**
1280
- * Creates resolved promise
1281
- * @param value resolve value
1282
- * @returns {Promise}
1283
- */
1284
- Promise.resolve = function Promise_resolve(value) {
1285
- return new Promise(function (resolve) { resolve(value); });
1286
- };
1287
-
1288
- /**
1289
- * Creates rejected promise
1290
- * @param reason rejection value
1291
- * @returns {Promise}
1292
- */
1293
- Promise.reject = function Promise_reject(reason) {
1294
- return new Promise(function (resolve, reject) { reject(reason); });
1295
- };
1296
-
1297
- Promise.prototype = {
1298
- _status: null,
1299
- _value: null,
1300
- _handlers: null,
1301
- _unhandledRejection: null,
1302
-
1303
- _updateStatus: function Promise__updateStatus(status, value) {
1304
- if (this._status === STATUS_RESOLVED ||
1305
- this._status === STATUS_REJECTED) {
1306
- return;
1307
- }
1308
-
1309
- if (status === STATUS_RESOLVED &&
1310
- Promise.isPromise(value)) {
1311
- value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
1312
- this._updateStatus.bind(this, STATUS_REJECTED));
1313
- return;
1314
- }
1315
-
1316
- this._status = status;
1317
- this._value = value;
1318
-
1319
- if (status === STATUS_REJECTED && this._handlers.length === 0) {
1320
- this._unhandledRejection = true;
1321
- HandlerManager.addUnhandledRejection(this);
1322
- }
1323
-
1324
- HandlerManager.scheduleHandlers(this);
1325
- },
1326
-
1327
- _resolve: function Promise_resolve(value) {
1328
- this._updateStatus(STATUS_RESOLVED, value);
1329
- },
1330
-
1331
- _reject: function Promise_reject(reason) {
1332
- this._updateStatus(STATUS_REJECTED, reason);
1333
- },
1334
-
1335
- then: function Promise_then(onResolve, onReject) {
1336
- var nextPromise = new Promise(function (resolve, reject) {
1337
- this.resolve = resolve;
1338
- this.reject = reject;
1339
- });
1340
- this._handlers.push({
1341
- thisPromise: this,
1342
- onResolve: onResolve,
1343
- onReject: onReject,
1344
- nextPromise: nextPromise
1345
- });
1346
- HandlerManager.scheduleHandlers(this);
1347
- return nextPromise;
1348
- },
1349
-
1350
- catch: function Promise_catch(onReject) {
1351
- return this.then(undefined, onReject);
1352
- }
1353
- };
1354
-
1355
- globalScope.Promise = Promise;
1356
- //#else
1357
- //throw new Error('DOM Promise is not present');
1358
- //#endif
1359
- })();
1360
-
1361
- var StatTimer = (function StatTimerClosure() {
1362
- function rpad(str, pad, length) {
1363
- while (str.length < length) {
1364
- str += pad;
1365
- }
1366
- return str;
1367
- }
1368
- function StatTimer() {
1369
- this.started = {};
1370
- this.times = [];
1371
- this.enabled = true;
1372
- }
1373
- StatTimer.prototype = {
1374
- time: function StatTimer_time(name) {
1375
- if (!this.enabled) {
1376
- return;
1377
- }
1378
- if (name in this.started) {
1379
- warn('Timer is already running for ' + name);
1380
- }
1381
- this.started[name] = Date.now();
1382
- },
1383
- timeEnd: function StatTimer_timeEnd(name) {
1384
- if (!this.enabled) {
1385
- return;
1386
- }
1387
- if (!(name in this.started)) {
1388
- warn('Timer has not been started for ' + name);
1389
- }
1390
- this.times.push({
1391
- 'name': name,
1392
- 'start': this.started[name],
1393
- 'end': Date.now()
1394
- });
1395
- // Remove timer from started so it can be called again.
1396
- delete this.started[name];
1397
- },
1398
- toString: function StatTimer_toString() {
1399
- var i, ii;
1400
- var times = this.times;
1401
- var out = '';
1402
- // Find the longest name for padding purposes.
1403
- var longest = 0;
1404
- for (i = 0, ii = times.length; i < ii; ++i) {
1405
- var name = times[i]['name'];
1406
- if (name.length > longest) {
1407
- longest = name.length;
1408
- }
1409
- }
1410
- for (i = 0, ii = times.length; i < ii; ++i) {
1411
- var span = times[i];
1412
- var duration = span.end - span.start;
1413
- out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
1414
- }
1415
- return out;
1416
- }
1417
- };
1418
- return StatTimer;
1419
- })();
1420
-
1421
- PDFJS.createBlob = function createBlob(data, contentType) {
1422
- if (typeof Blob !== 'undefined') {
1423
- return new Blob([data], { type: contentType });
1424
- }
1425
- // Blob builder is deprecated in FF14 and removed in FF18.
1426
- var bb = new MozBlobBuilder();
1427
- bb.append(data);
1428
- return bb.getBlob(contentType);
1429
- };
1430
-
1431
- PDFJS.createObjectURL = (function createObjectURLClosure() {
1432
- // Blob/createObjectURL is not available, falling back to data schema.
1433
- var digits =
1434
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
1435
-
1436
- return function createObjectURL(data, contentType) {
1437
- if (!PDFJS.disableCreateObjectURL &&
1438
- typeof URL !== 'undefined' && URL.createObjectURL) {
1439
- var blob = PDFJS.createBlob(data, contentType);
1440
- return URL.createObjectURL(blob);
1441
- }
1442
-
1443
- var buffer = 'data:' + contentType + ';base64,';
1444
- for (var i = 0, ii = data.length; i < ii; i += 3) {
1445
- var b1 = data[i] & 0xFF;
1446
- var b2 = data[i + 1] & 0xFF;
1447
- var b3 = data[i + 2] & 0xFF;
1448
- var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
1449
- var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
1450
- var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
1451
- buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
1452
- }
1453
- return buffer;
1454
- };
1455
- })();
1456
-
1457
- function MessageHandler(name, comObj) {
1458
- this.name = name;
1459
- this.comObj = comObj;
1460
- this.callbackIndex = 1;
1461
- this.postMessageTransfers = true;
1462
- var callbacksCapabilities = this.callbacksCapabilities = {};
1463
- var ah = this.actionHandler = {};
1464
-
1465
- ah['console_log'] = [function ahConsoleLog(data) {
1466
- console.log.apply(console, data);
1467
- }];
1468
- ah['console_error'] = [function ahConsoleError(data) {
1469
- console.error.apply(console, data);
1470
- }];
1471
- ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
1472
- UnsupportedManager.notify(data);
1473
- }];
1474
-
1475
- comObj.onmessage = function messageHandlerComObjOnMessage(event) {
1476
- var data = event.data;
1477
- if (data.isReply) {
1478
- var callbackId = data.callbackId;
1479
- if (data.callbackId in callbacksCapabilities) {
1480
- var callback = callbacksCapabilities[callbackId];
1481
- delete callbacksCapabilities[callbackId];
1482
- if ('error' in data) {
1483
- callback.reject(data.error);
1484
- } else {
1485
- callback.resolve(data.data);
1486
- }
1487
- } else {
1488
- error('Cannot resolve callback ' + callbackId);
1489
- }
1490
- } else if (data.action in ah) {
1491
- var action = ah[data.action];
1492
- if (data.callbackId) {
1493
- Promise.resolve().then(function () {
1494
- return action[0].call(action[1], data.data);
1495
- }).then(function (result) {
1496
- comObj.postMessage({
1497
- isReply: true,
1498
- callbackId: data.callbackId,
1499
- data: result
1500
- });
1501
- }, function (reason) {
1502
- comObj.postMessage({
1503
- isReply: true,
1504
- callbackId: data.callbackId,
1505
- error: reason
1506
- });
1507
- });
1508
- } else {
1509
- action[0].call(action[1], data.data);
1510
- }
1511
- } else {
1512
- error('Unknown action from worker: ' + data.action);
1513
- }
1514
- };
1515
- }
1516
-
1517
- MessageHandler.prototype = {
1518
- on: function messageHandlerOn(actionName, handler, scope) {
1519
- var ah = this.actionHandler;
1520
- if (ah[actionName]) {
1521
- error('There is already an actionName called "' + actionName + '"');
1522
- }
1523
- ah[actionName] = [handler, scope];
1524
- },
1525
- /**
1526
- * Sends a message to the comObj to invoke the action with the supplied data.
1527
- * @param {String} actionName Action to call.
1528
- * @param {JSON} data JSON data to send.
1529
- * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
1530
- */
1531
- send: function messageHandlerSend(actionName, data, transfers) {
1532
- var message = {
1533
- action: actionName,
1534
- data: data
1535
- };
1536
- this.postMessage(message, transfers);
1537
- },
1538
- /**
1539
- * Sends a message to the comObj to invoke the action with the supplied data.
1540
- * Expects that other side will callback with the response.
1541
- * @param {String} actionName Action to call.
1542
- * @param {JSON} data JSON data to send.
1543
- * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
1544
- * @returns {Promise} Promise to be resolved with response data.
1545
- */
1546
- sendWithPromise:
1547
- function messageHandlerSendWithPromise(actionName, data, transfers) {
1548
- var callbackId = this.callbackIndex++;
1549
- var message = {
1550
- action: actionName,
1551
- data: data,
1552
- callbackId: callbackId
1553
- };
1554
- var capability = createPromiseCapability();
1555
- this.callbacksCapabilities[callbackId] = capability;
1556
- try {
1557
- this.postMessage(message, transfers);
1558
- } catch (e) {
1559
- capability.reject(e);
1560
- }
1561
- return capability.promise;
1562
- },
1563
- /**
1564
- * Sends raw message to the comObj.
1565
- * @private
1566
- * @param message {Object} Raw message.
1567
- * @param transfers List of transfers/ArrayBuffers, or undefined.
1568
- */
1569
- postMessage: function (message, transfers) {
1570
- if (transfers && this.postMessageTransfers) {
1571
- this.comObj.postMessage(message, transfers);
1572
- } else {
1573
- this.comObj.postMessage(message);
1574
- }
1575
- }
1576
- };
1577
-
1578
- function loadJpegStream(id, imageUrl, objs) {
1579
- var img = new Image();
1580
- img.onload = (function loadJpegStream_onloadClosure() {
1581
- objs.resolve(id, img);
1582
- });
1583
- img.onerror = (function loadJpegStream_onerrorClosure() {
1584
- objs.resolve(id, null);
1585
- warn('Error during JPEG image loading');
1586
- });
1587
- img.src = imageUrl;
1588
- }
1
+ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
+ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
3
+ /* Copyright 2012 Mozilla Foundation
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /* globals Cmd, ColorSpace, Dict, MozBlobBuilder, Name, PDFJS, Ref, URL,
18
+ Promise */
19
+
20
+ 'use strict';
21
+
22
+ var globalScope = (typeof window === 'undefined') ? this : window;
23
+
24
+ var isWorker = (typeof window === 'undefined');
25
+
26
+ var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
27
+
28
+ var TextRenderingMode = {
29
+ FILL: 0,
30
+ STROKE: 1,
31
+ FILL_STROKE: 2,
32
+ INVISIBLE: 3,
33
+ FILL_ADD_TO_PATH: 4,
34
+ STROKE_ADD_TO_PATH: 5,
35
+ FILL_STROKE_ADD_TO_PATH: 6,
36
+ ADD_TO_PATH: 7,
37
+ FILL_STROKE_MASK: 3,
38
+ ADD_TO_PATH_FLAG: 4
39
+ };
40
+
41
+ var ImageKind = {
42
+ GRAYSCALE_1BPP: 1,
43
+ RGB_24BPP: 2,
44
+ RGBA_32BPP: 3
45
+ };
46
+
47
+ var AnnotationType = {
48
+ WIDGET: 1,
49
+ TEXT: 2,
50
+ LINK: 3
51
+ };
52
+
53
+ var StreamType = {
54
+ UNKNOWN: 0,
55
+ FLATE: 1,
56
+ LZW: 2,
57
+ DCT: 3,
58
+ JPX: 4,
59
+ JBIG: 5,
60
+ A85: 6,
61
+ AHX: 7,
62
+ CCF: 8,
63
+ RL: 9
64
+ };
65
+
66
+ var FontType = {
67
+ UNKNOWN: 0,
68
+ TYPE1: 1,
69
+ TYPE1C: 2,
70
+ CIDFONTTYPE0: 3,
71
+ CIDFONTTYPE0C: 4,
72
+ TRUETYPE: 5,
73
+ CIDFONTTYPE2: 6,
74
+ TYPE3: 7,
75
+ OPENTYPE: 8,
76
+ TYPE0: 9,
77
+ MMTYPE1: 10
78
+ };
79
+
80
+ // The global PDFJS object exposes the API
81
+ // In production, it will be declared outside a global wrapper
82
+ // In development, it will be declared here
83
+ if (!globalScope.PDFJS) {
84
+ globalScope.PDFJS = {};
85
+ }
86
+
87
+ globalScope.PDFJS.pdfBug = false;
88
+
89
+ PDFJS.VERBOSITY_LEVELS = {
90
+ errors: 0,
91
+ warnings: 1,
92
+ infos: 5
93
+ };
94
+
95
+ // All the possible operations for an operator list.
96
+ var OPS = PDFJS.OPS = {
97
+ // Intentionally start from 1 so it is easy to spot bad operators that will be
98
+ // 0's.
99
+ dependency: 1,
100
+ setLineWidth: 2,
101
+ setLineCap: 3,
102
+ setLineJoin: 4,
103
+ setMiterLimit: 5,
104
+ setDash: 6,
105
+ setRenderingIntent: 7,
106
+ setFlatness: 8,
107
+ setGState: 9,
108
+ save: 10,
109
+ restore: 11,
110
+ transform: 12,
111
+ moveTo: 13,
112
+ lineTo: 14,
113
+ curveTo: 15,
114
+ curveTo2: 16,
115
+ curveTo3: 17,
116
+ closePath: 18,
117
+ rectangle: 19,
118
+ stroke: 20,
119
+ closeStroke: 21,
120
+ fill: 22,
121
+ eoFill: 23,
122
+ fillStroke: 24,
123
+ eoFillStroke: 25,
124
+ closeFillStroke: 26,
125
+ closeEOFillStroke: 27,
126
+ endPath: 28,
127
+ clip: 29,
128
+ eoClip: 30,
129
+ beginText: 31,
130
+ endText: 32,
131
+ setCharSpacing: 33,
132
+ setWordSpacing: 34,
133
+ setHScale: 35,
134
+ setLeading: 36,
135
+ setFont: 37,
136
+ setTextRenderingMode: 38,
137
+ setTextRise: 39,
138
+ moveText: 40,
139
+ setLeadingMoveText: 41,
140
+ setTextMatrix: 42,
141
+ nextLine: 43,
142
+ showText: 44,
143
+ showSpacedText: 45,
144
+ nextLineShowText: 46,
145
+ nextLineSetSpacingShowText: 47,
146
+ setCharWidth: 48,
147
+ setCharWidthAndBounds: 49,
148
+ setStrokeColorSpace: 50,
149
+ setFillColorSpace: 51,
150
+ setStrokeColor: 52,
151
+ setStrokeColorN: 53,
152
+ setFillColor: 54,
153
+ setFillColorN: 55,
154
+ setStrokeGray: 56,
155
+ setFillGray: 57,
156
+ setStrokeRGBColor: 58,
157
+ setFillRGBColor: 59,
158
+ setStrokeCMYKColor: 60,
159
+ setFillCMYKColor: 61,
160
+ shadingFill: 62,
161
+ beginInlineImage: 63,
162
+ beginImageData: 64,
163
+ endInlineImage: 65,
164
+ paintXObject: 66,
165
+ markPoint: 67,
166
+ markPointProps: 68,
167
+ beginMarkedContent: 69,
168
+ beginMarkedContentProps: 70,
169
+ endMarkedContent: 71,
170
+ beginCompat: 72,
171
+ endCompat: 73,
172
+ paintFormXObjectBegin: 74,
173
+ paintFormXObjectEnd: 75,
174
+ beginGroup: 76,
175
+ endGroup: 77,
176
+ beginAnnotations: 78,
177
+ endAnnotations: 79,
178
+ beginAnnotation: 80,
179
+ endAnnotation: 81,
180
+ paintJpegXObject: 82,
181
+ paintImageMaskXObject: 83,
182
+ paintImageMaskXObjectGroup: 84,
183
+ paintImageXObject: 85,
184
+ paintInlineImageXObject: 86,
185
+ paintInlineImageXObjectGroup: 87,
186
+ paintImageXObjectRepeat: 88,
187
+ paintImageMaskXObjectRepeat: 89,
188
+ paintSolidColorImageMask: 90,
189
+ constructPath: 91
190
+ };
191
+
192
+ // A notice for devs. These are good for things that are helpful to devs, such
193
+ // as warning that Workers were disabled, which is important to devs but not
194
+ // end users.
195
+ function info(msg) {
196
+ if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) {
197
+ console.log('Info: ' + msg);
198
+ }
199
+ }
200
+
201
+ // Non-fatal warnings.
202
+ function warn(msg) {
203
+ if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) {
204
+ console.log('Warning: ' + msg);
205
+ }
206
+ }
207
+
208
+ // Fatal errors that should trigger the fallback UI and halt execution by
209
+ // throwing an exception.
210
+ function error(msg) {
211
+ // If multiple arguments were passed, pass them all to the log function.
212
+ if (arguments.length > 1) {
213
+ var logArguments = ['Error:'];
214
+ logArguments.push.apply(logArguments, arguments);
215
+ console.log.apply(console, logArguments);
216
+ // Join the arguments into a single string for the lines below.
217
+ msg = [].join.call(arguments, ' ');
218
+ } else {
219
+ console.log('Error: ' + msg);
220
+ }
221
+ console.log(backtrace());
222
+ UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown);
223
+ throw new Error(msg);
224
+ }
225
+
226
+ function backtrace() {
227
+ try {
228
+ throw new Error();
229
+ } catch (e) {
230
+ return e.stack ? e.stack.split('\n').slice(2).join('\n') : '';
231
+ }
232
+ }
233
+
234
+ function assert(cond, msg) {
235
+ if (!cond) {
236
+ error(msg);
237
+ }
238
+ }
239
+
240
+ var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = {
241
+ unknown: 'unknown',
242
+ forms: 'forms',
243
+ javaScript: 'javaScript',
244
+ smask: 'smask',
245
+ shadingPattern: 'shadingPattern',
246
+ font: 'font'
247
+ };
248
+
249
+ var UnsupportedManager = PDFJS.UnsupportedManager =
250
+ (function UnsupportedManagerClosure() {
251
+ var listeners = [];
252
+ return {
253
+ listen: function (cb) {
254
+ listeners.push(cb);
255
+ },
256
+ notify: function (featureId) {
257
+ warn('Unsupported feature "' + featureId + '"');
258
+ for (var i = 0, ii = listeners.length; i < ii; i++) {
259
+ listeners[i](featureId);
260
+ }
261
+ }
262
+ };
263
+ })();
264
+
265
+ // Combines two URLs. The baseUrl shall be absolute URL. If the url is an
266
+ // absolute URL, it will be returned as is.
267
+ function combineUrl(baseUrl, url) {
268
+ if (!url) {
269
+ return baseUrl;
270
+ }
271
+ if (/^[a-z][a-z0-9+\-.]*:/i.test(url)) {
272
+ return url;
273
+ }
274
+ var i;
275
+ if (url.charAt(0) === '/') {
276
+ // absolute path
277
+ i = baseUrl.indexOf('://');
278
+ if (url.charAt(1) === '/') {
279
+ ++i;
280
+ } else {
281
+ i = baseUrl.indexOf('/', i + 3);
282
+ }
283
+ return baseUrl.substring(0, i) + url;
284
+ } else {
285
+ // relative path
286
+ var pathLength = baseUrl.length;
287
+ i = baseUrl.lastIndexOf('#');
288
+ pathLength = i >= 0 ? i : pathLength;
289
+ i = baseUrl.lastIndexOf('?', pathLength);
290
+ pathLength = i >= 0 ? i : pathLength;
291
+ var prefixLength = baseUrl.lastIndexOf('/', pathLength);
292
+ return baseUrl.substring(0, prefixLength + 1) + url;
293
+ }
294
+ }
295
+
296
+ // Validates if URL is safe and allowed, e.g. to avoid XSS.
297
+ function isValidUrl(url, allowRelative) {
298
+ if (!url) {
299
+ return false;
300
+ }
301
+ // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1)
302
+ // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
303
+ var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url);
304
+ if (!protocol) {
305
+ return allowRelative;
306
+ }
307
+ protocol = protocol[0].toLowerCase();
308
+ switch (protocol) {
309
+ case 'http':
310
+ case 'https':
311
+ case 'ftp':
312
+ case 'mailto':
313
+ case 'tel':
314
+ return true;
315
+ default:
316
+ return false;
317
+ }
318
+ }
319
+ PDFJS.isValidUrl = isValidUrl;
320
+
321
+ function shadow(obj, prop, value) {
322
+ Object.defineProperty(obj, prop, { value: value,
323
+ enumerable: true,
324
+ configurable: true,
325
+ writable: false });
326
+ return value;
327
+ }
328
+ PDFJS.shadow = shadow;
329
+
330
+ var PasswordResponses = PDFJS.PasswordResponses = {
331
+ NEED_PASSWORD: 1,
332
+ INCORRECT_PASSWORD: 2
333
+ };
334
+
335
+ var PasswordException = (function PasswordExceptionClosure() {
336
+ function PasswordException(msg, code) {
337
+ this.name = 'PasswordException';
338
+ this.message = msg;
339
+ this.code = code;
340
+ }
341
+
342
+ PasswordException.prototype = new Error();
343
+ PasswordException.constructor = PasswordException;
344
+
345
+ return PasswordException;
346
+ })();
347
+ PDFJS.PasswordException = PasswordException;
348
+
349
+ var UnknownErrorException = (function UnknownErrorExceptionClosure() {
350
+ function UnknownErrorException(msg, details) {
351
+ this.name = 'UnknownErrorException';
352
+ this.message = msg;
353
+ this.details = details;
354
+ }
355
+
356
+ UnknownErrorException.prototype = new Error();
357
+ UnknownErrorException.constructor = UnknownErrorException;
358
+
359
+ return UnknownErrorException;
360
+ })();
361
+ PDFJS.UnknownErrorException = UnknownErrorException;
362
+
363
+ var InvalidPDFException = (function InvalidPDFExceptionClosure() {
364
+ function InvalidPDFException(msg) {
365
+ this.name = 'InvalidPDFException';
366
+ this.message = msg;
367
+ }
368
+
369
+ InvalidPDFException.prototype = new Error();
370
+ InvalidPDFException.constructor = InvalidPDFException;
371
+
372
+ return InvalidPDFException;
373
+ })();
374
+ PDFJS.InvalidPDFException = InvalidPDFException;
375
+
376
+ var MissingPDFException = (function MissingPDFExceptionClosure() {
377
+ function MissingPDFException(msg) {
378
+ this.name = 'MissingPDFException';
379
+ this.message = msg;
380
+ }
381
+
382
+ MissingPDFException.prototype = new Error();
383
+ MissingPDFException.constructor = MissingPDFException;
384
+
385
+ return MissingPDFException;
386
+ })();
387
+ PDFJS.MissingPDFException = MissingPDFException;
388
+
389
+ var UnexpectedResponseException =
390
+ (function UnexpectedResponseExceptionClosure() {
391
+ function UnexpectedResponseException(msg, status) {
392
+ this.name = 'UnexpectedResponseException';
393
+ this.message = msg;
394
+ this.status = status;
395
+ }
396
+
397
+ UnexpectedResponseException.prototype = new Error();
398
+ UnexpectedResponseException.constructor = UnexpectedResponseException;
399
+
400
+ return UnexpectedResponseException;
401
+ })();
402
+ PDFJS.UnexpectedResponseException = UnexpectedResponseException;
403
+
404
+ var NotImplementedException = (function NotImplementedExceptionClosure() {
405
+ function NotImplementedException(msg) {
406
+ this.message = msg;
407
+ }
408
+
409
+ NotImplementedException.prototype = new Error();
410
+ NotImplementedException.prototype.name = 'NotImplementedException';
411
+ NotImplementedException.constructor = NotImplementedException;
412
+
413
+ return NotImplementedException;
414
+ })();
415
+
416
+ var MissingDataException = (function MissingDataExceptionClosure() {
417
+ function MissingDataException(begin, end) {
418
+ this.begin = begin;
419
+ this.end = end;
420
+ this.message = 'Missing data [' + begin + ', ' + end + ')';
421
+ }
422
+
423
+ MissingDataException.prototype = new Error();
424
+ MissingDataException.prototype.name = 'MissingDataException';
425
+ MissingDataException.constructor = MissingDataException;
426
+
427
+ return MissingDataException;
428
+ })();
429
+
430
+ var XRefParseException = (function XRefParseExceptionClosure() {
431
+ function XRefParseException(msg) {
432
+ this.message = msg;
433
+ }
434
+
435
+ XRefParseException.prototype = new Error();
436
+ XRefParseException.prototype.name = 'XRefParseException';
437
+ XRefParseException.constructor = XRefParseException;
438
+
439
+ return XRefParseException;
440
+ })();
441
+
442
+
443
+ function bytesToString(bytes) {
444
+ assert(bytes !== null && typeof bytes === 'object' &&
445
+ bytes.length !== undefined, 'Invalid argument for bytesToString');
446
+ var length = bytes.length;
447
+ var MAX_ARGUMENT_COUNT = 8192;
448
+ if (length < MAX_ARGUMENT_COUNT) {
449
+ return String.fromCharCode.apply(null, bytes);
450
+ }
451
+ var strBuf = [];
452
+ for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
453
+ var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
454
+ var chunk = bytes.subarray(i, chunkEnd);
455
+ strBuf.push(String.fromCharCode.apply(null, chunk));
456
+ }
457
+ return strBuf.join('');
458
+ }
459
+
460
+ function stringToBytes(str) {
461
+ assert(typeof str === 'string', 'Invalid argument for stringToBytes');
462
+ var length = str.length;
463
+ var bytes = new Uint8Array(length);
464
+ for (var i = 0; i < length; ++i) {
465
+ bytes[i] = str.charCodeAt(i) & 0xFF;
466
+ }
467
+ return bytes;
468
+ }
469
+
470
+ function string32(value) {
471
+ return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff,
472
+ (value >> 8) & 0xff, value & 0xff);
473
+ }
474
+
475
+ function log2(x) {
476
+ var n = 1, i = 0;
477
+ while (x > n) {
478
+ n <<= 1;
479
+ i++;
480
+ }
481
+ return i;
482
+ }
483
+
484
+ function readInt8(data, start) {
485
+ return (data[start] << 24) >> 24;
486
+ }
487
+
488
+ function readUint16(data, offset) {
489
+ return (data[offset] << 8) | data[offset + 1];
490
+ }
491
+
492
+ function readUint32(data, offset) {
493
+ return ((data[offset] << 24) | (data[offset + 1] << 16) |
494
+ (data[offset + 2] << 8) | data[offset + 3]) >>> 0;
495
+ }
496
+
497
+ // Lazy test the endianness of the platform
498
+ // NOTE: This will be 'true' for simulated TypedArrays
499
+ function isLittleEndian() {
500
+ var buffer8 = new Uint8Array(2);
501
+ buffer8[0] = 1;
502
+ var buffer16 = new Uint16Array(buffer8.buffer);
503
+ return (buffer16[0] === 1);
504
+ }
505
+
506
+ Object.defineProperty(PDFJS, 'isLittleEndian', {
507
+ configurable: true,
508
+ get: function PDFJS_isLittleEndian() {
509
+ return shadow(PDFJS, 'isLittleEndian', isLittleEndian());
510
+ }
511
+ });
512
+
513
+ //#if !(FIREFOX || MOZCENTRAL || B2G || CHROME)
514
+ //// Lazy test if the userAgant support CanvasTypedArrays
515
+ function hasCanvasTypedArrays() {
516
+ var canvas = document.createElement('canvas');
517
+ canvas.width = canvas.height = 1;
518
+ var ctx = canvas.getContext('2d');
519
+ var imageData = ctx.createImageData(1, 1);
520
+ return (typeof imageData.data.buffer !== 'undefined');
521
+ }
522
+
523
+ Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', {
524
+ configurable: true,
525
+ get: function PDFJS_hasCanvasTypedArrays() {
526
+ return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays());
527
+ }
528
+ });
529
+
530
+ var Uint32ArrayView = (function Uint32ArrayViewClosure() {
531
+
532
+ function Uint32ArrayView(buffer, length) {
533
+ this.buffer = buffer;
534
+ this.byteLength = buffer.length;
535
+ this.length = length === undefined ? (this.byteLength >> 2) : length;
536
+ ensureUint32ArrayViewProps(this.length);
537
+ }
538
+ Uint32ArrayView.prototype = Object.create(null);
539
+
540
+ var uint32ArrayViewSetters = 0;
541
+ function createUint32ArrayProp(index) {
542
+ return {
543
+ get: function () {
544
+ var buffer = this.buffer, offset = index << 2;
545
+ return (buffer[offset] | (buffer[offset + 1] << 8) |
546
+ (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0;
547
+ },
548
+ set: function (value) {
549
+ var buffer = this.buffer, offset = index << 2;
550
+ buffer[offset] = value & 255;
551
+ buffer[offset + 1] = (value >> 8) & 255;
552
+ buffer[offset + 2] = (value >> 16) & 255;
553
+ buffer[offset + 3] = (value >>> 24) & 255;
554
+ }
555
+ };
556
+ }
557
+
558
+ function ensureUint32ArrayViewProps(length) {
559
+ while (uint32ArrayViewSetters < length) {
560
+ Object.defineProperty(Uint32ArrayView.prototype,
561
+ uint32ArrayViewSetters,
562
+ createUint32ArrayProp(uint32ArrayViewSetters));
563
+ uint32ArrayViewSetters++;
564
+ }
565
+ }
566
+
567
+ return Uint32ArrayView;
568
+ })();
569
+ //#else
570
+ //PDFJS.hasCanvasTypedArrays = true;
571
+ //#endif
572
+
573
+ var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
574
+
575
+ var Util = PDFJS.Util = (function UtilClosure() {
576
+ function Util() {}
577
+
578
+ var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')'];
579
+
580
+ // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids
581
+ // creating many intermediate strings.
582
+ Util.makeCssRgb = function Util_makeCssRgb(r, g, b) {
583
+ rgbBuf[1] = r;
584
+ rgbBuf[3] = g;
585
+ rgbBuf[5] = b;
586
+ return rgbBuf.join('');
587
+ };
588
+
589
+ // Concatenates two transformation matrices together and returns the result.
590
+ Util.transform = function Util_transform(m1, m2) {
591
+ return [
592
+ m1[0] * m2[0] + m1[2] * m2[1],
593
+ m1[1] * m2[0] + m1[3] * m2[1],
594
+ m1[0] * m2[2] + m1[2] * m2[3],
595
+ m1[1] * m2[2] + m1[3] * m2[3],
596
+ m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
597
+ m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
598
+ ];
599
+ };
600
+
601
+ // For 2d affine transforms
602
+ Util.applyTransform = function Util_applyTransform(p, m) {
603
+ var xt = p[0] * m[0] + p[1] * m[2] + m[4];
604
+ var yt = p[0] * m[1] + p[1] * m[3] + m[5];
605
+ return [xt, yt];
606
+ };
607
+
608
+ Util.applyInverseTransform = function Util_applyInverseTransform(p, m) {
609
+ var d = m[0] * m[3] - m[1] * m[2];
610
+ var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
611
+ var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
612
+ return [xt, yt];
613
+ };
614
+
615
+ // Applies the transform to the rectangle and finds the minimum axially
616
+ // aligned bounding box.
617
+ Util.getAxialAlignedBoundingBox =
618
+ function Util_getAxialAlignedBoundingBox(r, m) {
619
+
620
+ var p1 = Util.applyTransform(r, m);
621
+ var p2 = Util.applyTransform(r.slice(2, 4), m);
622
+ var p3 = Util.applyTransform([r[0], r[3]], m);
623
+ var p4 = Util.applyTransform([r[2], r[1]], m);
624
+ return [
625
+ Math.min(p1[0], p2[0], p3[0], p4[0]),
626
+ Math.min(p1[1], p2[1], p3[1], p4[1]),
627
+ Math.max(p1[0], p2[0], p3[0], p4[0]),
628
+ Math.max(p1[1], p2[1], p3[1], p4[1])
629
+ ];
630
+ };
631
+
632
+ Util.inverseTransform = function Util_inverseTransform(m) {
633
+ var d = m[0] * m[3] - m[1] * m[2];
634
+ return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d,
635
+ (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
636
+ };
637
+
638
+ // Apply a generic 3d matrix M on a 3-vector v:
639
+ // | a b c | | X |
640
+ // | d e f | x | Y |
641
+ // | g h i | | Z |
642
+ // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i],
643
+ // with v as [X,Y,Z]
644
+ Util.apply3dTransform = function Util_apply3dTransform(m, v) {
645
+ return [
646
+ m[0] * v[0] + m[1] * v[1] + m[2] * v[2],
647
+ m[3] * v[0] + m[4] * v[1] + m[5] * v[2],
648
+ m[6] * v[0] + m[7] * v[1] + m[8] * v[2]
649
+ ];
650
+ };
651
+
652
+ // This calculation uses Singular Value Decomposition.
653
+ // The SVD can be represented with formula A = USV. We are interested in the
654
+ // matrix S here because it represents the scale values.
655
+ Util.singularValueDecompose2dScale =
656
+ function Util_singularValueDecompose2dScale(m) {
657
+
658
+ var transpose = [m[0], m[2], m[1], m[3]];
659
+
660
+ // Multiply matrix m with its transpose.
661
+ var a = m[0] * transpose[0] + m[1] * transpose[2];
662
+ var b = m[0] * transpose[1] + m[1] * transpose[3];
663
+ var c = m[2] * transpose[0] + m[3] * transpose[2];
664
+ var d = m[2] * transpose[1] + m[3] * transpose[3];
665
+
666
+ // Solve the second degree polynomial to get roots.
667
+ var first = (a + d) / 2;
668
+ var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2;
669
+ var sx = first + second || 1;
670
+ var sy = first - second || 1;
671
+
672
+ // Scale values are the square roots of the eigenvalues.
673
+ return [Math.sqrt(sx), Math.sqrt(sy)];
674
+ };
675
+
676
+ // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2)
677
+ // For coordinate systems whose origin lies in the bottom-left, this
678
+ // means normalization to (BL,TR) ordering. For systems with origin in the
679
+ // top-left, this means (TL,BR) ordering.
680
+ Util.normalizeRect = function Util_normalizeRect(rect) {
681
+ var r = rect.slice(0); // clone rect
682
+ if (rect[0] > rect[2]) {
683
+ r[0] = rect[2];
684
+ r[2] = rect[0];
685
+ }
686
+ if (rect[1] > rect[3]) {
687
+ r[1] = rect[3];
688
+ r[3] = rect[1];
689
+ }
690
+ return r;
691
+ };
692
+
693
+ // Returns a rectangle [x1, y1, x2, y2] corresponding to the
694
+ // intersection of rect1 and rect2. If no intersection, returns 'false'
695
+ // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
696
+ Util.intersect = function Util_intersect(rect1, rect2) {
697
+ function compare(a, b) {
698
+ return a - b;
699
+ }
700
+
701
+ // Order points along the axes
702
+ var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare),
703
+ orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare),
704
+ result = [];
705
+
706
+ rect1 = Util.normalizeRect(rect1);
707
+ rect2 = Util.normalizeRect(rect2);
708
+
709
+ // X: first and second points belong to different rectangles?
710
+ if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
711
+ (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) {
712
+ // Intersection must be between second and third points
713
+ result[0] = orderedX[1];
714
+ result[2] = orderedX[2];
715
+ } else {
716
+ return false;
717
+ }
718
+
719
+ // Y: first and second points belong to different rectangles?
720
+ if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
721
+ (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) {
722
+ // Intersection must be between second and third points
723
+ result[1] = orderedY[1];
724
+ result[3] = orderedY[2];
725
+ } else {
726
+ return false;
727
+ }
728
+
729
+ return result;
730
+ };
731
+
732
+ Util.sign = function Util_sign(num) {
733
+ return num < 0 ? -1 : 1;
734
+ };
735
+
736
+ Util.appendToArray = function Util_appendToArray(arr1, arr2) {
737
+ Array.prototype.push.apply(arr1, arr2);
738
+ };
739
+
740
+ Util.prependToArray = function Util_prependToArray(arr1, arr2) {
741
+ Array.prototype.unshift.apply(arr1, arr2);
742
+ };
743
+
744
+ Util.extendObj = function extendObj(obj1, obj2) {
745
+ for (var key in obj2) {
746
+ obj1[key] = obj2[key];
747
+ }
748
+ };
749
+
750
+ Util.getInheritableProperty = function Util_getInheritableProperty(dict,
751
+ name) {
752
+ while (dict && !dict.has(name)) {
753
+ dict = dict.get('Parent');
754
+ }
755
+ if (!dict) {
756
+ return null;
757
+ }
758
+ return dict.get(name);
759
+ };
760
+
761
+ Util.inherit = function Util_inherit(sub, base, prototype) {
762
+ sub.prototype = Object.create(base.prototype);
763
+ sub.prototype.constructor = sub;
764
+ for (var prop in prototype) {
765
+ sub.prototype[prop] = prototype[prop];
766
+ }
767
+ };
768
+
769
+ Util.loadScript = function Util_loadScript(src, callback) {
770
+ var script = document.createElement('script');
771
+ var loaded = false;
772
+ script.setAttribute('src', src);
773
+ if (callback) {
774
+ script.onload = function() {
775
+ if (!loaded) {
776
+ callback();
777
+ }
778
+ loaded = true;
779
+ };
780
+ }
781
+ document.getElementsByTagName('head')[0].appendChild(script);
782
+ };
783
+
784
+ return Util;
785
+ })();
786
+
787
+ /**
788
+ * PDF page viewport created based on scale, rotation and offset.
789
+ * @class
790
+ * @alias PDFJS.PageViewport
791
+ */
792
+ var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() {
793
+ /**
794
+ * @constructor
795
+ * @private
796
+ * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates.
797
+ * @param scale {number} scale of the viewport.
798
+ * @param rotation {number} rotations of the viewport in degrees.
799
+ * @param offsetX {number} offset X
800
+ * @param offsetY {number} offset Y
801
+ * @param dontFlip {boolean} if true, axis Y will not be flipped.
802
+ */
803
+ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) {
804
+ this.viewBox = viewBox;
805
+ this.scale = scale;
806
+ this.rotation = rotation;
807
+ this.offsetX = offsetX;
808
+ this.offsetY = offsetY;
809
+
810
+ // creating transform to convert pdf coordinate system to the normal
811
+ // canvas like coordinates taking in account scale and rotation
812
+ var centerX = (viewBox[2] + viewBox[0]) / 2;
813
+ var centerY = (viewBox[3] + viewBox[1]) / 2;
814
+ var rotateA, rotateB, rotateC, rotateD;
815
+ rotation = rotation % 360;
816
+ rotation = rotation < 0 ? rotation + 360 : rotation;
817
+ switch (rotation) {
818
+ case 180:
819
+ rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1;
820
+ break;
821
+ case 90:
822
+ rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0;
823
+ break;
824
+ case 270:
825
+ rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0;
826
+ break;
827
+ //case 0:
828
+ default:
829
+ rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1;
830
+ break;
831
+ }
832
+
833
+ if (dontFlip) {
834
+ rotateC = -rotateC; rotateD = -rotateD;
835
+ }
836
+
837
+ var offsetCanvasX, offsetCanvasY;
838
+ var width, height;
839
+ if (rotateA === 0) {
840
+ offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
841
+ offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
842
+ width = Math.abs(viewBox[3] - viewBox[1]) * scale;
843
+ height = Math.abs(viewBox[2] - viewBox[0]) * scale;
844
+ } else {
845
+ offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
846
+ offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
847
+ width = Math.abs(viewBox[2] - viewBox[0]) * scale;
848
+ height = Math.abs(viewBox[3] - viewBox[1]) * scale;
849
+ }
850
+ // creating transform for the following operations:
851
+ // translate(-centerX, -centerY), rotate and flip vertically,
852
+ // scale, and translate(offsetCanvasX, offsetCanvasY)
853
+ this.transform = [
854
+ rotateA * scale,
855
+ rotateB * scale,
856
+ rotateC * scale,
857
+ rotateD * scale,
858
+ offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY,
859
+ offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY
860
+ ];
861
+
862
+ this.width = width;
863
+ this.height = height;
864
+ this.fontScale = scale;
865
+ }
866
+ PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ {
867
+ /**
868
+ * Clones viewport with additional properties.
869
+ * @param args {Object} (optional) If specified, may contain the 'scale' or
870
+ * 'rotation' properties to override the corresponding properties in
871
+ * the cloned viewport.
872
+ * @returns {PDFJS.PageViewport} Cloned viewport.
873
+ */
874
+ clone: function PageViewPort_clone(args) {
875
+ args = args || {};
876
+ var scale = 'scale' in args ? args.scale : this.scale;
877
+ var rotation = 'rotation' in args ? args.rotation : this.rotation;
878
+ return new PageViewport(this.viewBox.slice(), scale, rotation,
879
+ this.offsetX, this.offsetY, args.dontFlip);
880
+ },
881
+ /**
882
+ * Converts PDF point to the viewport coordinates. For examples, useful for
883
+ * converting PDF location into canvas pixel coordinates.
884
+ * @param x {number} X coordinate.
885
+ * @param y {number} Y coordinate.
886
+ * @returns {Object} Object that contains 'x' and 'y' properties of the
887
+ * point in the viewport coordinate space.
888
+ * @see {@link convertToPdfPoint}
889
+ * @see {@link convertToViewportRectangle}
890
+ */
891
+ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) {
892
+ return Util.applyTransform([x, y], this.transform);
893
+ },
894
+ /**
895
+ * Converts PDF rectangle to the viewport coordinates.
896
+ * @param rect {Array} xMin, yMin, xMax and yMax coordinates.
897
+ * @returns {Array} Contains corresponding coordinates of the rectangle
898
+ * in the viewport coordinate space.
899
+ * @see {@link convertToViewportPoint}
900
+ */
901
+ convertToViewportRectangle:
902
+ function PageViewport_convertToViewportRectangle(rect) {
903
+ var tl = Util.applyTransform([rect[0], rect[1]], this.transform);
904
+ var br = Util.applyTransform([rect[2], rect[3]], this.transform);
905
+ return [tl[0], tl[1], br[0], br[1]];
906
+ },
907
+ /**
908
+ * Converts viewport coordinates to the PDF location. For examples, useful
909
+ * for converting canvas pixel location into PDF one.
910
+ * @param x {number} X coordinate.
911
+ * @param y {number} Y coordinate.
912
+ * @returns {Object} Object that contains 'x' and 'y' properties of the
913
+ * point in the PDF coordinate space.
914
+ * @see {@link convertToViewportPoint}
915
+ */
916
+ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) {
917
+ return Util.applyInverseTransform([x, y], this.transform);
918
+ }
919
+ };
920
+ return PageViewport;
921
+ })();
922
+
923
+ var PDFStringTranslateTable = [
924
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
925
+ 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0,
926
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
927
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
928
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
929
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014,
930
+ 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C,
931
+ 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160,
932
+ 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC
933
+ ];
934
+
935
+ function stringToPDFString(str) {
936
+ var i, n = str.length, strBuf = [];
937
+ if (str[0] === '\xFE' && str[1] === '\xFF') {
938
+ // UTF16BE BOM
939
+ for (i = 2; i < n; i += 2) {
940
+ strBuf.push(String.fromCharCode(
941
+ (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1)));
942
+ }
943
+ } else {
944
+ for (i = 0; i < n; ++i) {
945
+ var code = PDFStringTranslateTable[str.charCodeAt(i)];
946
+ strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
947
+ }
948
+ }
949
+ return strBuf.join('');
950
+ }
951
+
952
+ function stringToUTF8String(str) {
953
+ return decodeURIComponent(escape(str));
954
+ }
955
+
956
+ function isEmptyObj(obj) {
957
+ for (var key in obj) {
958
+ return false;
959
+ }
960
+ return true;
961
+ }
962
+
963
+ function isBool(v) {
964
+ return typeof v === 'boolean';
965
+ }
966
+
967
+ function isInt(v) {
968
+ return typeof v === 'number' && ((v | 0) === v);
969
+ }
970
+
971
+ function isNum(v) {
972
+ return typeof v === 'number';
973
+ }
974
+
975
+ function isString(v) {
976
+ return typeof v === 'string';
977
+ }
978
+
979
+ function isName(v) {
980
+ return v instanceof Name;
981
+ }
982
+
983
+ function isCmd(v, cmd) {
984
+ return v instanceof Cmd && (cmd === undefined || v.cmd === cmd);
985
+ }
986
+
987
+ function isDict(v, type) {
988
+ if (!(v instanceof Dict)) {
989
+ return false;
990
+ }
991
+ if (!type) {
992
+ return true;
993
+ }
994
+ var dictType = v.get('Type');
995
+ return isName(dictType) && dictType.name === type;
996
+ }
997
+
998
+ function isArray(v) {
999
+ return v instanceof Array;
1000
+ }
1001
+
1002
+ function isStream(v) {
1003
+ return typeof v === 'object' && v !== null && v.getBytes !== undefined;
1004
+ }
1005
+
1006
+ function isArrayBuffer(v) {
1007
+ return typeof v === 'object' && v !== null && v.byteLength !== undefined;
1008
+ }
1009
+
1010
+ function isRef(v) {
1011
+ return v instanceof Ref;
1012
+ }
1013
+
1014
+ /**
1015
+ * Promise Capability object.
1016
+ *
1017
+ * @typedef {Object} PromiseCapability
1018
+ * @property {Promise} promise - A promise object.
1019
+ * @property {function} resolve - Fullfills the promise.
1020
+ * @property {function} reject - Rejects the promise.
1021
+ */
1022
+
1023
+ /**
1024
+ * Creates a promise capability object.
1025
+ * @alias PDFJS.createPromiseCapability
1026
+ *
1027
+ * @return {PromiseCapability} A capability object contains:
1028
+ * - a Promise, resolve and reject methods.
1029
+ */
1030
+ function createPromiseCapability() {
1031
+ var capability = {};
1032
+ capability.promise = new Promise(function (resolve, reject) {
1033
+ capability.resolve = resolve;
1034
+ capability.reject = reject;
1035
+ });
1036
+ return capability;
1037
+ }
1038
+
1039
+ PDFJS.createPromiseCapability = createPromiseCapability;
1040
+
1041
+ /**
1042
+ * Polyfill for Promises:
1043
+ * The following promise implementation tries to generally implement the
1044
+ * Promise/A+ spec. Some notable differences from other promise libaries are:
1045
+ * - There currently isn't a seperate deferred and promise object.
1046
+ * - Unhandled rejections eventually show an error if they aren't handled.
1047
+ *
1048
+ * Based off of the work in:
1049
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=810490
1050
+ */
1051
+ (function PromiseClosure() {
1052
+ if (globalScope.Promise) {
1053
+ // Promises existing in the DOM/Worker, checking presence of all/resolve
1054
+ if (typeof globalScope.Promise.all !== 'function') {
1055
+ globalScope.Promise.all = function (iterable) {
1056
+ var count = 0, results = [], resolve, reject;
1057
+ var promise = new globalScope.Promise(function (resolve_, reject_) {
1058
+ resolve = resolve_;
1059
+ reject = reject_;
1060
+ });
1061
+ iterable.forEach(function (p, i) {
1062
+ count++;
1063
+ p.then(function (result) {
1064
+ results[i] = result;
1065
+ count--;
1066
+ if (count === 0) {
1067
+ resolve(results);
1068
+ }
1069
+ }, reject);
1070
+ });
1071
+ if (count === 0) {
1072
+ resolve(results);
1073
+ }
1074
+ return promise;
1075
+ };
1076
+ }
1077
+ if (typeof globalScope.Promise.resolve !== 'function') {
1078
+ globalScope.Promise.resolve = function (value) {
1079
+ return new globalScope.Promise(function (resolve) { resolve(value); });
1080
+ };
1081
+ }
1082
+ if (typeof globalScope.Promise.reject !== 'function') {
1083
+ globalScope.Promise.reject = function (reason) {
1084
+ return new globalScope.Promise(function (resolve, reject) {
1085
+ reject(reason);
1086
+ });
1087
+ };
1088
+ }
1089
+ if (typeof globalScope.Promise.prototype.catch !== 'function') {
1090
+ globalScope.Promise.prototype.catch = function (onReject) {
1091
+ return globalScope.Promise.prototype.then(undefined, onReject);
1092
+ };
1093
+ }
1094
+ return;
1095
+ }
1096
+ //#if !MOZCENTRAL
1097
+ var STATUS_PENDING = 0;
1098
+ var STATUS_RESOLVED = 1;
1099
+ var STATUS_REJECTED = 2;
1100
+
1101
+ // In an attempt to avoid silent exceptions, unhandled rejections are
1102
+ // tracked and if they aren't handled in a certain amount of time an
1103
+ // error is logged.
1104
+ var REJECTION_TIMEOUT = 500;
1105
+
1106
+ var HandlerManager = {
1107
+ handlers: [],
1108
+ running: false,
1109
+ unhandledRejections: [],
1110
+ pendingRejectionCheck: false,
1111
+
1112
+ scheduleHandlers: function scheduleHandlers(promise) {
1113
+ if (promise._status === STATUS_PENDING) {
1114
+ return;
1115
+ }
1116
+
1117
+ this.handlers = this.handlers.concat(promise._handlers);
1118
+ promise._handlers = [];
1119
+
1120
+ if (this.running) {
1121
+ return;
1122
+ }
1123
+ this.running = true;
1124
+
1125
+ setTimeout(this.runHandlers.bind(this), 0);
1126
+ },
1127
+
1128
+ runHandlers: function runHandlers() {
1129
+ var RUN_TIMEOUT = 1; // ms
1130
+ var timeoutAt = Date.now() + RUN_TIMEOUT;
1131
+ while (this.handlers.length > 0) {
1132
+ var handler = this.handlers.shift();
1133
+
1134
+ var nextStatus = handler.thisPromise._status;
1135
+ var nextValue = handler.thisPromise._value;
1136
+
1137
+ try {
1138
+ if (nextStatus === STATUS_RESOLVED) {
1139
+ if (typeof handler.onResolve === 'function') {
1140
+ nextValue = handler.onResolve(nextValue);
1141
+ }
1142
+ } else if (typeof handler.onReject === 'function') {
1143
+ nextValue = handler.onReject(nextValue);
1144
+ nextStatus = STATUS_RESOLVED;
1145
+
1146
+ if (handler.thisPromise._unhandledRejection) {
1147
+ this.removeUnhandeledRejection(handler.thisPromise);
1148
+ }
1149
+ }
1150
+ } catch (ex) {
1151
+ nextStatus = STATUS_REJECTED;
1152
+ nextValue = ex;
1153
+ }
1154
+
1155
+ handler.nextPromise._updateStatus(nextStatus, nextValue);
1156
+ if (Date.now() >= timeoutAt) {
1157
+ break;
1158
+ }
1159
+ }
1160
+
1161
+ if (this.handlers.length > 0) {
1162
+ setTimeout(this.runHandlers.bind(this), 0);
1163
+ return;
1164
+ }
1165
+
1166
+ this.running = false;
1167
+ },
1168
+
1169
+ addUnhandledRejection: function addUnhandledRejection(promise) {
1170
+ this.unhandledRejections.push({
1171
+ promise: promise,
1172
+ time: Date.now()
1173
+ });
1174
+ this.scheduleRejectionCheck();
1175
+ },
1176
+
1177
+ removeUnhandeledRejection: function removeUnhandeledRejection(promise) {
1178
+ promise._unhandledRejection = false;
1179
+ for (var i = 0; i < this.unhandledRejections.length; i++) {
1180
+ if (this.unhandledRejections[i].promise === promise) {
1181
+ this.unhandledRejections.splice(i);
1182
+ i--;
1183
+ }
1184
+ }
1185
+ },
1186
+
1187
+ scheduleRejectionCheck: function scheduleRejectionCheck() {
1188
+ if (this.pendingRejectionCheck) {
1189
+ return;
1190
+ }
1191
+ this.pendingRejectionCheck = true;
1192
+ setTimeout(function rejectionCheck() {
1193
+ this.pendingRejectionCheck = false;
1194
+ var now = Date.now();
1195
+ for (var i = 0; i < this.unhandledRejections.length; i++) {
1196
+ if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) {
1197
+ var unhandled = this.unhandledRejections[i].promise._value;
1198
+ var msg = 'Unhandled rejection: ' + unhandled;
1199
+ if (unhandled.stack) {
1200
+ msg += '\n' + unhandled.stack;
1201
+ }
1202
+ warn(msg);
1203
+ this.unhandledRejections.splice(i);
1204
+ i--;
1205
+ }
1206
+ }
1207
+ if (this.unhandledRejections.length) {
1208
+ this.scheduleRejectionCheck();
1209
+ }
1210
+ }.bind(this), REJECTION_TIMEOUT);
1211
+ }
1212
+ };
1213
+
1214
+ function Promise(resolver) {
1215
+ this._status = STATUS_PENDING;
1216
+ this._handlers = [];
1217
+ try {
1218
+ resolver.call(this, this._resolve.bind(this), this._reject.bind(this));
1219
+ } catch (e) {
1220
+ this._reject(e);
1221
+ }
1222
+ }
1223
+ /**
1224
+ * Builds a promise that is resolved when all the passed in promises are
1225
+ * resolved.
1226
+ * @param {array} array of data and/or promises to wait for.
1227
+ * @return {Promise} New dependant promise.
1228
+ */
1229
+ Promise.all = function Promise_all(promises) {
1230
+ var resolveAll, rejectAll;
1231
+ var deferred = new Promise(function (resolve, reject) {
1232
+ resolveAll = resolve;
1233
+ rejectAll = reject;
1234
+ });
1235
+ var unresolved = promises.length;
1236
+ var results = [];
1237
+ if (unresolved === 0) {
1238
+ resolveAll(results);
1239
+ return deferred;
1240
+ }
1241
+ function reject(reason) {
1242
+ if (deferred._status === STATUS_REJECTED) {
1243
+ return;
1244
+ }
1245
+ results = [];
1246
+ rejectAll(reason);
1247
+ }
1248
+ for (var i = 0, ii = promises.length; i < ii; ++i) {
1249
+ var promise = promises[i];
1250
+ var resolve = (function(i) {
1251
+ return function(value) {
1252
+ if (deferred._status === STATUS_REJECTED) {
1253
+ return;
1254
+ }
1255
+ results[i] = value;
1256
+ unresolved--;
1257
+ if (unresolved === 0) {
1258
+ resolveAll(results);
1259
+ }
1260
+ };
1261
+ })(i);
1262
+ if (Promise.isPromise(promise)) {
1263
+ promise.then(resolve, reject);
1264
+ } else {
1265
+ resolve(promise);
1266
+ }
1267
+ }
1268
+ return deferred;
1269
+ };
1270
+
1271
+ /**
1272
+ * Checks if the value is likely a promise (has a 'then' function).
1273
+ * @return {boolean} true if value is thenable
1274
+ */
1275
+ Promise.isPromise = function Promise_isPromise(value) {
1276
+ return value && typeof value.then === 'function';
1277
+ };
1278
+
1279
+ /**
1280
+ * Creates resolved promise
1281
+ * @param value resolve value
1282
+ * @returns {Promise}
1283
+ */
1284
+ Promise.resolve = function Promise_resolve(value) {
1285
+ return new Promise(function (resolve) { resolve(value); });
1286
+ };
1287
+
1288
+ /**
1289
+ * Creates rejected promise
1290
+ * @param reason rejection value
1291
+ * @returns {Promise}
1292
+ */
1293
+ Promise.reject = function Promise_reject(reason) {
1294
+ return new Promise(function (resolve, reject) { reject(reason); });
1295
+ };
1296
+
1297
+ Promise.prototype = {
1298
+ _status: null,
1299
+ _value: null,
1300
+ _handlers: null,
1301
+ _unhandledRejection: null,
1302
+
1303
+ _updateStatus: function Promise__updateStatus(status, value) {
1304
+ if (this._status === STATUS_RESOLVED ||
1305
+ this._status === STATUS_REJECTED) {
1306
+ return;
1307
+ }
1308
+
1309
+ if (status === STATUS_RESOLVED &&
1310
+ Promise.isPromise(value)) {
1311
+ value.then(this._updateStatus.bind(this, STATUS_RESOLVED),
1312
+ this._updateStatus.bind(this, STATUS_REJECTED));
1313
+ return;
1314
+ }
1315
+
1316
+ this._status = status;
1317
+ this._value = value;
1318
+
1319
+ if (status === STATUS_REJECTED && this._handlers.length === 0) {
1320
+ this._unhandledRejection = true;
1321
+ HandlerManager.addUnhandledRejection(this);
1322
+ }
1323
+
1324
+ HandlerManager.scheduleHandlers(this);
1325
+ },
1326
+
1327
+ _resolve: function Promise_resolve(value) {
1328
+ this._updateStatus(STATUS_RESOLVED, value);
1329
+ },
1330
+
1331
+ _reject: function Promise_reject(reason) {
1332
+ this._updateStatus(STATUS_REJECTED, reason);
1333
+ },
1334
+
1335
+ then: function Promise_then(onResolve, onReject) {
1336
+ var nextPromise = new Promise(function (resolve, reject) {
1337
+ this.resolve = resolve;
1338
+ this.reject = reject;
1339
+ });
1340
+ this._handlers.push({
1341
+ thisPromise: this,
1342
+ onResolve: onResolve,
1343
+ onReject: onReject,
1344
+ nextPromise: nextPromise
1345
+ });
1346
+ HandlerManager.scheduleHandlers(this);
1347
+ return nextPromise;
1348
+ },
1349
+
1350
+ catch: function Promise_catch(onReject) {
1351
+ return this.then(undefined, onReject);
1352
+ }
1353
+ };
1354
+
1355
+ globalScope.Promise = Promise;
1356
+ //#else
1357
+ //throw new Error('DOM Promise is not present');
1358
+ //#endif
1359
+ })();
1360
+
1361
+ var StatTimer = (function StatTimerClosure() {
1362
+ function rpad(str, pad, length) {
1363
+ while (str.length < length) {
1364
+ str += pad;
1365
+ }
1366
+ return str;
1367
+ }
1368
+ function StatTimer() {
1369
+ this.started = {};
1370
+ this.times = [];
1371
+ this.enabled = true;
1372
+ }
1373
+ StatTimer.prototype = {
1374
+ time: function StatTimer_time(name) {
1375
+ if (!this.enabled) {
1376
+ return;
1377
+ }
1378
+ if (name in this.started) {
1379
+ warn('Timer is already running for ' + name);
1380
+ }
1381
+ this.started[name] = Date.now();
1382
+ },
1383
+ timeEnd: function StatTimer_timeEnd(name) {
1384
+ if (!this.enabled) {
1385
+ return;
1386
+ }
1387
+ if (!(name in this.started)) {
1388
+ warn('Timer has not been started for ' + name);
1389
+ }
1390
+ this.times.push({
1391
+ 'name': name,
1392
+ 'start': this.started[name],
1393
+ 'end': Date.now()
1394
+ });
1395
+ // Remove timer from started so it can be called again.
1396
+ delete this.started[name];
1397
+ },
1398
+ toString: function StatTimer_toString() {
1399
+ var i, ii;
1400
+ var times = this.times;
1401
+ var out = '';
1402
+ // Find the longest name for padding purposes.
1403
+ var longest = 0;
1404
+ for (i = 0, ii = times.length; i < ii; ++i) {
1405
+ var name = times[i]['name'];
1406
+ if (name.length > longest) {
1407
+ longest = name.length;
1408
+ }
1409
+ }
1410
+ for (i = 0, ii = times.length; i < ii; ++i) {
1411
+ var span = times[i];
1412
+ var duration = span.end - span.start;
1413
+ out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n';
1414
+ }
1415
+ return out;
1416
+ }
1417
+ };
1418
+ return StatTimer;
1419
+ })();
1420
+
1421
+ PDFJS.createBlob = function createBlob(data, contentType) {
1422
+ if (typeof Blob !== 'undefined') {
1423
+ return new Blob([data], { type: contentType });
1424
+ }
1425
+ // Blob builder is deprecated in FF14 and removed in FF18.
1426
+ var bb = new MozBlobBuilder();
1427
+ bb.append(data);
1428
+ return bb.getBlob(contentType);
1429
+ };
1430
+
1431
+ PDFJS.createObjectURL = (function createObjectURLClosure() {
1432
+ // Blob/createObjectURL is not available, falling back to data schema.
1433
+ var digits =
1434
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
1435
+
1436
+ return function createObjectURL(data, contentType) {
1437
+ if (!PDFJS.disableCreateObjectURL &&
1438
+ typeof URL !== 'undefined' && URL.createObjectURL) {
1439
+ var blob = PDFJS.createBlob(data, contentType);
1440
+ return URL.createObjectURL(blob);
1441
+ }
1442
+
1443
+ var buffer = 'data:' + contentType + ';base64,';
1444
+ for (var i = 0, ii = data.length; i < ii; i += 3) {
1445
+ var b1 = data[i] & 0xFF;
1446
+ var b2 = data[i + 1] & 0xFF;
1447
+ var b3 = data[i + 2] & 0xFF;
1448
+ var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
1449
+ var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
1450
+ var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
1451
+ buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
1452
+ }
1453
+ return buffer;
1454
+ };
1455
+ })();
1456
+
1457
+ function MessageHandler(name, comObj) {
1458
+ this.name = name;
1459
+ this.comObj = comObj;
1460
+ this.callbackIndex = 1;
1461
+ this.postMessageTransfers = true;
1462
+ var callbacksCapabilities = this.callbacksCapabilities = {};
1463
+ var ah = this.actionHandler = {};
1464
+
1465
+ ah['console_log'] = [function ahConsoleLog(data) {
1466
+ console.log.apply(console, data);
1467
+ }];
1468
+ ah['console_error'] = [function ahConsoleError(data) {
1469
+ console.error.apply(console, data);
1470
+ }];
1471
+ ah['_unsupported_feature'] = [function ah_unsupportedFeature(data) {
1472
+ UnsupportedManager.notify(data);
1473
+ }];
1474
+
1475
+ comObj.onmessage = function messageHandlerComObjOnMessage(event) {
1476
+ var data = event.data;
1477
+ if (data.isReply) {
1478
+ var callbackId = data.callbackId;
1479
+ if (data.callbackId in callbacksCapabilities) {
1480
+ var callback = callbacksCapabilities[callbackId];
1481
+ delete callbacksCapabilities[callbackId];
1482
+ if ('error' in data) {
1483
+ callback.reject(data.error);
1484
+ } else {
1485
+ callback.resolve(data.data);
1486
+ }
1487
+ } else {
1488
+ error('Cannot resolve callback ' + callbackId);
1489
+ }
1490
+ } else if (data.action in ah) {
1491
+ var action = ah[data.action];
1492
+ if (data.callbackId) {
1493
+ Promise.resolve().then(function () {
1494
+ return action[0].call(action[1], data.data);
1495
+ }).then(function (result) {
1496
+ comObj.postMessage({
1497
+ isReply: true,
1498
+ callbackId: data.callbackId,
1499
+ data: result
1500
+ });
1501
+ }, function (reason) {
1502
+ comObj.postMessage({
1503
+ isReply: true,
1504
+ callbackId: data.callbackId,
1505
+ error: reason
1506
+ });
1507
+ });
1508
+ } else {
1509
+ action[0].call(action[1], data.data);
1510
+ }
1511
+ } else {
1512
+ error('Unknown action from worker: ' + data.action);
1513
+ }
1514
+ };
1515
+ }
1516
+
1517
+ MessageHandler.prototype = {
1518
+ on: function messageHandlerOn(actionName, handler, scope) {
1519
+ var ah = this.actionHandler;
1520
+ if (ah[actionName]) {
1521
+ error('There is already an actionName called "' + actionName + '"');
1522
+ }
1523
+ ah[actionName] = [handler, scope];
1524
+ },
1525
+ /**
1526
+ * Sends a message to the comObj to invoke the action with the supplied data.
1527
+ * @param {String} actionName Action to call.
1528
+ * @param {JSON} data JSON data to send.
1529
+ * @param {Array} [transfers] Optional list of transfers/ArrayBuffers
1530
+ */
1531
+ send: function messageHandlerSend(actionName, data, transfers) {
1532
+ var message = {
1533
+ action: actionName,
1534
+ data: data
1535
+ };
1536
+ this.postMessage(message, transfers);
1537
+ },
1538
+ /**
1539
+ * Sends a message to the comObj to invoke the action with the supplied data.
1540
+ * Expects that other side will callback with the response.
1541
+ * @param {String} actionName Action to call.
1542
+ * @param {JSON} data JSON data to send.
1543
+ * @param {Array} [transfers] Optional list of transfers/ArrayBuffers.
1544
+ * @returns {Promise} Promise to be resolved with response data.
1545
+ */
1546
+ sendWithPromise:
1547
+ function messageHandlerSendWithPromise(actionName, data, transfers) {
1548
+ var callbackId = this.callbackIndex++;
1549
+ var message = {
1550
+ action: actionName,
1551
+ data: data,
1552
+ callbackId: callbackId
1553
+ };
1554
+ var capability = createPromiseCapability();
1555
+ this.callbacksCapabilities[callbackId] = capability;
1556
+ try {
1557
+ this.postMessage(message, transfers);
1558
+ } catch (e) {
1559
+ capability.reject(e);
1560
+ }
1561
+ return capability.promise;
1562
+ },
1563
+ /**
1564
+ * Sends raw message to the comObj.
1565
+ * @private
1566
+ * @param message {Object} Raw message.
1567
+ * @param transfers List of transfers/ArrayBuffers, or undefined.
1568
+ */
1569
+ postMessage: function (message, transfers) {
1570
+ if (transfers && this.postMessageTransfers) {
1571
+ this.comObj.postMessage(message, transfers);
1572
+ } else {
1573
+ this.comObj.postMessage(message);
1574
+ }
1575
+ }
1576
+ };
1577
+
1578
+ function loadJpegStream(id, imageUrl, objs) {
1579
+ var img = new Image();
1580
+ img.onload = (function loadJpegStream_onloadClosure() {
1581
+ objs.resolve(id, img);
1582
+ });
1583
+ img.onerror = (function loadJpegStream_onerrorClosure() {
1584
+ objs.resolve(id, null);
1585
+ warn('Error during JPEG image loading');
1586
+ });
1587
+ img.src = imageUrl;
1588
+ }